digiplay commited on
Commit
facffff
·
verified ·
1 Parent(s): 40a8b79

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -0
app.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import torch
4
+ import gradio as gr
5
+ from diffusers import StableDiffusionPipeline, StableDiffusionXLPipeline
6
+ from huggingface_hub import hf_hub_download, HfApi
7
+
8
+ def convert_and_push(source_repo, file_name, model_type, target_repo, hf_token):
9
+ # 檢查 Token 是否為空
10
+ if not hf_token:
11
+ return "❌ 錯誤:請輸入具有寫入權限的 Hugging Face Token!"
12
+
13
+ # 定義暫存目錄,轉換完會刪除
14
+ output_dir = "temp_diffusers_model"
15
+ api = HfApi()
16
+
17
+ try:
18
+ # --- 第一步:從雲端下載檔案 ---
19
+ gr.Info(f"正在從 {source_repo} 下載 {file_name}...")
20
+ # hf_hub_download 會把檔案抓到 Space 的快取暫存區
21
+ local_ckpt_path = hf_hub_download(
22
+ repo_id=source_repo.strip(),
23
+ filename=file_name.strip()
24
+ )
25
+
26
+ # --- 第二步:判斷模型版本並選擇對應的轉換引擎 ---
27
+ # SD 1.5/2.1 與 SDXL 的結構不同,所以必須切換類別
28
+ if model_type == "SDXL":
29
+ gr.Info("偵測到 SDXL,使用 StableDiffusionXLPipeline 轉換...")
30
+ pipeline_class = StableDiffusionXLPipeline
31
+ else:
32
+ gr.Info("使用 StableDiffusionPipeline 轉換 (SD1.5/2.1)...")
33
+ pipeline_class = StableDiffusionPipeline
34
+
35
+ # --- 第三步:執行核心轉換 ---
36
+ # from_single_file 是一個強大的方法,能把單一 .safetensors 拆解成 Diffusers 資料夾結構
37
+ # load_safety_checker=False: 關閉安全檢查器以節省 VRAM/RAM
38
+ # torch_dtype=torch.float32: 在免費 CPU Space 建議用 float32,最穩定
39
+ pipe = pipeline_class.from_single_file(
40
+ local_ckpt_path,
41
+ load_safety_checker=False,
42
+ torch_dtype=torch.float32
43
+ )
44
+
45
+ # 將轉換好的各個子元件(unet, vae, tokenizer 等)存入暫存資料夾
46
+ pipe.save_pretrained(output_dir)
47
+
48
+ # --- 第四步:推送到你的 Hugging Face 倉庫 ---
49
+ gr.Info(f"正在推送到目標倉庫: {target_repo}...")
50
+
51
+ # 1. 自動建立目標倉庫 (如果已經存在則會忽略)
52
+ api.create_repo(
53
+ repo_id=target_repo.strip(),
54
+ token=hf_token,
55
+ exist_ok=True,
56
+ repo_type="model"
57
+ )
58
+
59
+ # 2. 將整個資料夾上傳,這會自動完成 Diffusers 的標準檔案佈局
60
+ api.upload_folder(
61
+ folder_path=output_dir,
62
+ repo_id=target_repo.strip(),
63
+ token=hf_token,
64
+ repo_type="model"
65
+ )
66
+
67
+ # --- 第五步:清理暫存,釋放硬碟空間 ---
68
+ shutil.rmtree(output_dir)
69
+
70
+ return f"✅ 成功完成!\n模型已轉換並推送到:https://huggingface.co{target_repo}"
71
+
72
+ except Exception as e:
73
+ # 發生錯誤時也嘗試清理暫存,避免硬碟爆掉
74
+ if os.path.exists(output_dir):
75
+ shutil.rmtree(output_dir)
76
+ return f"❌ 出錯了:{str(e)}"
77
+
78
+ # --- Gradio UI 排版 ---
79
+ with gr.Blocks(theme=gr.themes.Soft(), title="SD 轉 Diffusers 工具") as demo:
80
+ gr.Markdown("# 🚀 SD to Diffusers 雲端自動推送工具")
81
+ gr.Markdown("本工具能將單一檔案模型 (.safetensors) 直接轉換為 Diffusers 格式並推送到你的個人 Repo。")
82
+
83
+ with gr.Row():
84
+ # 左邊區塊:來源模型資訊
85
+ with gr.Column():
86
+ gr.Markdown("### 📥 1. 來源模型 (Source)")
87
+ src_repo = gr.Textbox(label="來源 Repo ID", placeholder="作者/倉庫名稱")
88
+ src_file = gr.Textbox(label="來源檔案名稱", placeholder="包含副檔名,如 model.safetensors")
89
+ m_type = gr.Radio(["SD1.5 / SD2.1", "SDXL"], label="模型版本", value="SD1.5 / SD2.1")
90
+
91
+ # 右邊區塊:目標位置與金鑰
92
+ with gr.Column():
93
+ gr.Markdown("### 📤 2. 目標設定 (Target)")
94
+ tgt_repo = gr.Textbox(label="你的目標 Repo ID", placeholder="你的名稱/新倉庫名稱")
95
+ hf_token = gr.Textbox(label="Hugging Face Write Token", placeholder="需有 Write 權限的 Token", type="password")
96
+
97
+ # 執行按鈕
98
+ run_btn = gr.Button("🔥 開始轉換並推送", variant="primary")
99
+
100
+ # 狀態回饋
101
+ status_output = gr.Textbox(label="執行進度與狀態", lines=5)
102
+
103
+ # 綁定按鈕動作
104
+ run_btn.click(
105
+ fn=convert_and_push,
106
+ inputs=[src_repo, src_file, m_type, tgt_repo, hf_token],
107
+ outputs=status_output
108
+ )
109
+
110
+ demo.launch()