aied-lab commited on
Commit
45f90bb
·
1 Parent(s): 3e56a45

convert to gradio backend with secret token

Browse files
Files changed (5) hide show
  1. README.md +12 -3
  2. app.py +107 -0
  3. index.html +0 -318
  4. requirements.txt +3 -0
  5. style.css +0 -28
README.md CHANGED
@@ -3,9 +3,18 @@ title: Demo
3
  emoji: 👁
4
  colorFrom: purple
5
  colorTo: purple
6
- sdk: static
 
 
7
  pinned: false
8
- short_description: demo
9
  ---
10
 
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
3
  emoji: 👁
4
  colorFrom: purple
5
  colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 4.44.1
8
+ app_file: app.py
9
  pinned: false
10
+ short_description: Gemma multimodal image analysis
11
  ---
12
 
13
+ Gemma 多模態影像分析助手,透過 Hugging Face Router 呼叫多模態模型。
14
+
15
+ ## 設定
16
+
17
+ 請在此 Space 的 **Settings > Variables and secrets** 新增:
18
+
19
+ - `HF_TOKEN`(Secret):你的 Hugging Face access token
20
+ - `MODEL_ID`(Variable,選填):預設 `google/gemma-3-27b-it`,可換成其他 Router 支援的多模態模型
app.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ import base64
4
+ import requests
5
+ import gradio as gr
6
+
7
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
8
+ MODEL_ID = os.environ.get("MODEL_ID", "google/gemma-3-27b-it")
9
+ API_URL = "https://router.huggingface.co/v1/chat/completions"
10
+
11
+
12
+ def analyze(image, prompt):
13
+ if image is None:
14
+ return "請先上傳一張圖片!"
15
+ if not HF_TOKEN:
16
+ return "後端未設定 HF_TOKEN,請在 Space 的 Settings > Variables and secrets 加入 HF_TOKEN。"
17
+
18
+ prompt = (prompt or "").strip() or "用一句中文描述這張圖片"
19
+
20
+ buffered = io.BytesIO()
21
+ image.convert("RGB").save(buffered, format="JPEG", quality=85)
22
+ b64 = base64.b64encode(buffered.getvalue()).decode()
23
+ data_url = f"data:image/jpeg;base64,{b64}"
24
+
25
+ payload = {
26
+ "model": MODEL_ID,
27
+ "messages": [{
28
+ "role": "user",
29
+ "content": [
30
+ {"type": "text", "text": prompt},
31
+ {"type": "image_url", "image_url": {"url": data_url}},
32
+ ],
33
+ }],
34
+ "max_tokens": 300,
35
+ }
36
+
37
+ try:
38
+ resp = requests.post(
39
+ API_URL,
40
+ headers={
41
+ "Authorization": f"Bearer {HF_TOKEN}",
42
+ "Content-Type": "application/json",
43
+ },
44
+ json=payload,
45
+ timeout=120,
46
+ )
47
+ data = resp.json()
48
+ if resp.ok and data.get("choices"):
49
+ return data["choices"][0]["message"]["content"]
50
+ err = data.get("error", {})
51
+ msg = err.get("message") if isinstance(err, dict) else str(err)
52
+ return f"發生錯誤:{msg or data}"
53
+ except Exception as e:
54
+ return f"發生錯誤:{e}"
55
+
56
+
57
+ CSS = """
58
+ :root {
59
+ --neon-cyan: #00f0ff;
60
+ --neon-purple: #b026ff;
61
+ }
62
+ .gradio-container {
63
+ background-color: #0b0f19 !important;
64
+ background-image:
65
+ radial-gradient(circle at 10% 20%, rgba(176, 38, 255, 0.12) 0%, transparent 40%),
66
+ radial-gradient(circle at 90% 80%, rgba(0, 240, 255, 0.12) 0%, transparent 40%) !important;
67
+ color: #f3f4f6 !important;
68
+ max-width: 780px !important;
69
+ margin: 0 auto !important;
70
+ }
71
+ #title h1 {
72
+ background: linear-gradient(135deg, var(--neon-cyan), var(--neon-purple));
73
+ -webkit-background-clip: text;
74
+ -webkit-text-fill-color: transparent;
75
+ font-weight: 800;
76
+ }
77
+ #subtitle { color: #9ca3af !important; }
78
+ #analyze-btn {
79
+ background: linear-gradient(135deg, var(--neon-cyan), var(--neon-purple)) !important;
80
+ color: #000 !important;
81
+ font-weight: 700 !important;
82
+ border: none !important;
83
+ box-shadow: 0 4px 15px rgba(0, 240, 255, 0.2) !important;
84
+ }
85
+ #analyze-btn:hover { box-shadow: 0 6px 20px rgba(176, 38, 255, 0.45) !important; }
86
+ """
87
+
88
+ with gr.Blocks(css=CSS, title="Gemma 多模態影像分析助手") as demo:
89
+ with gr.Column(elem_id="title"):
90
+ gr.Markdown("# Gemma 多模態影像分析助手")
91
+ with gr.Column(elem_id="subtitle"):
92
+ gr.Markdown("透過 Hugging Face Router 呼叫多模態模型進行高精度影像辨識與分析。")
93
+
94
+ with gr.Row():
95
+ with gr.Column():
96
+ image_in = gr.Image(type="pil", label="上傳圖片")
97
+ prompt_in = gr.Textbox(
98
+ label="輸入提示詞 (Prompt)",
99
+ value="用一句中文描述這張圖片",
100
+ )
101
+ btn = gr.Button("啟動分析", elem_id="analyze-btn", variant="primary")
102
+ with gr.Column():
103
+ output = gr.Textbox(label="模型回應", lines=14, show_copy_button=True)
104
+
105
+ btn.click(analyze, inputs=[image_in, prompt_in], outputs=output)
106
+
107
+ demo.launch()
index.html DELETED
@@ -1,318 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="zh-Hant">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>Gemma 多模態影像分析助手</title>
7
- <style>
8
- :root {
9
- --bg-color: #0b0f19;
10
- --card-bg: rgba(17, 24, 39, 0.75);
11
- --border-glow: rgba(0, 240, 255, 0.3);
12
- --neon-cyan: #00f0ff;
13
- --neon-purple: #b026ff;
14
- --text-main: #f3f4f6;
15
- --text-muted: #9ca3af;
16
- }
17
-
18
- body {
19
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
20
- max-width: 650px;
21
- margin: 40px auto;
22
- padding: 20px;
23
- background-color: var(--bg-color);
24
- background-image:
25
- radial-gradient(circle at 10% 20%, rgba(176, 38, 255, 0.1) 0%, transparent 40%),
26
- radial-gradient(circle at 90% 80%, rgba(0, 240, 255, 0.1) 0%, transparent 40%);
27
- color: var(--text-main);
28
- min-height: 100vh;
29
- }
30
-
31
- .card {
32
- background: var(--card-bg);
33
- backdrop-filter: blur(16px);
34
- -webkit-backdrop-filter: blur(16px);
35
- padding: 30px;
36
- border-radius: 16px;
37
- border: 1px solid var(--border-glow);
38
- box-shadow: 0 0 30px rgba(0, 240, 255, 0.1), inset 0 0 15px rgba(176, 38, 255, 0.05);
39
- position: relative;
40
- overflow: hidden;
41
- }
42
-
43
- .card::before {
44
- content: '';
45
- position: absolute;
46
- top: 0;
47
- left: -100%;
48
- width: 100%;
49
- height: 2px;
50
- background: linear-gradient(90deg, transparent, var(--neon-cyan), transparent);
51
- animation: scanline 4s linear infinite;
52
- }
53
-
54
- @keyframes scanline {
55
- 0% { left: -100%; }
56
- 100% { left: 100%; }
57
- }
58
-
59
- h2 {
60
- margin-top: 0;
61
- font-size: 1.8rem;
62
- background: linear-gradient(135deg, var(--neon-cyan), var(--neon-purple));
63
- -webkit-background-clip: text;
64
- -webkit-text-fill-color: transparent;
65
- letter-spacing: 0.5px;
66
- }
67
-
68
- p {
69
- color: var(--text-muted);
70
- font-size: 0.95rem;
71
- margin-bottom: 24px;
72
- }
73
-
74
- .form-group {
75
- margin-bottom: 20px;
76
- }
77
-
78
- label {
79
- display: block;
80
- font-weight: 600;
81
- margin-bottom: 8px;
82
- font-size: 0.9rem;
83
- color: var(--neon-cyan);
84
- letter-spacing: 0.5px;
85
- }
86
-
87
- input[type="password"],
88
- input[type="text"],
89
- input[type="file"],
90
- textarea {
91
- width: 100%;
92
- padding: 12px 14px;
93
- background: rgba(3, 7, 18, 0.6);
94
- border: 1px solid rgba(255, 255, 255, 0.1);
95
- border-radius: 8px;
96
- box-sizing: border-box;
97
- color: var(--text-main);
98
- font-size: 0.95rem;
99
- transition: all 0.3s ease;
100
- }
101
-
102
- input:focus {
103
- outline: none;
104
- border-color: var(--neon-cyan);
105
- box-shadow: 0 0 10px rgba(0, 240, 255, 0.3);
106
- }
107
-
108
- input[type="file"]::file-selector-button {
109
- background: rgba(0, 240, 255, 0.1);
110
- color: var(--neon-cyan);
111
- border: 1px solid var(--neon-cyan);
112
- padding: 6px 12px;
113
- border-radius: 4px;
114
- cursor: pointer;
115
- transition: all 0.2s;
116
- }
117
-
118
- input[type="file"]::file-selector-button:hover {
119
- background: var(--neon-cyan);
120
- color: #000;
121
- }
122
-
123
- button {
124
- background: linear-gradient(135deg, var(--neon-cyan), var(--neon-purple));
125
- color: #000;
126
- border: none;
127
- padding: 12px 20px;
128
- font-weight: 700;
129
- border-radius: 8px;
130
- cursor: pointer;
131
- width: 100%;
132
- font-size: 1rem;
133
- letter-spacing: 1px;
134
- transition: all 0.3s ease;
135
- box-shadow: 0 4px 15px rgba(0, 240, 255, 0.2);
136
- }
137
-
138
- button:hover {
139
- opacity: 0.9;
140
- transform: translateY(-1px);
141
- box-shadow: 0 6px 20px rgba(176, 38, 255, 0.4);
142
- }
143
-
144
- button:disabled {
145
- background: #374151;
146
- color: #9ca3af;
147
- cursor: not-allowed;
148
- box-shadow: none;
149
- transform: none;
150
- }
151
-
152
- #preview-container {
153
- margin-top: 12px;
154
- text-align: center;
155
- }
156
-
157
- #imagePreview {
158
- max-width: 100%;
159
- max-height: 250px;
160
- border-radius: 8px;
161
- display: none;
162
- border: 1px solid var(--border-glow);
163
- box-shadow: 0 4px 12px rgba(0,0,0,0.5);
164
- }
165
-
166
- #result {
167
- margin-top: 12px;
168
- padding: 16px;
169
- background: rgba(3, 7, 18, 0.8);
170
- border: 1px solid rgba(255, 255, 255, 0.08);
171
- border-radius: 8px;
172
- white-space: pre-wrap;
173
- min-height: 60px;
174
- font-size: 0.95rem;
175
- color: #e5e7eb;
176
- box-shadow: inset 0 2px 4px rgba(0,0,0,0.4);
177
- }
178
- </style>
179
- </head>
180
- <body>
181
- <div class="card">
182
- <h2>Gemma 多模態影像分析助手</h2>
183
- <p>透過 Hugging Face Router 呼叫 gemma-4-31B-it 模型進行高精度影像辨識與分析。</p>
184
-
185
- <div class="form-group">
186
- <label for="imageInput">上傳圖片</label>
187
- <input type="file" id="imageInput" accept="image/*" onchange="previewSelectedImage(event)">
188
- <div id="preview-container">
189
- <img id="imagePreview" alt="圖片預覽">
190
- </div>
191
- </div>
192
-
193
- <div class="form-group">
194
- <label for="promptInput">輸入提示詞 (Prompt)</label>
195
- <input type="text" id="promptInput" value="Describe this image in one sentence in chinese">
196
- </div>
197
-
198
- <button id="submitBtn" onclick="analyzeImage()">啟動分析</button>
199
-
200
- <div class="form-group" style="margin-top: 24px;">
201
- <label>模型回應</label>
202
- <div id="result">系統待命,尚未開始分析...</div>
203
- </div>
204
- </div>
205
-
206
- <script>
207
- // 選擇圖片時即時顯示預覽
208
- function previewSelectedImage(event) {
209
- const file = event.target.files[0];
210
- const preview = document.getElementById('imagePreview');
211
- if (file) {
212
- const reader = new FileReader();
213
- reader.onload = function(e) {
214
- preview.src = e.target.result;
215
- preview.style.display = 'inline-block';
216
- }
217
- reader.readAsDataURL(file);
218
- } else {
219
- preview.src = '';
220
- preview.style.display = 'none';
221
- }
222
- }
223
-
224
- // 壓縮並轉成 Base64 的前端實作
225
- function compressImage(file, maxSize = 1024, quality = 0.85) {
226
- return new Promise((resolve, reject) => {
227
- const reader = new FileReader();
228
- reader.onload = function(e) {
229
- const img = new Image();
230
- img.onload = function() {
231
- let width = img.width;
232
- let height = img.height;
233
- if (width > height) {
234
- if (width > maxSize) {
235
- height *= maxSize / width;
236
- width = maxSize;
237
- }
238
- } else {
239
- if (height > maxSize) {
240
- width *= maxSize / height;
241
- height = maxSize;
242
- }
243
- }
244
- const canvas = document.createElement('canvas');
245
- canvas.width = width;
246
- canvas.height = height;
247
- const ctx = canvas.getContext('2d');
248
- ctx.drawImage(img, 0, 0, width, height);
249
- const dataUrl = canvas.toDataURL('image/jpeg', quality);
250
- resolve(dataUrl);
251
- };
252
- img.src = e.target.result;
253
- };
254
- reader.onerror = reject;
255
- reader.readAsDataURL(file);
256
- });
257
- }
258
-
259
- // ⚠️ 請在此填入你的 HF_TOKEN,否則 Router API 會回 401
260
- const HF_TOKEN = "";
261
-
262
- // 可更換的模型 ID(Hugging Face Router 支援的多模態模型)
263
- // 例如:google/gemma-3-27b-it, Qwen/Qwen2.5-VL-72B-Instruct, meta-llama/Llama-3.2-11B-Vision-Instruct
264
- const MODEL_ID = "google/gemma-3-27b-it";
265
-
266
- async function analyzeImage() {
267
- const imageFile = document.getElementById('imageInput').files[0];
268
- let prompt = document.getElementById('promptInput').value.trim();
269
- const resultDiv = document.getElementById('result');
270
- const submitBtn = document.getElementById('submitBtn');
271
-
272
- if (!imageFile) {
273
- alert('請先上傳一張圖片!');
274
- return;
275
- }
276
- if (!prompt) {
277
- prompt = "Describe this image in one sentence.";
278
- }
279
-
280
- submitBtn.disabled = true;
281
- resultDiv.innerText = '處理中,神經網路運算中...';
282
-
283
- try {
284
- const base64Image = await compressImage(imageFile);
285
- const response = await fetch("https://router.huggingface.co/v1/chat/completions", {
286
- method: "POST",
287
- headers: {
288
- "Authorization": `Bearer ${HF_TOKEN}`,
289
- "Content-Type": "application/json"
290
- },
291
- body: JSON.stringify({
292
- model: MODEL_ID,
293
- messages: [{
294
- role: "user",
295
- content: [
296
- { type: "text", text: prompt },
297
- { type: "image_url", image_url: { url: base64Image } }
298
- ]
299
- }],
300
- max_tokens: 300
301
- })
302
- });
303
-
304
- const data = await response.json();
305
- if (response.ok && data.choices && data.choices.length > 0) {
306
- resultDiv.innerText = data.choices[0].message.content;
307
- } else {
308
- resultDiv.innerText = `發生錯誤:${data.error?.message || JSON.stringify(data)}`;
309
- }
310
- } catch (error) {
311
- resultDiv.innerText = `發生錯誤:${error.message}`;
312
- } finally {
313
- submitBtn.disabled = false;
314
- }
315
- }
316
- </script>
317
- </body>
318
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio>=4.44.0
2
+ requests
3
+ Pillow
style.css DELETED
@@ -1,28 +0,0 @@
1
- body {
2
- padding: 2rem;
3
- font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;
4
- }
5
-
6
- h1 {
7
- font-size: 16px;
8
- margin-top: 0;
9
- }
10
-
11
- p {
12
- color: rgb(107, 114, 128);
13
- font-size: 15px;
14
- margin-bottom: 10px;
15
- margin-top: 5px;
16
- }
17
-
18
- .card {
19
- max-width: 620px;
20
- margin: 0 auto;
21
- padding: 16px;
22
- border: 1px solid lightgray;
23
- border-radius: 16px;
24
- }
25
-
26
- .card p:last-child {
27
- margin-bottom: 0;
28
- }