Skip to content

sqlalchemy_library ¤

Module implementing the NendoLibraryPlugin using SQLAlchemy.

This module implements an SQLAlchemy version of the NendoLibraryPlugin. The plugin is not suitable to be used by itself but should be inherited from when implementing a new backend for the Nendo Library using SQLAlchemy. An example is given by the DuckDB implementation used as the default Nendo Library.

SqlAlchemyNendoLibrary ¤

SqlAlchemyNendoLibrary(**kwargs: Any)

Bases: NendoLibraryPlugin

Implementation of the NendoLibraryPlugin using SQLAlchemy.

Source code in src/nendo/library/sqlalchemy_library.py
48
49
50
51
52
53
def __init__(  # noqa: D107
    self,
    **kwargs: Any,
) -> None:
    super().__init__(**kwargs)
    self.iter_index = 0

default_user property ¤

default_user

Default Nendo user.

plugin_type property ¤

plugin_type: str

Return type of plugin.

add_collection ¤

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 = schema.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.

'collection'
meta Dict[str, Any]

Metadata of the collection.

None

Returns:

Type Description
NendoCollection

The newly created NendoCollection object.

Source code in src/nendo/library/sqlalchemy_library.py
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
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: schema.Visibility = schema.Visibility.private,
    meta: Optional[Dict[str, Any]] = None,
) -> schema.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.
        meta (Dict[str, Any]): Metadata of the collection.

    Returns:
        NendoCollection: The newly created NendoCollection object.
    """
    user_id = self._ensure_user_uuid(user_id)
    if track_ids is None:
        track_ids = []
    with self.session_scope() as session:
        # Fetch the track objects
        track_objs = session.query(model.NendoTrackDB).filter(
            model.NendoTrackDB.id.in_(
                [uuid.UUID(t) if isinstance(t, str) else t for t in track_ids],
            ),
        )
        if user_id is not None:
            track_objs = track_objs.filter(model.NendoTrackDB.user_id == user_id)
        track_objs = track_objs.all()
        # Create a new collection object
        new_collection = model.NendoCollectionDB(
            name=name,
            user_id=user_id,
            description=description,
            collection_type=collection_type,
            visibility=visibility,
            meta=meta or {},
        )
        session.add(new_collection)
        session.commit()
        session.refresh(new_collection)
        # Create relationships from tracks to collection
        for idx, track in enumerate(track_objs):
            tc_relationship = model.TrackCollectionRelationshipDB(
                source_id=track.id,
                target_id=new_collection.id,
                relationship_type="track",
                meta={},
                relationship_position=idx,
            )
            session.add(tc_relationship)
        session.commit()
        session.refresh(new_collection)

        return schema.NendoCollection.model_validate(new_collection)

add_plugin_data ¤

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 Any

Data to save.

required
plugin_name str

Name of the plugin.

required
plugin_version str

Version of the plugin. If none is given, the currently loaded version of the plugin given by plugin_name will be used.

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. If undefined, the nendo configuration's replace_plugin_data value will be used.

None

Returns:

Type Description
NendoPluginData

The saved plugin data as a NendoPluginData object.

Source code in src/nendo/library/sqlalchemy_library.py
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
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
1239
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
1274
1275
1276
1277
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,
) -> schema.NendoPluginData:
    """Add plugin data to a NendoTrack and persist changes into the DB.

    Args:
        track_id (Union[str, UUID]): ID of the track to which
            the plugin data should be added.
        key (str): Key under which to save the data.
        value (Any): Data to save.
        plugin_name (str): Name of the plugin.
        plugin_version (str, optional): Version of the plugin. If none is given,
            the currently loaded version of the plugin given by `plugin_name`
            will be used.
        user_id (Union[str, 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. If undefined, the nendo configuration's
            `replace_plugin_data` value will be used.

    Returns:
        NendoPluginData: The saved plugin data as a NendoPluginData object.
    """
    # create plugin data
    user_id = self._ensure_user_uuid(user_id)
    replace = (
        replace
        if replace is not None
        else self.nendo_instance.config.replace_plugin_data
    )
    value_converted = self._convert_plugin_data(value=value, user_id=user_id)
    if plugin_version is None:
        try:
            plugin = getattr(self.nendo_instance.plugins, plugin_name)
        except AttributeError as e:  # noqa: F841
            self.logger.error(
                f"Plugin with name {plugin_name} is not loaded. "
                "You have to manually specify the plugin_version parameter.",
            )
            return None
        plugin_version = plugin.version
    plugin_data = schema.NendoPluginDataCreate(
        track_id=ensure_uuid(track_id),
        user_id=user_id,
        plugin_name=plugin_name,
        plugin_version=plugin_version,
        key=key,
        value=value_converted,
    )
    with self.session_scope() as session:
        existing_plugin_data = self._get_latest_plugin_data_db(
            track_id=track_id,
            plugin_name=plugin_name,
            plugin_version=plugin_version,
            key=key,
            session=session,
            user_id=user_id,
        )
        if replace is True:
            if existing_plugin_data is not None:
                db_plugin_data = self._update_plugin_data_db(
                    existing_plugin_data=existing_plugin_data,
                    plugin_data=plugin_data,
                    session=session,
                )
            else:
                db_plugin_data = self._insert_plugin_data_db(
                    plugin_data=plugin_data,
                    session=session,
                )
        else:
            db_plugin_data = self._insert_plugin_data_db(
                plugin_data=plugin_data,
                session=session,
            )
        return schema.NendoPluginData.model_validate(db_plugin_data)
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

Adds a new collection with a relationship to the given collection.

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/library/sqlalchemy_library.py
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
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,
) -> schema.NendoCollection:
    """Adds a new collection with a relationship to the given collection.

    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:
        NendoCollection: The newly added NendoCollection object.
    """
    user_id = self._ensure_user_uuid(user_id)
    # Create a new collection
    new_collection = self.add_collection(
        name=name,
        user_id=user_id,
        track_ids=track_ids,
        description=description,
        collection_type=relationship_type,
        meta=meta,
    )

    with self.session_scope() as session:
        if isinstance(collection_id, str):
            collection_id = uuid.UUID(collection_id)
        collection = (
            session.query(model.NendoCollectionDB)
            .filter_by(id=collection_id)
            .first()
        )

        # Check if the collection does not exist
        if not collection:
            raise schema.NendoCollectionNotFoundError(
                "Collection not found",
                id=collection_id,
            )

        relationship = schema.NendoRelationshipCreate(
            source_id=new_collection.id,
            target_id=collection_id,
            relationship_type=relationship_type,
            meta=meta or {},
        )
        relationship = model.CollectionCollectionRelationshipDB(
            **relationship.model_dump(),
        )
        session.add(relationship)
    return new_collection
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 a track from a file with a relationship to another track.

Source code in src/nendo/library/sqlalchemy_library.py
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
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,
) -> schema.NendoTrack:
    """Add a track from a file with a relationship to another track."""
    user_id = self._ensure_user_uuid(user_id=user_id)
    related_track_id = ensure_uuid(related_track_id)
    track = self.add_track(
        file_path=file_path,
        track_type=track_type,
        user_id=user_id,
        meta=track_meta,
    )
    relationship = schema.NendoRelationshipCreate(
        source_id=track.id,
        target_id=related_track_id,
        relationship_type=relationship_type,
        meta=meta or {},
    )
    with self.session_scope() as session:
        relationship = schema.NendoRelationship.model_validate(
            self._upsert_track_track_relationship(
                relationship=relationship,
                session=session,
            ),
        )
    return track
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 a track from a signal with a relationship to another track.

Source code in src/nendo/library/sqlalchemy_library.py
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
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,
) -> schema.NendoTrack:
    """Add a track from a signal with a relationship to another track."""
    user_id = self._ensure_user_uuid(user_id)
    related_track_id = ensure_uuid(related_track_id)
    track = self.add_track_from_signal(
        signal=signal,
        sr=sr,
        track_type=track_type,
        meta=track_meta,
    )
    relationship = schema.NendoRelationshipCreate(
        source_id=track.id,
        target_id=related_track_id,
        relationship_type=relationship_type,
        meta=meta or {},
    )
    with self.session_scope() as session:
        relationship = schema.NendoRelationship.model_validate(
            self._upsert_track_track_relationship(
                relationship=relationship,
                session=session,
            ),
        )
    return track

add_track ¤

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 be added.

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/library/sqlalchemy_library.py
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
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,
) -> schema.NendoTrack:
    """Add the track given by path to the library.

    Args:
        file_path (Union[FilePath, str]): Path to the file to be added.
        track_type (str, optional): 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:
        schema.NendoTrack: The track that was added to the library.
    """
    skip_duplicate = skip_duplicate or self.config.skip_duplicate
    track = self._create_track_from_file(
        file_path=file_path,
        track_type=track_type,
        copy_to_library=copy_to_library,
        skip_duplicate=skip_duplicate,
        user_id=user_id or self.user.id,
        meta=meta,
    )
    if track is not None:
        with self.session_scope() as session:
            db_track = self._upsert_track_db(track=track, session=session)
            track = schema.NendoTrack.model_validate(db_track)
    return track

add_track_from_signal ¤

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.

'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/library/sqlalchemy_library.py
 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
1008
1009
1010
1011
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,
) -> schema.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.
        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
    """
    track = self._create_track_from_signal(
        signal=signal,
        sr=sr,
        track_type=track_type,
        meta=meta,
        user_id=user_id or self.user.id,
    )
    if track is not None:
        with self.session_scope() as session:
            db_track = self._upsert_track_db(track=track, session=session)
            track = schema.NendoTrack.model_validate(db_track)
    return track

add_track_relationship ¤

add_track_relationship(
    track_one_id: Union[str, UUID],
    track_two_id: Union[str, UUID],
    relationship_type: str = "relationship",
    meta: Optional[Dict[str, Any]] = None,
) -> bool

Add a relationship between two tracks.

Source code in src/nendo/library/sqlalchemy_library.py
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
def add_track_relationship(
    self,
    track_one_id: Union[str, uuid.UUID],
    track_two_id: Union[str, uuid.UUID],
    relationship_type: str = "relationship",
    meta: Optional[Dict[str, Any]] = None,
) -> bool:
    """Add a relationship between two tracks."""
    track_one = self.get_track(track_one_id)  # track
    track_two = self.get_track(track_two_id)  # related

    # check that tracks are not the same
    if track_one_id == track_two_id:
        logger.error("Error must provide two different existing track ids")
        return False

    # check if tracks exist
    if track_one is None:
        logger.error("Error track id %s not found", str(track_one_id))
        return False

    if track_two is None:
        logger.error("Error track id %s not found", str(track_two_id))
        return False

    relationship = schema.NendoRelationshipCreate(
        source_id=track_one.id,
        target_id=track_two.id,
        relationship_type=relationship_type,
        meta=meta or {},
    )
    with self.session_scope() as session:
        relationship = schema.NendoRelationship.model_validate(
            self._upsert_track_track_relationship(
                relationship=relationship,
                session=session,
            ),
        )
    return True

add_track_to_collection ¤

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
track_id Union[str, UUID]

ID of the track to add.

required
collection_id Union[str, UUID]

ID of the collection to which to add the track.

required
position int

Target position of the track inside the collection.

None
meta Dict[str, Any]

Metadata of the relationship.

None

Returns:

Type Description
NendoCollection

The updated NendoCollection object.

Source code in src/nendo/library/sqlalchemy_library.py
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
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
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,
) -> schema.NendoCollection:
    """Creates a relationship from the track to the collection.

    Args:
        track_id (Union[str, uuid.UUID]): ID of the track to add.
        collection_id (Union[str, uuid.UUID]): ID of the collection to
            which to add the track.
        position (int, optional): Target position of the track inside
            the collection.
        meta (Dict[str, Any]): Metadata of the relationship.

    Returns:
        NendoCollection: The updated NendoCollection object.
    """
    with self.session_scope() as session:
        # Convert IDs to UUIDs if they're strings
        collection_id = ensure_uuid(collection_id)
        track_id = ensure_uuid(track_id)

        # Check the collection and track objects
        collection = (
            session.query(model.NendoCollectionDB)
            .filter_by(id=collection_id)
            .first()
        )
        track = session.query(model.NendoTrackDB).filter_by(id=track_id).first()
        if not collection:
            raise schema.NendoCollectionNotFoundError(
                "The collection does not exist",
                collection_id,
            )
        if not track:
            raise schema.NendoCollectionNotFoundError(
                "The track does not exist",
                track_id,
            )

        rc_rel_db = model.TrackCollectionRelationshipDB
        if position is not None:
            # Update other states to keep ordering consistent
            session.query(rc_rel_db).filter(
                rc_rel_db.target_id == collection_id,
                rc_rel_db.relationship_position >= position,
            ).update(
                {
                    rc_rel_db.relationship_position: rc_rel_db.relationship_position
                    + 1,
                },
            )
        else:
            # If no position specified, add at the end
            last_state = (
                session.query(model.TrackCollectionRelationshipDB)
                .filter_by(target_id=collection_id)
                .order_by(
                    model.TrackCollectionRelationshipDB.relationship_position.desc(),
                )
                .first()
            )
            position = last_state.relationship_position + 1 if last_state else 0

        # Create a relationship from the track to the collection
        tc_relationship = model.TrackCollectionRelationshipDB(
            source_id=track_id,
            target_id=collection_id,
            relationship_type="track",
            meta=meta or {},
            relationship_position=position,
        )
        session.add(tc_relationship)
        session.commit()
        session.refresh(collection)
        return schema.NendoCollection.model_validate(collection)

add_tracks ¤

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[str, DirectoryPath]

Path to the directory to be scanned

required
track_type str

Track type for the new tracks

'track'
user_id UUID

The ID of the user adding the track.

None
copy_to_library bool

Copy and convert the data into the nendo Library?

None
skip_duplicate bool

Skip adding duplicates?

True

Returns:

Type Description
tracks (list[NendoTrack]

The tracks that were added to the Library

Source code in src/nendo/library/sqlalchemy_library.py
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
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,
) -> schema.NendoCollection:
    """Scan the provided path and upsert the information into the library.

    Args:
        path (Union[str, DirectoryPath]): Path to the directory to be scanned
        track_type (str, optional): Track type for the new tracks
        user_id (UUID, optional): The ID of the user adding the track.
        copy_to_library (bool): Copy and convert the data into the nendo Library?
        skip_duplicate (bool): Skip adding duplicates?

    Returns:
        tracks (list[NendoTrack]): The tracks that were added to the Library
    """
    user_id = self._ensure_user_uuid(user_id)
    file_list = []
    if not os.path.exists(path):
        raise schema.NendoLibraryError(f"Source directory {path} does not exist.")
    for root, _, files in os.walk(path):
        file_list.extend(
            [
                os.path.join(root, file)
                for file in files
                if AudioFileUtils().is_supported_filetype(file)
            ],
        )
    tracks = self._add_tracks_db(
        file_paths=file_list,
        track_type=track_type,
        copy_to_library=copy_to_library,
        skip_duplicate=skip_duplicate,
        user_id=user_id,
    )
    return self.add_collection(name=path, track_ids=[t.id for t in tracks])

add_tracks_to_collection ¤

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/library/sqlalchemy_library.py
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
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,
) -> schema.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.
    """
    with self.session_scope() as session:
        # Convert IDs to UUIDs if they're strings
        collection_id = ensure_uuid(collection_id)
        track_ids = [ensure_uuid(track_id) for track_id in track_ids]

        # Check the collection and track objects
        collection = (
            session.query(model.NendoCollectionDB)
            .filter_by(id=collection_id)
            .first()
        )
        if not collection:
            raise schema.NendoCollectionNotFoundError(
                "The collection does not exist",
                collection_id,
            )
        existing_track_ids = (
            session.query(model.NendoTrackDB)
            .filter(model.NendoTrackDB.id.in_(track_ids))
            .all()
        )
        existing_track_ids = [t.id for t in existing_track_ids]
        missing_ids = [tid for tid in track_ids if tid not in existing_track_ids]
        if len(missing_ids) > 0:
            raise schema.NendoCollectionNotFoundError(
                "Tracks do not exist: ",
                missing_ids,
            )

        # append all tracks to the end of the collection
        last_postition = (
            session.query(model.TrackCollectionRelationshipDB)
            .filter_by(target_id=collection_id)
            .order_by(
                model.TrackCollectionRelationshipDB.relationship_position.desc(),
            )
            .first()
        )
        position = last_postition.relationship_position + 1 if last_postition else 0

        # create relationships from all tracks to the collection
        for track_id in track_ids:
            tc_relationship = model.TrackCollectionRelationshipDB(
                source_id=track_id,
                target_id=collection_id,
                relationship_type="track",
                meta=meta or {},
                relationship_position=position,
            )
            session.add(tc_relationship)
            position += 1
        session.commit()
        session.refresh(collection)
        return schema.NendoCollection.model_validate(collection)

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 ¤

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/library/sqlalchemy_library.py
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
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.
    """
    collection_id = ensure_uuid(collection_id)
    with self.session_scope() as session:
        return (
            session.query(model.NendoTrackDB)
            .join(
                model.TrackCollectionRelationshipDB,
                model.TrackCollectionRelationshipDB.source_id
                == model.NendoTrackDB.id,
            )
            .filter(model.TrackCollectionRelationshipDB.target_id == collection_id)
            .count()
        )

create_object ¤

create_object(
    user_id: Optional[Union[str, UUID]] = None,
    track_type: str = "text",
    meta: Optional[Dict[str, Any]] = None,
    visibility: Visibility = schema.Visibility.private,
    images: Optional[List[NendoResource]] = None,
    file_path: str = "",
    resource_type: ResourceType = schema.ResourceType.text,
    resource_meta: Optional[Dict[str, Any]] = None,
    copy_to_library: Optional[bool] = None,
) -> NendoTrack

Create a new object, manually.

Parameters:

Name Type Description Default
user_id UUID

The ID of the object's user.

None
track_type str

The type of the object. Defaults to "track".

'text'
meta Dict[str, Any]

Metadata about the object.

None
visibility Visibility

Visibility of the object. Defaults to "private".

private
images List[NendoResource]

List of (additional) images for the object.

None
file_path str

Path to a file to be added to the track as NendoResource. Defaults to "" (no file path).

''
resource_type ResourceType

Type of the resource to set. Defaults to "text".

text
resource_meta dict

Metadata about the NendoResource.

None
copy_to_library bool

Flag that determines, whether to copy the file to the library storage or not.

None

Returns:

Type Description
NendoTrack

The created track.

Source code in src/nendo/library/sqlalchemy_library.py
849
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
def create_object(
    self,
    user_id: Optional[Union[str, uuid.UUID]] = None,
    track_type: str = "text",
    meta: Optional[Dict[str, Any]] = None,
    visibility: schema.Visibility = schema.Visibility.private,
    images: Optional[List[schema.NendoResource]] = None,
    file_path: str = "",
    resource_type: schema.ResourceType = schema.ResourceType.text,
    resource_meta: Optional[Dict[str, Any]] = None,
    copy_to_library: Optional[bool] = None,
) -> schema.NendoTrack:
    """Create a new object, manually.

    Args:
        user_id (uuid.UUID, optional): The ID of the object's user.
        track_type (str): The type of the object. Defaults to "track".
        meta (Dict[str, Any], optional): Metadata about the object.
        visibility (Visibility): Visibility of the object. Defaults to "private".
        images (List[NendoResource], optional): List of (additional) images for
            the object.
        file_path (str): Path to a file to be added to the track as NendoResource.
            Defaults to "" (no file path).
        resource_type (ResourceType): Type of the resource to set.
            Defaults to "text".
        resource_meta (dict, optional): Metadata about the NendoResource.
        copy_to_library (bool, optional): Flag that determines, whether to copy
            the file to the library storage or not.

    Returns:
        NendoTrack: The created track.
    """
    user_id = self._ensure_user_uuid(user_id)
    resource = None
    if len(file_path) > 0:
        copy_to_library = copy_to_library or self.config.copy_to_library
        if copy_to_library:
            try:
                # save file to storage in its original format
                path_in_library = self.storage_driver.save_file(
                    file_name=self.storage_driver.generate_filename(
                        filetype=os.path.splitext(file_path)[1][1:],  # without dot
                        user_id=str(user_id),
                    ),
                    file_path=file_path,
                    user_id=str(user_id),
                )
                location = self.storage_driver.get_driver_location()
            except Exception as e:  # noqa: BLE001
                raise schema.NendoLibraryError(
                    f"Error copying file to the library: {e}.",
                ) from e
        else:
            path_in_library = file_path
            location = schema.ResourceLocation.original

        resource = schema.NendoResource(
            file_path=self.storage_driver.get_file_path(
                src=path_in_library,
                user_id=str(user_id),
            ),
            file_name=self.storage_driver.get_file_name(
                src=path_in_library,
                user_id=str(user_id),
            ),
            resource_type=resource_type,
            location=location,
            meta=resource_meta or {},
        )
    else:
        location = self.storage_driver.get_driver_location()
        resource = schema.NendoResource(
            file_path="",
            file_name="",
            resource_type=resource_type,
            location=location,
            meta=resource_meta or {},
        )
    track = schema.NendoTrackCreate(
        user_id=user_id,
        visibility=visibility,
        images=images or [],
        resource=resource.model_dump(),
        track_type=track_type,
        meta=meta or {},
    )
    with self.session_scope() as session:
        db_track = self._upsert_track_db(track=track, session=session)
        return schema.NendoTrack.model_validate(db_track)

export_collection ¤

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

Export the collection to a directory.

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/library/sqlalchemy_library.py
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
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 collection to a directory.

    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.
    """
    collection_tracks = self.get_collection_tracks(collection_id)
    now = datetime.now().strftime("%Y%m%d%H%M%S")  # noqa: DTZ005
    if not os.path.isdir(export_path):
        logger.info(
            f"Export path {export_path} does not exist, creating now.",
        )
        os.makedirs(export_path, exist_ok=True)
    track_file_paths = []
    for track in collection_tracks:
        if track.has_meta("original_filename"):
            original_filename = track.get_meta("original_filename")
        else:
            original_filename = track.resource.file_name
        file_name = f"{original_filename}_{filename_suffix}_{now}.{file_format}"
        file_path = os.path.join(export_path, file_name)
        track_file_path = self.export_track(
            track_id=track.id,
            file_path=file_path,
            file_format=file_format,
        )
        track_file_paths.append(track_file_path)
    return track_file_paths

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/library/sqlalchemy_library.py
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
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
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
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.
    """
    track = self.get_track(track_id=track_id)
    # Check if file_path is a directory
    if os.path.isdir(file_path):
        # Generate a filename with timestamp
        if track.has_meta("original_filename"):
            original_filename = track.get_meta("original_filename")
        else:
            original_filename = track.resource.file_name
        file_name = (
            f"{original_filename}_nendo_"
            f"{datetime.now().strftime('%Y%m%d%H%M%S')}"  # noqa: DTZ005
            f".{file_format}"
        )
        file_path = os.path.join(file_path, file_name)
    else:
        # Deduce file format from file extension
        file_format = os.path.splitext(file_path)[1].lstrip(".")

    # Exporting the audio
    temp_path = None
    signal = track.signal
    signal = np.transpose(signal) if signal.shape[0] <= 2 else signal
    if file_format in ("wav", "ogg"):
        sf.write(file_path, signal, track.sr, format=file_format)
    elif file_format == "mp3":
        # Create a temporary WAV file for conversion
        temp_path = file_path.rsplit(".", 1)[0] + ".wav"
        sf.write(temp_path, signal, track.sr)
        subprocess.run(
            ["ffmpeg", "-i", temp_path, "-acodec", "libmp3lame", file_path],
            check=False,
        )
    else:
        raise ValueError(
            "Unsupported file format. "
            "Supported formats are 'wav', 'mp3', and 'ogg'.",
        )

    # Clean up temporary file if used
    if temp_path and os.path.exists(temp_path):
        os.remove(temp_path)

    return file_path
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 ("to", "from", "both").

'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/library/sqlalchemy_library.py
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
1477
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
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 ("to", "from", "both").
        filters (dict, optional): Dictionary containing the filters to apply.
            Defaults to None.
        search_meta (dict, optional): 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
    """
    user_id = self._ensure_user_uuid(user_id)
    with self.session_scope() as session:
        query = self._get_related_tracks_query(
            track_id=ensure_uuid(track_id),
            session=session,
            direction=direction,
            user_id=user_id,
        )
        query = self._get_filtered_tracks_query(
            session=session,
            query=query,
            filters=filters,
            search_meta=search_meta,
            track_type=track_type,
            user_id=user_id,
            collection_id=collection_id,
            plugin_names=plugin_names,
        )
        return self.get_tracks(
            query=query,
            order_by=order_by,
            order=order,
            limit=limit,
            offset=offset,
            load_related_tracks=True,
            session=session,
        )

filter_tracks ¤

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,
    session: Optional[Session] = 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.meta and track.resource fields. The dictionary's values should contain singular search tokens and the keys currently have no effect but might in other implementations of the NendoLibrary. 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/library/sqlalchemy_library.py
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
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
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,
    session: Optional[Session] = 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, optional): Dictionary containing the keywords to
            search for over the `track.meta` and `track.resource` fields.
            The dictionary's values should contain singular search tokens
            and the keys currently have no effect but might in other
            implementations of the NendoLibrary. 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
    """
    user_id = self._ensure_user_uuid(user_id)
    s = session or self.session_scope()
    with s as session_local:
        """Obtain tracks from the db by filtering w.r.t. various fields."""
        query = self._get_filtered_tracks_query(
            session=session_local,
            filters=filters,
            search_meta=search_meta,
            track_type=track_type,
            user_id=user_id,
            collection_id=collection_id,
            plugin_names=plugin_names,
        )
        return self.get_tracks(
            query=query,
            order_by=order_by,
            order=order,
            limit=limit,
            offset=offset,
            load_related_tracks=False,
            session=session_local,
        )

find_collections ¤

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/library/sqlalchemy_library.py
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
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
    """
    user_id = self._ensure_user_uuid(user_id)
    with self.session_scope() as session:
        query = session.query(model.NendoCollectionDB)
        if value is not None and len(value) > 0:
            query = query.filter(
                and_(
                    or_(
                        model.NendoCollectionDB.name.ilike(f"%{value}%"),
                        model.NendoCollectionDB.description.ilike(f"%{value}%"),
                        # cast(
                        #     model.NendoCollectionDB.meta, Text()).ilike(f"%{value}%"
                        # ),
                    ),
                ),
            )
        if user_id is not None:
            query = query.filter(model.NendoCollectionDB.user_id == user_id)
        if collection_types is not None:
            query = query.filter(
                model.NendoCollectionDB.collection_type.in_(collection_types),
            )
        return self._get_collections_db(
            query,
            user_id,
            order_by,
            order,
            limit,
            offset,
            session,
        )

find_tracks ¤

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]

Obtain tracks from the db by fulltext search.

Parameters:

Name Type Description Default
value str

The value to search for. The value is matched against text representations of the track's meta and resource fields.

required
user_id Union[str, UUID]

The user ID to filter for.

None
order_by str

Key used for ordering the results.

None
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/library/sqlalchemy_library.py
1504
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
1546
1547
1548
1549
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]:
    """Obtain tracks from the db by fulltext search.

    Args:
        value (str): The value to search for. The value is matched against
            text representations of the track's `meta` and `resource` fields.
        user_id (Union[str, UUID], optional): The user ID to filter for.
        order_by (str, optional): Key used for ordering the results.
        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
    """
    user_id = self._ensure_user_uuid(user_id)
    with self.session_scope() as session:
        query = session.query(model.NendoTrackDB).filter(
            or_(
                cast(model.NendoTrackDB.resource, Text()).ilike(
                    "%{}%".format(value),
                ),
                cast(model.NendoTrackDB.meta, Text()).ilike(
                    "%{}%".format(value),
                ),
            ),
        )
        if user_id is not None:
            query = query.filter(model.NendoTrackDB.user_id == user_id)
        return self.get_tracks(
            query=query,
            order_by=order_by,
            order=order,
            limit=limit,
            offset=offset,
            load_related_tracks=False,
            session=session,
        )

get_collection ¤

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

Get a collection by its ID.

Parameters:

Name Type Description Default
collection_id UUID

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/library/sqlalchemy_library.py
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
def get_collection(
    self,
    collection_id: uuid.UUID,
    get_related_tracks: bool = True,
) -> schema.NendoCollection:
    """Get a collection by its ID.

    Args:
        collection_id (uuid.UUID): 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.
    """
    with self.session_scope() as session:
        query = session.query(model.NendoCollectionDB)
        if get_related_tracks:
            query = query.options(
                joinedload(model.NendoCollectionDB.related_tracks).joinedload(
                    model.TrackCollectionRelationshipDB.source,
                ),
            )
        else:
            query = query.options(
                noload(model.NendoCollectionDB.related_tracks),
            )
        collection_db = query.filter(
            model.NendoCollectionDB.id == collection_id,
        ).first()

        return (
            schema.NendoCollection.model_validate(collection_db)
            if collection_db is not None
            else None
        )

get_collection_tracks ¤

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

Get all tracks from 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/library/sqlalchemy_library.py
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
def get_collection_tracks(
    self,
    collection_id: uuid.UUID,
    order: Optional[str] = "asc",
) -> List[schema.NendoTrack]:
    """Get all tracks from 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.
    """
    with self.session_scope() as session:
        tracks_db = (
            session.query(model.NendoTrackDB).join(
                model.TrackCollectionRelationshipDB,
                model.TrackCollectionRelationshipDB.source_id
                == model.NendoTrackDB.id,
            )
            # .options(joinedload(model.NendoTrackDB.related_collections))
            .filter(model.TrackCollectionRelationshipDB.target_id == collection_id)
        )
        if order:
            if order == "random":
                tracks_db = tracks_db.order_by(func.random())
            elif order == "desc":
                tracks_db = tracks_db.order_by(
                    desc(
                        model.TrackCollectionRelationshipDB.relationship_position,
                    ),
                )
            else:
                tracks_db = tracks_db.order_by(
                    asc(
                        model.TrackCollectionRelationshipDB.relationship_position,
                    ),
                )

        tracks_db = tracks_db.all()

        return (
            [schema.NendoTrack.model_validate(t) for t in tracks_db]
            if tracks_db is not None
            else None
        )

get_collections ¤

get_collections(
    query: Optional[Query] = 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,
    session: Optional[Session] = None,
) -> Union[List, Iterator]

Get a list of collections.

Parameters:

Name Type Description Default
query Query

Query object to build from.

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
session Session

Session object to commit to.

None

Returns:

Type Description
Union[List, Iterator]

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

Source code in src/nendo/library/sqlalchemy_library.py
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
def get_collections(
    self,
    query: Optional[Query] = 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,
    session: Optional[Session] = None,
) -> Union[List, Iterator]:
    """Get a list of collections.

    Args:
        query (Query, optional): Query object to build from.
        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).
        session (sqlalchemy.Session): Session object to commit to.

    Returns:
        Union[List, Iterator]: List or generator of collections, depending on the
            configuration variable stream_mode
    """
    user_id = self._ensure_user_uuid(user_id)
    with self.session_scope() as session:
        query = session.query(model.NendoCollectionDB)
        if user_id is not None:
            query = query.filter(model.NendoCollectionDB.user_id == user_id)
        return self._get_collections_db(
            query,
            user_id,
            order_by,
            order,
            limit,
            offset,
            session,
        )

get_plugin_data ¤

get_plugin_data(
    track_id: Union[str, UUID],
    user_id: Optional[Union[str, UUID]] = None,
    plugin_name: Optional[str] = None,
    plugin_version: Optional[str] = None,
    key: Optional[str] = None,
) -> List[NendoPluginData]

Get all plugin data related to a track from the DB.

Parameters:

Name Type Description Default
track_id UUID

Track ID to get the related plugin data for.

required
user_id Union[str, UUID]

The user ID to filter for.

None
plugin_name str

The name of the plugin with which the plugin data was created.

None
plugin_version str

The version of the plugin with which the plugin data was created.

None
key str

The key for which to filter the plugin data.

None

Returns:

Type Description
List[NendoPluginData]

List of nendo plugin data entries.

Source code in src/nendo/library/sqlalchemy_library.py
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
def get_plugin_data(
    self,
    track_id: Union[str, uuid.UUID],
    user_id: Optional[Union[str, uuid.UUID]] = None,
    plugin_name: Optional[str] = None,
    plugin_version: Optional[str] = None,
    key: Optional[str] = None,
) -> List[schema.NendoPluginData]:
    """Get all plugin data related to a track from the DB.

    Args:
        track_id (UUID): Track ID to get the related plugin data for.
        user_id (Union[str, UUID], optional): The user ID to filter for.
        plugin_name (str, optional): The name of the plugin with which
            the plugin data was created.
        plugin_version (str, optional): The version of the plugin with which
            the plugin data was created.
        key (str, optional): The key for which to filter the plugin data.

    Returns:
        List[NendoPluginData]: List of nendo plugin data entries.
    """
    track_id = ensure_uuid(track_id)
    user_id = self._ensure_user_uuid(user_id=user_id)
    with self.session_scope() as session:
        plugin_data_db = self._get_plugin_data_db(
            track_id=track_id,
            user_id=user_id,
            session=session,
            plugin_name=plugin_name,
            plugin_version=plugin_version,
            key=key,
        )
        return [
            schema.NendoPluginData.model_validate(pdb) for pdb in plugin_data_db
        ]
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/library/sqlalchemy_library.py
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
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
    """
    user_id = self._ensure_user_uuid(user_id)
    with self.session_scope() as session:
        query = self._get_related_collections_query(
            collection_id=ensure_uuid(collection_id),
            session=session,
            direction=direction,
            user_id=user_id,
        )
        return self._get_collections_db(
            query,
            order_by,
            order,
            limit,
            offset,
            session,
        )
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 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'
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/library/sqlalchemy_library.py
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
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
1430
1431
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 (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".
        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
    """
    with self.session_scope() as session:
        query = self._get_related_tracks_query(
            track_id=ensure_uuid(track_id),
            session=session,
            direction=direction,
            user_id=user_id,
        )
        return self.get_tracks(
            query=query,
            order_by=order_by,
            order=order,
            limit=limit,
            offset=offset,
            load_related_tracks=True,
            session=session,
        )

get_track ¤

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

Get a single track from the library by ID.

Source code in src/nendo/library/sqlalchemy_library.py
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
def get_track(
    self,
    track_id: uuid.UUID,
    user_id: Optional[Union[str, uuid.UUID]] = None,
) -> schema.NendoTrack:
    """Get a single track from the library by ID."""
    with self.session_scope() as session:
        query = session.query(model.NendoTrackDB).filter(
            model.NendoTrackDB.id == track_id,
        )

        if user_id is not None:
            user_id = self._ensure_user_uuid(user_id)
            query = query.filter(model.NendoTrackDB.user_id == user_id)

        track_db = query.one_or_none()
        return (
            schema.NendoTrack.model_validate(track_db)
            if track_db is not None
            else None
        )

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 ¤

get_tracks(
    query: Optional[Query] = None,
    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,
    session: Optional[Session] = None,
) -> Union[List, Iterator]

Get tracks based on the given query parameters.

Parameters:

Name Type Description Default
query Query

Query object to build from.

None
user_id Union[str, UUID]

ID of user to filter tracks by.

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 that determines whether to populate related_tracks field.

False
session Session

Session object to commit to.

None

Returns:

Type Description
Union[List, Iterator]

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

Source code in src/nendo/library/sqlalchemy_library.py
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
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
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
@schema.NendoPlugin.stream_output
def get_tracks(
    self,
    query: Optional[Query] = None,
    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,
    session: Optional[Session] = None,
) -> Union[List, Iterator]:
    """Get tracks based on the given query parameters.

    Args:
        query (Query, optional): Query object to build from.
        user_id (Union[str, UUID], optional): ID of user to filter tracks by.
        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 that determines whether to
            populate related_tracks field.
        session (sqlalchemy.Session): Session object to commit to.

    Returns:
        Union[List, Iterator]: List or generator of tracks, depending on the
            configuration variable stream_mode
    """
    user_id = self._ensure_user_uuid(user_id)
    s = session or self.session_scope()
    with s as session_local:
        if query:
            query_local = query
        else:
            query_local = session_local.query(model.NendoTrackDB).filter(
                model.NendoTrackDB.user_id == user_id,
            )
            if user_id is not None:
                query_local = query_local.filter(
                    model.NendoTrackDB.user_id == user_id,
                )
        if order_by:
            if order_by == "random":
                query_local = query_local.order_by(func.random())
            elif order_by == "collection":
                if order == "desc":
                    query_local = query_local.order_by(
                        desc(
                            model.TrackCollectionRelationshipDB.relationship_position,
                        ),
                    )
                else:
                    query_local = query_local.order_by(
                        asc(
                            model.TrackCollectionRelationshipDB.relationship_position,
                        ),
                    )
            elif order == "desc":
                query_local = query_local.order_by(
                    desc(getattr(model.NendoTrackDB, order_by)),
                )
            else:
                query_local = query_local.order_by(
                    asc(getattr(model.NendoTrackDB, order_by)),
                )
        if limit:
            query_local = query_local.limit(limit)
            if offset:
                query_local = query_local.offset(offset)

        if not load_related_tracks:
            query_local = query_local.options(
                noload(model.NendoTrackDB.related_tracks),
            )

        if self.config.stream_chunk_size > 1:
            chunk = []
            for track in query_local:
                chunk.append(schema.NendoTrack.model_validate(track))
                if len(chunk) == self.config.stream_chunk_size:
                    yield chunk
                    chunk = []
            if chunk:  # yield remaining tracks in non-full chunk
                yield chunk
        else:
            for track in query_local:
                yield schema.NendoTrack.model_validate(track)

library_size ¤

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/library/sqlalchemy_library.py
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
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.
    """
    user_id = self._ensure_user_uuid(user_id)
    with self.session_scope() as session:
        query = session.query(model.NendoTrackDB)
        if user_id is not None:
            query = query.filter(model.NendoTrackDB.user_id == user_id)
        return query.count()

load_blob ¤

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/library/sqlalchemy_library.py
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
def load_blob(
    self,
    blob_id: uuid.UUID,
    user_id: Optional[Union[str, uuid.UUID]] = None,
) -> schema.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.
    """
    user_id = self._ensure_user_uuid(user_id)
    with self.session_scope() as session:
        blob_db = (
            session.query(model.NendoBlobDB)
            .filter(model.NendoBlobDB.id == blob_id)
            .one_or_none()
        )
        if blob_db is not None:
            blob = schema.NendoBlob.model_validate(blob_db)
            local_blob = self.storage_driver.as_local(
                file_path=blob.resource.src,
                location=blob.resource.location,
                user_id=str(user_id),
            )

            # load blob data into memory
            if os.path.splitext(local_blob)[1] == ".pkl":
                with open(local_blob, "rb") as f:
                    blob.data = pickle.load(f)  # noqa: S301
            elif os.path.splitext(local_blob)[1] == ".npy":
                blob.data = np.load(local_blob)
            elif os.path.splitext(local_blob)[1] == ".wav":
                librosa.load(local_blob, mono=False)
            else:
                logger.error(
                    "Blob file format not recognized. "
                    "Returning blob with empty data.",
                )

    return blob

remove_blob ¤

remove_blob(
    blob_id: UUID,
    remove_resources: bool = True,
    user_id: Optional[Union[str, 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/library/sqlalchemy_library.py
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
def remove_blob(
    self,
    blob_id: uuid.UUID,
    remove_resources: bool = True,
    user_id: Optional[Union[str, 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
    """
    user_id = self._ensure_user_uuid(user_id)
    with self.session_scope() as session:
        target = (
            session.query(model.NendoBlobDB)
            .filter(model.NendoBlobDB.id == blob_id)
            .first()
        )
        session.delete(target)
    if remove_resources:
        logger.info("Removing resources associated with Blob %s", str(blob_id))
        try:
            self.storage_driver.remove_file(
                file_name=target.resource["file_name"],
                user_id=str(user_id),
            )
        except Exception as e:  # noqa: BLE001
            logger.error(
                "Removing %s failed: %s",
                target.resource.model_dump().src,
                e,
            )
    return True

remove_collection ¤

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/library/sqlalchemy_library.py
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
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.
    """
    with self.session_scope() as session:
        # has_related_track = (
        #     session.query(model.TrackCollectionRelationshipDB)
        #     .filter(
        #         model.TrackCollectionRelationshipDB.target_id
        #         == collection_id
        #     )
        #     .first()
        # ) is not False
        has_related_collection = (
            session.query(model.CollectionCollectionRelationshipDB)
            .filter(
                or_(
                    model.CollectionCollectionRelationshipDB.source_id
                    == collection_id,
                    model.CollectionCollectionRelationshipDB.target_id
                    == collection_id,
                ),
            )
            .first()
        ) is not None

        if has_related_collection:  # or has_related_track:
            if remove_relationships:
                session.query(model.CollectionCollectionRelationshipDB).filter(
                    or_(
                        model.CollectionCollectionRelationshipDB.target_id
                        == collection_id,
                        model.CollectionCollectionRelationshipDB.source_id
                        == collection_id,
                    ),
                ).delete()
                session.commit()
            else:
                logger.warning(
                    "Cannot remove due to existing relationships. "
                    "Set `remove_relationships=True` to remove them.",
                )
                return False

        # clean up track-collection relationships
        session.query(model.TrackCollectionRelationshipDB).filter(
            model.TrackCollectionRelationshipDB.target_id == collection_id,
        ).delete()
        session.commit()

        # delete actual target
        query = session.query(model.NendoCollectionDB).filter(
            model.NendoCollectionDB.id == collection_id,
        )
        if user_id is not None:
            user_id = self._ensure_user_uuid(user_id)
            query = query.filter(
                model.NendoCollectionDB.user_id == user_id,
            )
        query.delete()

    return True

remove_track ¤

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

None
remove_relationships bool

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

False
remove_plugin_data bool

If False prevent deletion if related plugin data exist if True delete plugin data together with the object

True
remove_resources bool

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

True

Returns:

Type Description
success (bool

True if removal was successful, False otherwise.

Source code in src/nendo/library/sqlalchemy_library.py
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
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
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
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
        remove_relationships (bool):
            If False prevent deletion if related tracks exist,
            if True delete relationships together with the object
        remove_plugin_data (bool):
            If False prevent deletion if related plugin data exist
            if True delete plugin data together with the object
        remove_resources (bool):
            If False, keep the related resources, e.g. files
            if True, delete the related resources

    Returns:
        success (bool): True if removal was successful, False otherwise.
    """
    track_id = ensure_uuid(track_id)
    with self.session_scope() as session:
        tracks_with_relations = self._get_related_tracks_query(
            track_id=track_id,
            session=session,
            direction="both",
            user_id=uuid.UUID(user_id) if user_id is not None else None,
        ).all()
        collections_with_relations = (
            session.query(model.NendoCollectionDB)
            .join(
                model.TrackCollectionRelationshipDB,
                model.NendoCollectionDB.id
                == model.TrackCollectionRelationshipDB.target_id,
            )
            .filter(model.TrackCollectionRelationshipDB.source_id == track_id)
            .all()
        )
        user_id = self._ensure_user_uuid(user_id)
        related_plugin_data = self._get_plugin_data_db(
            track_id=track_id,
            user_id=user_id,
            session=session,
        )
        if len(related_plugin_data) > 0:
            if remove_plugin_data:
                logger.info("Removing %d plugin data", len(related_plugin_data))
                session.query(model.NendoPluginDataDB).filter(
                    model.NendoPluginDataDB.track_id == track_id,
                ).delete()
                session.commit()
            else:
                logger.warning(
                    "Cannot remove due to %d existing "
                    "plugin data entries. Set `remove_plugin_data=True` "
                    "to remove them.",
                    len(related_plugin_data),
                )
                return False
        n_rel = len(tracks_with_relations) + len(collections_with_relations)
        if n_rel > 0:
            if remove_relationships:
                session.query(model.TrackTrackRelationshipDB).filter(
                    model.TrackTrackRelationshipDB.target_id == track_id,
                ).delete()
                session.query(model.TrackTrackRelationshipDB).filter(
                    model.TrackTrackRelationshipDB.source_id == track_id,
                ).delete()
                # remove track from all collections
                for collection in collections_with_relations:
                    self._remove_track_from_collection_db(
                        track_id=track_id,
                        collection_id=collection.id,
                        session=session,
                    )
                session.commit()
            else:
                logger.warning(
                    "Cannot remove due to %s existing relationships. "
                    "Set `remove_relationships=True` to remove them.",
                    n_rel,
                )
                return False
        # delete actual target
        target = (
            session.query(model.NendoTrackDB)
            .filter(model.NendoTrackDB.id == track_id)
            .one_or_none()
        )
        target_track = schema.NendoTrack.model_validate(target)
        session.delete(target)
    # only delete if file has been copied to the library
    # ("original_filepath" is present)
    user_id = self._ensure_user_uuid(user_id)
    if remove_resources and target_track.resource.location != "original":
        logger.info("Removing resources associated with Track %s", str(track_id))
        return self.storage_driver.remove_file(
            file_name=target_track.resource.file_name,
            user_id=str(user_id),
        )
    return True

remove_track_from_collection ¤

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
track_id Union[str, UUID]

ID

required
collection_id Union[str, UUID]

Collection id.

required

Returns:

Type Description
success (bool

True if removal was successful, False otherwise.

Source code in src/nendo/library/sqlalchemy_library.py
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
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:
        track_id (Union[str, uuid.UUID]): ID
        collection_id (Union[str, uuid.UUID]): Collection id.

    Returns:
        success (bool): True if removal was successful, False otherwise.
    """
    with self.session_scope() as session:
        collection_id = ensure_uuid(collection_id)
        track_id = ensure_uuid(track_id)

        # # Check the collection and track objects
        # collection = (
        #     session.query(model.NendoCollectionDB)
        #     .filter_by(id=collection_id)
        #     .first()
        # )
        # track = session.query(model.NendoTrackDB).filter_by(id=track_id).first()
        # if not collection:
        #     raise ValueError("The collection does not exist")
        # if not track:
        #     raise ValueError("The track does not exist")

        # Remove the relationship from the track to the collection
        return self._remove_track_from_collection_db(
            track_id=track_id,
            collection_id=collection_id,
            session=session,
        )

reset ¤

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 everything.

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/library/sqlalchemy_library.py
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
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 everything.

    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.
    """
    user_id = self._ensure_user_uuid(user_id)
    should_proceed = (
        force
        or input(
            "Are you sure you want to reset the library? "
            "This will purge ALL tracks, collections and relationships!"
            "Enter 'y' to confirm: ",
        ).lower()
        == "y"
    )

    if not should_proceed:
        logger.info("Reset operation cancelled.")
        return

    logger.info("Resetting nendo library.")
    with self.session_scope() as session:
        # delete all relationships
        session.query(model.TrackTrackRelationshipDB).delete()
        session.query(model.TrackCollectionRelationshipDB).delete()
        session.query(model.CollectionCollectionRelationshipDB).delete()
        # delete all plugin data
        session.query(model.NendoPluginDataDB).delete()
        session.commit()
        # delete all collections
        session.query(model.NendoCollectionDB).delete()
        # delete all tracks
        session.query(model.NendoTrackDB).delete()
    # remove files
    for library_file in self.storage_driver.list_files(user_id=str(user_id)):
        self.storage_driver.remove_file(
            file_name=library_file,
            user_id=str(user_id),
        )

session_scope ¤

session_scope()

Provide a transactional scope around a series of operations.

Source code in src/nendo/library/sqlalchemy_library.py
66
67
68
69
70
71
72
73
74
75
76
77
@contextmanager
def session_scope(self):
    """Provide a transactional scope around a series of operations."""
    session = sessionmaker(autocommit=False, autoflush=False, bind=self.db)()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()

store_blob ¤

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

Stores a blob of data.

Parameters:

Name Type Description Default
file_path Union[str, FilePath]

The blob to store.

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/library/sqlalchemy_library.py
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
def store_blob(
    self,
    file_path: Union[str, FilePath],
    user_id: Optional[Union[str, uuid.UUID]] = None,
) -> schema.NendoBlob:
    """Stores a blob of data.

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

    Returns:
        schema.NendoBlob: The stored blob.
    """
    user_id = self._ensure_user_uuid(user_id)
    blob = self._create_blob_from_file(file_path=file_path, user_id=user_id)
    if blob is not None:
        with self.session_scope() as session:
            db_blob = self._upsert_blob_db(blob, session)
            blob = schema.NendoBlob.model_validate(db_blob)
    return blob

store_blob_from_bytes ¤

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/library/sqlalchemy_library.py
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
def store_blob_from_bytes(
    self,
    data: bytes,
    user_id: Optional[Union[str, uuid.UUID]] = None,
) -> schema.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.
    """
    user_id = self._ensure_user_uuid(user_id)
    blob = self._create_blob_from_bytes(data=data, user_id=user_id)
    if blob is not None:
        with self.session_scope() as session:
            db_blob = self._upsert_blob_db(blob, session)
            blob = schema.NendoBlob.model_validate(db_blob)
    return blob

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 ¤

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/library/sqlalchemy_library.py
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
def update_collection(
    self,
    collection: schema.NendoCollection,
) -> schema.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.
    """
    with self.session_scope() as session:
        collection_db = (
            session.query(model.NendoCollectionDB)
            .filter_by(id=collection.id)
            .first()
        )

        if collection_db is None:
            raise schema.NendoCollectionNotFoundError(
                "Collection not found",
                collection.id,
            )

        collection_db.name = collection.name
        collection_db.user_id = collection.user_id
        collection_db.description = collection.description
        collection_db.collection_type = collection.collection_type
        collection_db.visibility = collection.visibility
        collection_db.meta = collection.meta

        session.commit()
        session.refresh(collection_db)
        return schema.NendoCollection.model_validate(collection_db)

update_track ¤

update_track(track: NendoTrack) -> NendoTrack

Updates the given track 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/library/sqlalchemy_library.py
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
def update_track(
    self,
    track: schema.NendoTrack,
) -> schema.NendoTrack:
    """Updates the given track 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.
    """
    with self.session_scope() as session:
        # update existing track
        db_track = (
            session.query(model.NendoTrackDB).filter_by(id=track.id).one_or_none()
        )
        if db_track is None:
            raise schema.NendoTrackNotFoundError("Track not found", id=track.id)
        db_track.user_id = track.user_id
        db_track.visibility = track.visibility
        db_track.resource = track.resource.model_dump()
        db_track.track_type = track.track_type
        db_track.images = track.images
        db_track.meta = track.meta
        session.commit()
    return db_track

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"]