Skip to content

plugin ¤

Plugin classes of Nendo Core.

NendoAnalysisPlugin ¤

Bases: NendoPlugin

Basic class for nendo analysis plugins.

Analysis plugins are plugins that analyze a track or a collection and add metadata and other properties to the track or collection. Decorate your methods with @NendoAnalysisPlugin.plugin_data to add the return values of your methods as plugin data to the track or collection.

Decorate your methods with @NendoAnalysisPlugin.run_track to run your method on a track and use @NendoAnalysisPlugin.run_collection to run your method on a collection.

Examples:

from nendo import Nendo, NendoConfig

class MyPlugin(NendoAnalysisPlugin):
    ...

    @NendoAnalysisPlugin.plugin_data
    def my_plugin_data_function_one(self, track):
        # do something analysis on the track
        return {"key": "value"}

    @NendoAnalysisPlugin.plugin_data
    def my_plugin_data_function_two(self, track):
        # do some more analysis on the track
        return {"key": "value"}

    @NendoAnalysisPlugin.run_track
    def my_run_track_function(self, track):
        my_plugin_data_function_one(track)
        my_plugin_data_function_two(track)

plugin_type property ¤

plugin_type: str

Return type of plugin.

batch_process staticmethod ¤

batch_process(func)

Decorator to run functions multithreaded in batches.

This decorator function transforms the given function to run in multiple threads. It expects that the first argument to the function is a list of items, which will be processed in parallel, in batches of a given size.

Source code in src/nendo/schema/core.py
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
@staticmethod
def batch_process(func):
    """Decorator to run functions multithreaded in batches.

    This decorator function transforms the given function to run
    in multiple threads. It expects that the first argument to the function
    is a list of items, which will be processed in parallel,
    in batches of a given size.
    """

    @functools.wraps(func)
    def wrapper(self, track=None, file_paths=None, *args, **kwargs):
        target = track or file_paths
        if isinstance(target, NendoTrack):
            return func(self, track=target, **kwargs)
        elif isinstance(target, list):  # noqa: RET505
            max_threads = self.config.max_threads
            batch_size = self.config.batch_size
            total = len(target)
            batches = [
                target[i : i + batch_size] for i in range(0, total, batch_size)
            ]
            start_time = time.time()
            futures = []

            def run_batch(batch_index, batch):
                try:
                    batch_start_time = time.time()
                    results = []
                    if track:
                        for _, item in enumerate(batch):
                            result = func(
                                self,
                                track=item,
                                *args,  # noqa: B026
                                **kwargs,
                            )
                            results.extend(result)
                    elif file_paths:
                        result = func(
                            self,
                            file_paths=batch,
                            *args,  # noqa: B026
                            **kwargs,
                        )
                        results.extend(result)
                    batch_end_time = time.time()
                    batch_time = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(batch_end_time - batch_start_time),
                    )
                    total_elapsed_time = batch_end_time - start_time
                    average_time_per_batch = total_elapsed_time / (batch_index + 1)
                    estimated_total_time = average_time_per_batch * len(batches)
                    estimated_total_time_print = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(estimated_total_time),
                    )
                    remaining_time = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(estimated_total_time - total_elapsed_time),
                    )
                    logger.info(
                        f"Finished batch {batch_index + 1}/{len(batches)}.\n"
                        f"Time taken for this batch: {batch_time} - "
                        f"Estimated total time: {estimated_total_time_print} - "
                        f"Estimated remaining time: {remaining_time}\n",
                    )
                    return results
                except NendoError as e:
                    logger.exception(
                        "Error processing batch %d: %s",
                        batch_index,
                        e,
                    )

            with ThreadPoolExecutor(max_workers=max_threads) as executor:
                for batch_index, batch in enumerate(batches):
                    futures.append(executor.submit(run_batch, batch_index, batch))

            all_results = []
            for future in as_completed(futures):
                result = future.result()
                if result:
                    all_results.extend(future.result())
            return all_results
        else:
            raise TypeError("Expected NendoTrack or list of NendoTracks")

    return wrapper

plugin_data staticmethod ¤

plugin_data(
    func: Callable[
        [NendoPlugin, NendoTrack], Dict[str, Any]
    ]
) -> Callable[[NendoPlugin, NendoTrack], Dict[str, Any]]

Decorator to enrich a NendoTrack with data from a plugin.

Parameters:

Name Type Description Default
func Callable[[NendoPlugin, NendoTrack], Dict[str, Any]]

Callable[[NendoPlugin, NendoTrack], Dict[str, Any]]: The function to register.

required

Returns:

Type Description
Callable[[NendoPlugin, NendoTrack], Dict[str, Any]]

The wrapped function.

Source code in src/nendo/schema/plugin.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
@staticmethod
def plugin_data(
    func: Callable[[NendoPlugin, NendoTrack], Dict[str, Any]],
) -> Callable[[NendoPlugin, NendoTrack], Dict[str, Any]]:
    """Decorator to enrich a NendoTrack with data from a plugin.

    Args:
        func: Callable[[NendoPlugin, NendoTrack], Dict[str, Any]]: The function to register.

    Returns:
        Callable[[NendoPlugin, NendoTrack], Dict[str, Any]]: The wrapped function.
    """

    def wrapper(self, track: NendoTrack):
        try:
            f_result = func(self, track)
        except NendoError as e:
            raise NendoPluginRuntimeError(
                f"Error running plugin function: {e}",
            ) from None
        for k, v in f_result.items():
            track.add_plugin_data(
                plugin_name=self.plugin_name,
                plugin_version=self.plugin_version,
                key=str(k),
                value=v,
            )
        return f_result

    return wrapper

run_collection staticmethod ¤

run_collection(
    func: Callable[
        [NendoPlugin, NendoCollection, Any], None
    ]
) -> Callable[[NendoPlugin, Any], NendoCollection]

Decorator to register a function as a collection running function for a NendoAnalysisPlugin.

This decorator wraps the function and allows a plugin user to call the plugin with either a collection or a track.

Parameters:

Name Type Description Default
func Callable[[NendoPlugin, NendoCollection, Any], None]

Callable[[NendoPlugin, NendoCollection, Any], None]: The function to register.

required

Returns:

Type Description
Callable[[NendoPlugin, Any], NendoCollection]

The wrapped function.

Source code in src/nendo/schema/plugin.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
@staticmethod
def run_collection(
    func: Callable[[NendoPlugin, NendoCollection, Any], None],
) -> Callable[[NendoPlugin, Any], NendoCollection]:
    """Decorator to register a function as a collection running function for a `NendoAnalysisPlugin`.

    This decorator wraps the function and allows a plugin user to call the plugin with either a collection or a track.

    Args:
        func: Callable[[NendoPlugin, NendoCollection, Any], None]: The function to register.

    Returns:
        Callable[[NendoPlugin, Any], NendoCollection]: The wrapped function.
    """

    @functools.wraps(func)
    def wrapper(self, **kwargs: Any) -> NendoCollection:
        track_or_collection, kwargs = self._pop_track_or_collection_from_args(
            **kwargs,
        )
        if isinstance(track_or_collection, NendoCollection):
            func(self, track_or_collection, **kwargs)
            return self.nendo_instance.library.get_collection(
                track_or_collection.id,
            )

        tmp_collection = self.nendo_instance.library.add_collection(
            name="tmp",
            track_ids=[track_or_collection.id],
            collection_type="temp",
        )
        func(self, tmp_collection, **kwargs)
        return self.nendo_instance.library.get_track(track_or_collection.id)

    return wrapper

run_track staticmethod ¤

Decorator to register a function as a track running function for a NendoAnalysisPlugin.

This decorator wraps the function and allows a plugin user to call the plugin with either a collection or a track.

Parameters:

Name Type Description Default
func Callable[[NendoPlugin, NendoTrack, Any], None]

Callable[[NendoPlugin, NendoTrack, Any], None]: The function to register.

required

Returns:

Type Description
Callable[[NendoPlugin, Any], NendoCollection]

The wrapped function.

Source code in src/nendo/schema/plugin.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
@staticmethod
def run_track(
    func: Callable[[NendoPlugin, NendoTrack, Any], None],
) -> Callable[[NendoPlugin, Any], Union[NendoTrack, NendoCollection]]:
    """Decorator to register a function as a track running function for a `NendoAnalysisPlugin`.

    This decorator wraps the function and allows a plugin user to call the plugin with either a collection or a track.

    Args:
        func: Callable[[NendoPlugin, NendoTrack, Any], None]: The function to register.

    Returns:
        Callable[[NendoPlugin, Any], NendoCollection]: The wrapped function.
    """

    @functools.wraps(func)
    def wrapper(self, **kwargs: Any) -> Union[NendoTrack, NendoCollection]:
        track_or_collection, kwargs = self._pop_track_or_collection_from_args(
            **kwargs,
        )
        if isinstance(track_or_collection, NendoTrack):
            func(self, track_or_collection, **kwargs)
            return self.nendo_instance.library.get_track(track_or_collection.id)
        [func(self, track, **kwargs) for track in track_or_collection.tracks()]
        return self.nendo_instance.library.get_collection(track_or_collection.id)

    return wrapper

stream_output staticmethod ¤

stream_output(func)

Decorator to turn on streaming mode for functions.

The requirement for this decorator to work on a function is that it would normally return a list.

Source code in src/nendo/schema/core.py
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
@staticmethod
def stream_output(func):
    """Decorator to turn on streaming mode for functions.

    The requirement for this decorator to work on a function is that it would
    normally return a list.
    """

    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        result = func(self, *args, **kwargs)
        if self.config.stream_mode:
            return result
        # function is yielding single tracks if stream_chunk_size == 1
        elif self.config.stream_chunk_size > 1:  # noqa: RET505
            return [track for chunk in result for track in chunk]
        else:
            return list(result)

    return wrapper

NendoEffectPlugin ¤

Bases: NendoPlugin

Basic class for nendo effects plugins.

Effects plugins are plugins that add effects to tracks or collections. Decorate your methods with @NendoGeneratePlugin.run_track to run your method on a track, use @NendoGeneratePlugin.run_collection to run your method on a collection and use @NendoGeneratePlugin.run_signal to run your method on a signal.

Examples:

from nendo import Nendo, NendoConfig

class MyPlugin(NendoGeneratePlugin):
    ...

    @NendoAnalysisPlugin.run_signal
    def my_effect_function(self, signal, sr, arg_one="foo"):
        # add some effect to the signal
        new_signal = apply_effect(signal, sr, arg_one)

        return new_signal, sr

plugin_type property ¤

plugin_type: str

Return type of plugin.

batch_process staticmethod ¤

batch_process(func)

Decorator to run functions multithreaded in batches.

This decorator function transforms the given function to run in multiple threads. It expects that the first argument to the function is a list of items, which will be processed in parallel, in batches of a given size.

Source code in src/nendo/schema/core.py
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
@staticmethod
def batch_process(func):
    """Decorator to run functions multithreaded in batches.

    This decorator function transforms the given function to run
    in multiple threads. It expects that the first argument to the function
    is a list of items, which will be processed in parallel,
    in batches of a given size.
    """

    @functools.wraps(func)
    def wrapper(self, track=None, file_paths=None, *args, **kwargs):
        target = track or file_paths
        if isinstance(target, NendoTrack):
            return func(self, track=target, **kwargs)
        elif isinstance(target, list):  # noqa: RET505
            max_threads = self.config.max_threads
            batch_size = self.config.batch_size
            total = len(target)
            batches = [
                target[i : i + batch_size] for i in range(0, total, batch_size)
            ]
            start_time = time.time()
            futures = []

            def run_batch(batch_index, batch):
                try:
                    batch_start_time = time.time()
                    results = []
                    if track:
                        for _, item in enumerate(batch):
                            result = func(
                                self,
                                track=item,
                                *args,  # noqa: B026
                                **kwargs,
                            )
                            results.extend(result)
                    elif file_paths:
                        result = func(
                            self,
                            file_paths=batch,
                            *args,  # noqa: B026
                            **kwargs,
                        )
                        results.extend(result)
                    batch_end_time = time.time()
                    batch_time = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(batch_end_time - batch_start_time),
                    )
                    total_elapsed_time = batch_end_time - start_time
                    average_time_per_batch = total_elapsed_time / (batch_index + 1)
                    estimated_total_time = average_time_per_batch * len(batches)
                    estimated_total_time_print = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(estimated_total_time),
                    )
                    remaining_time = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(estimated_total_time - total_elapsed_time),
                    )
                    logger.info(
                        f"Finished batch {batch_index + 1}/{len(batches)}.\n"
                        f"Time taken for this batch: {batch_time} - "
                        f"Estimated total time: {estimated_total_time_print} - "
                        f"Estimated remaining time: {remaining_time}\n",
                    )
                    return results
                except NendoError as e:
                    logger.exception(
                        "Error processing batch %d: %s",
                        batch_index,
                        e,
                    )

            with ThreadPoolExecutor(max_workers=max_threads) as executor:
                for batch_index, batch in enumerate(batches):
                    futures.append(executor.submit(run_batch, batch_index, batch))

            all_results = []
            for future in as_completed(futures):
                result = future.result()
                if result:
                    all_results.extend(future.result())
            return all_results
        else:
            raise TypeError("Expected NendoTrack or list of NendoTracks")

    return wrapper

run_collection staticmethod ¤

Decorator to register a function as a collection running function for a NendoEffectPlugin.

This decorator wraps the function and allows a plugin user to call the plugin with either a collection or a track.

Parameters:

Name Type Description Default
func Callable[[NendoPlugin, NendoCollection, Any], NendoCollection]

Callable[[NendoPlugin, NendoCollection, Any], NendoCollection]: The function to register.

required

Returns:

Type Description
Callable[[NendoPlugin, Any], NendoCollection]

The wrapped function.

Source code in src/nendo/schema/plugin.py
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
@staticmethod
def run_collection(
    func: Callable[[NendoPlugin, NendoCollection, Any], NendoCollection],
) -> Callable[[NendoPlugin, Any], NendoCollection]:
    """Decorator to register a function as a collection running function for a `NendoEffectPlugin`.

    This decorator wraps the function and allows a plugin user to call the plugin with either a collection or a track.

    Args:
        func: Callable[[NendoPlugin, NendoCollection, Any], NendoCollection]: The function to register.

    Returns:
        Callable[[NendoPlugin, Any], NendoCollection]: The wrapped function.
    """

    @functools.wraps(func)
    def wrapper(self, **kwargs: Any) -> NendoCollection:
        track_or_collection, kwargs = self._pop_track_or_collection_from_args(
            **kwargs,
        )
        if isinstance(track_or_collection, NendoCollection):
            return func(self, track_or_collection, **kwargs)

        tmp_collection = self.nendo_instance.library.add_collection(
            name="tmp",
            track_ids=[track_or_collection.id],
            collection_type="temp",
        )
        return func(self, tmp_collection, **kwargs)

    return wrapper

run_signal staticmethod ¤

run_signal(
    func: Callable[
        [NendoPlugin, ndarray, int, Any],
        Tuple[ndarray, int],
    ]
) -> Callable[
    [NendoPlugin, Any], Union[NendoTrack, NendoCollection]
]

Decorator to register a function as a signal running function for a NendoEffectPlugin.

This decorator wraps the function and allows a plugin user to call the plugin with either a collection or a track.

Parameters:

Name Type Description Default
func Callable[[NendoPlugin, ndarray, int, Any], Tuple[ndarray, int]]

Callable[[NendoPlugin, np.ndarray, int, Any], Tuple[np.ndarray, int]]: The function to register.

required

Returns:

Type Description
Callable[[NendoPlugin, Any], NendoTrack]

The wrapped function.

Source code in src/nendo/schema/plugin.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
@staticmethod
def run_signal(
    func: Callable[[NendoPlugin, np.ndarray, int, Any], Tuple[np.ndarray, int]],
) -> Callable[[NendoPlugin, Any], Union[NendoTrack, NendoCollection]]:
    """Decorator to register a function as a signal running function for a `NendoEffectPlugin`.

    This decorator wraps the function and allows a plugin user to call the plugin with either a collection or a track.

    Args:
        func: Callable[[NendoPlugin, np.ndarray, int, Any], Tuple[np.ndarray, int]]: The function to register.

    Returns:
        Callable[[NendoPlugin, Any], NendoTrack]: The wrapped function.
    """

    @functools.wraps(func)
    def wrapper(self, **kwargs: Any) -> Union[NendoTrack, NendoCollection]:
        track_or_collection, kwargs = self._pop_track_or_collection_from_args(
            **kwargs,
        )
        processed_tracks = []
        if isinstance(track_or_collection, NendoTrack):
            signal, sr = track_or_collection.signal, track_or_collection.sr
            new_signal, new_sr = func(self, signal, sr, **kwargs)

            # TODO update track instead of adding a new one to the library
            return self.nendo_instance.library.add_related_track_from_signal(
                new_signal,
                sr,
                related_track_id=track_or_collection.id,
            )

        for track in track_or_collection.tracks():
            new_signal, new_sr = func(
                self,
                track.signal,
                track.sr,
                **kwargs,
            )

            # TODO update track instead of adding a new one to the library
            processed_tracks.append(
                self.nendo_instance.library.add_related_track_from_signal(
                    new_signal,
                    track.sr,
                    related_track_id=track.id,
                ),
            )

        return self.nendo_instance.library.add_collection(
            name="tmp",
            track_ids=[track.id for track in processed_tracks],
            collection_type="temp",
        )

    return wrapper

run_track staticmethod ¤

Decorator to register a function as a track running function for a NendoEffectPlugin.

This decorator wraps the function and allows a plugin user to call the plugin with either a collection or a track.

Parameters:

Name Type Description Default
func Callable[[NendoPlugin, NendoTrack, Any], Union[NendoTrack, List[NendoTrack]]]

Callable[[NendoPlugin, NendoTrack, Any], Union[NendoTrack, List[NendoTrack]]]: The function to register.

required

Returns:

Type Description
Callable[[NendoPlugin, Any], NendoTrack]

The wrapped function.

Source code in src/nendo/schema/plugin.py
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
@staticmethod
def run_track(
    func: Callable[
        [NendoPlugin, NendoTrack, Any],
        Union[NendoTrack, List[NendoTrack]],
    ],
) -> Callable[[NendoPlugin, Any], NendoTrack]:
    """Decorator to register a function as a track running function for a `NendoEffectPlugin`.

    This decorator wraps the function and allows a plugin user to call the plugin with either a collection or a track.

    Args:
        func: Callable[[NendoPlugin, NendoTrack, Any], Union[NendoTrack, List[NendoTrack]]]: The function to register.

    Returns:
        Callable[[NendoPlugin, Any], NendoTrack]: The wrapped function.
    """

    @functools.wraps(func)
    def wrapper(self, **kwargs: Any) -> Union[NendoTrack, NendoCollection]:
        track_or_collection, kwargs = self._pop_track_or_collection_from_args(
            **kwargs,
        )
        if isinstance(track_or_collection, NendoTrack):
            return func(self, track_or_collection, **kwargs)

        processed_tracks = [
            func(self, track, **kwargs) for track in track_or_collection.tracks()
        ]
        return self.nendo_instance.library.add_collection(
            name="tmp",
            track_ids=[track.id for track in processed_tracks],
            collection_type="temp",
        )

    return wrapper

stream_output staticmethod ¤

stream_output(func)

Decorator to turn on streaming mode for functions.

The requirement for this decorator to work on a function is that it would normally return a list.

Source code in src/nendo/schema/core.py
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
@staticmethod
def stream_output(func):
    """Decorator to turn on streaming mode for functions.

    The requirement for this decorator to work on a function is that it would
    normally return a list.
    """

    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        result = func(self, *args, **kwargs)
        if self.config.stream_mode:
            return result
        # function is yielding single tracks if stream_chunk_size == 1
        elif self.config.stream_chunk_size > 1:  # noqa: RET505
            return [track for chunk in result for track in chunk]
        else:
            return list(result)

    return wrapper

NendoEmbeddingPlugin ¤

Bases: NendoPlugin

Basic class for nendo embedding plugins.

Embedding plugins are plugins that are used by nendo to embed NendoTracks or query strings into an n-dimensional vector space. To implement such a plugin, at least one function should exist that is annotated with the @run_text decorator. Alternatively or in addition to, any of the other decorators, @run_signal_and_text, @run_track, and @run_collection can be implemented and will be used when the plugin is directly called.

plugin_type property ¤

plugin_type: str

Return type of plugin.

batch_process staticmethod ¤

batch_process(func)

Decorator to run functions multithreaded in batches.

This decorator function transforms the given function to run in multiple threads. It expects that the first argument to the function is a list of items, which will be processed in parallel, in batches of a given size.

Source code in src/nendo/schema/core.py
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
@staticmethod
def batch_process(func):
    """Decorator to run functions multithreaded in batches.

    This decorator function transforms the given function to run
    in multiple threads. It expects that the first argument to the function
    is a list of items, which will be processed in parallel,
    in batches of a given size.
    """

    @functools.wraps(func)
    def wrapper(self, track=None, file_paths=None, *args, **kwargs):
        target = track or file_paths
        if isinstance(target, NendoTrack):
            return func(self, track=target, **kwargs)
        elif isinstance(target, list):  # noqa: RET505
            max_threads = self.config.max_threads
            batch_size = self.config.batch_size
            total = len(target)
            batches = [
                target[i : i + batch_size] for i in range(0, total, batch_size)
            ]
            start_time = time.time()
            futures = []

            def run_batch(batch_index, batch):
                try:
                    batch_start_time = time.time()
                    results = []
                    if track:
                        for _, item in enumerate(batch):
                            result = func(
                                self,
                                track=item,
                                *args,  # noqa: B026
                                **kwargs,
                            )
                            results.extend(result)
                    elif file_paths:
                        result = func(
                            self,
                            file_paths=batch,
                            *args,  # noqa: B026
                            **kwargs,
                        )
                        results.extend(result)
                    batch_end_time = time.time()
                    batch_time = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(batch_end_time - batch_start_time),
                    )
                    total_elapsed_time = batch_end_time - start_time
                    average_time_per_batch = total_elapsed_time / (batch_index + 1)
                    estimated_total_time = average_time_per_batch * len(batches)
                    estimated_total_time_print = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(estimated_total_time),
                    )
                    remaining_time = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(estimated_total_time - total_elapsed_time),
                    )
                    logger.info(
                        f"Finished batch {batch_index + 1}/{len(batches)}.\n"
                        f"Time taken for this batch: {batch_time} - "
                        f"Estimated total time: {estimated_total_time_print} - "
                        f"Estimated remaining time: {remaining_time}\n",
                    )
                    return results
                except NendoError as e:
                    logger.exception(
                        "Error processing batch %d: %s",
                        batch_index,
                        e,
                    )

            with ThreadPoolExecutor(max_workers=max_threads) as executor:
                for batch_index, batch in enumerate(batches):
                    futures.append(executor.submit(run_batch, batch_index, batch))

            all_results = []
            for future in as_completed(futures):
                result = future.result()
                if result:
                    all_results.extend(future.result())
            return all_results
        else:
            raise TypeError("Expected NendoTrack or list of NendoTracks")

    return wrapper

run_collection staticmethod ¤

Decorator to register a function to create a NendoEmbedding from a collection.

This decorator wraps the function and allows a plugin user to call the plugin with either a set of (signal, sr, text), a track or a collection.

Parameters:

Name Type Description Default
func Callable[[NendoPlugin, NendoCollection, Any], None]

Callable[[NendoPlugin, np.array, int, str, Any], None]: The function to register.

required

Returns:

Type Description
Callable[[NendoPlugin, Any], Union[NendoEmbedding, List[NendoEmbedding]]]

The wrapped function.

Source code in src/nendo/schema/plugin.py
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
@staticmethod
def run_collection(
    func: Callable[[NendoPlugin, NendoCollection, Any], None],
) -> Callable[[NendoPlugin, Any], Union[NendoEmbedding, List[NendoEmbedding]]]:
    """Decorator to register a function to create a `NendoEmbedding` from a collection.

    This decorator wraps the function and allows a plugin user to call the plugin with either a set of (signal, sr, text), a track or a collection.

    Args:
        func: Callable[[NendoPlugin, np.array, int, str, Any], None]: The function to register.

    Returns:
        Callable[[NendoPlugin, Any], Union[NendoEmbedding, List[NendoEmbedding]]]: The wrapped function.
    """

    @functools.wraps(func)
    def wrapper(self, **kwargs: Any) -> Union[NendoEmbedding, List[NendoEmbedding]]:
        track_or_collection, kwargs = self._pop_track_or_collection_from_args(
            **kwargs,
        )
        # TODO we currently have no way of handling embeddings of collections,
        # so we just return the function value(s) directly
        if isinstance(track_or_collection, NendoCollection):
            return func(self, track_or_collection, **kwargs)
        if track_or_collection is None:
            signal = kwargs.get("signal", None)
            sr = kwargs.get("sr", None)
            text = kwargs.get("text", None)
            track_or_collection = self.nendo_instance.library.add_track_from_signal(
                signal=signal if signal is not None else np.array([]),
                sr=sr if sr is not None else self.config.default_sr,
                meta={"text": text},
            )
            kwargs.pop("signal", None)
            kwargs.pop("sr", None)
            kwargs.pop("text", None)

        tmp_collection = self.nendo_instance.library.add_collection(
            name="tmp",
            track_ids=[track_or_collection.id],
            collection_type="temp",
        )
        return func(self, tmp_collection, **kwargs)

    return wrapper

run_signal_and_text staticmethod ¤

run_signal_and_text(
    func: Callable[
        [NendoPlugin, array, int, str, Any], None
    ]
) -> Callable[
    [NendoPlugin, Any],
    Union[NendoEmbedding, List[NendoEmbedding]],
]

Decorator to register a function as a function to create a NendoEmbedding from a given signal, sr, and text.

This decorator wraps the function and allows a plugin user to call the plugin with either a set of (signal, sr, text), a track or a collection.

Parameters:

Name Type Description Default
func Callable[[NendoPlugin, array, int, str, Any], None]

Callable[[NendoPlugin, np.array, int, str, Any], None]: The function to register.

required

Returns:

Type Description
Callable[[NendoPlugin, Any], Union[NendoEmbedding, List[NendoEmbedding]]]

The wrapped function.

Source code in src/nendo/schema/plugin.py
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
@staticmethod
def run_signal_and_text(
    func: Callable[[NendoPlugin, np.array, int, str, Any], None],
) -> Callable[[NendoPlugin, Any], Union[NendoEmbedding, List[NendoEmbedding]]]:
    """Decorator to register a function as a function to create a `NendoEmbedding` from a given signal, sr, and text.

    This decorator wraps the function and allows a plugin user to call the plugin with either a set of (signal, sr, text), a track or a collection.

    Args:
        func: Callable[[NendoPlugin, np.array, int, str, Any], None]: The function to register.

    Returns:
        Callable[[NendoPlugin, Any], Union[NendoEmbedding, List[NendoEmbedding]]]: The wrapped function.
    """

    @functools.wraps(func)
    def wrapper(self, **kwargs: Any) -> Union[NendoEmbedding, List[NendoEmbedding]]:
        track_or_collection, kwargs = self._pop_track_or_collection_from_args(
            **kwargs,
        )
        if track_or_collection is None:
            signal = kwargs.get("signal", None)
            sr = kwargs.get("sr", None)
            text, embedding_vector = func(self, **kwargs)
            new_track = self.nendo_instance.library.add_track_from_signal(
                signal=signal if signal is not None else np.array([]),
                sr=sr if sr is not None else self.config.default_sr,
            )
            embedding = NendoEmbedding(
                track_id=new_track.id,
                user_id=self.nendo_instance.library.user.id,
                plugin_name=self.plugin_name,
                plugin_version=self.plugin_version,
                text=text,
                embedding=embedding_vector,
            )
            try:
                if self.config.replace_plugin_data is True:
                    existing_embeddings = (
                        self.nendo_instance.library.get_embeddings(
                            track_id=track_or_collection.id,
                            plugin_name=self.plugin_name,
                            plugin_version=self.plugin_version,
                        )
                    )
                    if len(existing_embeddings) > 0:
                        embedding_update = existing_embeddings[0]
                        embedding_update.text = text
                        embedding_update.embedding = embedding_vector
                        embedding = self.nendo_instance.library.update_embedding(
                            embedding_update,
                        )
                    else:
                        embedding = self.nendo_instance.library.add_embedding(
                            embedding=embedding,
                        )
                else:
                    embedding = self.nendo_instance.library.add_embedding(
                        embedding=embedding,
                    )
            except AttributeError as e:  # noqa: F841
                self.logger.error(
                    "Failed to save the embedding to the library. "
                    "Please use a library plugin with vector support to "
                    "enable automatic storing of embeddings.",
                )
            return embedding
        if isinstance(track_or_collection, NendoTrack):
            kwargs["signal"] = track_or_collection.signal
            kwargs["sr"] = track_or_collection.sr
            kwargs["text"] = self.track_to_text(track=track_or_collection)
            text, embedding_vector = func(self, **kwargs)
            embedding = NendoEmbedding(
                track_id=track_or_collection.id,
                user_id=self.nendo_instance.library.user.id,
                plugin_name=self.plugin_name,
                plugin_version=self.plugin_version,
                text=text,
                embedding=embedding_vector,
            )
            try:
                if self.config.replace_plugin_data is True:
                    existing_embeddings = (
                        self.nendo_instance.library.get_embeddings(
                            track_id=track_or_collection.id,
                            plugin_name=self.plugin_name,
                            plugin_version=self.plugin_version,
                        )
                    )
                    if len(existing_embeddings) > 0:
                        embedding_update = existing_embeddings[0]
                        embedding_update.text = text
                        embedding_update.embedding = embedding_vector
                        embedding = self.nendo_instance.library.update_embedding(
                            embedding_update,
                        )
                    else:
                        embedding = self.nendo_instance.library.add_embedding(
                            embedding=embedding,
                        )
                else:
                    embedding = self.nendo_instance.library.add_embedding(
                        embedding=embedding,
                    )
            except AttributeError as e:  # noqa: F841
                self.logger.error(
                    "Failed to save the embedding to the library. "
                    "Please use a library plugin with vector support to "
                    "enable automatic storing of embeddings.",
                )
            return embedding
        embeddings = []
        for track in track_or_collection.tracks():
            kwargs["signal"] = track.signal
            kwargs["sr"] = track.sr
            kwargs["text"] = self.track_to_text(track=track)
            text, embedding_vector = func(self, **kwargs)
            embedding = NendoEmbedding(
                track_id=track.id,
                user_id=self.nendo_instance.library.user.id,
                plugin_name=self.plugin_name,
                plugin_version=self.plugin_version,
                text=text,
                embedding=embedding_vector,
            )
            try:
                if self.config.replace_plugin_data is True:
                    existing_embeddings = (
                        self.nendo_instance.library.get_embeddings(
                            track_id=track_or_collection.id,
                            plugin_name=self.plugin_name,
                            plugin_version=self.plugin_version,
                        )
                    )
                    if len(existing_embeddings) > 0:
                        embedding_update = existing_embeddings[0]
                        embedding_update.text = text
                        embedding_update.embedding = embedding_vector
                        embedding = self.nendo_instance.library.update_embedding(
                            embedding_update,
                        )
                    else:
                        embedding = self.nendo_instance.library.add_embedding(
                            embedding=embedding,
                        )
                else:
                    embedding = self.nendo_instance.library.add_embedding(
                        embedding=embedding,
                    )
            except AttributeError as e:  # noqa: F841
                self.logger.error(
                    "Failed to save the embedding to the library. "
                    "Please use a library plugin with vector support to "
                    "enable automatic storing of embeddings.",
                )
            embeddings.append(embedding)
        return embeddings

    return wrapper

run_text staticmethod ¤

run_text(
    func: Callable[
        [NendoPlugin, str, Any], Tuple[str, ndarray]
    ]
) -> Callable[
    [NendoPlugin, Any],
    Union[
        Tuple[str, ndarray],
        NendoEmbedding,
        List[NendoEmbedding],
    ],
]

Decorator to register a function that embeds a given text string into a vector space.

This decorator wraps the function and allows a plugin user to call the plugin with either a text, a track, or a collection.

Parameters:

Name Type Description Default
func Callable[[NendoPlugin, str, Any], Tuple[str, ndarray]]

Callable[[NendoPlugin, str, Any], Tuple[str, np.ndarray]]: The function to register.

required

Returns:

Type Description
Callable[[NendoPlugin, Any], Union[[str, ndarray], NendoEmbedding, List[NendoEmbedding]]]

The wrapped function.

Source code in src/nendo/schema/plugin.py
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
@staticmethod
def run_text(
    func: Callable[[NendoPlugin, str, Any], Tuple[str, np.ndarray]],
) -> Callable[
    [NendoPlugin, Any],
    Union[Tuple[str, np.ndarray], NendoEmbedding, List[NendoEmbedding]],
]:
    """Decorator to register a function that embeds a given text string into a vector space.

    This decorator wraps the function and allows a plugin user to call the plugin with either a text, a track, or a collection.

    Args:
        func: Callable[[NendoPlugin, str, Any], Tuple[str, np.ndarray]]: The function to register.

    Returns:
        Callable[[NendoPlugin, Any], Union[[str, np.ndarray], NendoEmbedding, List[NendoEmbedding]]]: The wrapped function.
    """

    @functools.wraps(func)
    def wrapper(
        self,
        **kwargs: Any,
    ) -> Union[Tuple[str, np.ndarray], NendoEmbedding, List[NendoEmbedding]]:
        track_or_collection, kwargs = self._pop_track_or_collection_from_args(
            **kwargs,
        )
        if track_or_collection is None:
            kwargs.pop("signal", None)
            kwargs.pop("sr", None)
            text, embedding_vector = func(self, **kwargs)
            return text, embedding_vector
        if isinstance(track_or_collection, NendoTrack):
            text, embedding_vector = func(
                self,
                text=self.track_to_text(track=track_or_collection),
                **kwargs,
            )
            embedding = NendoEmbedding(
                track_id=track_or_collection.id,
                user_id=self.nendo_instance.library.user.id,
                plugin_name=self.plugin_name,
                plugin_version=self.plugin_version,
                text=text,
                embedding=embedding_vector,
            )
            try:
                if self.config.replace_plugin_data is True:
                    existing_embeddings = (
                        self.nendo_instance.library.get_embeddings(
                            track_id=track_or_collection.id,
                            plugin_name=self.plugin_name,
                            plugin_version=self.plugin_version,
                        )
                    )
                    if len(existing_embeddings) > 0:
                        embedding_update = existing_embeddings[0]
                        embedding_update.text = text
                        embedding_update.embedding = embedding_vector
                        embedding = self.nendo_instance.library.update_embedding(
                            embedding_update,
                        )
                    else:
                        embedding = self.nendo_instance.library.add_embedding(
                            embedding=embedding,
                        )
                else:
                    embedding = self.nendo_instance.library.add_embedding(
                        embedding=embedding,
                    )
            except AttributeError as e:  # noqa: F841
                self.logger.error(
                    "Failed to save the embedding to the library. "
                    "Please use a library plugin with vector support to "
                    "enable automatic storing of embeddings.",
                )
            return embedding
        processed_tracks = []
        for track in track_or_collection.tracks():
            text, embedding_vector = func(
                self,
                text=self.track_to_text(track=track),
                **kwargs,
            )
            embedding = NendoEmbedding(
                track_id=track.id,
                user_id=self.nendo_instance.library.user.id,
                plugin_name=self.plugin_name,
                plugin_version=self.plugin_version,
                text=text,
                embedding=embedding_vector,
            )
            try:
                if self.config.replace_plugin_data is True:
                    existing_embeddings = (
                        self.nendo_instance.library.get_embeddings(
                            track_id=track_or_collection.id,
                            plugin_name=self.plugin_name,
                            plugin_version=self.plugin_version,
                        )
                    )
                    if len(existing_embeddings) > 0:
                        embedding_update = existing_embeddings[0]
                        embedding_update.text = text
                        embedding_update.embedding = embedding_vector
                        embedding = self.nendo_instance.library.update_embedding(
                            embedding_update,
                        )
                    else:
                        embedding = self.nendo_instance.library.add_embedding(
                            embedding=embedding,
                        )
                else:
                    embedding = self.nendo_instance.library.add_embedding(
                        embedding=embedding,
                    )
            except AttributeError as e:  # noqa: F841
                self.logger.error(
                    "Failed to save the embedding to the library. "
                    "Please use a library plugin with vector support to "
                    "enable automatic storing of embeddings.",
                )
            processed_tracks.append(embedding)
        return processed_tracks

    return wrapper

run_track staticmethod ¤

Decorator to register a function to create a NendoEmbedding from a track.

This decorator wraps the function and allows a plugin user to call the plugin with either a set of (signal, sr, text), a track or a collection.

Parameters:

Name Type Description Default
func Callable[[NendoPlugin, NendoTrack, Any], None]

Callable[[NendoPlugin, np.array, int, str, Any], None]: The function to register.

required

Returns:

Type Description
Callable[[NendoPlugin, Any], Union[NendoEmbedding, List[NendoEmbedding]]]

The wrapped function.

Source code in src/nendo/schema/plugin.py
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
@staticmethod
def run_track(
    func: Callable[[NendoPlugin, NendoTrack, Any], None],
) -> Callable[[NendoPlugin, Any], Union[NendoEmbedding, List[NendoEmbedding]]]:
    """Decorator to register a function to create a `NendoEmbedding` from a track.

    This decorator wraps the function and allows a plugin user to call the plugin with either a set of (signal, sr, text), a track or a collection.

    Args:
        func: Callable[[NendoPlugin, np.array, int, str, Any], None]: The function to register.

    Returns:
        Callable[[NendoPlugin, Any], Union[NendoEmbedding, List[NendoEmbedding]]]: The wrapped function.
    """

    @functools.wraps(func)
    def wrapper(self, **kwargs: Any) -> Union[NendoEmbedding, List[NendoEmbedding]]:
        track_or_collection, kwargs = self._pop_track_or_collection_from_args(
            **kwargs,
        )
        if isinstance(track_or_collection, NendoTrack):
            text, embedding_vector = func(self, track_or_collection, **kwargs)
            embedding = NendoEmbedding(
                track_id=track_or_collection.id,
                user_id=self.nendo_instance.library.user.id,
                plugin_name=self.plugin_name,
                plugin_version=self.plugin_version,
                text=text,
                embedding=embedding_vector,
            )
            try:
                if self.config.replace_plugin_data is True:
                    existing_embeddings = (
                        self.nendo_instance.library.get_embeddings(
                            track_id=track_or_collection.id,
                            plugin_name=self.plugin_name,
                            plugin_version=self.plugin_version,
                        )
                    )
                    if len(existing_embeddings) > 0:
                        embedding_update = existing_embeddings[0]
                        embedding_update.text = text
                        embedding_update.embedding = embedding_vector
                        embedding = self.nendo_instance.library.update_embedding(
                            embedding_update,
                        )
                    else:
                        embedding = self.nendo_instance.library.add_embedding(
                            embedding=embedding,
                        )
                else:
                    embedding = self.nendo_instance.library.add_embedding(
                        embedding=embedding,
                    )
            except AttributeError as e:  # noqa: F841
                self.logger.error(
                    "Failed to save the embedding to the library. "
                    "Please use a library plugin with vector support to "
                    "enable automatic storing of embeddings.",
                )
            return embedding
        if isinstance(track_or_collection, NendoCollection):
            embeddings = []
            for track in track_or_collection.tracks():
                text, embedding_vector = func(self, track, **kwargs)
                embedding = NendoEmbedding(
                    track_id=track.id,
                    user_id=self.nendo_instance.library.user.id,
                    plugin_name=self.plugin_name,
                    plugin_version=self.plugin_version,
                    text=text,
                    embedding=embedding_vector,
                )
                try:
                    if self.config.replace_plugin_data is True:
                        existing_embeddings = (
                            self.nendo_instance.library.get_embeddings(
                                track_id=track_or_collection.id,
                                plugin_name=self.plugin_name,
                                plugin_version=self.plugin_version,
                            )
                        )
                        if len(existing_embeddings) > 0:
                            embedding_update = existing_embeddings[0]
                            embedding_update.text = text
                            embedding_update.embedding = embedding_vector
                            embedding = (
                                self.nendo_instance.library.update_embedding(
                                    embedding_update,
                                )
                            )
                        else:
                            embedding = self.nendo_instance.library.add_embedding(
                                embedding=embedding,
                            )
                    else:
                        embedding = self.nendo_instance.library.add_embedding(
                            embedding=embedding,
                        )
                except AttributeError as e:  # noqa: F841
                    self.logger.error(
                        "Failed to save the embedding to the library. "
                        "Please use a library plugin with vector support to "
                        "enable automatic storing of embeddings.",
                    )
                embeddings.append(embedding)
            return embeddings
        signal = kwargs.get("signal", None)
        sr = kwargs.get("sr", None)
        text = kwargs.get("text", None)
        new_track = self.nendo_instance.library.add_track_from_signal(
            signal=signal if signal is not None else np.array([]),
            sr=sr if sr is not None else self.config.default_sr,
            meta={"text": text},
        )
        kwargs.pop("signal", None)
        kwargs.pop("sr", None)
        kwargs.pop("text", None)
        text, embedding_vector = func(self, track=new_track, **kwargs)
        embedding = NendoEmbedding(
            track_id=new_track.id,
            user_id=self.nendo_instance.library.user.id,
            plugin_name=self.plugin_name,
            plugin_version=self.plugin_version,
            text=text,
            embedding=embedding_vector,
        )
        try:
            if self.config.replace_plugin_data is True:
                existing_embeddings = self.nendo_instance.library.get_embeddings(
                    track_id=track_or_collection.id,
                    plugin_name=self.plugin_name,
                    plugin_version=self.plugin_version,
                )
                if len(existing_embeddings) > 0:
                    embedding_update = existing_embeddings[0]
                    embedding_update.text = text
                    embedding_update.embedding = embedding_vector
                    embedding = self.nendo_instance.library.update_embedding(
                        embedding_update,
                    )
                else:
                    embedding = self.nendo_instance.library.add_embedding(
                        embedding=embedding,
                    )
            else:
                embedding = self.nendo_instance.library.add_embedding(
                    embedding=embedding,
                )
        except AttributeError as e:  # noqa: F841
            self.logger.error(
                "Failed to save the embedding to the library. "
                "Please use a library plugin with vector support to "
                "enable automatic storing of embeddings.",
            )
        return embedding

    return wrapper

stream_output staticmethod ¤

stream_output(func)

Decorator to turn on streaming mode for functions.

The requirement for this decorator to work on a function is that it would normally return a list.

Source code in src/nendo/schema/core.py
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
@staticmethod
def stream_output(func):
    """Decorator to turn on streaming mode for functions.

    The requirement for this decorator to work on a function is that it would
    normally return a list.
    """

    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        result = func(self, *args, **kwargs)
        if self.config.stream_mode:
            return result
        # function is yielding single tracks if stream_chunk_size == 1
        elif self.config.stream_chunk_size > 1:  # noqa: RET505
            return [track for chunk in result for track in chunk]
        else:
            return list(result)

    return wrapper

track_to_text ¤

track_to_text(track: NendoTrack) -> str

Convert the given track into a string.

Can be used by embedding plugins to avoid implementing their own track-to-string conversion.

Parameters:

Name Type Description Default
track NendoTrack

The track to be converted.

required

Returns:

Type Description
str

The string representation of the given track.

Source code in src/nendo/schema/plugin.py
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
def track_to_text(self, track: NendoTrack) -> str:
    """Convert the given track into a string.

    Can be used by embedding plugins to avoid implementing their own
    track-to-string conversion.

    Args:
        track (NendoTrack): The track to be converted.

    Returns:
        str: The string representation of the given track.
    """
    text = ""
    meta_items = [
        "artist",
        "album",
        "title",
        "genre",
        "year",
        "duration",
        "content",
    ]
    for i in meta_items:
        if track.get_meta(i) is not None:
            text += f"{i}: {track.get_meta(i)}; "
    for pd in track.get_plugin_data():
        text += f"{pd.key}: {pd.value}; "
    return text

NendoGeneratePlugin ¤

Bases: NendoPlugin

Basic class for nendo generate plugins.

Generate plugins are plugins that generate new tracks or collections, either from scratch or based on existing tracks or collections. Decorate your methods with @NendoGeneratePlugin.run_track to run your method on a track, use @NendoGeneratePlugin.run_collection to run your method on a collection and use @NendoGeneratePlugin.run_signal to run your method on a signal.

Examples:

from nendo import Nendo, NendoConfig

class MyPlugin(NendoGeneratePlugin):
    ...

    @NendoAnalysisPlugin.run_track
    def my_generate_track_function(self, track, arg_one="foo"):
        # generate some new audio

        # add audio to the nendo library
        return self.nendo_instance.library.add_related_track_from_signal(
            signal,
            sr,
            related_track_id=track.id,
        )

plugin_type property ¤

plugin_type: str

Return type of plugin.

batch_process staticmethod ¤

batch_process(func)

Decorator to run functions multithreaded in batches.

This decorator function transforms the given function to run in multiple threads. It expects that the first argument to the function is a list of items, which will be processed in parallel, in batches of a given size.

Source code in src/nendo/schema/core.py
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
@staticmethod
def batch_process(func):
    """Decorator to run functions multithreaded in batches.

    This decorator function transforms the given function to run
    in multiple threads. It expects that the first argument to the function
    is a list of items, which will be processed in parallel,
    in batches of a given size.
    """

    @functools.wraps(func)
    def wrapper(self, track=None, file_paths=None, *args, **kwargs):
        target = track or file_paths
        if isinstance(target, NendoTrack):
            return func(self, track=target, **kwargs)
        elif isinstance(target, list):  # noqa: RET505
            max_threads = self.config.max_threads
            batch_size = self.config.batch_size
            total = len(target)
            batches = [
                target[i : i + batch_size] for i in range(0, total, batch_size)
            ]
            start_time = time.time()
            futures = []

            def run_batch(batch_index, batch):
                try:
                    batch_start_time = time.time()
                    results = []
                    if track:
                        for _, item in enumerate(batch):
                            result = func(
                                self,
                                track=item,
                                *args,  # noqa: B026
                                **kwargs,
                            )
                            results.extend(result)
                    elif file_paths:
                        result = func(
                            self,
                            file_paths=batch,
                            *args,  # noqa: B026
                            **kwargs,
                        )
                        results.extend(result)
                    batch_end_time = time.time()
                    batch_time = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(batch_end_time - batch_start_time),
                    )
                    total_elapsed_time = batch_end_time - start_time
                    average_time_per_batch = total_elapsed_time / (batch_index + 1)
                    estimated_total_time = average_time_per_batch * len(batches)
                    estimated_total_time_print = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(estimated_total_time),
                    )
                    remaining_time = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(estimated_total_time - total_elapsed_time),
                    )
                    logger.info(
                        f"Finished batch {batch_index + 1}/{len(batches)}.\n"
                        f"Time taken for this batch: {batch_time} - "
                        f"Estimated total time: {estimated_total_time_print} - "
                        f"Estimated remaining time: {remaining_time}\n",
                    )
                    return results
                except NendoError as e:
                    logger.exception(
                        "Error processing batch %d: %s",
                        batch_index,
                        e,
                    )

            with ThreadPoolExecutor(max_workers=max_threads) as executor:
                for batch_index, batch in enumerate(batches):
                    futures.append(executor.submit(run_batch, batch_index, batch))

            all_results = []
            for future in as_completed(futures):
                result = future.result()
                if result:
                    all_results.extend(future.result())
            return all_results
        else:
            raise TypeError("Expected NendoTrack or list of NendoTracks")

    return wrapper

run_collection staticmethod ¤

Decorator to register a function as a collection running function for a NendoGeneratePlugin.

This decorator wraps the function and allows a plugin user to call the plugin with either a collection or a track.

Parameters:

Name Type Description Default
func Callable[[NendoPlugin, Optional[NendoCollection], Any], NendoCollection]

Callable[[NendoPlugin, NendoCollection, Any], NendoCollection]: The function to register.

required

Returns:

Type Description
Callable[[NendoPlugin, Any], NendoCollection]

The wrapped function.

Source code in src/nendo/schema/plugin.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
@staticmethod
def run_collection(
    func: Callable[[NendoPlugin, Optional[NendoCollection], Any], NendoCollection],
) -> Callable[[NendoPlugin, Any], NendoCollection]:
    """Decorator to register a function as a collection running function for a `NendoGeneratePlugin`.

    This decorator wraps the function and allows a plugin user to call the plugin with either a collection or a track.

    Args:
        func: Callable[[NendoPlugin, NendoCollection, Any], NendoCollection]: The function to register.

    Returns:
        Callable[[NendoPlugin, Any], NendoCollection]: The wrapped function.
    """

    @functools.wraps(func)
    def wrapper(self, **kwargs: Any) -> NendoCollection:
        track_or_collection, kwargs = self._pop_track_or_collection_from_args(
            **kwargs,
        )
        if track_or_collection is None:
            return func(self, **kwargs)

        if isinstance(track_or_collection, NendoCollection):
            return func(self, track_or_collection, **kwargs)

        tmp_collection = self.nendo_instance.library.add_collection(
            name="tmp",
            track_ids=[track_or_collection.id],
            collection_type="temp",
        )
        return func(self, tmp_collection, **kwargs)

    return wrapper

run_signal staticmethod ¤

run_signal(
    func: Callable[
        [
            NendoPlugin,
            Optional[ndarray],
            Optional[int],
            Any,
        ],
        Tuple[ndarray, int],
    ]
) -> Callable[
    [NendoPlugin, Any], Union[NendoTrack, NendoCollection]
]

Decorator to register a function as a signal running function for a NendoGeneratePlugin.

This decorator wraps the function and allows a plugin user to call the plugin with either a collection or a track.

Parameters:

Name Type Description Default
func Callable[[NendoPlugin, Optional[ndarray], Optional[int], Any], Tuple[ndarray, int]]

Callable[[NendoPlugin, np.ndarray, int, Any], Tuple[np.ndarray, int]]: The function to register.

required

Returns:

Type Description
Callable[[NendoPlugin, Any], NendoCollection]

The wrapped function.

Source code in src/nendo/schema/plugin.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
@staticmethod
def run_signal(
    func: Callable[
        [NendoPlugin, Optional[np.ndarray], Optional[int], Any],
        Tuple[np.ndarray, int],
    ],
) -> Callable[[NendoPlugin, Any], Union[NendoTrack, NendoCollection]]:
    """Decorator to register a function as a signal running function for a `NendoGeneratePlugin`.

    This decorator wraps the function and allows a plugin user to call the plugin with either a collection or a track.

    Args:
        func: Callable[[NendoPlugin, np.ndarray, int, Any], Tuple[np.ndarray, int]]: The function to register.

    Returns:
        Callable[[NendoPlugin, Any], NendoCollection]: The wrapped function.
    """

    @functools.wraps(func)
    def wrapper(self, **kwargs: Any) -> Union[NendoTrack, NendoCollection]:
        track_or_collection, kwargs = self._pop_track_or_collection_from_args(
            **kwargs,
        )
        if track_or_collection is None:
            signal, sr = func(self, **kwargs)
            return self.nendo_instance.library.add_track_from_signal(
                signal,
                sr,
            )
        if isinstance(track_or_collection, NendoTrack):
            signal, sr = track_or_collection.signal, track_or_collection.sr
            new_signal, new_sr = func(self, signal, sr, **kwargs)
            return self.nendo_instance.library.add_related_track_from_signal(
                new_signal,
                sr,
                related_track_id=track_or_collection.id,
            )
        processed_tracks = []
        for track in track_or_collection.tracks():
            new_signal, new_sr = func(
                self,
                track.signal,
                track.sr,
                **kwargs,
            )
            processed_tracks.append(
                self.nendo_instance.library.add_related_track_from_signal(
                    new_signal,
                    track.sr,
                    related_track_id=track.id,
                ),
            )
        return self.nendo_instance.library.add_collection(
            name="tmp",
            track_ids=[track.id for track in processed_tracks],
            collection_type="temp",
        )

    return wrapper

run_track staticmethod ¤

Decorator to register a function as a track running function for a NendoGeneratePlugin.

This decorator wraps the function and allows a plugin user to call the plugin with either a collection or a track.

Parameters:

Name Type Description Default
func Callable[[NendoPlugin, Optional[NendoTrack], Any], Union[NendoTrack, List[NendoTrack]]]

Callable[[NendoPlugin, NendoTrack, Any], Union[NendoTrack, List[NendoTrack]]]: The function to register.

required

Returns:

Type Description
Callable[[NendoPlugin, Any], NendoCollection]

The wrapped function.

Source code in src/nendo/schema/plugin.py
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
@staticmethod
def run_track(
    func: Callable[
        [NendoPlugin, Optional[NendoTrack], Any],
        Union[NendoTrack, List[NendoTrack]],
    ],
) -> Callable[[NendoPlugin, Any], Union[NendoTrack, NendoCollection]]:
    """Decorator to register a function as a track running function for a `NendoGeneratePlugin`.

    This decorator wraps the function and allows a plugin user to call the plugin with either a collection or a track.

    Args:
        func: Callable[[NendoPlugin, NendoTrack, Any], Union[NendoTrack, List[NendoTrack]]]: The function to register.

    Returns:
        Callable[[NendoPlugin, Any], NendoCollection]: The wrapped function.
    """

    @functools.wraps(func)
    def wrapper(self, **kwargs: Any) -> Union[NendoTrack, NendoCollection]:
        track_or_collection, kwargs = self._pop_track_or_collection_from_args(
            **kwargs,
        )
        processed_tracks = []
        if track_or_collection is None:
            track = func(self, **kwargs)

            # may be multiple tracks as a result
            if not isinstance(track, list):
                return track
            processed_tracks.extend(track)
        elif isinstance(track_or_collection, NendoTrack):
            track = func(self, track_or_collection, **kwargs)

            # may be multiple tracks as a result
            if not isinstance(track, list):
                return track
            processed_tracks.extend(track)
        else:
            for track in track_or_collection.tracks():
                processed_track = func(self, track, **kwargs)

                # may be multiple tracks as a result
                if isinstance(processed_track, list):
                    processed_tracks.extend(processed_track)
                else:
                    processed_tracks.append(processed_track)

        return self.nendo_instance.library.add_collection(
            name="tmp",
            track_ids=[track.id for track in processed_tracks],
            collection_type="temp",
        )

    return wrapper

stream_output staticmethod ¤

stream_output(func)

Decorator to turn on streaming mode for functions.

The requirement for this decorator to work on a function is that it would normally return a list.

Source code in src/nendo/schema/core.py
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
@staticmethod
def stream_output(func):
    """Decorator to turn on streaming mode for functions.

    The requirement for this decorator to work on a function is that it would
    normally return a list.
    """

    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        result = func(self, *args, **kwargs)
        if self.config.stream_mode:
            return result
        # function is yielding single tracks if stream_chunk_size == 1
        elif self.config.stream_chunk_size > 1:  # noqa: RET505
            return [track for chunk in result for track in chunk]
        else:
            return list(result)

    return wrapper

NendoLibraryPlugin ¤

Bases: NendoPlugin

Basic class for nendo library plugins.

plugin_type property ¤

plugin_type: str

Return type of plugin.

add_collection abstractmethod ¤

add_collection(
    name: str,
    user_id: Optional[Union[str, UUID]] = None,
    track_ids: Optional[List[Union[str, UUID]]] = None,
    description: str = "",
    collection_type: str = "collection",
    visibility: Visibility = Visibility.private,
    meta: Optional[Dict[str, Any]] = None,
) -> NendoCollection

Creates a new collection and saves it into the DB.

Parameters:

Name Type Description Default
track_ids List[Union[str, UUID]]

List of track ids to be added to the collection.

None
name str

Name of the collection.

required
user_id UUID

The ID of the user adding the collection.

None
description str

Description of the collection.

''
collection_type str

Type of the collection. Defaults to "collection".

'collection'
visibility str

Visibility of the track in multi-user settings. Defaults to "private".

private
meta Dict[str, Any]

Metadata of the collection.

None

Returns:

Type Description
NendoCollection

The newly created NendoCollection object.

Source code in src/nendo/schema/plugin.py
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
@abstractmethod
def add_collection(
    self,
    name: str,
    user_id: Optional[Union[str, uuid.UUID]] = None,
    track_ids: Optional[List[Union[str, uuid.UUID]]] = None,
    description: str = "",
    collection_type: str = "collection",
    visibility: Visibility = Visibility.private,
    meta: Optional[Dict[str, Any]] = None,
) -> NendoCollection:
    """Creates a new collection and saves it into the DB.

    Args:
        track_ids (List[Union[str, uuid.UUID]]): List of track ids
            to be added to the collection.
        name (str): Name of the collection.
        user_id (UUID, optional): The ID of the user adding the collection.
        description (str): Description of the collection.
        collection_type (str): Type of the collection. Defaults to "collection".
        visibility (str, optional): Visibility of the track in multi-user settings.
            Defaults to "private".
        meta (Dict[str, Any]): Metadata of the collection.

    Returns:
        schema.NendoCollection: The newly created NendoCollection object.
    """
    raise NotImplementedError

add_plugin_data abstractmethod ¤

add_plugin_data(
    track_id: Union[str, UUID],
    key: str,
    value: Any,
    plugin_name: str,
    plugin_version: Optional[str] = None,
    user_id: Optional[Union[str, UUID]] = None,
    replace: Optional[bool] = None,
) -> NendoPluginData

Add plugin data to a NendoTrack and persist changes into the DB.

Parameters:

Name Type Description Default
track_id Union[str, UUID]

ID of the track to which the plugin data should be added.

required
key str

Key under which to save the data.

required
value str

Data to save.

required
plugin_name str

Name of the plugin.

required
plugin_version str

Version of the plugin. Defaults to None in which case the version will be inferred from the currently registered version of the plugin.

None
user_id Union[str, UUID]

ID of user adding the plugin data.

None
replace bool

Flag that determines whether the last existing data point for the given plugin name and -version is overwritten or not. Defaults to False.

None

Returns:

Type Description
NendoPluginData

The saved plugin data as a NendoPluginData object.

Source code in src/nendo/schema/plugin.py
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
@abstractmethod
def add_plugin_data(
    self,
    track_id: Union[str, uuid.UUID],
    key: str,
    value: Any,
    plugin_name: str,
    plugin_version: Optional[str] = None,
    user_id: Optional[Union[str, uuid.UUID]] = None,
    replace: Optional[bool] = None,
) -> NendoPluginData:
    """Add plugin data to a NendoTrack and persist changes into the DB.

    Args:
        track_id (Union[str, uuid.UUID]): ID of the track to which
            the plugin data should be added.
        key (str): Key under which to save the data.
        value (str): Data to  save.
        plugin_name (str): Name of the plugin.
        plugin_version (str, optional): Version of the plugin. Defaults to None
            in which case the version will be inferred from the currently
            registered version of the plugin.
        user_id (Union[str, uuid.UUID], optional): ID of user adding the
            plugin data.
        replace (bool, optional): Flag that determines whether
            the last existing data point for the given plugin name and -version
            is overwritten or not. Defaults to False.

    Returns:
        NendoPluginData: The saved plugin data as a NendoPluginData object.
    """
    raise NotImplementedError
add_related_collection(
    track_ids: List[Union[str, UUID]],
    collection_id: Union[str, UUID],
    name: str,
    description: str = "",
    user_id: Optional[Union[str, UUID]] = None,
    relationship_type: str = "relationship",
    meta: Optional[Dict[str, Any]] = None,
) -> NendoCollection

Add a collection that is related to another NendoCollection.

Add a new collection with a relationship to and from the collection with the given collection_id.

Parameters:

Name Type Description Default
track_ids List[Union[str, UUID]]

List of track ids.

required
collection_id Union[str, UUID]

Existing collection id.

required
name str

Name of the new related collection.

required
description str

Description of the new related collection.

''
user_id UUID

The ID of the user adding the collection.

None
relationship_type str

Type of the relationship.

'relationship'
meta Dict[str, Any]

Meta of the new related collection.

None

Returns:

Type Description
NendoCollection

The newly added NendoCollection object.

Source code in src/nendo/schema/plugin.py
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
@abstractmethod
def add_related_collection(
    self,
    track_ids: List[Union[str, uuid.UUID]],
    collection_id: Union[str, uuid.UUID],
    name: str,
    description: str = "",
    user_id: Optional[Union[str, uuid.UUID]] = None,
    relationship_type: str = "relationship",
    meta: Optional[Dict[str, Any]] = None,
) -> NendoCollection:
    """Add a collection that is related to another `NendoCollection`.

    Add a new collection with a relationship to and from the collection
    with the given collection_id.

    Args:
        track_ids (List[Union[str, uuid.UUID]]): List of track ids.
        collection_id (Union[str, uuid.UUID]): Existing collection id.
        name (str): Name of the new related collection.
        description (str): Description of the new related collection.
        user_id (UUID, optional): The ID of the user adding the collection.
        relationship_type (str): Type of the relationship.
        meta (Dict[str, Any]): Meta of the new related collection.

    Returns:
        schema.NendoCollection: The newly added NendoCollection object.
    """
    raise NotImplementedError
add_related_track(
    file_path: Union[FilePath, str],
    related_track_id: Union[str, UUID],
    track_type: str = "str",
    user_id: Optional[Union[str, UUID]] = None,
    track_meta: Optional[Dict[str, Any]] = None,
    relationship_type: str = "relationship",
    meta: Optional[Dict[str, Any]] = None,
) -> NendoTrack

Add track that is related to another NendoTrack.

Add the track found in the given path to the library and create a relationship in the new track that points to the track identified by related_to.

Parameters:

Name Type Description Default
file_path Union[FilePath, str]

Path to the file to add as track.

required
related_track_id Union[str, UUID]

ID of the related track.

required
track_type str

Track type. Defaults to "track".

'str'
user_id Union[str, UUID]

ID of the user adding the track.

None
track_meta dict

Dictionary containing the track metadata.

None
relationship_type str

Type of the relationship. Defaults to "relationship".

'relationship'
meta dict

Dictionary containing metadata about the relationship. Defaults to None in which case it'll be set to {}.

None

Returns:

Type Description
NendoTrack

The track that was added to the Library

Source code in src/nendo/schema/plugin.py
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
@abstractmethod
def add_related_track(
    self,
    file_path: Union[FilePath, str],
    related_track_id: Union[str, uuid.UUID],
    track_type: str = "str",
    user_id: Optional[Union[str, uuid.UUID]] = None,
    track_meta: Optional[Dict[str, Any]] = None,
    relationship_type: str = "relationship",
    meta: Optional[Dict[str, Any]] = None,
) -> NendoTrack:
    """Add track that is related to another `NendoTrack`.

    Add the track found in the given path to the library and create a relationship
    in the new track that points to the track identified by related_to.

    Args:
        file_path (Union[FilePath, str]): Path to the file to add as track.
        related_track_id (Union[str, uuid.UUID]): ID of the related track.
        track_type (str, optional): Track type. Defaults to "track".
        user_id (Union[str, UUID], optional): ID of the user adding the track.
        track_meta (dict, optional): Dictionary containing the track metadata.
        relationship_type (str, optional): Type of the relationship.
            Defaults to "relationship".
        meta (dict, optional): Dictionary containing metadata about
            the relationship. Defaults to None in which case it'll be set to {}.

    Returns:
        NendoTrack: The track that was added to the Library
    """
    raise NotImplementedError
add_related_track_from_signal(
    signal: ndarray,
    sr: int,
    related_track_id: Union[str, UUID],
    track_type: str = "track",
    user_id: Optional[Union[str, UUID]] = None,
    track_meta: Optional[Dict[str, Any]] = None,
    relationship_type: str = "relationship",
    meta: Optional[Dict[str, Any]] = None,
) -> NendoTrack

Add signal as track that is related to another NendoTrack.

Add the track represented by the provided signal to the library and create a relationship in the new track that points to the track passed as related_to.

Parameters:

Name Type Description Default
signal ndarray

Waveform of the track in numpy array form.

required
sr int

Sampling rate of the waveform.

required
related_track_id Union[str, UUID]

ID to which the relationship should point to.

required
track_type str

Track type. Defaults to "track".

'track'
user_id Union[str, UUID]

ID of the user adding the track.

None
track_meta (dict

Dictionary containing the track metadata.

None
relationship_type str

Type of the relationship. Defaults to "relationship".

'relationship'
meta dict

Dictionary containing metadata about the relationship. Defaults to None in which case it'll be set to {}.

None

Returns:

Type Description
NendoTrack

The added track with the relationship.

Source code in src/nendo/schema/plugin.py
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
@abstractmethod
def add_related_track_from_signal(
    self,
    signal: np.ndarray,
    sr: int,
    related_track_id: Union[str, uuid.UUID],
    track_type: str = "track",
    user_id: Optional[Union[str, uuid.UUID]] = None,
    track_meta: Optional[Dict[str, Any]] = None,
    relationship_type: str = "relationship",
    meta: Optional[Dict[str, Any]] = None,
) -> NendoTrack:
    """Add signal as track that is related to another `NendoTrack`.

    Add the track represented by the provided signal to the library and create a
    relationship in the new track that points to the track passed as related_to.

    Args:
        signal (np.ndarray): Waveform of the track in numpy array form.
        sr (int): Sampling rate of the waveform.
        related_track_id (Union[str, uuid.UUID]): ID to which the relationship
            should point to.
        track_type (str, optional): Track type. Defaults to "track".
        user_id (Union[str, uuid.UUID], optional): ID of the user adding the track.
        track_meta  (dict, optional): Dictionary containing the track metadata.
        relationship_type (str, optional): Type of the relationship.
            Defaults to "relationship".
        meta (dict, optional): Dictionary containing metadata about
            the relationship. Defaults to None in which case it'll be set to {}.

    Returns:
        NendoTrack: The added track with the relationship.
    """
    raise NotImplementedError

add_track abstractmethod ¤

add_track(
    file_path: Union[FilePath, str],
    track_type: str = "track",
    copy_to_library: Optional[bool] = None,
    skip_duplicate: Optional[bool] = None,
    user_id: Optional[UUID] = None,
    meta: Optional[Dict[str, Any]] = None,
) -> NendoTrack

Add the track given by path to the library.

Parameters:

Name Type Description Default
file_path Union[FilePath, str]

Path to the file to add as track.

required
track_type str

Type of the track. Defaults to "track".

'track'
copy_to_library bool

Flag that specifies whether the file should be copied into the library directory. Defaults to None.

None
skip_duplicate bool

Flag that specifies whether a file should be added that already exists in the library, based on its file checksum. Defaults to None.

None
user_id UUID

ID of user adding the track.

None
meta dict

Metadata to attach to the track upon adding.

None

Returns:

Type Description
NendoTrack

The track that was added to the library.

Source code in src/nendo/schema/plugin.py
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
@abstractmethod
def add_track(
    self,
    file_path: Union[FilePath, str],
    track_type: str = "track",
    copy_to_library: Optional[bool] = None,
    skip_duplicate: Optional[bool] = None,
    user_id: Optional[uuid.UUID] = None,
    meta: Optional[Dict[str, Any]] = None,
) -> NendoTrack:
    """Add the track given by path to the library.

    Args:
        file_path (Union[FilePath, str]): Path to the file to add as track.
        track_type (str): Type of the track. Defaults to "track".
        copy_to_library (bool, optional): Flag that specifies whether
            the file should be copied into the library directory.
            Defaults to None.
        skip_duplicate (bool, optional): Flag that specifies whether a
            file should be added that already exists in the library, based on its
            file checksum. Defaults to None.
        user_id (UUID, optional): ID of user adding the track.
        meta (dict, optional): Metadata to attach to the track upon adding.

    Returns:
        NendoTrack: The track that was added to the library.
    """
    raise NotImplementedError

add_track_from_signal abstractmethod ¤

add_track_from_signal(
    signal: ndarray,
    sr: int,
    track_type: str = "track",
    user_id: Optional[UUID] = None,
    meta: Optional[Dict[str, Any]] = None,
) -> NendoTrack

Add a track to the library that is described by the given signal.

Parameters:

Name Type Description Default
signal ndarray

The numpy array containing the audio signal.

required
sr int

Sample rate

required
track_type str

Track type. Defaults to "track".

'track'
user_id UUID

The ID of the user adding the track.

None
meta Dict[str, Any]

Track metadata. Defaults to {}.

None

Returns:

Type Description
NendoTrack

The added NendoTrack

Source code in src/nendo/schema/plugin.py
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
@abstractmethod
def add_track_from_signal(
    self,
    signal: np.ndarray,
    sr: int,
    track_type: str = "track",
    user_id: Optional[uuid.UUID] = None,
    meta: Optional[Dict[str, Any]] = None,
) -> NendoTrack:
    """Add a track to the library that is described by the given signal.

    Args:
        signal (np.ndarray): The numpy array containing the audio signal.
        sr (int): Sample rate
        track_type (str): Track type. Defaults to "track".
        user_id (UUID, optional): The ID of the user adding the track.
        meta (Dict[str, Any], optional): Track metadata. Defaults to {}.

    Returns:
        schema.NendoTrack: The added NendoTrack
    """
    raise NotImplementedError

add_track_to_collection abstractmethod ¤

add_track_to_collection(
    track_id: Union[str, UUID],
    collection_id: Union[str, UUID],
    position: Optional[int] = None,
    meta: Optional[Dict[str, Any]] = None,
) -> NendoCollection

Creates a relationship from the track to the collection.

Parameters:

Name Type Description Default
collection_id Union[str, UUID]

Collection id.

required
track_id Union[str, UUID]

Track id.

required

Returns:

Type Description
NendoCollection

The updated NendoCollection object.

Source code in src/nendo/schema/plugin.py
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
@abstractmethod
def add_track_to_collection(
    self,
    track_id: Union[str, uuid.UUID],
    collection_id: Union[str, uuid.UUID],
    position: Optional[int] = None,
    meta: Optional[Dict[str, Any]] = None,
) -> NendoCollection:
    """Creates a relationship from the track to the collection.

    Args:
        collection_id (Union[str, uuid.UUID]): Collection id.
        track_id (Union[str, uuid.UUID]): Track id.

    Returns:
        schema.NendoCollection: The updated NendoCollection object.
    """
    raise NotImplementedError

add_tracks abstractmethod ¤

add_tracks(
    path: Union[str, DirectoryPath],
    track_type: str = "track",
    user_id: Optional[Union[str, UUID]] = None,
    copy_to_library: Optional[bool] = None,
    skip_duplicate: bool = True,
) -> NendoCollection

Scan the provided path and upsert the information into the library.

Parameters:

Name Type Description Default
path Union[DirectoryPath, str]

Path to the directory to scan.

required
track_type str

Track type. Defaults to "track".

'track'
user_id UUID

The ID of the user adding the tracks.

None
copy_to_library bool

Flag that specifies whether the file should be copied into the library directory. Defaults to None.

None
skip_duplicate bool

Flag that specifies whether a file should be added that already exists in the library, based on its file checksum. Defaults to None.

True

Returns:

Type Description
collection (NendoCollection

The collection of tracks that were added to the Library

Source code in src/nendo/schema/plugin.py
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
@abstractmethod
def add_tracks(
    self,
    path: Union[str, DirectoryPath],
    track_type: str = "track",
    user_id: Optional[Union[str, uuid.UUID]] = None,
    copy_to_library: Optional[bool] = None,
    skip_duplicate: bool = True,
) -> NendoCollection:
    """Scan the provided path and upsert the information into the library.

    Args:
        path (Union[DirectoryPath, str]): Path to the directory to scan.
        track_type (str): Track type. Defaults to "track".
        user_id (UUID, optional): The ID of the user adding the tracks.
        copy_to_library (bool, optional): Flag that specifies whether
            the file should be copied into the library directory.
            Defaults to None.
        skip_duplicate (bool, optional): Flag that specifies whether a
            file should be added that already exists in the library, based on its
            file checksum. Defaults to None.

    Returns:
        collection (NendoCollection): The collection of tracks that were added to the Library
    """
    raise NotImplementedError

add_tracks_to_collection abstractmethod ¤

add_tracks_to_collection(
    track_ids: List[Union[str, UUID]],
    collection_id: Union[str, UUID],
    meta: Optional[Dict[str, Any]] = None,
) -> NendoCollection

Creates a relationship from the track to the collection.

Parameters:

Name Type Description Default
track_ids List[Union[str, UUID]]

List of track ids to add.

required
collection_id Union[str, UUID]

ID of the collection to which to add the track.

required
meta Dict[str, Any]

Metadata of the relationship.

None

Returns:

Type Description
NendoCollection

The updated NendoCollection object.

Source code in src/nendo/schema/plugin.py
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
@abstractmethod
def add_tracks_to_collection(
    self,
    track_ids: List[Union[str, uuid.UUID]],
    collection_id: Union[str, uuid.UUID],
    meta: Optional[Dict[str, Any]] = None,
) -> NendoCollection:
    """Creates a relationship from the track to the collection.

    Args:
        track_ids (List[Union[str, uuid.UUID]]): List of track ids to add.
        collection_id (Union[str, uuid.UUID]): ID of the collection to
            which to add the track.
        meta (Dict[str, Any], optional): Metadata of the relationship.

    Returns:
        NendoCollection: The updated NendoCollection object.
    """
    return NotImplementedError

batch_process staticmethod ¤

batch_process(func)

Decorator to run functions multithreaded in batches.

This decorator function transforms the given function to run in multiple threads. It expects that the first argument to the function is a list of items, which will be processed in parallel, in batches of a given size.

Source code in src/nendo/schema/core.py
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
@staticmethod
def batch_process(func):
    """Decorator to run functions multithreaded in batches.

    This decorator function transforms the given function to run
    in multiple threads. It expects that the first argument to the function
    is a list of items, which will be processed in parallel,
    in batches of a given size.
    """

    @functools.wraps(func)
    def wrapper(self, track=None, file_paths=None, *args, **kwargs):
        target = track or file_paths
        if isinstance(target, NendoTrack):
            return func(self, track=target, **kwargs)
        elif isinstance(target, list):  # noqa: RET505
            max_threads = self.config.max_threads
            batch_size = self.config.batch_size
            total = len(target)
            batches = [
                target[i : i + batch_size] for i in range(0, total, batch_size)
            ]
            start_time = time.time()
            futures = []

            def run_batch(batch_index, batch):
                try:
                    batch_start_time = time.time()
                    results = []
                    if track:
                        for _, item in enumerate(batch):
                            result = func(
                                self,
                                track=item,
                                *args,  # noqa: B026
                                **kwargs,
                            )
                            results.extend(result)
                    elif file_paths:
                        result = func(
                            self,
                            file_paths=batch,
                            *args,  # noqa: B026
                            **kwargs,
                        )
                        results.extend(result)
                    batch_end_time = time.time()
                    batch_time = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(batch_end_time - batch_start_time),
                    )
                    total_elapsed_time = batch_end_time - start_time
                    average_time_per_batch = total_elapsed_time / (batch_index + 1)
                    estimated_total_time = average_time_per_batch * len(batches)
                    estimated_total_time_print = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(estimated_total_time),
                    )
                    remaining_time = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(estimated_total_time - total_elapsed_time),
                    )
                    logger.info(
                        f"Finished batch {batch_index + 1}/{len(batches)}.\n"
                        f"Time taken for this batch: {batch_time} - "
                        f"Estimated total time: {estimated_total_time_print} - "
                        f"Estimated remaining time: {remaining_time}\n",
                    )
                    return results
                except NendoError as e:
                    logger.exception(
                        "Error processing batch %d: %s",
                        batch_index,
                        e,
                    )

            with ThreadPoolExecutor(max_workers=max_threads) as executor:
                for batch_index, batch in enumerate(batches):
                    futures.append(executor.submit(run_batch, batch_index, batch))

            all_results = []
            for future in as_completed(futures):
                result = future.result()
                if result:
                    all_results.extend(future.result())
            return all_results
        else:
            raise TypeError("Expected NendoTrack or list of NendoTracks")

    return wrapper

collection_size abstractmethod ¤

collection_size(collection_id: Union[str, UUID]) -> int

Get the number of tracks in a collection.

Parameters:

Name Type Description Default
collection_id Union[str, UUID]

The ID of the collection.

required

Returns:

Type Description
int

The number of tracks.

Source code in src/nendo/schema/plugin.py
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
@abstractmethod
def collection_size(
    self,
    collection_id: Union[str, uuid.UUID],
) -> int:
    """Get the number of tracks in a collection.

    Args:
        collection_id (Union[str, uuid.UUID]): The ID of the collection.

    Returns:
        int: The number of tracks.
    """
    raise NotImplementedError

export_collection ¤

export_collection(
    collection_id: Union[str, UUID],
    export_path: str,
    filename_suffix: str = "_nendo",
    file_format: str = "wav",
) -> List[str]

Export the track to a file.

Parameters:

Name Type Description Default
collection_id Union[str, UUID]

The ID of the target collection to export.

required
export_path str

Path to a directory into which the collection's tracks should be exported.

required
filename_suffix str

The suffix which should be appended to each exported track's filename.

'_nendo'
file_format str

Format of the exported track. Ignored if file_path is a full file path. Defaults to "wav".

'wav'

Returns:

Type Description
List[str]

A list with all full paths to the exported files.

Source code in src/nendo/schema/plugin.py
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
def export_collection(
    self,
    collection_id: Union[str, uuid.UUID],
    export_path: str,
    filename_suffix: str = "_nendo",
    file_format: str = "wav",
) -> List[str]:
    """Export the track to a file.

    Args:
        collection_id (Union[str, uuid.UUID]): The ID of the target
            collection to export.
        export_path (str): Path to a directory into which the collection's tracks
            should be exported.
        filename_suffix (str): The suffix which should be appended to each
            exported track's filename.
        file_format (str, optional): Format of the exported track. Ignored if
            file_path is a full file path. Defaults to "wav".

    Returns:
        List[str]: A list with all full paths to the exported files.
    """
    raise NotImplementedError

export_track ¤

export_track(
    track_id: Union[str, UUID],
    file_path: str,
    file_format: str = "wav",
) -> str

Export the track to a file.

Parameters:

Name Type Description Default
track_id Union[str, UUID]

The ID of the target track to export.

required
file_path str

Path to the exported file. Can be either a full file path or a directory path. If a directory path is given, a filename will be automatically generated and the file will be exported to the format specified as file_format. If a full file path is given, the format will be deduced from the path and the file_format parameter will be ignored.

required
file_format str

Format of the exported track. Ignored if file_path is a full file path. Defaults to "wav".

'wav'

Returns:

Type Description
str

The path to the exported file.

Source code in src/nendo/schema/plugin.py
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
def export_track(
    self,
    track_id: Union[str, uuid.UUID],
    file_path: str,
    file_format: str = "wav",
) -> str:
    """Export the track to a file.

    Args:
        track_id (Union[str, uuid.UUID]): The ID of the target track to export.
        file_path (str): Path to the exported file. Can be either a full
            file path or a directory path. If a directory path is given,
            a filename will be automatically generated and the file will be
            exported to the format specified as file_format. If a full file
            path is given, the format will be deduced from the path and the
            file_format parameter will be ignored.
        file_format (str, optional): Format of the exported track. Ignored if
            file_path is a full file path. Defaults to "wav".

    Returns:
        str: The path to the exported file.
    """
    raise NotImplementedError
filter_related_tracks(
    track_id: Union[str, UUID],
    direction: str = "to",
    filters: Optional[Dict[str, Any]] = None,
    search_meta: Optional[Dict[str, Any]] = None,
    track_type: Optional[Union[str, List[str]]] = None,
    user_id: Optional[Union[str, UUID]] = None,
    collection_id: Optional[Union[str, UUID]] = None,
    plugin_names: Optional[List[str]] = None,
    order_by: Optional[str] = None,
    order: Optional[str] = "asc",
    limit: Optional[int] = None,
    offset: Optional[int] = None,
) -> Union[List, Iterator]

Get tracks with a relationship to a track and filter the results.

Parameters:

Name Type Description Default
track_id Union[str, UUID]

ID of the track to be searched for.

required
direction str

The relationship direction Can be either one of "to", "from", or "both". Defaults to "to".

'to'
filters dict

Dictionary containing the filters to apply. Defaults to None.

None
search_meta dict

Dictionary containing the keywords to search for over the track.resource.meta field. The dictionary's values should contain singular search tokens and the keys currently have no effect but might in the future. Defaults to {}.

None
track_type Union[str, List[str]]

Track type to filter for. Can be a singular type or a list of types. Defaults to None.

None
user_id Union[str, UUID]

The user ID to filter for.

None
collection_id Union[str, UUID]

Collection id to which the filtered tracks must have a relationship. Defaults to None.

None
plugin_names list

List used for applying the filter only to data of certain plugins. If None, all plugin data related to the track is used for filtering.

None
order_by str

Key used for ordering the results.

None
order str

Order in which to retrieve results ("asc" or "desc").

'asc'
limit int

Limit the number of returned results.

None
offset int

Offset into the paginated results (requires limit).

None

Returns:

Type Description
Union[List, Iterator]

List or generator of tracks, depending on the configuration variable stream_mode

Source code in src/nendo/schema/plugin.py
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
@abstractmethod
def filter_related_tracks(
    self,
    track_id: Union[str, uuid.UUID],
    direction: str = "to",
    filters: Optional[Dict[str, Any]] = None,
    search_meta: Optional[Dict[str, Any]] = None,
    track_type: Optional[Union[str, List[str]]] = None,
    user_id: Optional[Union[str, uuid.UUID]] = None,
    collection_id: Optional[Union[str, uuid.UUID]] = None,
    plugin_names: Optional[List[str]] = None,
    order_by: Optional[str] = None,
    order: Optional[str] = "asc",
    limit: Optional[int] = None,
    offset: Optional[int] = None,
) -> Union[List, Iterator]:
    """Get tracks with a relationship to a track and filter the results.

    Args:
        track_id (Union[str, UUID]): ID of the track to be searched for.
        direction (str, optional): The relationship direction
            Can be either one of "to", "from", or "both". Defaults to "to".
        filters (dict, optional): Dictionary containing the filters to apply.
            Defaults to None.
        search_meta (dict): Dictionary containing the keywords to search for
            over the track.resource.meta field. The dictionary's values
            should contain singular search tokens and the keys currently have no
            effect but might in the future. Defaults to {}.
        track_type (Union[str, List[str]], optional): Track type to filter for.
            Can be a singular type or a list of types. Defaults to None.
        user_id (Union[str, UUID], optional): The user ID to filter for.
        collection_id (Union[str, uuid.UUID], optional): Collection id to
            which the filtered tracks must have a relationship. Defaults to None.
        plugin_names (list, optional): List used for applying the filter only to
            data of certain plugins. If None, all plugin data related to the track
            is used for filtering.
        order_by (str, optional): Key used for ordering the results.
        order (str, optional): Order in which to retrieve results ("asc" or "desc").
        limit (int, optional): Limit the number of returned results.
        offset (int, optional): Offset into the paginated results (requires limit).

    Returns:
        Union[List, Iterator]: List or generator of tracks, depending on the
            configuration variable stream_mode
    """
    raise NotImplementedError

filter_tracks abstractmethod ¤

filter_tracks(
    filters: Optional[Dict[str, Any]] = None,
    search_meta: Optional[Dict[str, Any]] = None,
    track_type: Optional[Union[str, List[str]]] = None,
    user_id: Optional[Union[str, UUID]] = None,
    collection_id: Optional[Union[str, UUID]] = None,
    plugin_names: Optional[List[str]] = None,
    order_by: Optional[str] = None,
    order: str = "asc",
    limit: Optional[int] = None,
    offset: Optional[int] = None,
) -> Union[List, Iterator]

Obtain tracks from the db by filtering over plugin data.

Parameters:

Name Type Description Default
filters dict

Dictionary containing the filters to apply. Defaults to None.

None
search_meta dict

Dictionary containing the keywords to search for over the track.resource.meta field. The dictionary's values should contain singular search tokens and the keys currently have no effect but might in the future. Defaults to {}.

None
track_type Union[str, List[str]]

Track type to filter for. Can be a singular type or a list of types. Defaults to None.

None
user_id Union[str, UUID]

The user ID to filter for.

None
collection_id Union[str, UUID]

Collection id to which the filtered tracks must have a relationship. Defaults to None.

None
plugin_names list

List used for applying the filter only to data of certain plugins. If None, all plugin data related to the track is used for filtering.

None
order_by str

Key used for ordering the results.

None
order str

Ordering ("asc" vs "desc"). Defaults to "asc".

'asc'
limit int

Limit the number of returned results.

None
offset int

Offset into the paginated results (requires limit).

None

Returns:

Type Description
Union[List, Iterator]

List or generator of tracks, depending on the configuration variable stream_mode

Source code in src/nendo/schema/plugin.py
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
@abstractmethod
def filter_tracks(
    self,
    filters: Optional[Dict[str, Any]] = None,
    search_meta: Optional[Dict[str, Any]] = None,
    track_type: Optional[Union[str, List[str]]] = None,
    user_id: Optional[Union[str, uuid.UUID]] = None,
    collection_id: Optional[Union[str, uuid.UUID]] = None,
    plugin_names: Optional[List[str]] = None,
    order_by: Optional[str] = None,
    order: str = "asc",
    limit: Optional[int] = None,
    offset: Optional[int] = None,
) -> Union[List, Iterator]:
    """Obtain tracks from the db by filtering over plugin data.

    Args:
        filters (dict, optional): Dictionary containing the filters to apply.
            Defaults to None.
        search_meta (dict): Dictionary containing the keywords to search for
            over the track.resource.meta field. The dictionary's values
            should contain singular search tokens and  the keys currently have no
            effect but might in the future. Defaults to {}.
        track_type (Union[str, List[str]], optional): Track type to filter for.
            Can be a singular type or a list of types. Defaults to None.
        user_id (Union[str, UUID], optional): The user ID to filter for.
        collection_id (Union[str, uuid.UUID], optional): Collection id to
            which the filtered tracks must have a relationship. Defaults to None.
        plugin_names (list, optional): List used for applying the filter only to
            data of certain plugins. If None, all plugin data related to the track
            is used for filtering.
        order_by (str, optional): Key used for ordering the results.
        order (str, optional): Ordering ("asc" vs "desc"). Defaults to "asc".
        limit (int, optional): Limit the number of returned results.
        offset (int, optional): Offset into the paginated results (requires limit).

    Returns:
        Union[List, Iterator]: List or generator of tracks, depending on the
            configuration variable stream_mode
    """
    raise NotImplementedError

find_collections abstractmethod ¤

find_collections(
    value: str = "",
    collection_types: Optional[List[str]] = None,
    user_id: Optional[Union[str, UUID]] = None,
    order_by: Optional[str] = None,
    order: Optional[str] = "asc",
    limit: Optional[int] = None,
    offset: Optional[int] = None,
) -> Union[List, Iterator]

Find collections with a search term in the description or meta field.

Parameters:

Name Type Description Default
value str

Term to be searched for in the description and meta field.

''
collection_types List[str]

Collection types to filter for.

None
user_id Union[str, UUID]

The user ID to filter for.

None
order_by str

Key used for ordering the results.

None
order str

Order in which to retrieve results ("asc" or "desc").

'asc'
limit int

Limit the number of returned results.

None
offset int

Offset into the paginated results (requires limit).

None

Returns:

Type Description
Union[List, Iterator]

List or generator of collections, depending on the configuration variable stream_mode

Source code in src/nendo/schema/plugin.py
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
@abstractmethod
def find_collections(
    self,
    value: str = "",
    collection_types: Optional[List[str]] = None,
    user_id: Optional[Union[str, uuid.UUID]] = None,
    order_by: Optional[str] = None,
    order: Optional[str] = "asc",
    limit: Optional[int] = None,
    offset: Optional[int] = None,
) -> Union[List, Iterator]:
    """Find collections with a search term in the description or meta field.

    Args:
        value (str): Term to be searched for in the description and meta field.
        collection_types (List[str], optional): Collection types to filter for.
        user_id (Union[str, UUID], optional): The user ID to filter for.
        order_by (str, optional): Key used for ordering the results.
        order (str, optional): Order in which to retrieve results ("asc" or "desc").
        limit (int, optional): Limit the number of returned results.
        offset (int, optional): Offset into the paginated results (requires limit).

    Returns:
        Union[List, Iterator]: List or generator of collections, depending on the
            configuration variable stream_mode
    """
    raise NotImplementedError

find_tracks abstractmethod ¤

find_tracks(
    value: str,
    user_id: Optional[Union[str, UUID]] = None,
    order_by: Optional[str] = None,
    order: str = "asc",
    limit: Optional[int] = None,
    offset: Optional[int] = None,
) -> Union[List, Iterator]

Find tracks by searching for a string through the resource metadata.

Parameters:

Name Type Description Default
value str

The search value to filter by.

required
user_id Union[str, UUID]

The user ID to filter for.

None
order_by str

Name of the field by which to order. Defaults to None in which case no specific ordering will be applied.

None
order str

Ordering direction. Defaults to "asc".

'asc'
limit str

Pagination limit.

None
offset str

Pagination offset.

None

Returns:

Type Description
Union[List, Iterator]

List or generator of tracks, depending on the configuration variable stream_mode

Source code in src/nendo/schema/plugin.py
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
@abstractmethod
def find_tracks(
    self,
    value: str,
    user_id: Optional[Union[str, uuid.UUID]] = None,
    order_by: Optional[str] = None,
    order: str = "asc",
    limit: Optional[int] = None,
    offset: Optional[int] = None,
) -> Union[List, Iterator]:
    """Find tracks by searching for a string through the resource metadata.

    Args:
        value (str): The search value to filter by.
        user_id (Union[str, UUID], optional): The user ID to filter for.
        order_by (str, optional): Name of the field by which to order.
            Defaults to None in which case no specific ordering will be applied.
        order (str, optional): Ordering direction. Defaults to "asc".
        limit (str, optional): Pagination limit.
        offset (str, optional): Pagination offset.

    Returns:
        Union[List, Iterator]: List or generator of tracks, depending on the
            configuration variable stream_mode
    """
    raise NotImplementedError

get_collection abstractmethod ¤

get_collection(
    collection_id: uuid4, get_related_tracks: bool = True
) -> NendoCollection

Get a collection by its ID.

Parameters:

Name Type Description Default
collection_id uuid4

ID of the target collection.

required
get_related_tracks bool

Flag that defines whether the returned collection should contain the related_tracks. Defaults to True.

True

Returns:

Type Description
NendoCollection

The collection object.

Source code in src/nendo/schema/plugin.py
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
@abstractmethod
def get_collection(
    self,
    collection_id: uuid.uuid4,
    get_related_tracks: bool = True,
) -> NendoCollection:
    """Get a collection by its ID.

    Args:
        collection_id (uuid.uuid4): ID of the target collection.
        get_related_tracks (bool, optional): Flag that defines whether the
            returned collection should contain the `related_tracks`.
            Defaults to True.

    Returns:
        NendoCollection: The collection object.
    """
    raise NotImplementedError

get_collection_tracks abstractmethod ¤

get_collection_tracks(
    collection_id: UUID, order: Optional[str] = "asc"
) -> List[NendoTrack]

Get all tracks of a collection.

Parameters:

Name Type Description Default
collection_id Union[str, UUID]

ID of the collection from which to get all tracks.

required
order str

Ordering direction. Defaults to "asc".

'asc'

Returns:

Type Description
List[NendoTrack]

List of tracks in the collection.

Source code in src/nendo/schema/plugin.py
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
@abstractmethod
def get_collection_tracks(
    self,
    collection_id: uuid.UUID,
    order: Optional[str] = "asc",
) -> List[NendoTrack]:
    """Get all tracks of a collection.

    Args:
        collection_id (Union[str, uuid.UUID]): ID of the collection from which to
            get all tracks.
        order (str, optional): Ordering direction. Defaults to "asc".

    Returns:
        List[NendoTrack]: List of tracks in the collection.
    """
    raise NotImplementedError

get_collections abstractmethod ¤

get_collections(
    user_id: Optional[Union[str, UUID]] = None,
    order_by: Optional[str] = None,
    order: Optional[str] = "asc",
    limit: Optional[int] = None,
    offset: Optional[int] = None,
) -> Union[List, Iterator]

Get a list of collections.

Parameters:

Name Type Description Default
user_id Union[str, UUID]

The user ID to filter for.

None
order_by str

Key used for ordering the results.

None
order str

Order in which to retrieve results ("asc" or "desc").

'asc'
limit int

Limit the number of returned results.

None
offset int

Offset into the paginated results (requires limit).

None

Returns:

Type Description
Union[List, Iterator]

List or generator of collections, depending on the configuration variable stream_mode

Source code in src/nendo/schema/plugin.py
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
@abstractmethod
@NendoPlugin.stream_output
def get_collections(
    self,
    user_id: Optional[Union[str, uuid.UUID]] = None,
    order_by: Optional[str] = None,
    order: Optional[str] = "asc",
    limit: Optional[int] = None,
    offset: Optional[int] = None,
) -> Union[List, Iterator]:
    """Get a list of collections.

    Args:
        user_id (Union[str, UUID], optional): The user ID to filter for.
        order_by (str, optional): Key used for ordering the results.
        order (str, optional): Order in which to retrieve results
            ("asc" or "desc").
        limit (int, optional): Limit the number of returned results.
        offset (int, optional): Offset into the paginated results (requires limit).

    Returns:
        Union[List, Iterator]: List or generator of collections, depending on the
            configuration variable stream_mode
    """
    raise NotImplementedError
get_related_collections(
    collection_id: Union[str, UUID],
    direction: str = "to",
    user_id: Optional[Union[str, UUID]] = None,
    order_by: Optional[str] = None,
    order: Optional[str] = "asc",
    limit: Optional[int] = None,
    offset: Optional[int] = None,
) -> Union[List, Iterator]

Get collections with a relationship to the collection with collection_id.

Parameters:

Name Type Description Default
collection_id str

ID of the collection to be searched for.

required
direction str

The relationship direction Can be either one of "to", "from", or "both". Defaults to "to".

'to'
user_id Union[str, UUID]

The user ID to filter for.

None
order_by str

Key used for ordering the results.

None
order str

Order in which to retrieve results ("asc" or "desc").

'asc'
limit int

Limit the number of returned results.

None
offset int

Offset into the paginated results (requires limit).

None

Returns:

Type Description
Union[List, Iterator]

List or generator of collections, depending on the configuration variable stream_mode

Source code in src/nendo/schema/plugin.py
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
@abstractmethod
def get_related_collections(
    self,
    collection_id: Union[str, uuid.UUID],
    direction: str = "to",
    user_id: Optional[Union[str, uuid.UUID]] = None,
    order_by: Optional[str] = None,
    order: Optional[str] = "asc",
    limit: Optional[int] = None,
    offset: Optional[int] = None,
) -> Union[List, Iterator]:
    """Get collections with a relationship to the collection with collection_id.

    Args:
        collection_id (str): ID of the collection to be searched for.
        direction (str, optional): The relationship direction
            Can be either one of "to", "from", or "both". Defaults to "to".
        user_id (Union[str, UUID], optional): The user ID to filter for.
        order_by (str, optional): Key used for ordering the results.
        order (str, optional): Order in which to retrieve results ("asc" or "desc").
        limit (int, optional): Limit the number of returned results.
        offset (int, optional): Offset into the paginated results (requires limit).

    Returns:
        Union[List, Iterator]: List or generator of collections, depending on the
            configuration variable stream_mode
    """
    raise NotImplementedError
get_related_tracks(
    track_id: Union[str, UUID],
    direction: str = "to",
    user_id: Optional[Union[str, UUID]] = None,
    order_by: Optional[str] = None,
    order: Optional[str] = "asc",
    limit: Optional[int] = None,
    offset: Optional[int] = None,
) -> Union[List, Iterator]

Get tracks with a relationship to the track with track_id.

Parameters:

Name Type Description Default
track_id str

ID of the track to be searched for.

required
direction str

The relationship direction Can be either one of "to", "from", or "both". Defaults to "to".

'to'
user_id Union[str, UUID]

The user ID to filter for.

None
order_by str

Key used for ordering the results.

None
order str

Order in which to retrieve results ("asc" or "desc").

'asc'
limit int

Limit the number of returned results.

None
offset int

Offset into the paginated results (requires limit).

None

Returns:

Type Description
Union[List, Iterator]

List or generator of tracks, depending on the configuration variable stream_mode

Source code in src/nendo/schema/plugin.py
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
@abstractmethod
def get_related_tracks(
    self,
    track_id: Union[str, uuid.UUID],
    direction: str = "to",
    user_id: Optional[Union[str, uuid.UUID]] = None,
    order_by: Optional[str] = None,
    order: Optional[str] = "asc",
    limit: Optional[int] = None,
    offset: Optional[int] = None,
) -> Union[List, Iterator]:
    """Get tracks with a relationship to the track with track_id.

    Args:
        track_id (str): ID of the track to be searched for.
        direction (str, optional): The relationship direction
            Can be either one of "to", "from", or "both". Defaults to "to".
        user_id (Union[str, UUID], optional): The user ID to filter for.
        order_by (str, optional): Key used for ordering the results.
        order (str, optional): Order in which to retrieve results ("asc" or "desc").
        limit (int, optional): Limit the number of returned results.
        offset (int, optional): Offset into the paginated results (requires limit).

    Returns:
        Union[List, Iterator]: List or generator of tracks, depending on the
            configuration variable stream_mode
    """
    raise NotImplementedError

get_track abstractmethod ¤

get_track(
    track_id: UUID,
    user_id: Optional[Union[str, UUID]] = None,
) -> NendoTrack

Get a single track from the library by ID.

If no track with the given ID was found, return None.

Parameters:

Name Type Description Default
track_id Any

The ID of the track to get.

required
user_id uuid4

ID of user adding the plugin data.

None

Returns:

Type Description
track (NendoTrack

The track with the given ID

Source code in src/nendo/schema/plugin.py
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
@abstractmethod
def get_track(
    self,
    track_id: uuid.UUID,
    user_id: Optional[Union[str, uuid.UUID]] = None,
) -> NendoTrack:
    """Get a single track from the library by ID.

    If no track with the given ID was found, return None.

    Args:
        track_id (Any): The ID of the track to get.
        user_id (uuid4, optional): ID of user adding the plugin data.

    Returns:
        track (NendoTrack): The track with the given ID
    """
    raise NotImplementedError

get_track_or_collection ¤

get_track_or_collection(
    target_id: Union[str, UUID]
) -> Union[NendoTrack, NendoCollection]

Return a track or a collection based on the given target_id.

Parameters:

Name Type Description Default
target_id Union[str, UUID]

The target ID to obtain.

required

Returns:

Type Description
Union[NendoTrack, NendoCollection]

The track or the collection.

Source code in src/nendo/schema/plugin.py
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
def get_track_or_collection(
    self,
    target_id: Union[str, uuid.UUID],
) -> Union[NendoTrack, NendoCollection]:
    """Return a track or a collection based on the given target_id.

    Args:
        target_id (Union[str, uuid.UUID]): The target ID to obtain.

    Returns:
        Union[NendoTrack, NendoCollection]: The track or the collection.
    """
    target_id = ensure_uuid(target_id)
    collection = self.get_collection(target_id)
    if collection is not None:
        return collection

    # assume the id is a track id
    return self.get_track(target_id)

get_tracks abstractmethod ¤

get_tracks(
    user_id: Optional[Union[str, UUID]] = None,
    order_by: Optional[str] = None,
    order: str = "asc",
    limit: Optional[int] = None,
    offset: Optional[int] = None,
    load_related_tracks: bool = False,
) -> Union[List, Iterator]

Get tracks based on the given query parameters.

Parameters:

Name Type Description Default
user_id Union[str, UUID]

ID of user getting the tracks.

None
order_by str

Key used for ordering the results.

None
order str

Order in which to retrieve results ("asc" or "desc").

'asc'
limit int

Limit the number of returned results.

None
offset int

Offset into the paginated results (requires limit).

None
load_related_tracks bool

Flag to control whether the related_tracks will be populated or not. Defaults to False.

False

Returns:

Type Description
Union[List, Iterator]

List or generator of tracks, depending on the configuration variable stream_mode

Source code in src/nendo/schema/plugin.py
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
@abstractmethod
@NendoPlugin.stream_output
def get_tracks(
    self,
    user_id: Optional[Union[str, uuid.UUID]] = None,
    order_by: Optional[str] = None,
    order: str = "asc",
    limit: Optional[int] = None,
    offset: Optional[int] = None,
    load_related_tracks: bool = False,
) -> Union[List, Iterator]:
    """Get tracks based on the given query parameters.

    Args:
        user_id (Union[str, UUID], optional): ID of user getting the tracks.
        order_by (str, optional): Key used for ordering the results.
        order (str, optional): Order in which to retrieve results
            ("asc" or "desc").
        limit (int, optional): Limit the number of returned results.
        offset (int, optional): Offset into the paginated results (requires limit).
        load_related_tracks (bool, optional): Flag to control whether the
            `related_tracks` will be populated or not. Defaults to False.

    Returns:
        Union[List, Iterator]: List or generator of tracks, depending on the
            configuration variable stream_mode
    """
    raise NotImplementedError

library_size abstractmethod ¤

library_size(
    user_id: Optional[Union[str, UUID]] = None
) -> int

Get the number of all tracks in the library (per user).

Parameters:

Name Type Description Default
user_id Union[str, UUID]

The ID of the user. If not specified, the number of all tracks across all users is returned. Defaults to None.

None

Returns:

Type Description
int

The number of tracks.

Source code in src/nendo/schema/plugin.py
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
@abstractmethod
def library_size(
    self,
    user_id: Optional[Union[str, uuid.UUID]] = None,
) -> int:
    """Get the number of all tracks in the library (per user).

    Args:
        user_id (Union[str, uuid.UUID], optional): The ID of the user.
            If not specified, the number of all tracks across all users is
            returned. Defaults to None.

    Returns:
        int: The number of tracks.
    """
    raise NotImplementedError

load_blob abstractmethod ¤

load_blob(
    blob_id: UUID,
    user_id: Optional[Union[str, UUID]] = None,
) -> NendoBlob

Loads a blob of data into memory.

Parameters:

Name Type Description Default
blob_id UUID

The UUID of the blob.

required
user_id Union[str, UUID]

ID of the user who's loading the blob.

None

Returns:

Type Description
NendoBlob

The loaded blob.

Source code in src/nendo/schema/plugin.py
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
@abstractmethod
def load_blob(
    self,
    blob_id: uuid.UUID,
    user_id: Optional[Union[str, uuid.UUID]] = None,
) -> NendoBlob:
    """Loads a blob of data into memory.

    Args:
        blob_id (uuid.UUID): The UUID of the blob.
        user_id (Union[str, uuid.UUID], optional): ID of the user
            who's loading the blob.

    Returns:
        schema.NendoBlob: The loaded blob.
    """
    raise NotImplementedError

remove_blob abstractmethod ¤

remove_blob(
    blob_id: UUID,
    remove_resources: bool = True,
    user_id: Optional[UUID] = None,
) -> bool

Deletes a blob of data.

Parameters:

Name Type Description Default
blob_id UUID

The UUID of the blob.

required
remove_resources bool

If True, remove associated resources.

True
user_id Union[str, UUID]

ID of the user who's removing the blob.

None

Returns:

Type Description
success (bool

True if removal was successful, False otherwise

Source code in src/nendo/schema/plugin.py
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
@abstractmethod
def remove_blob(
    self,
    blob_id: uuid.UUID,
    remove_resources: bool = True,
    user_id: Optional[uuid.UUID] = None,
) -> bool:
    """Deletes a blob of data.

    Args:
        blob_id (uuid.UUID): The UUID of the blob.
        remove_resources (bool): If True, remove associated resources.
        user_id (Union[str, uuid.UUID], optional): ID of the user
            who's removing the blob.

    Returns:
        success (bool): True if removal was successful, False otherwise
    """
    raise NotImplementedError

remove_collection abstractmethod ¤

remove_collection(
    collection_id: UUID,
    user_id: Optional[Union[str, UUID]] = None,
    remove_relationships: bool = False,
) -> bool

Deletes the collection identified by collection_id.

Parameters:

Name Type Description Default
collection_id UUID

ID of the collection to remove.

required
user_id Union[str, UUID]

The ID of the user.

None
remove_relationships bool

If False prevent deletion if related tracks exist, if True delete relationships together with the object. Defaults to False.

False

Returns:

Type Description
bool

True if deletion was successful, False otherwise.

Source code in src/nendo/schema/plugin.py
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
@abstractmethod
def remove_collection(
    self,
    collection_id: uuid.UUID,
    user_id: Optional[Union[str, uuid.UUID]] = None,
    remove_relationships: bool = False,
) -> bool:
    """Deletes the collection identified by `collection_id`.

    Args:
        collection_id (uuid.UUID): ID of the collection to remove.
        user_id (Union[str, UUID], optional): The ID of the user.
        remove_relationships (bool, optional):
            If False prevent deletion if related tracks exist,
            if True delete relationships together with the object.
            Defaults to False.

    Returns:
        bool: True if deletion was successful, False otherwise.
    """
    raise NotImplementedError

remove_track abstractmethod ¤

remove_track(
    track_id: Union[str, UUID],
    user_id: Optional[Union[str, UUID]] = None,
    remove_relationships: bool = False,
    remove_plugin_data: bool = True,
    remove_resources: bool = True,
) -> bool

Delete track from library by ID.

Parameters:

Name Type Description Default
track_id Union[str, UUID]

The ID of the track to remove.

required
user_id Union[str, UUID]

The ID of the user owning the track.

None
remove_relationships bool

If False prevent deletion if related tracks exist, if True delete relationships together with the object. Defaults to False.

False
remove_plugin_data bool

If False prevent deletion if related plugin data exist, if True delete plugin data together with the object. Defaults to True.

True
remove_resources bool

If False, keep the related resources, e.g. files, if True, delete the related resources. Defaults to True.

True

Returns:

Type Description
success (bool

True if removal was successful, False otherwise

Source code in src/nendo/schema/plugin.py
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
@abstractmethod
def remove_track(
    self,
    track_id: Union[str, uuid.UUID],
    user_id: Optional[Union[str, uuid.UUID]] = None,
    remove_relationships: bool = False,
    remove_plugin_data: bool = True,
    remove_resources: bool = True,
) -> bool:
    """Delete track from library by ID.

    Args:
        track_id (Union[str, uuid.UUID]): The ID of the track to remove.
        user_id (Union[str, UUID], optional): The ID of the user
            owning the track.
        remove_relationships (bool):
            If False prevent deletion if related tracks exist,
            if True delete relationships together with the object.
            Defaults to False.
        remove_plugin_data (bool):
            If False prevent deletion if related plugin data exist,
            if True delete plugin data together with the object.
            Defaults to True.
        remove_resources (bool):
            If False, keep the related resources, e.g. files,
            if True, delete the related resources.
            Defaults to True.

    Returns:
        success (bool): True if removal was successful, False otherwise
    """
    raise NotImplementedError

remove_track_from_collection abstractmethod ¤

remove_track_from_collection(
    track_id: Union[str, UUID],
    collection_id: Union[str, UUID],
) -> bool

Deletes a relationship from the track to the collection.

Parameters:

Name Type Description Default
collection_id Union[str, UUID]

Collection id.

required
track_id Union[str, UUID]

Track id.

required

Returns:

Type Description
success (bool

True if removal was successful, False otherwise.

Source code in src/nendo/schema/plugin.py
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
@abstractmethod
def remove_track_from_collection(
    self,
    track_id: Union[str, uuid.UUID],
    collection_id: Union[str, uuid.UUID],
) -> bool:
    """Deletes a relationship from the track to the collection.

    Args:
        collection_id (Union[str, uuid.UUID]): Collection id.
        track_id (Union[str, uuid.UUID]): Track id.

    Returns:
        success (bool): True if removal was successful, False otherwise.
    """
    raise NotImplementedError

reset abstractmethod ¤

reset(
    force: bool = False,
    user_id: Optional[Union[str, UUID]] = None,
) -> None

Reset the nendo library.

Erase all tracks, collections and relationships. Ask before erasing.

Parameters:

Name Type Description Default
force bool

Flag that specifies whether to ask the user for confirmation of the operation. Default is to ask the user.

False
user_id Union[str, UUID]

ID of the user who's resetting the library. If none is given, the configured nendo default user will be used.

None
Source code in src/nendo/schema/plugin.py
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
@abstractmethod
def reset(
    self,
    force: bool = False,
    user_id: Optional[Union[str, uuid.UUID]] = None,
) -> None:
    """Reset the nendo library.

    Erase all tracks, collections and relationships.
    Ask before erasing.

    Args:
        force (bool, optional): Flag that specifies whether to ask the user for
            confirmation of the operation. Default is to ask the user.
        user_id (Union[str, uuid.UUID], optional): ID of the user
            who's resetting the library. If none is given, the configured
            nendo default user will be used.
    """
    raise NotImplementedError

store_blob abstractmethod ¤

store_blob(
    file_path: Union[FilePath, str],
    user_id: Optional[Union[str, UUID]] = None,
) -> NendoBlob

Stores a blob of data.

Parameters:

Name Type Description Default
file_path Union[FilePath, str]

Path to the file to store as blob.

required
user_id Union[str, UUID]

ID of the user who's storing the file to blob.

None

Returns:

Type Description
NendoBlob

The stored blob.

Source code in src/nendo/schema/plugin.py
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
@abstractmethod
def store_blob(
    self,
    file_path: Union[FilePath, str],
    user_id: Optional[Union[str, uuid.UUID]] = None,
) -> NendoBlob:
    """Stores a blob of data.

    Args:
        file_path (Union[FilePath, str]): Path to the file to store as blob.
        user_id (Union[str, uuid.UUID], optional): ID of the user
            who's storing the file to blob.

    Returns:
        schema.NendoBlob: The stored blob.
    """
    raise NotImplementedError

store_blob_from_bytes abstractmethod ¤

store_blob_from_bytes(
    data: bytes, user_id: Optional[Union[str, UUID]] = None
) -> NendoBlob

Stores a data of type bytes to a blob.

Parameters:

Name Type Description Default
data bytes

The blob to store.

required
user_id Union[str, UUID]

ID of the user who's storing the bytes to blob.

None

Returns:

Type Description
NendoBlob

The stored blob.

Source code in src/nendo/schema/plugin.py
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
@abstractmethod
def store_blob_from_bytes(
    self,
    data: bytes,
    user_id: Optional[Union[str, uuid.UUID]] = None,
) -> NendoBlob:
    """Stores a data of type `bytes` to a blob.

    Args:
        data (bytes): The blob to store.
        user_id (Union[str, uuid.UUID], optional): ID of the user
            who's storing the bytes to blob.

    Returns:
        schema.NendoBlob: The stored blob.
    """
    raise NotImplementedError

stream_output staticmethod ¤

stream_output(func)

Decorator to turn on streaming mode for functions.

The requirement for this decorator to work on a function is that it would normally return a list.

Source code in src/nendo/schema/core.py
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
@staticmethod
def stream_output(func):
    """Decorator to turn on streaming mode for functions.

    The requirement for this decorator to work on a function is that it would
    normally return a list.
    """

    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        result = func(self, *args, **kwargs)
        if self.config.stream_mode:
            return result
        # function is yielding single tracks if stream_chunk_size == 1
        elif self.config.stream_chunk_size > 1:  # noqa: RET505
            return [track for chunk in result for track in chunk]
        else:
            return list(result)

    return wrapper

update_collection abstractmethod ¤

update_collection(
    collection: NendoCollection,
) -> NendoCollection

Updates the given collection by storing it to the database.

Parameters:

Name Type Description Default
collection NendoCollection

The collection to store.

required

Raises:

Type Description
NendoCollectionNotFoundError

If the collection with the given ID was not found.

Returns:

Type Description
NendoCollection

The updated collection.

Source code in src/nendo/schema/plugin.py
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
@abstractmethod
def update_collection(
    self,
    collection: NendoCollection,
) -> NendoCollection:
    """Updates the given collection by storing it to the database.

    Args:
        collection (NendoCollection): The collection to store.

    Raises:
        NendoCollectionNotFoundError: If the collection with
            the given ID was not found.

    Returns:
        NendoCollection: The updated collection.
    """
    raise NotImplementedError

update_track abstractmethod ¤

update_track(track: NendoTrack) -> NendoTrack

Updates the given collection by storing it to the database.

Parameters:

Name Type Description Default
track NendoTrack

The track to be stored to the database.

required

Raises:

Type Description
NendoTrackNotFoundError

If the track passed to the function does not exist in the database.

Returns:

Type Description
NendoTrack

The updated track.

Source code in src/nendo/schema/plugin.py
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
@abstractmethod
def update_track(
    self,
    track: NendoTrack,
) -> NendoTrack:
    """Updates the given collection by storing it to the database.

    Args:
        track (NendoTrack): The track to be stored to the database.

    Raises:
        NendoTrackNotFoundError: If the track passed to the function
            does not exist in the database.

    Returns:
        NendoTrack: The updated track.
    """
    raise NotImplementedError

verify ¤

verify(
    action: Optional[str] = None, user_id: str = ""
) -> None

Verify the library's integrity.

Parameters:

Name Type Description Default
action str

Default action to choose when an inconsistency is detected. Choose between (i)gnore and (r)emove.

None
Source code in src/nendo/schema/plugin.py
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
def verify(self, action: Optional[str] = None, user_id: str = "") -> None:
    """Verify the library's integrity.

    Args:
        action (str, optional): Default action to choose when an
            inconsistency is detected. Choose between (i)gnore and (r)emove.
    """
    original_config = {}
    try:
        original_config["stream_mode"] = self.config.stream_mode
        original_config["stream_chunk_size"] = self.config.stream_chunk_size
        self.config.stream_mode = False
        self.config.stream_chunk_size = 16
        for track in self.get_tracks():
            if not self.storage_driver.file_exists(
                file_name=track.resource.file_name,
                user_id=user_id,
            ):
                action = (
                    action
                    or input(
                        f"Inconsistency detected: {track.resource.src} "
                        "does not exist. Please choose an action:\n"
                        "(i) ignore - (r) remove",
                    ).lower()
                )
                if action == "i":
                    self.logger.warning(
                        "Detected missing file "
                        f"{track.resource.src} but instructed "
                        "to ignore.",
                    )
                    continue
                if action == "r":
                    self.logger.info(
                        f"Removing track with ID {track.id} "
                        f"due to missing file {track.resource.src}",
                    )
                    self.remove_track(
                        track_id=track.id,
                        remove_plugin_data=True,
                        remove_relationships=True,
                        remove_resources=False,
                    )
        for library_file in self.storage_driver.list_files(user_id=user_id):
            file_without_ext = os.path.splitext(library_file)[0]
            if len(self.find_tracks(value=file_without_ext)) == 0:
                action = (
                    action
                    or input(
                        f"Inconsistency detected: File {library_file} "
                        "cannot be fonud in database. Please choose an action:\n"
                        "(i) ignore - (r) remove",
                    ).lower()
                )
                if action == "i":
                    self.logger.warning(
                        f"Detected orphaned file {library_file} "
                        f"but instructed to ignore.",
                    )
                    continue
                if action == "r":
                    self.logger.info(f"Removing orphaned file {library_file}")
                    self.storage_driver.remove_file(
                        file_name=library_file,
                        user_id=user_id,
                    )

    finally:
        self.config.stream_mode = original_config["stream_mode"]
        self.config.stream_chunk_size = original_config["stream_chunk_size"]

NendoUtilityPlugin ¤

Bases: NendoPlugin

Basic class for nendo utility plugins.

plugin_type property ¤

plugin_type: str

Return type of plugin.

batch_process staticmethod ¤

batch_process(func)

Decorator to run functions multithreaded in batches.

This decorator function transforms the given function to run in multiple threads. It expects that the first argument to the function is a list of items, which will be processed in parallel, in batches of a given size.

Source code in src/nendo/schema/core.py
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
@staticmethod
def batch_process(func):
    """Decorator to run functions multithreaded in batches.

    This decorator function transforms the given function to run
    in multiple threads. It expects that the first argument to the function
    is a list of items, which will be processed in parallel,
    in batches of a given size.
    """

    @functools.wraps(func)
    def wrapper(self, track=None, file_paths=None, *args, **kwargs):
        target = track or file_paths
        if isinstance(target, NendoTrack):
            return func(self, track=target, **kwargs)
        elif isinstance(target, list):  # noqa: RET505
            max_threads = self.config.max_threads
            batch_size = self.config.batch_size
            total = len(target)
            batches = [
                target[i : i + batch_size] for i in range(0, total, batch_size)
            ]
            start_time = time.time()
            futures = []

            def run_batch(batch_index, batch):
                try:
                    batch_start_time = time.time()
                    results = []
                    if track:
                        for _, item in enumerate(batch):
                            result = func(
                                self,
                                track=item,
                                *args,  # noqa: B026
                                **kwargs,
                            )
                            results.extend(result)
                    elif file_paths:
                        result = func(
                            self,
                            file_paths=batch,
                            *args,  # noqa: B026
                            **kwargs,
                        )
                        results.extend(result)
                    batch_end_time = time.time()
                    batch_time = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(batch_end_time - batch_start_time),
                    )
                    total_elapsed_time = batch_end_time - start_time
                    average_time_per_batch = total_elapsed_time / (batch_index + 1)
                    estimated_total_time = average_time_per_batch * len(batches)
                    estimated_total_time_print = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(estimated_total_time),
                    )
                    remaining_time = time.strftime(
                        "%H:%M:%S",
                        time.gmtime(estimated_total_time - total_elapsed_time),
                    )
                    logger.info(
                        f"Finished batch {batch_index + 1}/{len(batches)}.\n"
                        f"Time taken for this batch: {batch_time} - "
                        f"Estimated total time: {estimated_total_time_print} - "
                        f"Estimated remaining time: {remaining_time}\n",
                    )
                    return results
                except NendoError as e:
                    logger.exception(
                        "Error processing batch %d: %s",
                        batch_index,
                        e,
                    )

            with ThreadPoolExecutor(max_workers=max_threads) as executor:
                for batch_index, batch in enumerate(batches):
                    futures.append(executor.submit(run_batch, batch_index, batch))

            all_results = []
            for future in as_completed(futures):
                result = future.result()
                if result:
                    all_results.extend(future.result())
            return all_results
        else:
            raise TypeError("Expected NendoTrack or list of NendoTracks")

    return wrapper

run_utility staticmethod ¤

Run utility plugin.

Source code in src/nendo/schema/plugin.py
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
@staticmethod
def run_utility(
    func: Callable[
        [NendoPlugin, Optional[NendoTrack], Any],
        Union[str, float, int, bool, List],
    ],
) -> Callable[[NendoPlugin, Any], Union[str, float, int, bool, List]]:
    """Run utility plugin."""

    @functools.wraps(func)
    def wrapper(self, **kwargs: Any) -> Union[str, float, int, bool, List]:
        track_or_collection, kwargs = self._pop_track_or_collection_from_args(
            **kwargs,
        )
        if track_or_collection is None:
            return func(self, **kwargs)
        return func(self, track_or_collection, **kwargs)

    return wrapper

stream_output staticmethod ¤

stream_output(func)

Decorator to turn on streaming mode for functions.

The requirement for this decorator to work on a function is that it would normally return a list.

Source code in src/nendo/schema/core.py
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
@staticmethod
def stream_output(func):
    """Decorator to turn on streaming mode for functions.

    The requirement for this decorator to work on a function is that it would
    normally return a list.
    """

    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        result = func(self, *args, **kwargs)
        if self.config.stream_mode:
            return result
        # function is yielding single tracks if stream_chunk_size == 1
        elif self.config.stream_chunk_size > 1:  # noqa: RET505
            return [track for chunk in result for track in chunk]
        else:
            return list(result)

    return wrapper