import gradio as gr import requests import mimetypes import json, os import asyncio import aiohttp LLM_API = os.environ.get("LLM_API") LLM_URL = os.environ.get("LLM_URL") USER_ID = "HuggingFace Space" async def send_chat_message(LLM_URL, LLM_API, user_input, file_id): payload = { "inputs": {}, "query": user_input, "response_mode": "streaming", "conversation_id": "", "user": USER_ID, "files": [{ "type": "image", "transfer_method": "local_file", "upload_file_id": file_id }] } 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 == 404: return "Error: Endpoint not found (404)" last_thought = None async for line in response.content: if line: try: data = json.loads(line.decode("utf-8").replace("data: ", "")) if data.get("data", {}).get("outputs", {}).get("answer"): last_thought = data["data"]["outputs"]["answer"] break except Exception: continue return last_thought.strip() if last_thought else "Error: No answer found." 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" mime_type, _ = mimetypes.guess_type(file_path) with open(file_path, 'rb') as f: async with aiohttp.ClientSession() as session: form_data = aiohttp.FormData() form_data.add_field('file', f, filename=file_path, 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: Upload endpoint not found" text = await response.text() try: json_resp = json.loads(text) return json_resp except json.JSONDecodeError: return "Error: Upload returned invalid JSON" async def handle_input(file_path, user_input): upload_response = await upload_file(LLM_URL, LLM_API, file_path, USER_ID) if isinstance(upload_response, str) and "Error" in upload_response: return upload_response file_id = upload_response.get("id") if not file_id: return "Error: No file ID from upload" return await send_chat_message(LLM_URL, LLM_API, user_input, file_id) # --- Gradio UI 設定 --- 定義界面標題和描述 TITLE = """