import gradio as gr import requests import mimetypes import json, os import asyncio import aiohttp import subprocess # pip 升級 def upgrade_pip(): try: subprocess.check_call([os.sys.executable, "-m", "pip", "install", "--upgrade", "pip"]) print("pip 升級成功") except subprocess.CalledProcessError: print("pip 升級失敗") upgrade_pip() LLM_API = os.environ.get("LLM_API", "").strip() LLM_URL = os.environ.get("LLM_URL") USER_ID = "HuggingFace Space" async def send_chat_message(LLM_URL, LLM_API, category, file_url): payload = { "inputs": {}, "query": category, "conversation_id": "", "user": USER_ID, "response_mode": "streaming", "files": [ { "type": "image", "transfer_method": "remote_url", "url": file_url } ] } answer = "" async with aiohttp.ClientSession() as session: async with session.post( f"{LLM_URL}/chat-messages", headers={ "Authorization": f"Bearer {LLM_API}", "Content-Type": "application/json" }, json=payload ) as response: async for line_bytes in response.content: line = line_bytes.decode("utf-8").strip() if line.startswith("data: "): try: data = json.loads(line[6:]) if "answer" in data: answer += data["answer"] except: continue return answer or "No answer returned" # async def send_chat_message(LLM_URL, LLM_API, category, file_id): # payload = { # "inputs": {}, # "query": category, # "conversation_id": "", # "user": USER_ID, # "files": [ # { # "type": "image", # "transfer_method": "remote_url", # "upload_file_id": file_id # } # ] # } # try: # async with aiohttp.ClientSession() as session: # async with session.post( # f"{LLM_URL}/chat-messages", # headers={"Authorization": f"Bearer {LLM_API}"}, # json=payload # ) as response: # if response.status != 200: # error_text = await response.text() # return f"Error: Server returned status {response.status} - {error_text}" # try: # data = await response.json() # return data.get("thought", "Error: No thought in response") # except Exception as e: # return f"Error: Failed to parse JSON - {e}" # except Exception as e: # return f"Error: Unexpected exception - {e}" async def upload_file(LLM_URL, LLM_API, file_path, user_id): if not os.path.exists(file_path): return f"Error: File {file_path} not found" # ✅ 先定義 filename 和 mime_type mime_type, _ = mimetypes.guess_type(file_path) filename = os.path.basename(file_path) # ✅ print 放在這裡 print("Uploading file:", filename, "mime_type:", mime_type) with open(file_path, 'rb') as f: async with aiohttp.ClientSession() as session: form_data = aiohttp.FormData() form_data.add_field('file', f, filename=filename, content_type=mime_type) form_data.add_field('user', user_id) async with session.post( f"{LLM_URL}/files/upload", headers={"Authorization": f"Bearer {LLM_API}"}, data=form_data ) as response: if response.status == 404: return "Error: Endpoint not found (404)" response_text = await response.text() print("Upload response:", response_text) try: return json.loads(response_text) except json.JSONDecodeError: return "Error: Invalid JSON response" async def handle_input(file_path, category): # 取得檔名 filename = os.path.basename(file_path) # 直接用 HuggingFace repo URL file_url = f"https://huggingface.co/spaces/DeepLearning101/Multimodal-Playground/blob/main/DEMO/{filename}?raw=true" return await send_chat_message(LLM_URL, LLM_API, category, file_url) # async def handle_input(file_path, category): # # 如果 tmp 路徑不存在,改成 repo 內的 DEMO 路徑 # if not os.path.exists(file_path): # file_path = os.path.join("DEMO", os.path.basename(file_path)) # upload_response = await upload_file(LLM_URL, LLM_API, file_path, USER_ID) # if isinstance(upload_response, str) and upload_response.startswith("Error"): # return upload_response # file_id = upload_response.get("id") # if not file_id: # return "Error: No file ID returned from upload" # return await send_chat_message(LLM_URL, LLM_API, category, file_id) # UI 元件 & 資料 examples = [ ['DEMO/Medical1.jpg', '診斷證明書'], ['DEMO/Medical2.jpg', '診斷證明書'], ['DEMO/passport.png', '護照'], ['DEMO/residence.png', '居留證'], ['DEMO/boarding-pass.png', '機票'], ['DEMO/taxi.jpg', '計程車乘車證明'], ['DEMO/etag.jpg', '通行明細 (etag)'], ["DEMO/qrcode.jpg", 'QRCODE發票'], ['DEMO/mthsr.JPG', '超商高鐵車票'], ['DEMO/thsr.jpg', '高鐵車票'], ['DEMO/mtra.jpg', '超商台鐵車票'], ['DEMO/tra.JPG', '台鐵車票'], ['DEMO/ID-back.png', '身份證背面'], ['DEMO/ID.png', '身份證正面'], ['DEMO/health.png', '健保卡'], ] TITLE = """