aprender-core 0.29.2

Next-generation machine learning library in pure Rust
1
2
3
4
5
6
7
8
9
10
11
12
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Model Zoo Protocol (spec ยง8)
//!
//! Defines the protocol for model sharing and discovery in the Aprender ecosystem.
//! Supports interactive.paiml.com, presentar, and the model zoo repository.
//!
//! # Overview
//!
//! The Model Zoo provides:
//! - Standardized model metadata format for discovery
//! - Quality score caching for quick filtering
//! - Version management for model evolution
//! - Download tracking and popularity metrics
//!
//! # Example
//!
//! ```
//! use aprender::zoo::{ModelZooEntry, ModelZooIndex, AuthorInfo};
//!
//! let entry = ModelZooEntry::new(
//!     "linear-regression-housing",
//!     "Housing Price Predictor",
//! )
//! .with_description("Linear regression model for predicting housing prices")
//! .with_author(AuthorInfo::new("Jane Doe", "jane@example.com"))
//! .with_quality_score(85.5)
//! .with_tag("regression")
//! .with_tag("housing");
//!
//! assert_eq!(entry.id, "linear-regression-housing");
//! ```

use std::collections::HashMap;
use std::fmt;

/// Model zoo entry for sharing and discovery
#[derive(Debug, Clone)]
pub struct ModelZooEntry {
    /// Unique model identifier (slug format)
    pub id: String,

    /// Human-readable name
    pub name: String,

    /// Model description
    pub description: String,

    /// Version string (semver)
    pub version: String,

    /// Author information
    pub author: AuthorInfo,

    /// Model type identifier
    pub model_type: ModelZooType,

    /// Quality score (cached, 0-100)
    pub quality_score: f32,

    /// Tags for discovery
    pub tags: Vec<String>,

    /// Download URL
    pub download_url: String,

    /// File size in bytes
    pub size_bytes: u64,

    /// SHA-256 hash for verification
    pub sha256: String,

    /// License identifier (SPDX)
    pub license: String,

    /// Creation timestamp (ISO 8601)
    pub created_at: String,

    /// Last updated timestamp (ISO 8601)
    pub updated_at: String,

    /// Download count
    pub downloads: u64,

    /// Star count (user favorites)
    pub stars: u64,

    /// Custom metadata
    pub metadata: HashMap<String, String>,
}

impl ModelZooEntry {
    /// Create a new model zoo entry
    #[must_use]
    pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            description: String::new(),
            version: "1.0.0".to_string(),
            author: AuthorInfo::default(),
            model_type: ModelZooType::Other,
            quality_score: 0.0,
            tags: Vec::new(),
            download_url: String::new(),
            size_bytes: 0,
            sha256: String::new(),
            license: "MIT".to_string(),
            created_at: String::new(),
            updated_at: String::new(),
            downloads: 0,
            stars: 0,
            metadata: HashMap::new(),
        }
    }

    /// Set description
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = description.into();
        self
    }

    /// Set version
    #[must_use]
    pub fn with_version(mut self, version: impl Into<String>) -> Self {
        self.version = version.into();
        self
    }

    /// Set author
    #[must_use]
    pub fn with_author(mut self, author: AuthorInfo) -> Self {
        self.author = author;
        self
    }

    /// Set model type
    #[must_use]
    pub fn with_model_type(mut self, model_type: ModelZooType) -> Self {
        self.model_type = model_type;
        self
    }

    /// Set quality score
    #[must_use]
    pub fn with_quality_score(mut self, score: f32) -> Self {
        self.quality_score = score.clamp(0.0, 100.0);
        self
    }

    /// Add a tag
    #[must_use]
    pub fn with_tag(mut self, tag: impl Into<String>) -> Self {
        self.tags.push(tag.into());
        self
    }

    /// Set download URL
    #[must_use]
    pub fn with_download_url(mut self, url: impl Into<String>) -> Self {
        self.download_url = url.into();
        self
    }

    /// Set file size
    #[must_use]
    pub fn with_size(mut self, size_bytes: u64) -> Self {
        self.size_bytes = size_bytes;
        self
    }

    /// Set SHA-256 hash
    #[must_use]
    pub fn with_sha256(mut self, hash: impl Into<String>) -> Self {
        self.sha256 = hash.into();
        self
    }

    /// Set license
    #[must_use]
    pub fn with_license(mut self, license: impl Into<String>) -> Self {
        self.license = license.into();
        self
    }

    /// Set timestamps
    #[must_use]
    pub fn with_timestamps(
        mut self,
        created: impl Into<String>,
        updated: impl Into<String>,
    ) -> Self {
        self.created_at = created.into();
        self.updated_at = updated.into();
        self
    }

    /// Add custom metadata
    #[must_use]
    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Get human-readable file size
    #[must_use]
    pub fn human_size(&self) -> String {
        human_bytes(self.size_bytes)
    }

    /// Check if entry matches search query
    #[must_use]
    pub fn matches_query(&self, query: &str) -> bool {
        let query_lower = query.to_lowercase();
        self.id.to_lowercase().contains(&query_lower)
            || self.name.to_lowercase().contains(&query_lower)
            || self.description.to_lowercase().contains(&query_lower)
            || self
                .tags
                .iter()
                .any(|t| t.to_lowercase().contains(&query_lower))
    }

    /// Check if entry has tag
    #[must_use]
    pub fn has_tag(&self, tag: &str) -> bool {
        let tag_lower = tag.to_lowercase();
        self.tags.iter().any(|t| t.to_lowercase() == tag_lower)
    }

    /// Get quality grade letter
    #[must_use]
    pub fn quality_grade(&self) -> &'static str {
        match self.quality_score {
            s if s >= 97.0 => "A+",
            s if s >= 93.0 => "A",
            s if s >= 90.0 => "A-",
            s if s >= 87.0 => "B+",
            s if s >= 83.0 => "B",
            s if s >= 80.0 => "B-",
            s if s >= 77.0 => "C+",
            s if s >= 73.0 => "C",
            s if s >= 70.0 => "C-",
            s if s >= 60.0 => "D",
            _ => "F",
        }
    }
}

impl fmt::Display for ModelZooEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "{} ({})", self.name, self.id)?;
        writeln!(
            f,
            "  Version: {} | Size: {} | Quality: {:.0} ({})",
            self.version,
            self.human_size(),
            self.quality_score,
            self.quality_grade()
        )?;
        if !self.description.is_empty() {
            writeln!(f, "  {}", self.description)?;
        }
        if !self.tags.is_empty() {
            writeln!(f, "  Tags: {}", self.tags.join(", "))?;
        }
        Ok(())
    }
}

/// Author information
#[derive(Debug, Clone, Default)]
pub struct AuthorInfo {
    /// Author name
    pub name: String,
    /// Author email
    pub email: String,
    /// Author URL (optional)
    pub url: Option<String>,
    /// Organization (optional)
    pub organization: Option<String>,
}

impl AuthorInfo {
    /// Create new author info
    #[must_use]
    pub fn new(name: impl Into<String>, email: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            email: email.into(),
            url: None,
            organization: None,
        }
    }

    /// Set URL
    #[must_use]
    pub fn with_url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }

    /// Set organization
    #[must_use]
    pub fn with_organization(mut self, org: impl Into<String>) -> Self {
        self.organization = Some(org.into());
        self
    }
}

impl fmt::Display for AuthorInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name)?;
        if !self.email.is_empty() {
            write!(f, " <{}>", self.email)?;
        }
        if let Some(org) = &self.organization {
            write!(f, " ({org})")?;
        }
        Ok(())
    }
}

/// Model type for zoo classification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ModelZooType {
    /// Linear regression
    LinearRegression,
    /// Logistic regression
    LogisticRegression,
    /// Decision tree
    DecisionTree,
    /// Random forest
    RandomForest,
    /// Gradient boosting
    GradientBoosting,
    /// K-Nearest Neighbors
    Knn,
    /// K-Means clustering
    KMeans,
    /// Support Vector Machine
    Svm,
    /// Naive Bayes
    NaiveBayes,
    /// Neural network
    NeuralNetwork,
    /// Ensemble model
    Ensemble,
    /// Time series (ARIMA, etc.)
    TimeSeries,
    /// Other/custom
    #[default]
    Other,
}

impl ModelZooType {
    /// Get type name
    #[must_use]
    pub const fn name(&self) -> &'static str {
        match self {
            Self::LinearRegression => "Linear Regression",
            Self::LogisticRegression => "Logistic Regression",
            Self::DecisionTree => "Decision Tree",
            Self::RandomForest => "Random Forest",
            Self::GradientBoosting => "Gradient Boosting",
            Self::Knn => "K-Nearest Neighbors",
            Self::KMeans => "K-Means",
            Self::Svm => "SVM",
            Self::NaiveBayes => "Naive Bayes",
            Self::NeuralNetwork => "Neural Network",
            Self::Ensemble => "Ensemble",
            Self::TimeSeries => "Time Series",
            Self::Other => "Other",
        }
    }

    /// Get category
    #[must_use]
    pub const fn category(&self) -> ModelCategory {
        match self {
            Self::LinearRegression => ModelCategory::Regression,
            Self::LogisticRegression
            | Self::DecisionTree
            | Self::RandomForest
            | Self::GradientBoosting
            | Self::Knn
            | Self::Svm
            | Self::NaiveBayes => ModelCategory::Classification,
            Self::KMeans => ModelCategory::Clustering,
            Self::NeuralNetwork => ModelCategory::DeepLearning,
            Self::Ensemble => ModelCategory::Ensemble,
            Self::TimeSeries => ModelCategory::TimeSeries,
            Self::Other => ModelCategory::Other,
        }
    }
}

impl fmt::Display for ModelZooType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

/// Model category for filtering
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ModelCategory {
    /// Regression models
    Regression,
    /// Classification models
    Classification,
    /// Clustering models
    Clustering,
    /// Deep learning models
    DeepLearning,
    /// Ensemble models
    Ensemble,
    /// Time series models
    TimeSeries,
    /// Other
    Other,
}

impl ModelCategory {
    /// Get category name
    #[must_use]
    pub const fn name(&self) -> &'static str {
        match self {
            Self::Regression => "Regression",
            Self::Classification => "Classification",
            Self::Clustering => "Clustering",
            Self::DeepLearning => "Deep Learning",
            Self::Ensemble => "Ensemble",
            Self::TimeSeries => "Time Series",
            Self::Other => "Other",
        }
    }
}

impl fmt::Display for ModelCategory {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

include!("index.rs");