Translsis commited on
Commit
48a7391
·
verified ·
1 Parent(s): e1c5175

Delete app (9).py

Browse files
Files changed (1) hide show
  1. app (9).py +0 -162
app (9).py DELETED
@@ -1,162 +0,0 @@
1
- import gradio as gr
2
- import asyncio, shutil, os, tempfile
3
- from pathlib import Path
4
- from huggingface_hub import HfApi, login, create_repo, upload_file
5
- import git
6
-
7
- # === GLOBAL ===
8
- api = HfApi()
9
- temp_dir = Path(tempfile.mkdtemp())
10
- token = None
11
- last_download_path = None
12
-
13
- def login_hf(t):
14
- global token
15
- if not t or not t.strip():
16
- return "Token không được để trống!"
17
- try:
18
- login(t.strip())
19
- api.whoami(token=t.strip())
20
- token = t.strip()
21
- return "Login thành công! Sẵn sàng sử dụng tất cả chức năng"
22
- except Exception as e:
23
- return f"Login thất bại: {e}"
24
-
25
- async def download(url, type_, progress=gr.Progress()):
26
- global last_download_path
27
- if not url.strip(): return "Nhập URL!", None
28
-
29
- out = temp_dir / "downloaded"
30
- if out.exists(): shutil.rmtree(out)
31
- out.mkdir(parents=True, exist_ok=True)
32
-
33
- try:
34
- progress(0, desc="Chuẩn bị...")
35
- if type_ == "git":
36
- progress(0.2, desc="Clone bằng git...")
37
- await asyncio.to_thread(git.Repo.clone_from, url.strip(), out, depth=1)
38
- else:
39
- progress(0.2, desc="Tải bằng wget...")
40
- proc = await asyncio.create_subprocess_exec(
41
- "wget", "-r", "-np", "-nH", "--cut-dirs=10", "-P", str(out), url.strip(),
42
- stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
43
- )
44
- await proc.communicate()
45
-
46
- count = len(list(out.rglob("*")))
47
- last_download_path = str(out)
48
- return f"Tải thành công! {count} file/thư mục", last_download_path
49
- except Exception as e:
50
- shutil.rmtree(out, ignore_errors=True)
51
- return f"Lỗi tải: {e}", None
52
-
53
- async def create_repo(name, rtype, private):
54
- if not token: return "Chưa login!"
55
- name = name.strip()
56
- if "/" not in name: return "Tên repo sai định dạng!"
57
- try:
58
- create_repo(repo_id=name, repo_type=rtype, private=private, token=token, exist_ok=True)
59
- return f"Tạo repo thành công!\nhttps://huggingface.co/{name}"
60
- except Exception as e:
61
- return f"Lỗi: {e}"
62
-
63
- async def upload(folder, repo, rtype, zip_it, password, use_dl, dl_path, progress=gr.Progress()):
64
- if not token: return "Chưa login!"
65
- repo = repo.strip()
66
- path = Path(dl_path if use_dl and dl_path else folder) if folder or dl_path else None
67
- if not path or not path.exists(): return "Thư mục không tồn tại!"
68
-
69
- try:
70
- if zip_it:
71
- progress(0, desc="Nén ZIP...")
72
- zip_name = f"{repo.split('/')[-1]}_archive.zip"
73
- zip_path = temp_dir / zip_name
74
- cmd = ["zip", "-r"] + (["-P", password] if password else []) + [str(zip_path), "."]
75
- proc = await asyncio.create_subprocess_exec(*cmd, cwd=str(path))
76
- await proc.wait()
77
-
78
- progress(0.7, desc="Upload ZIP...")
79
- await asyncio.to_thread(upload_file, path_or_fileobj=str(zip_path), path_in_repo=zip_name,
80
- repo_id=repo, repo_type=rtype, token=token)
81
- return f"Upload ZIP thành công!\nhttps://huggingface.co/{repo}/blob/main/{zip_name}"
82
- else:
83
- files = [f for f in path.rglob("*") if f.is_file()]
84
- if not files: return "Không có file để upload!"
85
- for i, f in enumerate(files):
86
- rel = f.relative_to(path)
87
- await asyncio.to_thread(upload_file, path_or_fileobj=str(f), path_in_repo=str(rel),
88
- repo_id=repo, repo_type=rtype, token=token)
89
- progress((i+1)/len(files), desc=f"Upload {i+1}/{len(files)}")
90
- return f"Upload thành công {len(files)} file!\nhttps://huggingface.co/{repo}"
91
- except Exception as e:
92
- return f"Upload lỗi: {e}"
93
-
94
- async def delete_files(local, repo, rtype, dry, progress=gr.Progress()):
95
- if not token: return "Chưa login!"
96
- try:
97
- local_path = Path(local)
98
- if not local_path.exists(): return "Thư mục local không tồn tại!"
99
- repo_files = await asyncio.to_thread(api.list_repo_files, repo_id=repo, repo_type=rtype, token=token)
100
- to_del = [str(p.relative_to(local_path)) for p in local_path.rglob("*") if p.is_file() and str(p.relative_to(local_path)) in repo_files]
101
-
102
- if not to_del: return "Không có file nào để xóa."
103
- if dry:
104
- return f"Dry-run: Sẽ xóa {len(to_del)} file:\n" + "\n".join(f"- {f}" for f in to_del[:15]) + \
105
- (f"\n... và {len(to_del)-15} file khác" if len(to_del)>15 else "")
106
-
107
- for i, f in enumerate(to_del):
108
- await asyncio.to_thread(api.delete_file, path_in_repo=f, repo_id=repo, repo_type=rtype, token=token)
109
- progress((i+1)/len(to_del))
110
- return f"Đã xóa {len(to_del)} file thành công!"
111
- except Exception as e:
112
- return f"Lỗi xóa: {e}"
113
-
114
- # ====================== GIAO DIỆN TƯƠNG THÍCH MỌI NỀN TẢNG ======================
115
- with gr.Blocks() as app: # Đã bỏ theme=... để tương thích Gradio cũ
116
- gr.Markdown("# HF Manager Pro\nTải • Tạo • Upload • Xóa - Siêu tiện!")
117
-
118
- with gr.Tab("Login"):
119
- tk = gr.Textbox(label="Token HF", type="password", placeholder="hf_...")
120
- gr.Button("Login").click(login_hf, tk, tk)
121
-
122
- with gr.Tab("Tải xuống"):
123
- url = gr.Textbox(label="URL (GitHub, direct link, git repo)", placeholder="https://...")
124
- typ = gr.Radio(["wget", "git"], label="Phương thức", value="wget")
125
- dl_btn = gr.Button("Tải ngay", variant="primary")
126
- dl_out = gr.Textbox(label="Trạng thái")
127
- dl_path = gr.Textbox(visible=False)
128
- dl_btn.click(download, [url, typ], [dl_out, dl_path])
129
-
130
- with gr.Tab("Tạo Repo"):
131
- name = gr.Textbox(label="Tên repo", placeholder="username/my-model")
132
- rt = gr.Dropdown(["model", "dataset", "space"], value="model", label="Loại")
133
- priv = gr.Checkbox(label="Private", value=True)
134
- gr.Button("Tạo repo", variant="primary").click(create_repo, [name, rt, priv], name)
135
-
136
- with gr.Tab("Upload"):
137
- folder = gr.Textbox(label="Thư mục local (nếu không dùng tải sẵn)", placeholder="/path/to/folder")
138
- use_dl = gr.Checkbox(label="Dùng thư mục vừa tải xuống", value=True)
139
- repo = gr.Textbox(label="Repo đích", placeholder="username/my-model")
140
- rt2 = gr.Dropdown(["model", "dataset", "space"], value="model")
141
- zipc = gr.Checkbox(label="Nén ZIP + có thể đặt mật khẩu")
142
- pw = gr.Textbox(label="Mật khẩu ZIP (tùy chọn)", type="password", visible=False)
143
- zipc.change(lambda x: gr.update(visible=x), zipc, pw)
144
- up_out = gr.Textbox(label="Kết quả", lines=4)
145
- gr.Button("Upload ngay", variant="primary").click(
146
- upload, [folder, repo, rt2, zipc, pw, use_dl, dl_path], up_out
147
- )
148
-
149
- with gr.Tab("Xóa file trên repo"):
150
- loc = gr.Textbox(label="Thư mục local để đối chiếu")
151
- repo2 = gr.Textbox(label="Repo cần xóa")
152
- rt3 = gr.Dropdown(["model", "dataset", "space"], value="model")
153
- dry = gr.Checkbox(label="Chỉ xem trước (Dry-run)", value=True)
154
- del_out = gr.Textbox(label="Kết quả", lines=6)
155
- gr.Button("Thực hiện xóa", variant="stop").click(
156
- delete_files, [loc, repo2, rt3, dry], del_out
157
- )
158
-
159
- gr.Markdown("Mẹo: Tick 'Dùng thư mục vừa tải' để không cần nhập lại đường dẫn!")
160
-
161
- # Khởi chạy tương thích mọi nơi
162
- app.queue().launch(share=True, debug=True)