Skip to content

Datasets API

The datasets module manages GNU/OPENSOURCE datasets with quality control.

DatasetManager

qfzz.datasets.manager.DatasetManager

Manages music datasets with quality scoring and license validation.

Source code in qfzz/datasets/manager.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
class DatasetManager:
    """
    Manages music datasets with quality scoring and license validation.
    """

    def __init__(self, allowed_licenses: Optional[list[str]] = None):
        """
        Initialize Dataset Manager.

        Args:
            allowed_licenses: List of allowed license types
        """
        self._datasets: dict[str, Dataset] = {}
        self._allowed_licenses = allowed_licenses or ["CC-BY", "CC-BY-SA", "CC0"]
        logger.info(f"Dataset Manager initialized with licenses: {self._allowed_licenses}")

    def add_dataset(self, dataset: Dataset) -> bool:
        """
        Add a dataset to the manager.

        Args:
            dataset: Dataset to add

        Returns:
            True if added successfully, False otherwise
        """
        # Validate license
        if not dataset.license.is_compatible_with(self._allowed_licenses):
            logger.warning(
                f"Dataset {dataset.dataset_id} license not compatible: {dataset.license.license_type}"
            )
            return False

        # Calculate quality score
        quality_score = self.calculate_quality_score(dataset)
        dataset.quality_score = quality_score

        # Add to collection
        self._datasets[dataset.dataset_id] = dataset
        logger.info(f"Added dataset {dataset.dataset_id} (quality: {quality_score:.2f})")
        return True

    def remove_dataset(self, dataset_id: str) -> bool:
        """
        Remove a dataset from the manager.

        Args:
            dataset_id: Dataset identifier

        Returns:
            True if removed, False if not found
        """
        if dataset_id in self._datasets:
            del self._datasets[dataset_id]
            logger.info(f"Removed dataset {dataset_id}")
            return True

        logger.warning(f"Dataset {dataset_id} not found")
        return False

    def get_dataset(self, dataset_id: str) -> Optional[Dataset]:
        """
        Get a dataset by ID.

        Args:
            dataset_id: Dataset identifier

        Returns:
            Dataset if found, None otherwise
        """
        return self._datasets.get(dataset_id)

    def list_datasets(self, min_quality: Optional[float] = None) -> list[Dataset]:
        """
        List all datasets, optionally filtered by minimum quality.

        Args:
            min_quality: Minimum quality score filter

        Returns:
            List of datasets
        """
        datasets = list(self._datasets.values())

        if min_quality is not None:
            datasets = [d for d in datasets if d.quality_score >= min_quality]

        return sorted(datasets, key=lambda d: d.quality_score, reverse=True)

    def calculate_quality_score(self, dataset: Dataset) -> float:
        """
        Calculate quality score for a dataset.

        The score is based on multiple factors:
        - Completeness of metadata
        - Consistency of data
        - Size and diversity
        - License permissiveness

        Args:
            dataset: Dataset to score

        Returns:
            Quality score from 0.0 to 1.0
        """
        score = 0.0
        weights_sum = 0.0

        # Metadata completeness (weight: 0.3)
        metadata_weight = 0.3
        metadata_score = self._score_metadata_completeness(dataset)
        score += metadata_score * metadata_weight
        weights_sum += metadata_weight

        # Data consistency (weight: 0.25)
        consistency_weight = 0.25
        consistency_score = self._score_data_consistency(dataset)
        score += consistency_score * consistency_weight
        weights_sum += consistency_weight

        # Dataset size (weight: 0.2)
        size_weight = 0.2
        size_score = self._score_dataset_size(dataset)
        score += size_score * size_weight
        weights_sum += size_weight

        # Diversity (weight: 0.15)
        diversity_weight = 0.15
        diversity_score = self._score_diversity(dataset)
        score += diversity_score * diversity_weight
        weights_sum += diversity_weight

        # License permissiveness (weight: 0.1)
        license_weight = 0.1
        license_score = self._score_license(dataset.license)
        score += license_score * license_weight
        weights_sum += license_weight

        # Normalize
        if weights_sum > 0:
            score = score / weights_sum

        return min(1.0, max(0.0, score))

    def _score_metadata_completeness(self, dataset: Dataset) -> float:
        """
        Score metadata completeness.

        Args:
            dataset: Dataset to score

        Returns:
            Score from 0.0 to 1.0
        """
        if not dataset.tracks:
            return 0.0

        required_fields = ["title", "artist", "genre", "duration"]
        optional_fields = ["album", "year", "mood", "energy", "tempo"]

        total_score = 0.0
        for track in dataset.tracks:
            track_score = 0.0

            # Required fields (70% of score)
            required_present = sum(
                1 for field in required_fields if field in track and track[field]
            )
            track_score += (required_present / len(required_fields)) * 0.7

            # Optional fields (30% of score)
            optional_present = sum(
                1 for field in optional_fields if field in track and track[field]
            )
            track_score += (optional_present / len(optional_fields)) * 0.3

            total_score += track_score

        return total_score / len(dataset.tracks)

    def _score_data_consistency(self, dataset: Dataset) -> float:
        """
        Score data consistency.

        Args:
            dataset: Dataset to score

        Returns:
            Score from 0.0 to 1.0
        """
        if not dataset.tracks:
            return 0.0

        # Check consistency of fields across tracks
        fields_consistency = 0.0
        sample_track = dataset.tracks[0]
        sample_fields = set(sample_track.keys())

        for track in dataset.tracks:
            track_fields = set(track.keys())
            # Calculate field overlap
            if sample_fields:
                overlap = len(sample_fields & track_fields) / len(sample_fields)
                fields_consistency += overlap

        fields_consistency /= len(dataset.tracks)

        # Check for valid values
        valid_values_score = 0.0
        for track in dataset.tracks:
            track_score = 1.0

            # Check duration is positive
            if "duration" in track and track["duration"] <= 0:
                track_score -= 0.2

            # Check energy is in valid range
            if "energy" in track and not 0.0 <= track["energy"] <= 1.0:
                track_score -= 0.2

            valid_values_score += max(0.0, track_score)

        valid_values_score /= len(dataset.tracks)

        return fields_consistency * 0.5 + valid_values_score * 0.5

    def _score_dataset_size(self, dataset: Dataset) -> float:
        """
        Score dataset size.

        Args:
            dataset: Dataset to score

        Returns:
            Score from 0.0 to 1.0
        """
        track_count = len(dataset.tracks)

        # Logarithmic scoring: good datasets have 100+ tracks
        if track_count == 0:
            return 0.0
        elif track_count < 10:
            return 0.2
        elif track_count < 50:
            return 0.4
        elif track_count < 100:
            return 0.6
        elif track_count < 500:
            return 0.8
        else:
            return 1.0

    def _score_diversity(self, dataset: Dataset) -> float:
        """
        Score dataset diversity (genres, artists, etc.).

        Args:
            dataset: Dataset to score

        Returns:
            Score from 0.0 to 1.0
        """
        if not dataset.tracks:
            return 0.0

        # Genre diversity
        genres = set()
        artists = set()

        for track in dataset.tracks:
            if "genre" in track:
                genres.add(track["genre"])
            if "artist" in track:
                artists.add(track["artist"])

        track_count = len(dataset.tracks)

        # Score based on unique genres and artists
        genre_diversity = min(1.0, len(genres) / 10.0)  # 10+ genres = full score
        artist_diversity = min(
            1.0, len(artists) / max(1, track_count / 5)
        )  # Avg 5 tracks per artist

        return genre_diversity * 0.5 + artist_diversity * 0.5

    def _score_license(self, license: DatasetLicense) -> float:
        """
        Score license permissiveness.

        Args:
            license: Dataset license

        Returns:
            Score from 0.0 to 1.0
        """
        score = 0.5  # Base score

        if license.commercial_use:
            score += 0.2

        if license.derivative_works:
            score += 0.2

        if not license.share_alike:
            score += 0.1

        return min(1.0, score)

    def validate_license(self, license: DatasetLicense) -> bool:
        """
        Validate if a license is acceptable.

        Args:
            license: License to validate

        Returns:
            True if valid, False otherwise
        """
        return license.is_compatible_with(self._allowed_licenses)

    def get_statistics(self) -> dict[str, Any]:
        """
        Get statistics about managed datasets.

        Returns:
            Dictionary of statistics
        """
        total_datasets = len(self._datasets)
        total_tracks = sum(d.get_track_count() for d in self._datasets.values())

        avg_quality = 0.0
        if total_datasets > 0:
            avg_quality = sum(d.quality_score for d in self._datasets.values()) / total_datasets

        all_genres = set()
        all_artists = set()
        for dataset in self._datasets.values():
            all_genres.update(dataset.get_genres())
            all_artists.update(dataset.get_artists())

        return {
            "total_datasets": total_datasets,
            "total_tracks": total_tracks,
            "average_quality_score": round(avg_quality, 3),
            "unique_genres": len(all_genres),
            "unique_artists": len(all_artists),
            "allowed_licenses": self._allowed_licenses,
        }

__init__(allowed_licenses=None)

Initialize Dataset Manager.

Parameters:

Name Type Description Default
allowed_licenses Optional[list[str]]

List of allowed license types

None
Source code in qfzz/datasets/manager.py
18
19
20
21
22
23
24
25
26
27
def __init__(self, allowed_licenses: Optional[list[str]] = None):
    """
    Initialize Dataset Manager.

    Args:
        allowed_licenses: List of allowed license types
    """
    self._datasets: dict[str, Dataset] = {}
    self._allowed_licenses = allowed_licenses or ["CC-BY", "CC-BY-SA", "CC0"]
    logger.info(f"Dataset Manager initialized with licenses: {self._allowed_licenses}")

add_dataset(dataset)

Add a dataset to the manager.

Parameters:

Name Type Description Default
dataset Dataset

Dataset to add

required

Returns:

Type Description
bool

True if added successfully, False otherwise

Source code in qfzz/datasets/manager.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def add_dataset(self, dataset: Dataset) -> bool:
    """
    Add a dataset to the manager.

    Args:
        dataset: Dataset to add

    Returns:
        True if added successfully, False otherwise
    """
    # Validate license
    if not dataset.license.is_compatible_with(self._allowed_licenses):
        logger.warning(
            f"Dataset {dataset.dataset_id} license not compatible: {dataset.license.license_type}"
        )
        return False

    # Calculate quality score
    quality_score = self.calculate_quality_score(dataset)
    dataset.quality_score = quality_score

    # Add to collection
    self._datasets[dataset.dataset_id] = dataset
    logger.info(f"Added dataset {dataset.dataset_id} (quality: {quality_score:.2f})")
    return True

calculate_quality_score(dataset)

Calculate quality score for a dataset.

The score is based on multiple factors: - Completeness of metadata - Consistency of data - Size and diversity - License permissiveness

Parameters:

Name Type Description Default
dataset Dataset

Dataset to score

required

Returns:

Type Description
float

Quality score from 0.0 to 1.0

Source code in qfzz/datasets/manager.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
def calculate_quality_score(self, dataset: Dataset) -> float:
    """
    Calculate quality score for a dataset.

    The score is based on multiple factors:
    - Completeness of metadata
    - Consistency of data
    - Size and diversity
    - License permissiveness

    Args:
        dataset: Dataset to score

    Returns:
        Quality score from 0.0 to 1.0
    """
    score = 0.0
    weights_sum = 0.0

    # Metadata completeness (weight: 0.3)
    metadata_weight = 0.3
    metadata_score = self._score_metadata_completeness(dataset)
    score += metadata_score * metadata_weight
    weights_sum += metadata_weight

    # Data consistency (weight: 0.25)
    consistency_weight = 0.25
    consistency_score = self._score_data_consistency(dataset)
    score += consistency_score * consistency_weight
    weights_sum += consistency_weight

    # Dataset size (weight: 0.2)
    size_weight = 0.2
    size_score = self._score_dataset_size(dataset)
    score += size_score * size_weight
    weights_sum += size_weight

    # Diversity (weight: 0.15)
    diversity_weight = 0.15
    diversity_score = self._score_diversity(dataset)
    score += diversity_score * diversity_weight
    weights_sum += diversity_weight

    # License permissiveness (weight: 0.1)
    license_weight = 0.1
    license_score = self._score_license(dataset.license)
    score += license_score * license_weight
    weights_sum += license_weight

    # Normalize
    if weights_sum > 0:
        score = score / weights_sum

    return min(1.0, max(0.0, score))

get_dataset(dataset_id)

Get a dataset by ID.

Parameters:

Name Type Description Default
dataset_id str

Dataset identifier

required

Returns:

Type Description
Optional[Dataset]

Dataset if found, None otherwise

Source code in qfzz/datasets/manager.py
73
74
75
76
77
78
79
80
81
82
83
def get_dataset(self, dataset_id: str) -> Optional[Dataset]:
    """
    Get a dataset by ID.

    Args:
        dataset_id: Dataset identifier

    Returns:
        Dataset if found, None otherwise
    """
    return self._datasets.get(dataset_id)

get_statistics()

Get statistics about managed datasets.

Returns:

Type Description
dict[str, Any]

Dictionary of statistics

Source code in qfzz/datasets/manager.py
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
def get_statistics(self) -> dict[str, Any]:
    """
    Get statistics about managed datasets.

    Returns:
        Dictionary of statistics
    """
    total_datasets = len(self._datasets)
    total_tracks = sum(d.get_track_count() for d in self._datasets.values())

    avg_quality = 0.0
    if total_datasets > 0:
        avg_quality = sum(d.quality_score for d in self._datasets.values()) / total_datasets

    all_genres = set()
    all_artists = set()
    for dataset in self._datasets.values():
        all_genres.update(dataset.get_genres())
        all_artists.update(dataset.get_artists())

    return {
        "total_datasets": total_datasets,
        "total_tracks": total_tracks,
        "average_quality_score": round(avg_quality, 3),
        "unique_genres": len(all_genres),
        "unique_artists": len(all_artists),
        "allowed_licenses": self._allowed_licenses,
    }

list_datasets(min_quality=None)

List all datasets, optionally filtered by minimum quality.

Parameters:

Name Type Description Default
min_quality Optional[float]

Minimum quality score filter

None

Returns:

Type Description
list[Dataset]

List of datasets

Source code in qfzz/datasets/manager.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def list_datasets(self, min_quality: Optional[float] = None) -> list[Dataset]:
    """
    List all datasets, optionally filtered by minimum quality.

    Args:
        min_quality: Minimum quality score filter

    Returns:
        List of datasets
    """
    datasets = list(self._datasets.values())

    if min_quality is not None:
        datasets = [d for d in datasets if d.quality_score >= min_quality]

    return sorted(datasets, key=lambda d: d.quality_score, reverse=True)

remove_dataset(dataset_id)

Remove a dataset from the manager.

Parameters:

Name Type Description Default
dataset_id str

Dataset identifier

required

Returns:

Type Description
bool

True if removed, False if not found

Source code in qfzz/datasets/manager.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def remove_dataset(self, dataset_id: str) -> bool:
    """
    Remove a dataset from the manager.

    Args:
        dataset_id: Dataset identifier

    Returns:
        True if removed, False if not found
    """
    if dataset_id in self._datasets:
        del self._datasets[dataset_id]
        logger.info(f"Removed dataset {dataset_id}")
        return True

    logger.warning(f"Dataset {dataset_id} not found")
    return False

validate_license(license)

Validate if a license is acceptable.

Parameters:

Name Type Description Default
license DatasetLicense

License to validate

required

Returns:

Type Description
bool

True if valid, False otherwise

Source code in qfzz/datasets/manager.py
321
322
323
324
325
326
327
328
329
330
331
def validate_license(self, license: DatasetLicense) -> bool:
    """
    Validate if a license is acceptable.

    Args:
        license: License to validate

    Returns:
        True if valid, False otherwise
    """
    return license.is_compatible_with(self._allowed_licenses)

Dataset

qfzz.datasets.dataset.Dataset dataclass

Represents a GNU/OPENSOURCE dataset

Attributes:

Name Type Description
id str

Unique dataset identifier

name str

Dataset name

description str

Dataset description

license DatasetLicense

Open source license type

source_url str

URL to dataset source

quality_score float

Quality score from 0.0 to 1.0

category str

Dataset category (e.g., "music", "conversation", "knowledge")

size_mb float

Dataset size in megabytes

created_at datetime

Creation timestamp

downloads int

Number of downloads

community_rating float

Community rating score (0.0-1.0)

verified bool

Whether dataset is blockchain verified

Source code in qfzz/datasets/dataset.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@dataclass
class Dataset:
    """Represents a GNU/OPENSOURCE dataset

    Attributes:
        id: Unique dataset identifier
        name: Dataset name
        description: Dataset description
        license: Open source license type
        source_url: URL to dataset source
        quality_score: Quality score from 0.0 to 1.0
        category: Dataset category (e.g., "music", "conversation", "knowledge")
        size_mb: Dataset size in megabytes
        created_at: Creation timestamp
        downloads: Number of downloads
        community_rating: Community rating score (0.0-1.0)
        verified: Whether dataset is blockchain verified
    """

    id: str
    name: str
    description: str
    license: DatasetLicense
    source_url: str
    quality_score: float
    category: str
    size_mb: float
    created_at: datetime = field(default_factory=datetime.now)
    downloads: int = 0
    community_rating: float = 0.0
    verified: bool = False

DatasetLicense

qfzz.datasets.dataset.DatasetLicense

Bases: Enum

Supported open source licenses

Source code in qfzz/datasets/dataset.py
 8
 9
10
11
12
13
14
15
16
17
class DatasetLicense(Enum):
    """Supported open source licenses"""

    GPL = "GPL"
    MIT = "MIT"
    APACHE = "Apache"
    BSD = "BSD"
    CC_BY = "CC-BY"
    CC_BY_SA = "CC-BY-SA"
    PUBLIC_DOMAIN = "Public Domain"

Usage Example

from qfzz import DatasetManager, Dataset, DatasetLicense

# Create manager
manager = DatasetManager(opensource_only=True, min_quality=0.7)

# Register dataset
dataset = Dataset(
    id="ds_001",
    name="OpenMusic Dataset",
    description="High-quality open source music",
    license=DatasetLicense.CC_BY,
    source_url="https://example.com/dataset",
    quality_score=0.9,
    category="music",
    size_mb=150.0
)

success = manager.register_dataset(dataset)
if success:
    manager.verify_dataset_blockchain(dataset.id)

# Get high quality datasets
high_quality = manager.get_high_quality_datasets()
print(f"Found {len(high_quality)} high quality datasets")