chatyou commited on
Commit
8a38b7c
·
verified ·
1 Parent(s): 826fd80

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +392 -61
app.py CHANGED
@@ -1,11 +1,7 @@
1
  import os
2
  import tempfile
3
  from flask import Flask, request, jsonify, send_file
4
- from huggingface_hub import (
5
- batch_bucket_files,
6
- download_bucket_files,
7
- list_bucket_tree
8
- )
9
 
10
  app = Flask(__name__)
11
 
@@ -14,73 +10,359 @@ HF_TOKEN = os.environ.get("HF_TOKEN")
14
  if not HF_TOKEN:
15
  raise ValueError("HF_TOKEN environment variable not set. Please add it to Space Secrets.")
16
 
 
 
17
  # 你的 Bucket ID(格式:用户名/存储桶名)
18
  BUCKET_ID = "nagose/filebed"
19
 
20
- # 嵌入 HTML 前端(完整保留)
21
  HTML_CONTENT = """<!DOCTYPE html>
22
- <html>
23
  <head>
24
  <meta charset="UTF-8">
25
- <title>HF Bucket 上传</title>
 
26
  <style>
27
- body { font-family: sans-serif; max-width: 800px; margin: 20px auto; }
28
- .log { background: #1e293b; color: #b9e6f0; padding: 12px; border-radius: 8px; max-height: 300px; overflow: auto; }
29
- .file-item { display: flex; justify-content: space-between; padding: 10px; background: #f8fafc; margin-bottom: 8px; }
30
- button { padding: 8px 16px; background: #2563eb; color: white; border: none; border-radius: 4px; cursor: pointer; }
31
- button.danger { background: #dc2626; }
32
- input[type="file"] { margin: 10px 0; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  </style>
34
  </head>
35
  <body>
36
- <h1>HF Bucket 上传测试</h1>
37
- <input type="file" id="fileInput">
38
- <button id="uploadBtn">上传</button>
39
- <div class="log" id="log"></div>
40
- <h2>文件列表</h2>
41
- <div id="fileList"></div>
42
-
43
- <script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  const fileInput = document.getElementById('fileInput');
45
  const uploadBtn = document.getElementById('uploadBtn');
 
46
  const logDiv = document.getElementById('log');
47
  const fileListDiv = document.getElementById('fileList');
 
 
 
 
 
 
48
 
 
49
  function addLog(msg, isErr = false) {
50
  const p = document.createElement('p');
51
- p.textContent = `[${new Date().toLocaleTimeString()}] ${isErr ? '❌ ' : ''}${msg}`;
 
52
  if (isErr) p.style.color = '#f87171';
53
  logDiv.appendChild(p);
54
  logDiv.scrollTop = logDiv.scrollHeight;
55
  }
 
56
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  async function loadList() {
58
  try {
 
59
  const res = await fetch('/list');
 
 
 
 
60
  const files = await res.json();
61
- if (files.length === 0) fileListDiv.innerHTML = '<p>暂无文件</p>';
62
- else {
 
63
  fileListDiv.innerHTML = files.map(f => `
64
  <div class="file-item">
65
- <a href="/file/${encodeURIComponent(f)}" target="_blank">${f}</a>
66
- <button class="danger" onclick="deleteFile('${f.replace(/'/g, "\\\\'")}')">删除</button>
67
  </div>
68
  `).join('');
69
  }
70
  } catch (err) {
71
- fileListDiv.innerHTML = '<p>加载失败</p>';
 
72
  }
73
  }
74
 
 
75
  window.deleteFile = async function(filename) {
76
- if (!confirm('确定删除?')) return;
77
- const res = await fetch('/delete/' + encodeURIComponent(filename), { method: 'DELETE' });
78
- if (res.ok) loadList();
 
 
 
 
 
 
 
 
79
  };
80
 
 
 
 
 
 
 
 
 
 
 
81
  uploadBtn.addEventListener('click', async () => {
82
  const file = fileInput.files[0];
83
- if (!file) return alert('请选择文件');
 
 
84
  addLog('开始上传: ' + file.name);
85
  uploadBtn.disabled = true;
86
 
@@ -90,13 +372,11 @@ HTML_CONTENT = """<!DOCTYPE html>
90
  try {
91
  const res = await fetch('/upload', { method: 'POST', body: formData });
92
  const data = await res.json();
93
- if (res.ok) {
94
- addLog('✅ 上传成功');
95
- fileInput.value = '';
96
- loadList();
97
- } else {
98
- addLog('❌ ' + data.error, true);
99
- }
100
  } catch (err) {
101
  addLog('❌ ' + err.message, true);
102
  } finally {
@@ -104,8 +384,59 @@ HTML_CONTENT = """<!DOCTYPE html>
104
  }
105
  });
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  loadList();
108
- </script>
 
109
  </body>
110
  </html>"""
111
 
@@ -124,11 +455,12 @@ def upload():
124
  with tempfile.NamedTemporaryFile(delete=False) as tmp:
125
  file.save(tmp.name)
126
  try:
127
- # 使用 batch_bucket_files 上传文件(与文档完全一致)
128
- batch_bucket_files(
129
- bucket_id=BUCKET_ID,
130
- add=[(tmp.name, file.filename)],
131
- token=HF_TOKEN # 显式传递 token 确保认证
 
132
  )
133
  except Exception as e:
134
  return jsonify({'error': str(e)}), 500
@@ -140,13 +472,10 @@ def upload():
140
  @app.route('/list')
141
  def list_files():
142
  try:
143
- # 使用 list_bucket_tree 获取文件列表
144
- items = list_bucket_tree(
145
- bucket_id=BUCKET_ID,
146
- recursive=True,
147
- token=HF_TOKEN
148
  )
149
- files = [item.path for item in items if item.type == 'file']
150
  return jsonify(files)
151
  except Exception as e:
152
  return jsonify({'error': str(e)}), 500
@@ -154,12 +483,15 @@ def list_files():
154
  @app.route('/file/<path:filename>')
155
  def get_file(filename):
156
  try:
 
 
 
157
  with tempfile.TemporaryDirectory() as tmpdir:
158
- local_path = os.path.join(tmpdir, filename)
159
- # 使用 download_bucket_files 下载文件
160
- download_bucket_files(
161
- bucket_id=BUCKET_ID,
162
- files=[(filename, local_path)],
163
  token=HF_TOKEN
164
  )
165
  return send_file(local_path, as_attachment=True, download_name=filename)
@@ -169,11 +501,10 @@ def get_file(filename):
169
  @app.route('/delete/<path:filename>', methods=['DELETE'])
170
  def delete_file(filename):
171
  try:
172
- # 使用 batch_bucket_files 删除文件(通过 delete 参数)
173
- batch_bucket_files(
174
- bucket_id=BUCKET_ID,
175
- delete=[filename],
176
- token=HF_TOKEN
177
  )
178
  return jsonify({'success': True})
179
  except Exception as e:
 
1
  import os
2
  import tempfile
3
  from flask import Flask, request, jsonify, send_file
4
+ from huggingface_hub import HfApi
 
 
 
 
5
 
6
  app = Flask(__name__)
7
 
 
10
  if not HF_TOKEN:
11
  raise ValueError("HF_TOKEN environment variable not set. Please add it to Space Secrets.")
12
 
13
+ api = HfApi(token=HF_TOKEN)
14
+
15
  # 你的 Bucket ID(格式:用户名/存储桶名)
16
  BUCKET_ID = "nagose/filebed"
17
 
18
+ # 美化后的 HTML 前端(包含文件管理和 API 测试)
19
  HTML_CONTENT = """<!DOCTYPE html>
20
+ <html lang="zh-CN">
21
  <head>
22
  <meta charset="UTF-8">
23
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
24
+ <title>HF Bucket 文件管理 · 美化版</title>
25
  <style>
26
+ * { margin: 0; padding: 0; box-sizing: border-box; }
27
+ body {
28
+ font-family: 'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
29
+ background: linear-gradient(145deg, #f0f4fa 0%, #e6ecf4 100%);
30
+ min-height: 100vh;
31
+ padding: 2rem 1rem;
32
+ display: flex;
33
+ justify-content: center;
34
+ align-items: center;
35
+ }
36
+ .container {
37
+ max-width: 1200px;
38
+ width: 100%;
39
+ margin: 0 auto;
40
+ }
41
+ .grid {
42
+ display: grid;
43
+ grid-template-columns: 1fr 1fr;
44
+ gap: 1.5rem;
45
+ }
46
+ .card {
47
+ background: rgba(255, 255, 255, 0.8);
48
+ backdrop-filter: blur(10px);
49
+ -webkit-backdrop-filter: blur(10px);
50
+ border: 1px solid rgba(255, 255, 255, 0.5);
51
+ border-radius: 28px;
52
+ box-shadow: 0 20px 40px -12px rgba(0, 20, 40, 0.25);
53
+ padding: 1.8rem;
54
+ transition: transform 0.2s ease, box-shadow 0.2s ease;
55
+ }
56
+ .card:hover {
57
+ transform: translateY(-4px);
58
+ box-shadow: 0 30px 50px -15px rgba(0, 30, 60, 0.3);
59
+ }
60
+ h2 {
61
+ font-size: 1.8rem;
62
+ font-weight: 600;
63
+ margin-bottom: 1.5rem;
64
+ color: #1a2b3c;
65
+ display: flex;
66
+ align-items: center;
67
+ gap: 0.5rem;
68
+ }
69
+ h2::before {
70
+ font-size: 2rem;
71
+ }
72
+ .upload-area {
73
+ display: flex;
74
+ flex-direction: column;
75
+ gap: 1.2rem;
76
+ margin-bottom: 2rem;
77
+ }
78
+ .file-label {
79
+ background: #f1f5f9;
80
+ border-radius: 60px;
81
+ padding: 0.8rem 1.5rem;
82
+ display: inline-flex;
83
+ align-items: center;
84
+ gap: 0.8rem;
85
+ border: 2px dashed #b0c4de;
86
+ cursor: pointer;
87
+ transition: all 0.2s;
88
+ width: fit-content;
89
+ font-weight: 500;
90
+ color: #1e293b;
91
+ }
92
+ .file-label:hover {
93
+ background: #e2eaf3;
94
+ border-color: #3b82f6;
95
+ }
96
+ input[type="file"] { display: none; }
97
+ .button {
98
+ background: #3b82f6;
99
+ border: none;
100
+ color: white;
101
+ font-weight: 600;
102
+ padding: 0.8rem 2rem;
103
+ border-radius: 40px;
104
+ font-size: 1rem;
105
+ cursor: pointer;
106
+ box-shadow: 0 6px 14px rgba(59, 130, 246, 0.3);
107
+ transition: all 0.15s ease;
108
+ width: fit-content;
109
+ border: 1px solid rgba(255,255,255,0.2);
110
+ }
111
+ .button:hover {
112
+ background: #2563eb;
113
+ transform: scale(1.02);
114
+ box-shadow: 0 10px 20px rgba(37, 99, 235, 0.4);
115
+ }
116
+ .button.secondary {
117
+ background: #64748b;
118
+ box-shadow: 0 6px 14px rgba(100, 116, 139, 0.3);
119
+ }
120
+ .button.secondary:hover {
121
+ background: #475569;
122
+ }
123
+ .button.danger {
124
+ background: #ef4444;
125
+ box-shadow: 0 6px 14px rgba(239, 68, 68, 0.25);
126
+ }
127
+ .button.danger:hover {
128
+ background: #dc2626;
129
+ }
130
+ .button.small {
131
+ padding: 0.4rem 1rem;
132
+ font-size: 0.9rem;
133
+ }
134
+ .log {
135
+ background: #1e293b;
136
+ color: #b9e6f0;
137
+ padding: 1.2rem;
138
+ border-radius: 24px;
139
+ font-family: 'JetBrains Mono', monospace;
140
+ font-size: 0.9rem;
141
+ border-left: 6px solid #3b82f6;
142
+ white-space: pre-wrap;
143
+ max-height: 250px;
144
+ overflow: auto;
145
+ margin-top: 1.5rem;
146
+ }
147
+ .log p { margin: 0.2rem 0; }
148
+ .timestamp { color: #94a3b8; margin-right: 0.5rem; }
149
+ .file-list {
150
+ display: flex;
151
+ flex-direction: column;
152
+ gap: 0.6rem;
153
+ margin-top: 1rem;
154
+ max-height: 300px;
155
+ overflow-y: auto;
156
+ padding-right: 0.5rem;
157
+ }
158
+ .file-item {
159
+ display: flex;
160
+ justify-content: space-between;
161
+ align-items: center;
162
+ background: #ffffffd6;
163
+ backdrop-filter: blur(4px);
164
+ padding: 0.8rem 1.5rem;
165
+ border-radius: 40px;
166
+ box-shadow: 0 4px 8px rgba(0,0,0,0.02);
167
+ border: 1px solid rgba(255,255,255,0.6);
168
+ }
169
+ .file-link {
170
+ color: #1e3a8a;
171
+ font-weight: 500;
172
+ text-decoration: none;
173
+ word-break: break-all;
174
+ }
175
+ .file-link:hover {
176
+ text-decoration: underline;
177
+ color: #2563eb;
178
+ }
179
+ .empty-message {
180
+ text-align: center;
181
+ color: #64748b;
182
+ padding: 2rem;
183
+ font-style: italic;
184
+ }
185
+ .api-test {
186
+ display: flex;
187
+ flex-direction: column;
188
+ gap: 1rem;
189
+ }
190
+ .api-row {
191
+ display: flex;
192
+ align-items: center;
193
+ gap: 1rem;
194
+ flex-wrap: wrap;
195
+ }
196
+ .api-input {
197
+ flex: 1;
198
+ padding: 0.8rem 1.2rem;
199
+ border-radius: 40px;
200
+ border: 1px solid #cbd5e1;
201
+ font-size: 1rem;
202
+ background: white;
203
+ }
204
+ .api-result {
205
+ background: #1e293b;
206
+ color: #b9e6f0;
207
+ padding: 1rem;
208
+ border-radius: 20px;
209
+ font-family: monospace;
210
+ font-size: 0.9rem;
211
+ white-space: pre-wrap;
212
+ max-height: 200px;
213
+ overflow: auto;
214
+ }
215
+ footer {
216
+ margin-top: 2rem;
217
+ text-align: center;
218
+ color: #64748b;
219
+ font-size: 0.9rem;
220
+ }
221
+ @media (max-width: 768px) {
222
+ .grid { grid-template-columns: 1fr; }
223
+ }
224
  </style>
225
  </head>
226
  <body>
227
+ <div class="container">
228
+ <h1 style="font-size: 2.5rem; margin-bottom: 2rem; color: #0f172a;">📦 HF Bucket 管理器</h1>
229
+ <div class="grid">
230
+ <!-- 左侧:文件上传与列表 -->
231
+ <div class="card">
232
+ <h2>📤 文件上传</h2>
233
+ <div class="upload-area">
234
+ <label for="fileInput" class="file-label" id="fileLabel">📎 选择文件</label>
235
+ <input type="file" id="fileInput">
236
+ <button class="button" id="uploadBtn">⬆️ 上传到 Bucket</button>
237
+ </div>
238
+ <h2 style="margin-top: 2rem;">📁 文件列表</h2>
239
+ <div id="fileList" class="file-list">
240
+ <div class="empty-message">加载中...</div>
241
+ </div>
242
+ <div class="log" id="log">就绪</div>
243
+ </div>
244
+
245
+ <!-- 右侧:API 测试面板 -->
246
+ <div class="card">
247
+ <h2>🧪 API 测试</h2>
248
+ <div class="api-test">
249
+ <div class="api-row">
250
+ <button class="button secondary small" id="apiListBtn">📋 列出文件</button>
251
+ <span style="color:#64748b;">GET /list</span>
252
+ </div>
253
+ <div class="api-row">
254
+ <input type="text" class="api-input" id="apiFilename" placeholder="输入文件名(如 test.txt)">
255
+ <button class="button secondary small" id="apiGetBtn">📥 获取文件</button>
256
+ <span style="color:#64748b;">GET /file/&lt;filename&gt;</span>
257
+ </div>
258
+ <div class="api-row">
259
+ <input type="text" class="api-input" id="apiDeleteFilename" placeholder="要删除的文件名">
260
+ <button class="button danger small" id="apiDeleteBtn">🗑️ 删除文件</button>
261
+ <span style="color:#64748b;">DELETE /delete/&lt;filename&gt;</span>
262
+ </div>
263
+ <div class="api-row">
264
+ <span style="color:#64748b;">上传请使用左侧表单</span>
265
+ </div>
266
+ <div class="api-result" id="apiResult">点击按钮查看结果</div>
267
+ </div>
268
+ </div>
269
+ </div>
270
+ <footer>Powered by Hugging Face Buckets · 安全令牌通过环境变量注入</footer>
271
+ </div>
272
+
273
+ <script>
274
+ (function() {
275
+ // DOM 元素
276
  const fileInput = document.getElementById('fileInput');
277
  const uploadBtn = document.getElementById('uploadBtn');
278
+ const fileLabel = document.getElementById('fileLabel');
279
  const logDiv = document.getElementById('log');
280
  const fileListDiv = document.getElementById('fileList');
281
+ const apiResult = document.getElementById('apiResult');
282
+ const apiListBtn = document.getElementById('apiListBtn');
283
+ const apiGetBtn = document.getElementById('apiGetBtn');
284
+ const apiDeleteBtn = document.getElementById('apiDeleteBtn');
285
+ const apiFilename = document.getElementById('apiFilename');
286
+ const apiDeleteFilename = document.getElementById('apiDeleteFilename');
287
 
288
+ // 辅助函数:添加日志
289
  function addLog(msg, isErr = false) {
290
  const p = document.createElement('p');
291
+ const ts = new Date().toLocaleTimeString();
292
+ p.innerHTML = '<span class="timestamp">[' + ts + ']</span> ' + (isErr ? '❌ ' : '') + msg;
293
  if (isErr) p.style.color = '#f87171';
294
  logDiv.appendChild(p);
295
  logDiv.scrollTop = logDiv.scrollHeight;
296
  }
297
+ function clearLog() { logDiv.innerHTML = ''; }
298
 
299
+ // 显示 API 结果
300
+ function showApiResult(data, isError = false) {
301
+ if (typeof data === 'object') {
302
+ apiResult.textContent = JSON.stringify(data, null, 2);
303
+ } else {
304
+ apiResult.textContent = data;
305
+ }
306
+ if (isError) apiResult.style.color = '#f87171';
307
+ else apiResult.style.color = '#b9e6f0';
308
+ }
309
+
310
+ // 加载文件列表
311
  async function loadList() {
312
  try {
313
+ fileListDiv.innerHTML = '<div class="empty-message">加载中...</div>';
314
  const res = await fetch('/list');
315
+ if (!res.ok) {
316
+ const err = await res.text();
317
+ throw new Error(`HTTP ${res.status}: ${err}`);
318
+ }
319
  const files = await res.json();
320
+ if (files.length === 0) {
321
+ fileListDiv.innerHTML = '<div class="empty-message">📭 暂无文件</div>';
322
+ } else {
323
  fileListDiv.innerHTML = files.map(f => `
324
  <div class="file-item">
325
+ <a href="/file/${encodeURIComponent(f)}" target="_blank" class="file-link">${f}</a>
326
+ <button class="button danger small" onclick="deleteFile('${f.replace(/'/g, "\\\\'")}')">删除</button>
327
  </div>
328
  `).join('');
329
  }
330
  } catch (err) {
331
+ fileListDiv.innerHTML = '<div class="empty-message">❌ 加载失败</div>';
332
+ addLog('列表加载错误: ' + err.message, true);
333
  }
334
  }
335
 
336
+ // 删除文件(全局函数,供按钮调用)
337
  window.deleteFile = async function(filename) {
338
+ if (!confirm(`确定删除 ${filename} 吗?`)) return;
339
+ try {
340
+ addLog('正在删除: ' + filename);
341
+ const res = await fetch('/delete/' + encodeURIComponent(filename), { method: 'DELETE' });
342
+ const text = await res.text();
343
+ if (!res.ok) throw new Error(`删除失败 (${res.status}): ${text}`);
344
+ addLog('✅ 删除成功: ' + filename);
345
+ loadList();
346
+ } catch (err) {
347
+ addLog(err.message, true);
348
+ }
349
  };
350
 
351
+ // 文件选择显示
352
+ fileInput.addEventListener('change', function() {
353
+ if (fileInput.files.length > 0) {
354
+ fileLabel.textContent = '📄 ' + fileInput.files[0].name;
355
+ } else {
356
+ fileLabel.textContent = '📎 选择文件';
357
+ }
358
+ });
359
+
360
+ // 上传按钮
361
  uploadBtn.addEventListener('click', async () => {
362
  const file = fileInput.files[0];
363
+ if (!file) { alert('请选择文件'); return; }
364
+
365
+ clearLog();
366
  addLog('开始上传: ' + file.name);
367
  uploadBtn.disabled = true;
368
 
 
372
  try {
373
  const res = await fetch('/upload', { method: 'POST', body: formData });
374
  const data = await res.json();
375
+ if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
376
+ addLog('✅ 上传成功!');
377
+ fileInput.value = '';
378
+ fileLabel.textContent = '📎 选择文件';
379
+ loadList();
 
 
380
  } catch (err) {
381
  addLog('❌ ' + err.message, true);
382
  } finally {
 
384
  }
385
  });
386
 
387
+ // API 测试:列出文件
388
+ apiListBtn.addEventListener('click', async () => {
389
+ try {
390
+ showApiResult('正在请求 /list ...');
391
+ const res = await fetch('/list');
392
+ const data = await res.json();
393
+ if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
394
+ showApiResult(data);
395
+ } catch (err) {
396
+ showApiResult(err.message, true);
397
+ }
398
+ });
399
+
400
+ // API 测试:获取文件
401
+ apiGetBtn.addEventListener('click', async () => {
402
+ const filename = apiFilename.value.trim();
403
+ if (!filename) { alert('请输入文件名'); return; }
404
+ try {
405
+ showApiResult('正在请求 /file/' + filename + ' ...');
406
+ // 这里我们只是展示文件的元信息,实际下载会跳转
407
+ const res = await fetch('/file/' + encodeURIComponent(filename), { method: 'HEAD' });
408
+ if (res.ok) {
409
+ showApiResult({ status: 'OK', url: '/file/' + filename, message: '文件可访问,点击链接下载' });
410
+ } else {
411
+ const text = await res.text();
412
+ throw new Error(`HTTP ${res.status}: ${text}`);
413
+ }
414
+ } catch (err) {
415
+ showApiResult(err.message, true);
416
+ }
417
+ });
418
+
419
+ // API 测试:删除文件
420
+ apiDeleteBtn.addEventListener('click', async () => {
421
+ const filename = apiDeleteFilename.value.trim();
422
+ if (!filename) { alert('请输入文件名'); return; }
423
+ if (!confirm(`确定通过 API 删除 ${filename} 吗?`)) return;
424
+ try {
425
+ showApiResult('正在删除 ' + filename + ' ...');
426
+ const res = await fetch('/delete/' + encodeURIComponent(filename), { method: 'DELETE' });
427
+ const text = await res.text();
428
+ if (!res.ok) throw new Error(`HTTP ${res.status}: ${text}`);
429
+ showApiResult({ success: true, message: '文件已删除' });
430
+ loadList(); // 刷新列表
431
+ } catch (err) {
432
+ showApiResult(err.message, true);
433
+ }
434
+ });
435
+
436
+ // 初始化
437
  loadList();
438
+ })();
439
+ </script>
440
  </body>
441
  </html>"""
442
 
 
455
  with tempfile.NamedTemporaryFile(delete=False) as tmp:
456
  file.save(tmp.name)
457
  try:
458
+ # 使用 HfApi 上传文件
459
+ api.upload_file(
460
+ path_or_fileobj=tmp.name,
461
+ path_in_repo=file.filename,
462
+ repo_id=BUCKET_ID,
463
+ repo_type="bucket"
464
  )
465
  except Exception as e:
466
  return jsonify({'error': str(e)}), 500
 
472
  @app.route('/list')
473
  def list_files():
474
  try:
475
+ files = api.list_repo_files(
476
+ repo_id=BUCKET_ID,
477
+ repo_type="bucket"
 
 
478
  )
 
479
  return jsonify(files)
480
  except Exception as e:
481
  return jsonify({'error': str(e)}), 500
 
483
  @app.route('/file/<path:filename>')
484
  def get_file(filename):
485
  try:
486
+ # 直接重定向到 Hugging Face 的下载链接(或使用代理)
487
+ # 这里为了简单,使用 hf_hub_download 下载后返回
488
+ from huggingface_hub import hf_hub_download
489
  with tempfile.TemporaryDirectory() as tmpdir:
490
+ local_path = hf_hub_download(
491
+ repo_id=BUCKET_ID,
492
+ filename=filename,
493
+ repo_type="bucket",
494
+ local_dir=tmpdir,
495
  token=HF_TOKEN
496
  )
497
  return send_file(local_path, as_attachment=True, download_name=filename)
 
501
  @app.route('/delete/<path:filename>', methods=['DELETE'])
502
  def delete_file(filename):
503
  try:
504
+ api.delete_file(
505
+ path_in_repo=filename,
506
+ repo_id=BUCKET_ID,
507
+ repo_type="bucket"
 
508
  )
509
  return jsonify({'success': True})
510
  except Exception as e: