Spaces:
Running
Running
convert to gradio backend with secret token
Browse filesFiles changed (5)
- README.md+12-3
- app.pyAdded+107
- index.htmlDeleted-318
- requirements.txtAdded+3
- style.cssDeleted-28
2 unmodified lines345678910112 unmodified linesemoji: 👁colorFrom: purplecolorTo: purplesdk: staticpinned: falseshort_description: demo---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference2 unmodified lines345678910111213141516171819202 unmodified linesemoji: 👁colorFrom: purplecolorTo: purplesdk: gradiosdk_version: 4.44.1app_file: app.pypinned: falseshort_description: Gemma multimodal image analysis---Gemma 多模態影像分析助手,透過 Hugging Face Router 呼叫多模態模型。## 設定請在此 Space 的 **Settings > Variables and secrets** 新增:- `HF_TOKEN`(Secret):你的 Hugging Face access token- `MODEL_ID`(Variable,選填):預設 `google/gemma-3-27b-it`,可換成其他 Router 支援的多模態模型
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107import osimport ioimport base64import requestsimport gradio as gr
HF_TOKEN = os.environ.get("HF_TOKEN", "")MODEL_ID = os.environ.get("MODEL_ID", "google/gemma-3-27b-it")API_URL = "https://router.huggingface.co/v1/chat/completions"
def analyze(image, prompt): if image is None: return "請先上傳一張圖片!" if not HF_TOKEN: return "後端未設定 HF_TOKEN,請在 Space 的 Settings > Variables and secrets 加入 HF_TOKEN。"
prompt = (prompt or "").strip() or "用一句中文描述這張圖片"
buffered = io.BytesIO() image.convert("RGB").save(buffered, format="JPEG", quality=85) b64 = base64.b64encode(buffered.getvalue()).decode() data_url = f"data:image/jpeg;base64,{b64}"
payload = { "model": MODEL_ID, "messages": [{ "role": "user", "content": [ {"type": "text", "text": prompt}, {"type": "image_url", "image_url": {"url": data_url}}, ], }], "max_tokens": 300, }
try: resp = requests.post( API_URL, headers={ "Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json", }, json=payload, timeout=120, ) data = resp.json() if resp.ok and data.get("choices"): return data["choices"][0]["message"]["content"] err = data.get("error", {}) msg = err.get("message") if isinstance(err, dict) else str(err) return f"發生錯誤:{msg or data}" except Exception as e: return f"發生錯誤:{e}"
CSS = """:root { --neon-cyan: #00f0ff; --neon-purple: #b026ff;}.gradio-container { background-color: #0b0f19 !important; background-image: radial-gradient(circle at 10% 20%, rgba(176, 38, 255, 0.12) 0%, transparent 40%), radial-gradient(circle at 90% 80%, rgba(0, 240, 255, 0.12) 0%, transparent 40%) !important; color: #f3f4f6 !important; max-width: 780px !important; margin: 0 auto !important;}#title h1 { background: linear-gradient(135deg, var(--neon-cyan), var(--neon-purple)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-weight: 800;}#subtitle { color: #9ca3af !important; }#analyze-btn { background: linear-gradient(135deg, var(--neon-cyan), var(--neon-purple)) !important; color: #000 !important; font-weight: 700 !important; border: none !important; box-shadow: 0 4px 15px rgba(0, 240, 255, 0.2) !important;}#analyze-btn:hover { box-shadow: 0 6px 20px rgba(176, 38, 255, 0.45) !important; }"""
with gr.Blocks(css=CSS, title="Gemma 多模態影像分析助手") as demo: with gr.Column(elem_id="title"): gr.Markdown("# Gemma 多模態影像分析助手") with gr.Column(elem_id="subtitle"): gr.Markdown("透過 Hugging Face Router 呼叫多模態模型進行高精度影像辨識與分析。")
with gr.Row(): with gr.Column(): image_in = gr.Image(type="pil", label="上傳圖片") prompt_in = gr.Textbox( label="輸入提示詞 (Prompt)", value="用一句中文描述這張圖片", ) btn = gr.Button("啟動分析", elem_id="analyze-btn", variant="primary") with gr.Column(): output = gr.Textbox(label="模型回應", lines=14, show_copy_button=True)
btn.click(analyze, inputs=[image_in, prompt_in], outputs=output)
demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318<!DOCTYPE html><html lang="zh-Hant"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Gemma 多模態影像分析助手</title> <style> :root { --bg-color: #0b0f19; --card-bg: rgba(17, 24, 39, 0.75); --border-glow: rgba(0, 240, 255, 0.3); --neon-cyan: #00f0ff; --neon-purple: #b026ff; --text-main: #f3f4f6; --text-muted: #9ca3af; }
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; max-width: 650px; margin: 40px auto; padding: 20px; background-color: var(--bg-color); background-image: radial-gradient(circle at 10% 20%, rgba(176, 38, 255, 0.1) 0%, transparent 40%), radial-gradient(circle at 90% 80%, rgba(0, 240, 255, 0.1) 0%, transparent 40%); color: var(--text-main); min-height: 100vh; }
.card { background: var(--card-bg); backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px); padding: 30px; border-radius: 16px; border: 1px solid var(--border-glow); box-shadow: 0 0 30px rgba(0, 240, 255, 0.1), inset 0 0 15px rgba(176, 38, 255, 0.05); position: relative; overflow: hidden; }
.card::before { content: ''; position: absolute; top: 0; left: -100%; width: 100%; height: 2px; background: linear-gradient(90deg, transparent, var(--neon-cyan), transparent); animation: scanline 4s linear infinite; }
@keyframes scanline { 0% { left: -100%; } 100% { left: 100%; } }
h2 { margin-top: 0; font-size: 1.8rem; background: linear-gradient(135deg, var(--neon-cyan), var(--neon-purple)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; letter-spacing: 0.5px; }
p { color: var(--text-muted); font-size: 0.95rem; margin-bottom: 24px; }
.form-group { margin-bottom: 20px; }
label { display: block; font-weight: 600; margin-bottom: 8px; font-size: 0.9rem; color: var(--neon-cyan); letter-spacing: 0.5px; }
input[type="password"], input[type="text"], input[type="file"], textarea { width: 100%; padding: 12px 14px; background: rgba(3, 7, 18, 0.6); border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 8px; box-sizing: border-box; color: var(--text-main); font-size: 0.95rem; transition: all 0.3s ease; }
input:focus { outline: none; border-color: var(--neon-cyan); box-shadow: 0 0 10px rgba(0, 240, 255, 0.3); }
input[type="file"]::file-selector-button { background: rgba(0, 240, 255, 0.1); color: var(--neon-cyan); border: 1px solid var(--neon-cyan); padding: 6px 12px; border-radius: 4px; cursor: pointer; transition: all 0.2s; }
input[type="file"]::file-selector-button:hover { background: var(--neon-cyan); color: #000; }
button { background: linear-gradient(135deg, var(--neon-cyan), var(--neon-purple)); color: #000; border: none; padding: 12px 20px; font-weight: 700; border-radius: 8px; cursor: pointer; width: 100%; font-size: 1rem; letter-spacing: 1px; transition: all 0.3s ease; box-shadow: 0 4px 15px rgba(0, 240, 255, 0.2); }
button:hover { opacity: 0.9; transform: translateY(-1px); box-shadow: 0 6px 20px rgba(176, 38, 255, 0.4); }
button:disabled { background: #374151; color: #9ca3af; cursor: not-allowed; box-shadow: none; transform: none; }
#preview-container { margin-top: 12px; text-align: center; }
#imagePreview { max-width: 100%; max-height: 250px; border-radius: 8px; display: none; border: 1px solid var(--border-glow); box-shadow: 0 4px 12px rgba(0,0,0,0.5); }
#result { margin-top: 12px; padding: 16px; background: rgba(3, 7, 18, 0.8); border: 1px solid rgba(255, 255, 255, 0.08); border-radius: 8px; white-space: pre-wrap; min-height: 60px; font-size: 0.95rem; color: #e5e7eb; box-shadow: inset 0 2px 4px rgba(0,0,0,0.4); } </style></head><body> <div class="card"> <h2>Gemma 多模態影像分析助手</h2> <p>透過 Hugging Face Router 呼叫 gemma-4-31B-it 模型進行高精度影像辨識與分析。</p> <div class="form-group"> <label for="imageInput">上傳圖片</label> <input type="file" id="imageInput" accept="image/*" onchange="previewSelectedImage(event)"> <div id="preview-container"> <img id="imagePreview" alt="圖片預覽"> </div> </div> <div class="form-group"> <label for="promptInput">輸入提示詞 (Prompt)</label> <input type="text" id="promptInput" value="Describe this image in one sentence in chinese"> </div> <button id="submitBtn" onclick="analyzeImage()">啟動分析</button> <div class="form-group" style="margin-top: 24px;"> <label>模型回應</label> <div id="result">系統待命,尚未開始分析...</div> </div> </div>
<script> // 選擇圖片時即時顯示預覽 function previewSelectedImage(event) { const file = event.target.files[0]; const preview = document.getElementById('imagePreview'); if (file) { const reader = new FileReader(); reader.onload = function(e) { preview.src = e.target.result; preview.style.display = 'inline-block'; } reader.readAsDataURL(file); } else { preview.src = ''; preview.style.display = 'none'; } }
// 壓縮並轉成 Base64 的前端實作 function compressImage(file, maxSize = 1024, quality = 0.85) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = function(e) { const img = new Image(); img.onload = function() { let width = img.width; let height = img.height; if (width > height) { if (width > maxSize) { height *= maxSize / width; width = maxSize; } } else { if (height > maxSize) { width *= maxSize / height; height = maxSize; } } const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); const dataUrl = canvas.toDataURL('image/jpeg', quality); resolve(dataUrl); }; img.src = e.target.result; }; reader.onerror = reject; reader.readAsDataURL(file); }); }
// ⚠️ 請在此填入你的 HF_TOKEN,否則 Router API 會回 401 const HF_TOKEN = "";
// 可更換的模型 ID(Hugging Face Router 支援的多模態模型) // 例如:google/gemma-3-27b-it, Qwen/Qwen2.5-VL-72B-Instruct, meta-llama/Llama-3.2-11B-Vision-Instruct const MODEL_ID = "google/gemma-3-27b-it";
async function analyzeImage() { const imageFile = document.getElementById('imageInput').files[0]; let prompt = document.getElementById('promptInput').value.trim(); const resultDiv = document.getElementById('result'); const submitBtn = document.getElementById('submitBtn');
if (!imageFile) { alert('請先上傳一張圖片!'); return; } if (!prompt) { prompt = "Describe this image in one sentence."; }
submitBtn.disabled = true; resultDiv.innerText = '處理中,神經網路運算中...';
try { const base64Image = await compressImage(imageFile); const response = await fetch("https://router.huggingface.co/v1/chat/completions", { method: "POST", headers: { "Authorization": `Bearer ${HF_TOKEN}`, "Content-Type": "application/json" }, body: JSON.stringify({ model: MODEL_ID, messages: [{ role: "user", content: [ { type: "text", text: prompt }, { type: "image_url", image_url: { url: base64Image } } ] }], max_tokens: 300 }) });
const data = await response.json(); if (response.ok && data.choices && data.choices.length > 0) { resultDiv.innerText = data.choices[0].message.content; } else { resultDiv.innerText = `發生錯誤:${data.error?.message || JSON.stringify(data)}`; } } catch (error) { resultDiv.innerText = `發生錯誤:${error.message}`; } finally { submitBtn.disabled = false; } } </script></body></html>123gradio>=4.44.0requestsPillow12345678910111213141516171819202122232425262728body { padding: 2rem; font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;}
h1 { font-size: 16px; margin-top: 0;}
p { color: rgb(107, 114, 128); font-size: 15px; margin-bottom: 10px; margin-top: 5px;}
.card { max-width: 620px; margin: 0 auto; padding: 16px; border: 1px solid lightgray; border-radius: 16px;}
.card p:last-child { margin-bottom: 0;}README.md+12-3
app.pyAdded+107
index.htmlDeleted-318
requirements.txtAdded+3
style.cssDeleted-28