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