callback_example/
callback_example.rs

1// 回调示例 - 使用自定义回调来跟踪下载进度
2use async_trait::async_trait;
3use modelscope_ng::{ModelScope, ProgressCallback};
4
5/// 自定义回调实现 - 将进度信息保存到结构体中
6#[derive(Clone)]
7struct CustomCallback;
8
9#[async_trait]
10impl ProgressCallback for CustomCallback {
11    async fn on_file_start(&self, file_name: &str, file_size: u64) {
12        println!("[开始] 文件: {} (大小: {} bytes)", file_name, file_size);
13    }
14
15    async fn on_file_progress(&self, file_name: &str, downloaded: u64, total: u64) {
16        let percent = if total > 0 {
17            (downloaded as f64 / total as f64 * 100.0) as u32
18        } else {
19            0
20        };
21        // 只在进度变化较大时打印,避免输出过多
22        if percent % 10 == 0 || downloaded == total {
23            println!("[进度] {} - {}% ({} / {} bytes)", file_name, percent, downloaded, total);
24        }
25    }
26
27    async fn on_file_complete(&self, file_name: &str) {
28        println!("[完成] {}", file_name);
29    }
30
31    async fn on_file_error(&self, file_name: &str, error: &str) {
32        eprintln!("[错误] {} - {}", file_name, error);
33    }
34}
35
36#[tokio::main]
37async fn main() -> anyhow::Result<()> {
38    // 示例 1: 使用内置的 SimpleCallback(简单打印进度)
39    println!("=== 示例 1: 使用 SimpleCallback ===");
40    ModelScope::download_with_callback(
41        "damo/nlp_structbert_backbone_base_std",
42        "./models",
43        modelscope_ng::SimpleCallback,
44    )
45    .await?;
46
47    // 示例 2: 使用自定义回调
48    println!("\n=== 示例 2: 使用自定义回调 ===");
49    let callback = CustomCallback;
50    ModelScope::download_with_callback(
51        "damo/nlp_structbert_backbone_base_std",
52        "./models_custom",
53        callback,
54    )
55    .await?;
56
57    // 示例 3: 使用进度条回调(默认行为)
58    println!("\n=== 示例 3: 使用进度条回调(默认) ===");
59    ModelScope::download(
60        "damo/nlp_structbert_backbone_base_std",
61        "./models_progress",
62    )
63    .await?;
64
65    // 示例 4: 下载单个文件
66    println!("\n=== 示例 4: 下载单个文件 ===");
67    ModelScope::download_single_file_with_callback(
68        "damo/nlp_structbert_backbone_base_std",
69        "config.json",
70        "./single_file",
71        modelscope_ng::SimpleCallback,
72    )
73    .await?;
74
75    Ok(())
76}