Spaces:
Sleeping
Sleeping
Upload 4 files
Browse files- .gitattributes +35 -35
- README.md +13 -13
- app.py +219 -0
- requirements.txt +4 -0
.gitattributes
CHANGED
|
@@ -1,35 +1,35 @@
|
|
| 1 |
-
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
|
@@ -1,13 +1,13 @@
|
|
| 1 |
-
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version: 5.
|
| 8 |
-
app_file: app.py
|
| 9 |
-
pinned: false
|
| 10 |
-
short_description:
|
| 11 |
-
---
|
| 12 |
-
|
| 13 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: HFclone
|
| 3 |
+
emoji: 🏃
|
| 4 |
+
colorFrom: purple
|
| 5 |
+
colorTo: red
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 5.37.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
short_description: '1'
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from huggingface_hub import HfApi
|
| 3 |
+
import os
|
| 4 |
+
import git
|
| 5 |
+
import requests
|
| 6 |
+
import tempfile
|
| 7 |
+
import shutil
|
| 8 |
+
import json
|
| 9 |
+
import threading
|
| 10 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
import base64
|
| 13 |
+
import sys
|
| 14 |
+
import io
|
| 15 |
+
from urllib.parse import unquote
|
| 16 |
+
import time
|
| 17 |
+
|
| 18 |
+
# --- 全局设置 ---
|
| 19 |
+
TEMP_DIR = tempfile.mkdtemp()
|
| 20 |
+
|
| 21 |
+
# --- 日志捕获工具 ---
|
| 22 |
+
class LogCapture:
|
| 23 |
+
def __init__(self): self.log_stream = io.StringIO()
|
| 24 |
+
def __enter__(self): self.old_stdout = sys.stdout; sys.stdout = self.log_stream; return self
|
| 25 |
+
def __exit__(self, exc_type, exc_val, exc_tb): sys.stdout = self.old_stdout
|
| 26 |
+
def get_value(self): return self.log_stream.getvalue()
|
| 27 |
+
|
| 28 |
+
# --- 后端逻辑函数 ---
|
| 29 |
+
def prepare_repo(hf_token, repo_id, repo_type, space_sdk):
|
| 30 |
+
if not hf_token: raise gr.Error("必须提供 Hugging Face Token!")
|
| 31 |
+
if not repo_id: raise gr.Error("必须提供目标 Hugging Face 仓库ID!")
|
| 32 |
+
api = HfApi(token=hf_token)
|
| 33 |
+
try:
|
| 34 |
+
sdk_to_use = space_sdk if repo_type == "space" else None
|
| 35 |
+
api.create_repo(repo_id=repo_id, repo_type=repo_type, space_sdk=sdk_to_use, exist_ok=True)
|
| 36 |
+
return api
|
| 37 |
+
except Exception as e: raise gr.Error(f"创建或访问仓库失败: {e}")
|
| 38 |
+
|
| 39 |
+
class CloneProgress(git.remote.RemoteProgress):
|
| 40 |
+
def __init__(self, progress_bar): super().__init__(); self.progress = progress_bar
|
| 41 |
+
def update(self, op_code, cur_count, max_count=None, message=''):
|
| 42 |
+
if max_count: self.progress(cur_count / max_count, desc=f"克隆中: {message.strip()} ({int(cur_count)}/{int(max_count)})")
|
| 43 |
+
|
| 44 |
+
def clone_github_repo(github_url, progress=gr.Progress()):
|
| 45 |
+
if not github_url: raise gr.Error("必须提供 GitHub 仓库链接!")
|
| 46 |
+
progress(0, desc="准备克隆...")
|
| 47 |
+
repo_name = github_url.split('/')[-1].replace('.git', '')
|
| 48 |
+
clone_path = os.path.join(TEMP_DIR, repo_name)
|
| 49 |
+
if os.path.exists(clone_path): shutil.rmtree(clone_path)
|
| 50 |
+
try: git.Repo.clone_from(github_url, clone_path, progress=CloneProgress(progress))
|
| 51 |
+
except Exception as e: raise gr.Error(f"克隆仓库失败: {e}")
|
| 52 |
+
progress(1, "克隆完成!")
|
| 53 |
+
items = ["上传整个仓库"] + os.listdir(clone_path)
|
| 54 |
+
return gr.update(choices=items, value="上传整个仓库", visible=True), gr.update(visible=True), f"✅ 成功克隆 '{repo_name}'。", clone_path
|
| 55 |
+
|
| 56 |
+
def update_folder_upload_options(selection, clone_path):
|
| 57 |
+
if selection and clone_path and selection != "上传整个仓库":
|
| 58 |
+
if os.path.isdir(os.path.join(clone_path, selection)): return gr.update(visible=True)
|
| 59 |
+
return gr.update(visible=False)
|
| 60 |
+
|
| 61 |
+
def upload_from_github(hf_token, repo_id, repo_type, space_sdk, path_in_repo, selection, folder_upload_mode, clone_path, progress=gr.Progress()):
|
| 62 |
+
if not clone_path: raise gr.Error("克隆路径状态丢失,请重新克隆仓库!")
|
| 63 |
+
progress(0, desc="准备上传...")
|
| 64 |
+
api = prepare_repo(hf_token, repo_id, repo_type, space_sdk)
|
| 65 |
+
source_path = os.path.join(clone_path, selection)
|
| 66 |
+
try:
|
| 67 |
+
if selection == "上传整个仓库":
|
| 68 |
+
progress(0.5, desc=f"正在上传整个仓库 (忽略 .git)...")
|
| 69 |
+
api.upload_folder(folder_path=clone_path, repo_id=repo_id, repo_type=repo_type, path_in_repo=path_in_repo, ignore_patterns=[".git", ".gitignore"])
|
| 70 |
+
message = "📂 成功上传了整个仓库"
|
| 71 |
+
elif os.path.isdir(source_path):
|
| 72 |
+
final_path_in_repo = path_in_repo if folder_upload_mode == "仅上传文件夹内容" else os.path.join(path_in_repo, selection)
|
| 73 |
+
progress(0.5, desc=f"正在上传文件夹 '{selection}'...")
|
| 74 |
+
api.upload_folder(folder_path=source_path, repo_id=repo_id, repo_type=repo_type, path_in_repo=final_path_in_repo)
|
| 75 |
+
message = f"📂 成功上传文件夹 '{selection}'"
|
| 76 |
+
else:
|
| 77 |
+
progress(0.5, desc=f"正在上传文件: {selection}")
|
| 78 |
+
api.upload_file(path_or_fileobj=source_path, repo_id=repo_id, repo_type=repo_type, path_in_repo=os.path.join(path_in_repo, selection))
|
| 79 |
+
message = f"📄 成功上传文件 '{selection}'"
|
| 80 |
+
progress(1, "上传完成!")
|
| 81 |
+
return f"✅ {message} 到 '{repo_id}'."
|
| 82 |
+
except Exception as e: raise gr.Error(f"上传失败: {e}")
|
| 83 |
+
|
| 84 |
+
def download_file_with_progress(url, download_dir, single_file_progress=None):
|
| 85 |
+
try:
|
| 86 |
+
with requests.get(url, stream=True, timeout=30) as r:
|
| 87 |
+
r.raise_for_status()
|
| 88 |
+
filename = unquote(url.split('/')[-1].split('?')[0] or "downloaded_file")
|
| 89 |
+
filepath = os.path.join(download_dir, filename)
|
| 90 |
+
total_size = int(r.headers.get('content-length', 0))
|
| 91 |
+
with open(filepath, 'wb') as f, tqdm(total=total_size, unit='B', unit_scale=True, unit_divisor=1024, desc=f"下载 {filename}", ascii=True, file=sys.stdout) as t:
|
| 92 |
+
chunk_size = 8192
|
| 93 |
+
for chunk in r.iter_content(chunk_size=chunk_size):
|
| 94 |
+
f.write(chunk)
|
| 95 |
+
t.update(len(chunk))
|
| 96 |
+
if single_file_progress and total_size > 0:
|
| 97 |
+
downloaded = t.n; single_file_progress(downloaded / total_size, desc=f"下载中: {filename} ({downloaded/1e6:.2f}/{total_size/1e6:.2f} MB)")
|
| 98 |
+
return filepath
|
| 99 |
+
except Exception as e: print(f"下载失败 {url}: {e}"); return e
|
| 100 |
+
|
| 101 |
+
def download_from_url(url_text, mode, thread_count, progress=gr.Progress()):
|
| 102 |
+
if not url_text: raise gr.Error("必须提供下载链接!")
|
| 103 |
+
urls = [url.strip() for url in url_text.split('\n') if url.strip()]; download_dir = os.path.join(TEMP_DIR, "downloads"); os.makedirs(download_dir, exist_ok=True); downloaded_files, errors = [], []; log_capture = LogCapture()
|
| 104 |
+
yield gr.update(), gr.update(visible=False), gr.update(), gr.update(value="", visible=True), gr.update()
|
| 105 |
+
with log_capture:
|
| 106 |
+
if mode == "单线程":
|
| 107 |
+
for i, url in enumerate(urls):
|
| 108 |
+
progress(i / len(urls), desc=f"开始下载第 {i+1}/{len(urls)} 个文件..."); result = download_file_with_progress(url, download_dir, progress); yield gr.update(), gr.update(), gr.update(), gr.update(value=log_capture.get_value()), gr.update()
|
| 109 |
+
if isinstance(result, str) and os.path.exists(result): downloaded_files.append(result)
|
| 110 |
+
else: errors.append(result)
|
| 111 |
+
else:
|
| 112 |
+
threads = []
|
| 113 |
+
with ThreadPoolExecutor(max_workers=thread_count) as executor:
|
| 114 |
+
for url in urls: threads.append(executor.submit(download_file_with_progress, url, download_dir))
|
| 115 |
+
while any(t.running() for t in threads):
|
| 116 |
+
completed_count = sum(1 for t in threads if t.done()); progress(completed_count / len(threads), desc=f"已完成 {completed_count}/{len(threads)} 个文件下载任务"); yield gr.update(), gr.update(), gr.update(), gr.update(value=log_capture.get_value()), gr.update(); time.sleep(0.5)
|
| 117 |
+
for thread in threads:
|
| 118 |
+
result = thread.result()
|
| 119 |
+
if isinstance(result, str) and os.path.exists(result): downloaded_files.append(result)
|
| 120 |
+
else: errors.append(result)
|
| 121 |
+
progress(1, "所有下载任务已完成!"); status_msg = f"✅ 成功下载 {len(downloaded_files)} 个文件。";
|
| 122 |
+
if errors: status_msg += f" ❌ 失败 {len(errors)} 个: {', '.join(map(str, errors[:2]))}...";
|
| 123 |
+
file_names = [os.path.basename(f) for f in downloaded_files]; final_log = log_capture.get_value()
|
| 124 |
+
yield gr.update(choices=file_names, value=file_names, visible=True), gr.update(visible=True), status_msg, gr.update(value=final_log), download_dir
|
| 125 |
+
|
| 126 |
+
def upload_from_url(hf_token, repo_id, repo_type, space_sdk, path_in_repo, selected_files, download_dir, progress=gr.Progress()):
|
| 127 |
+
if not download_dir: raise gr.Error("下载目录状态丢失,请重新下载文件!");
|
| 128 |
+
if not selected_files: raise gr.Error("请选择要上传的文件!");
|
| 129 |
+
api = prepare_repo(hf_token, repo_id, repo_type, space_sdk)
|
| 130 |
+
for i, filename in enumerate(selected_files): progress((i + 1) / len(selected_files), desc=f"正在上传 {filename}..."); api.upload_file(path_or_fileobj=os.path.join(download_dir, filename), path_in_repo=os.path.join(path_in_repo, filename), repo_id=repo_id, repo_type=repo_type)
|
| 131 |
+
return f"✅ 成功将 {len(selected_files)} 个文件上传到 '{repo_id}'."
|
| 132 |
+
|
| 133 |
+
def upload_from_local(hf_token, repo_id, repo_type, space_sdk, path_in_repo, local_files, progress=gr.Progress()):
|
| 134 |
+
if not local_files: raise gr.Error("请至少上传一个文件!");
|
| 135 |
+
api = prepare_repo(hf_token, repo_id, repo_type, space_sdk);
|
| 136 |
+
for i, file_obj in enumerate(local_files): progress((i + 1) / len(local_files), desc=f"正在上传 {os.path.basename(file_obj.name)}..."); api.upload_file(path_or_fileobj=file_obj.name, path_in_repo=os.path.join(path_in_repo, os.path.basename(file_obj.name)), repo_id=repo_id, repo_type=repo_type)
|
| 137 |
+
return f"✅ 成功上传 {len(local_files)} 个本地文件到 '{repo_id}'."
|
| 138 |
+
|
| 139 |
+
def generate_share_link(repo_id, repo_type, space_sdk, path_in_repo, github_url, url_text, download_mode, thread_count):
|
| 140 |
+
config = {"repo_id": repo_id, "repo_type": repo_type, "space_sdk": space_sdk, "path_in_repo": path_in_repo,"github_url": github_url, "url_text": url_text, "download_mode": download_mode, "thread_count": thread_count}
|
| 141 |
+
encoded = base64.urlsafe_b64encode(json.dumps(config).encode()).decode(); return f"将此编码粘贴到URL参数 `?config=` 后面: \n\n{encoded}"
|
| 142 |
+
|
| 143 |
+
def apply_config(config_data):
|
| 144 |
+
try:
|
| 145 |
+
if isinstance(config_data, str): config = json.loads(base64.urlsafe_b64decode(config_data).decode())
|
| 146 |
+
else:
|
| 147 |
+
with open(config_data.name, "r") as f: config = json.load(f)
|
| 148 |
+
except Exception as e: raise gr.Error(f"解析配置失败: {e}")
|
| 149 |
+
repo_type = config.get("repo_type", "space"); mode = config.get("download_mode", "多线程")
|
| 150 |
+
return gr.update(value=config.get("repo_id", "")),gr.update(value=repo_type),gr.update(value=config.get("space_sdk", "docker"), visible=(repo_type == "space")),gr.update(value=config.get("path_in_repo", "")),gr.update(value=config.get("github_url", "")),gr.update(value=config.get("url_text", "")),gr.update(value=mode),gr.update(value=config.get("thread_count", 8), visible=(mode == "多线程"))
|
| 151 |
+
|
| 152 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="云端同步工具 Pro") as demo:
|
| 153 |
+
gr.Markdown("# ☁️ 云端同步工具 Pro (V11 最终定义修复版)")
|
| 154 |
+
global_progress = gr.Progress()
|
| 155 |
+
status_output = gr.Markdown()
|
| 156 |
+
with gr.Accordion("⚙️ 导入/导出配置", open=False):
|
| 157 |
+
with gr.Row(): gen_link_btn = gr.Button("生成分享配置")
|
| 158 |
+
share_link_output = gr.Textbox(label="分享配置编码", interactive=False, max_lines=3, visible=False)
|
| 159 |
+
with gr.Row():
|
| 160 |
+
config_link_input = gr.Textbox(label="粘贴配置编码", scale=3)
|
| 161 |
+
config_file_input = gr.UploadButton("或上传配置文件", file_types=[".json"])
|
| 162 |
+
apply_config_btn = gr.Button("应用配置", variant="primary")
|
| 163 |
+
gr.Markdown("---")
|
| 164 |
+
gr.Markdown("### **第一步:设置目标仓库**")
|
| 165 |
+
with gr.Row(): hf_token_input = gr.Textbox(label="Hugging Face Token", type="password", info="请提供有 'write' 写入权限的Token。")
|
| 166 |
+
with gr.Row():
|
| 167 |
+
hf_repo_input = gr.Textbox(label="目标 HF 仓库 ID", scale=2)
|
| 168 |
+
hf_repo_type_input = gr.Dropdown(label="仓库类型", choices=["space", "dataset", "model"], value="space")
|
| 169 |
+
hf_space_sdk_input = gr.Dropdown(label="Space SDK", choices=["docker", "gradio", "streamlit", "static"], value="docker", visible=True)
|
| 170 |
+
hf_path_in_repo_input = gr.Textbox(label="仓库内路径 (可选)")
|
| 171 |
+
def toggle_sdk_visibility(repo_type): return gr.update(visible=repo_type == "space")
|
| 172 |
+
hf_repo_type_input.change(fn=toggle_sdk_visibility, inputs=hf_repo_type_input, outputs=hf_space_sdk_input)
|
| 173 |
+
gr.Markdown("### **第二步:选择同步源并执行**")
|
| 174 |
+
with gr.Tabs():
|
| 175 |
+
with gr.TabItem("从 GitHub 同步"):
|
| 176 |
+
github_url_input = gr.Textbox(label="GitHub 仓库链接")
|
| 177 |
+
clone_btn = gr.Button("1. 克隆", variant="secondary")
|
| 178 |
+
upload_github_btn = gr.Button("2. 上传到 Hugging Face", variant="primary", visible=False)
|
| 179 |
+
github_selection_radio = gr.Radio(label="选择要上传的内容", visible=False)
|
| 180 |
+
github_folder_mode_radio = gr.Radio(["上传文件夹本身", "仅上传文件夹内容"], label="文件夹上传模式", value="上传文件夹本身", visible=False)
|
| 181 |
+
github_clone_path_state = gr.State()
|
| 182 |
+
with gr.TabItem("从 URL 链接下载"):
|
| 183 |
+
url_input = gr.TextArea(label="下载链接 (每行一个)")
|
| 184 |
+
with gr.Row():
|
| 185 |
+
url_download_mode = gr.Radio(["单线程", "多线程"], label="下载模式", value="多线程")
|
| 186 |
+
url_thread_count = gr.Number(label="线程数", value=8, minimum=1, maximum=32, step=1, visible=True)
|
| 187 |
+
def toggle_thread_count(mode): return gr.update(visible=mode == "多线程")
|
| 188 |
+
url_download_mode.change(fn=toggle_thread_count, inputs=url_download_mode, outputs=url_thread_count)
|
| 189 |
+
download_btn = gr.Button("1. 下载", variant="secondary")
|
| 190 |
+
upload_url_btn = gr.Button("2. 上传到 Hugging Face", variant="primary", visible=False)
|
| 191 |
+
url_selection_checkbox = gr.CheckboxGroup(label="选择要上传的文件", visible=False)
|
| 192 |
+
download_log_output = gr.Textbox(label="下载日志", lines=10, interactive=False, visible=False)
|
| 193 |
+
url_download_dir_state = gr.State()
|
| 194 |
+
with gr.TabItem("从本地上传"):
|
| 195 |
+
local_file_input = gr.File(label="选择本地文件", file_count="multiple")
|
| 196 |
+
upload_local_btn = gr.Button("上传到 Hugging Face", variant="primary")
|
| 197 |
+
|
| 198 |
+
# --- V11 核心修复: 将所有变量列表的定义移到最前面 ---
|
| 199 |
+
all_config_inputs = [hf_repo_input, hf_repo_type_input, hf_space_sdk_input, hf_path_in_repo_input, github_url_input, url_input, url_download_mode, url_thread_count]
|
| 200 |
+
upload_inputs = [hf_token_input, hf_repo_input, hf_repo_type_input, hf_space_sdk_input, hf_path_in_repo_input]
|
| 201 |
+
|
| 202 |
+
# --- 绑定UI和逻辑 ---
|
| 203 |
+
gen_link_btn.click(fn=generate_share_link, inputs=all_config_inputs, outputs=share_link_output).then(lambda: gr.update(visible=True), outputs=share_link_output)
|
| 204 |
+
def apply_wrapper(config_data, config_link): return apply_config(config_data if config_data else config_link)
|
| 205 |
+
apply_config_btn.click(fn=apply_wrapper, inputs=[config_file_input, config_link_input], outputs=all_config_inputs)
|
| 206 |
+
clone_btn.click(fn=clone_github_repo, inputs=[github_url_input], outputs=[github_selection_radio, upload_github_btn, status_output, github_clone_path_state], api_name="clone_github")
|
| 207 |
+
github_selection_radio.change(fn=update_folder_upload_options, inputs=[github_selection_radio, github_clone_path_state], outputs=github_folder_mode_radio)
|
| 208 |
+
upload_github_btn.click(fn=upload_from_github, inputs=upload_inputs + [github_selection_radio, github_folder_mode_radio, github_clone_path_state], outputs=[status_output], api_name="upload_github")
|
| 209 |
+
download_btn.click(fn=download_from_url, inputs=[url_input, url_download_mode, url_thread_count], outputs=[url_selection_checkbox, upload_url_btn, status_output, download_log_output, url_download_dir_state], api_name="download_url")
|
| 210 |
+
upload_url_btn.click(fn=upload_from_url, inputs=upload_inputs + [url_selection_checkbox, url_download_dir_state], outputs=[status_output], api_name="upload_url")
|
| 211 |
+
upload_local_btn.click(fn=upload_from_local, inputs=upload_inputs + [local_file_input], outputs=[status_output], api_name="upload_local")
|
| 212 |
+
def get_url_params(request: gr.Request):
|
| 213 |
+
if request and "config" in request.query_params: return apply_config(request.query_params["config"])
|
| 214 |
+
return (gr.update(),) * len(all_config_inputs)
|
| 215 |
+
demo.load(get_url_params, inputs=None, outputs=all_config_inputs)
|
| 216 |
+
demo.unload(lambda: shutil.rmtree(TEMP_DIR, ignore_errors=True))
|
| 217 |
+
|
| 218 |
+
if __name__ == "__main__":
|
| 219 |
+
demo.launch(debug=True)
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
huggingface_hub
|
| 3 |
+
GitPython
|
| 4 |
+
requests
|