thomasjamie commited on
Commit
bb5c19a
·
verified ·
1 Parent(s): 7ba0082

Upload cf.py

Browse files
Files changed (1) hide show
  1. cf.py +353 -0
cf.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import uuid
4
+ import datetime
5
+ import requests
6
+ from functools import wraps
7
+ from flask import Flask, request, jsonify, render_template_string, redirect, session, url_for, Response, stream_with_context
8
+ from flask_cors import CORS
9
+ from huggingface_hub import HfApi, CommitOperationDelete
10
+ from werkzeug.middleware.proxy_fix import ProxyFix
11
+
12
+ app = Flask(__name__)
13
+ CORS(app)
14
+ # app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
15
+
16
+ app.secret_key = "my-fixed-secret-key-2026"
17
+ app.config.update(
18
+ SESSION_COOKIE_SECURE=True,
19
+ SESSION_COOKIE_SAMESITE='None',
20
+ PERMANENT_SESSION_LIFETIME=datetime.timedelta(days=30)
21
+ )
22
+
23
+ HF_TOKEN = os.environ.get("HF_TOKEN")
24
+ DATASET_NAME = os.environ.get("DATASET_NAME")
25
+ SPACE_HOST = os.environ.get("SPACE_HOST", "localhost:7860")
26
+ BASE_URL = f"https://{SPACE_HOST}" if "localhost" not in SPACE_HOST else f"http://{SPACE_HOST}"
27
+ ADMIN_USER = os.environ.get("ADMIN_USER")
28
+ ADMIN_PASS = os.environ.get("ADMIN_PASS")
29
+
30
+ # ==========================================
31
+ # 👇 关键修复:智能处理自定义域名格式
32
+ # ==========================================
33
+ CUSTOM_DOMAIN = os.environ.get("CUSTOM_DOMAIN")
34
+ if CUSTOM_DOMAIN:
35
+ # 1. 去除结尾的斜杠
36
+ if CUSTOM_DOMAIN.endswith("/"):
37
+ CUSTOM_DOMAIN = CUSTOM_DOMAIN[:-1]
38
+
39
+ # 2. 👇 漏掉的就是这几行:如果没有 https://,自动加上
40
+ # 这样 Flask 就知道这是个绝对网址,不会把它当成相对路径去拼接了
41
+ if not CUSTOM_DOMAIN.startswith("http"):
42
+ CUSTOM_DOMAIN = f"https://{CUSTOM_DOMAIN}"
43
+ # ==========================================
44
+
45
+ if HF_TOKEN: api = HfApi(token=HF_TOKEN)
46
+ CACHE_DIR = "/app/cache"
47
+ if not os.path.exists(CACHE_DIR): os.makedirs(CACHE_DIR)
48
+
49
+ def format_size(size):
50
+ if size is None: return "未知"
51
+ for unit in ['B', 'KB', 'MB', 'GB']:
52
+ if size < 1024: return f"{size:.1f} {unit}"
53
+ size /= 1024
54
+ return f"{size:.1f} TB"
55
+
56
+ def login_required(f):
57
+ @wraps(f)
58
+ def decorated_function(*args, **kwargs):
59
+ if ADMIN_USER and ADMIN_PASS and not session.get('logged_in'):
60
+ # 未登录跳转逻辑
61
+ if CUSTOM_DOMAIN:
62
+ return redirect(f"{CUSTOM_DOMAIN}/login")
63
+ return redirect(url_for('login'))
64
+ return f(*args, **kwargs)
65
+ return decorated_function
66
+
67
+ # 1. 登录页面
68
+ LOGIN_TEMPLATE = """<!DOCTYPE html><html><head><title>登录</title><meta name="viewport" content="width=device-width, initial-scale=1"><style>body{margin:0;height:100vh;display:flex;justify-content:center;align-items:center;font-family:-apple-system,sans-serif;background:url('https://images.unsplash.com/photo-1519681393784-d120267933ba?ixlib=rb-4.0.3&auto=format&fit=crop&w=1920&q=80') no-repeat center center fixed;background-size:cover}.glass-box{width:300px;padding:40px 30px;text-align:center;background:rgba(255,255,255,0.1);backdrop-filter:blur(25px);-webkit-backdrop-filter:blur(25px);border-radius:24px;border:1px solid rgba(255,255,255,0.2);box-shadow:0 8px 32px 0 rgba(0,0,0,0.1);color:white}h2{margin:0 0 25px 0;font-weight:500}input{width:100%;padding:14px;margin:10px 0;border-radius:12px;border:1px solid rgba(255,255,255,0.3);background:rgba(255,255,255,0.15);color:white;outline:none;transition:0.3s;box-sizing:border-box}input:focus{background:rgba(255,255,255,0.25);border-color:rgba(255,255,255,0.8)}button{width:100%;padding:14px;margin-top:20px;background:rgba(255,255,255,0.9);color:#333;border:none;border-radius:12px;font-weight:bold;cursor:pointer;transition:0.3s}button:hover{background:white;transform:translateY(-2px)}.err{color:#ffcccc;background:rgba(255,0,0,0.2);padding:5px;border-radius:5px;font-size:14px;margin-bottom:10px}</style></head><body><div class="glass-box"><h2>CloudGallery</h2>{% if error %}<div class="err">{{ error }}</div>{% endif %}<form method="post"><input type="text" name="username" placeholder="Username" required><input type="password" name="password" placeholder="Password" required><button type="submit">Sign In</button></form></div></body></html>"""
69
+
70
+ # 2. 全屏查看
71
+ VIEW_TEMPLATE = """<!DOCTYPE html><html><head><title>查看</title><style>body{margin:0;background:#000;display:flex;justify-content:center;align-items:center;height:100vh;overflow:hidden}img{width:100%;height:100%;object-fit:contain}</style></head><body><img src="{{ real_url }}"></body></html>"""
72
+
73
+ # 3. 主页模板
74
+ HTML_TEMPLATE = """
75
+ <!DOCTYPE html>
76
+ <html lang="zh-CN">
77
+ <head>
78
+ <meta charset="UTF-8">
79
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
80
+ <title>CloudGallery</title>
81
+ <style>
82
+ * { box-sizing: border-box; }
83
+ :root { --primary: #3b82f6; --bg: #f8fafc; }
84
+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background-color: var(--bg); color: #333; margin: 0; padding: 20px; overflow-x: hidden; }
85
+ .container { max-width: 1200px; margin: 0 auto; }
86
+ .top-nav { display: flex; justify-content: flex-end; margin-bottom: 10px; }
87
+ .logout-btn { text-decoration: none; color: #ef4444; font-size: 13px; padding: 6px 12px; background: white; border: 1px solid #fee2e2; border-radius: 20px; transition: 0.2s; }
88
+ .logout-btn:hover { background: #fef2f2; border-color: #fecaca; }
89
+ .upload-section { background: white; padding: 30px; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.05); text-align: center; margin-bottom: 30px; margin-top: 10px; }
90
+ .upload-wrapper { position: relative; display: inline-block; overflow: hidden; }
91
+ .btn { background: white; border: 2px solid var(--primary); color: var(--primary); padding: 10px 24px; border-radius: 8px; font-weight: bold; cursor: pointer; transition: 0.3s; }
92
+ .btn:hover { background: var(--primary); color: white; }
93
+ .upload-wrapper input { position: absolute; left: 0; top: 0; font-size: 100px; opacity: 0; cursor: pointer; }
94
+ #status { margin-top: 15px; color: #666; font-size: 14px; }
95
+ .gallery-header { display: flex; justify-content: space-between; margin-bottom: 20px; align-items: center; }
96
+ .refresh-btn { background: none; border: none; cursor: pointer; color: #64748b; font-size: 14px; display: flex; align-items: center; gap: 5px; }
97
+ .refresh-btn:hover { color: var(--primary); }
98
+ .gallery-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 20px; }
99
+ .card { background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.05); position: relative; transition: 0.2s; }
100
+ .card:hover { transform: translateY(-3px); box-shadow: 0 10px 20px rgba(0,0,0,0.1); }
101
+ .img-container { height: 160px; overflow: hidden; background: #eee; display: flex; align-items: center; justify-content: center; cursor: zoom-in; }
102
+ .img-container img { width: 100%; height: 100%; object-fit: cover; }
103
+ .card-body { padding: 12px; display: flex; flex-direction: column; gap: 6px; }
104
+ .file-name { font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: bold; }
105
+ .meta-info { font-size: 10px; color: #999; display: flex; justify-content: space-between; }
106
+ .copy-btn { background: #f1f5f9; border: none; padding: 6px; border-radius: 4px; color: #475569; font-size: 12px; cursor: pointer; width: 100%; margin-top: 5px; }
107
+ .copy-btn:hover { background: #e2e8f0; color: #0f172a; }
108
+ .copy-btn.primary { background: #eff6ff; color: #2563eb; }
109
+ .delete-btn { position: absolute; top: 5px; right: 5px; background: rgba(255,255,255,0.9); color: red; border: none; width: 24px; height: 24px; border-radius: 50%; cursor: pointer; opacity: 0; font-weight: bold; transition: 0.2s; }
110
+ .card:hover .delete-btn { opacity: 1; }
111
+ .lightbox-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 1000; background-color: rgba(255, 255, 255, 0.4); backdrop-filter: blur(25px); -webkit-backdrop-filter: blur(25px); flex-direction: column; justify-content: center; align-items: center; }
112
+ .lb-main { flex: 1; width: 100%; display: flex; justify-content: center; align-items: center; overflow: hidden; position: relative; }
113
+ .lb-img { max-width: 70%; max-height: 70%; object-fit: contain; transition: transform 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94); cursor: grab; border-radius: 8px; box-shadow: 0 30px 80px rgba(0,0,0,0.25); }
114
+ .floating-close { position: absolute; top: 20px; right: 20px; width: 40px; height: 40px; border-radius: 50%; background: rgba(0,0,0,0.05); color: #333; display: flex; justify-content: center; align-items: center; font-size: 24px; cursor: pointer; z-index: 1020; transition:0.2s; }
115
+ .floating-close:hover { background: rgba(0,0,0,0.1); }
116
+ .lb-bottom-container { width: 100%; display: flex; justify-content: center; position: absolute; bottom: 130px; pointer-events: none; z-index: 1010; }
117
+ .lb-controls { background: rgba(255, 255, 255, 0.7); backdrop-filter: blur(15px); -webkit-backdrop-filter: blur(15px); padding: 8px 20px; border-radius: 50px; border: 1px solid rgba(0,0,0,0.05); box-shadow: 0 10px 30px rgba(0,0,0,0.1); display: flex; gap: 15px; pointer-events: auto; align-items: center; }
118
+ .lb-ctl-btn { background: transparent; border: none; color: #333; font-size: 16px; cursor: pointer; padding: 5px 10px; border-radius: 20px; transition: 0.2s; }
119
+ .lb-ctl-btn:hover { background: rgba(0,0,0,0.05); }
120
+ .divider { width: 1px; background: rgba(0,0,0,0.1); height: 20px; }
121
+ .filmstrip-container { position: absolute; bottom: 30px; width: 100%; display: flex; justify-content: center; z-index: 1005; }
122
+ .filmstrip { height: 70px; width: auto; max-width: 90vw; background: rgba(255, 255, 255, 0.6); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); border-radius: 35px; border: 1px solid rgba(255,255,255,0.5); box-shadow: 0 10px 30px rgba(0,0,0,0.08); display: flex; align-items: center; gap: 12px; padding: 0 20px; overflow-x: auto; scrollbar-width: none; }
123
+ .filmstrip::-webkit-scrollbar { display: none; }
124
+ .thumb { width: 44px; height: 44px; border-radius: 10px; object-fit: cover; cursor: pointer; flex-shrink: 0; opacity: 0.5; transform: scale(0.9); filter: grayscale(0.2); transition: all 0.3s ease; border: 2px solid transparent; }
125
+ .thumb:hover { opacity: 0.9; }
126
+ .thumb.active { opacity: 1; filter: grayscale(0); transform: scale(1.1); border: 2px solid #3b82f6; box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2); }
127
+ @media (max-width: 600px) { .gallery-grid { grid-template-columns: repeat(2, 1fr); } }
128
+ </style>
129
+ </head>
130
+ <body>
131
+ <div class="container">
132
+ <div class="top-nav"><a href="/logout" class="logout-btn">🔴 退出</a></div>
133
+ <div class="upload-section">
134
+ <h2 style="margin-top:0;">☁️ CloudGallery</h2>
135
+ <div class="upload-wrapper">
136
+ <button class="btn">+ 上传图片 (多选)</button>
137
+ <input type="file" id="fileInput" accept="image/*" multiple onchange="handleUpload()">
138
+ </div>
139
+ <div id="status">准备就绪</div>
140
+ </div>
141
+ <div class="gallery-header">
142
+ <h3 style="margin:0">🖼️ 图片列表</h3>
143
+ <button class="refresh-btn" onclick="location.reload()">🔄 刷新</button>
144
+ </div>
145
+ <div class="gallery-grid">
146
+ {% for img in images %}
147
+ <div class="card" id="card-{{ loop.index0 }}">
148
+ <div class="img-container" onclick="openViewer({{ loop.index0 }})">
149
+ <img src="{{ img.raw_url }}" loading="lazy" onload="updateRes(this)">
150
+ </div>
151
+ <button class="delete-btn" onclick="deleteImage('{{ img.name }}', {{ loop.index0 }})">×</button>
152
+ <div class="card-body">
153
+ <div class="file-name" title="{{ img.name }}">{{ img.name }}</div>
154
+ <div class="meta-info"><span>{{ img.size_fmt }}</span><span class="res-tag">...</span></div>
155
+ <button class="copy-btn primary" onclick="copyLink(this, '{{ img.raw_url }}')">📋 复制链接</button>
156
+ <button class="copy-btn" onclick="copyMarkdown(this, '{{ img.name }}', '{{ img.raw_url }}')">📝 复制 Markdown</button>
157
+ </div>
158
+ </div>
159
+ {% endfor %}
160
+ </div>
161
+ </div>
162
+
163
+ <div id="lightbox" class="lightbox-overlay" onclick="closeViewer(event)">
164
+ <div class="floating-close" onclick="closeViewer()">×</div>
165
+ <div class="lb-main"><img id="lb-img" class="lb-img" onclick="event.stopPropagation()"></div>
166
+ <div class="lb-bottom-container">
167
+ <div class="lb-controls" onclick="event.stopPropagation()">
168
+ <button class="lb-ctl-btn" onclick="zoom(-0.2)" title="缩小">-</button>
169
+ <button class="lb-ctl-btn" onclick="resetZoom()" title="1:1" style="font-size:14px">1:1</button>
170
+ <button class="lb-ctl-btn" onclick="zoom(0.2)" title="放大">+</button>
171
+ <span class="divider"></span>
172
+ <button class="lb-ctl-btn" onclick="copyCurrentLink()" title="复制链接">🔗</button>
173
+ </div>
174
+ </div>
175
+ <div class="filmstrip-container"><div class="filmstrip" id="filmstrip" onclick="event.stopPropagation()"></div></div>
176
+ </div>
177
+
178
+ <script>
179
+ const galleryData = [
180
+ {% for img in images %}
181
+ { name: "{{img.name}}", url: "{{img.raw_url}}", view_url: "{{img.view_url}}" },
182
+ {% endfor %}
183
+ ];
184
+ let curIdx = 0, scale = 1;
185
+
186
+ async function handleUpload() {
187
+ const inp = document.getElementById('fileInput');
188
+ if (!inp.files.length) return;
189
+ document.getElementById('status').innerText = `🚀 上传 ${inp.files.length} 张...`;
190
+ const fd = new FormData();
191
+ for (let f of inp.files) fd.append('files', f);
192
+ try {
193
+ const res = await fetch('/upload', { method: 'POST', body: fd });
194
+ const d = await res.json();
195
+ if(d.status==='success') setTimeout(()=>location.reload(), 1000);
196
+ } catch(e) {}
197
+ }
198
+
199
+ async function deleteImage(name, idx) {
200
+ if(!confirm('删除?')) return;
201
+ const fd = new FormData(); fd.append('filename', name);
202
+ const res = await fetch('/delete', { method: 'POST', body: fd });
203
+ if ((await res.json()).status === 'success') document.getElementById('card-'+idx).remove();
204
+ }
205
+
206
+ function openViewer(idx) {
207
+ curIdx = idx;
208
+ const lb = document.getElementById('lightbox');
209
+ const fs = document.getElementById('filmstrip');
210
+ fs.innerHTML = '';
211
+ galleryData.forEach((img, i) => {
212
+ const t = document.createElement('img');
213
+ t.src = img.url; t.className = `thumb ${i===idx?'active':''}`;
214
+ t.onclick = () => showImage(i);
215
+ fs.appendChild(t);
216
+ });
217
+ lb.style.display = 'flex';
218
+ setTimeout(() => lb.style.opacity = '1', 10);
219
+ showImage(idx);
220
+ }
221
+
222
+ function showImage(idx) {
223
+ curIdx = idx; scale = 1;
224
+ const img = document.getElementById('lb-img');
225
+ img.src = galleryData[idx].url;
226
+ img.style.transform = `scale(1)`;
227
+ document.querySelectorAll('.thumb').forEach((t, i) => {
228
+ t.className = `thumb ${i===idx?'active':''}`;
229
+ if(i===idx) t.scrollIntoView({behavior:"smooth", inline:"center"});
230
+ });
231
+ }
232
+
233
+ function closeViewer(e) {
234
+ if(!e || e.target === e.currentTarget || e.target.classList.contains('floating-close')) {
235
+ document.getElementById('lightbox').style.display = 'none';
236
+ }
237
+ }
238
+ function zoom(d) { scale += d; if(scale<0.1) scale=0.1; document.getElementById('lb-img').style.transform = `scale(${scale})`; }
239
+ function resetZoom() { scale = 1; document.getElementById('lb-img').style.transform = `scale(1)`; }
240
+ function copyCurrentLink() { copyLink(null, galleryData[curIdx].view_url); alert('已复制'); }
241
+ function updateRes(img) { if(img.naturalWidth) img.closest('.card').querySelector('.res-tag').innerText = img.naturalWidth+'x'+img.naturalHeight; }
242
+ function copyLink(btn, txt) { navigator.clipboard.writeText(txt); if(btn){let t=btn.innerText;btn.innerText='✅';setTimeout(()=>btn.innerText=t,1500);} }
243
+ function copyMarkdown(btn, n, u) { copyLink(btn, `![${n}](${u})`); }
244
+
245
+ document.getElementById('lb-img').addEventListener('wheel', function(e) {
246
+ e.preventDefault(); e.deltaY < 0 ? zoom(0.1) : zoom(-0.1);
247
+ }, { passive: false });
248
+ </script>
249
+ </body>
250
+ </html>
251
+ """
252
+
253
+ @app.route('/login', methods=['GET', 'POST'])
254
+ def login():
255
+ if request.method == 'POST':
256
+ if request.form.get('username') == ADMIN_USER and request.form.get('password') == ADMIN_PASS:
257
+ session.permanent = True; session['logged_in'] = True;
258
+
259
+ if CUSTOM_DOMAIN:
260
+ return redirect(f"{CUSTOM_DOMAIN}/")
261
+ return redirect("/")
262
+
263
+ return render_template_string(LOGIN_TEMPLATE, error="Error")
264
+ return render_template_string(LOGIN_TEMPLATE)
265
+
266
+ @app.route('/logout')
267
+ def logout():
268
+ session.pop('logged_in', None);
269
+ if CUSTOM_DOMAIN:
270
+ return redirect(f"{CUSTOM_DOMAIN}/login")
271
+ return redirect('/login')
272
+
273
+ @app.route('/')
274
+ @login_required
275
+ def home():
276
+ if not HF_TOKEN: return "Missing Env"
277
+ try:
278
+ tree = api.list_repo_tree(repo_id=DATASET_NAME, repo_type="dataset", token=HF_TOKEN, recursive=False)
279
+ images = []
280
+
281
+ current_host = CUSTOM_DOMAIN if CUSTOM_DOMAIN else BASE_URL
282
+
283
+ for item in tree:
284
+ if item.path.lower().endswith(('.png','.jpg','.jpeg','.gif','.webp','.bmp')):
285
+
286
+ raw_url = f"{current_host}/file/{item.path}"
287
+
288
+ # view_url 也走代理
289
+ view_url = f"{current_host}/view/{item.path}"
290
+
291
+ images.append({
292
+ "name": item.path,
293
+ "raw_url": raw_url,
294
+ "real_url": f"https://huggingface.co/datasets/{DATASET_NAME}/resolve/main/{item.path}",
295
+ "view_url": view_url,
296
+ "size_fmt": format_size(item.size) if hasattr(item, 'size') else "?"
297
+ })
298
+ images.reverse()
299
+ return render_template_string(HTML_TEMPLATE, images=images, dataset_name=DATASET_NAME)
300
+ except: return "Error loading images"
301
+
302
+ @app.route('/upload', methods=['POST'])
303
+ @login_required
304
+ def upload_file():
305
+ files = request.files.getlist('files')
306
+ count = 0
307
+ for file in files:
308
+ if not file.filename: continue
309
+ ext = os.path.splitext(file.filename)[1].lower()
310
+ if not ext: ext = ".jpg"
311
+ name = f"{uuid.uuid4().hex[:4]}{ext}"
312
+ path = os.path.join(CACHE_DIR, name)
313
+ try:
314
+ file.save(path)
315
+ api.upload_file(path_or_fileobj=path, path_in_repo=name, repo_id=DATASET_NAME, repo_type="dataset", token=HF_TOKEN)
316
+ os.remove(path)
317
+ count += 1
318
+ except: pass
319
+ return jsonify({"status": "success", "count": count})
320
+
321
+ @app.route('/delete', methods=['POST'])
322
+ @login_required
323
+ def delete_file():
324
+ name = request.form.get('filename')
325
+ try:
326
+ api.create_commit(repo_id=DATASET_NAME, repo_type="dataset", operations=[CommitOperationDelete(path_in_repo=name)], commit_message=f"Del {name}")
327
+ return jsonify({"status": "success"})
328
+ except Exception as e: return jsonify({"error": str(e)})
329
+
330
+ @app.route('/view/<path:filename>')
331
+ def view_image(filename):
332
+ current_host = CUSTOM_DOMAIN if CUSTOM_DOMAIN else BASE_URL
333
+ real_url = f"{current_host}/file/{filename}"
334
+ return render_template_string(VIEW_TEMPLATE, real_url=real_url)
335
+
336
+ @app.route('/file/<path:filename>')
337
+ def get_image_file(filename):
338
+ try:
339
+ url = f"https://huggingface.co/datasets/{DATASET_NAME}/resolve/main/{filename}"
340
+ headers = {"Authorization": f"Bearer {HF_TOKEN}"}
341
+ r = requests.get(url, headers=headers, stream=True)
342
+ if r.status_code != 200: return f"Error: {r.status_code}", r.status_code
343
+
344
+ # 构造响应流
345
+ response = Response(stream_with_context(r.iter_content(chunk_size=1024)), content_type=r.headers.get('Content-Type'))
346
+
347
+ # 🔥 缓存设置
348
+ response.headers['Cache-Control'] = 'public, max-age=31536000'
349
+
350
+ return response
351
+ except Exception as e: return f"Proxy Error: {str(e)}", 500
352
+
353
+ if __name__ == '__main__': app.run(host='0.0.0.0', port=7860)