| | import os, json, requests, gradio as gr |
| | |
| | import gradio_client.utils as _gcu |
| | if not getattr(_gcu, "_patched_bool", False): |
| | _orig_get_type = _gcu.get_type |
| | def _get_type_fixed(schema): |
| | if isinstance(schema, bool): |
| | return "boolean" |
| | return _orig_get_type(schema) |
| | _gcu.get_type = _get_type_fixed |
| | _gcu._patched_bool = True |
| |
|
| | |
| | APP_PASSWORD = os.getenv("APP_PASSWORD", "") |
| | RUNPOD_TOKEN = os.getenv("RUNPOD_BEARER_TOKEN") |
| | RUNPOD_ENDPOINT_ID = os.getenv("RUNPOD_ENDPOINT_ID") |
| | if RUNPOD_ENDPOINT_ID: |
| | URL = f"https://api.runpod.ai/v2/{RUNPOD_ENDPOINT_ID}/runsync" |
| | else: |
| | URL = None |
| | HEAD = {"Authorization": f"Bearer {RUNPOD_TOKEN}"} if RUNPOD_TOKEN else {} |
| |
|
| | |
| |
|
| | def call_backend(query: str) -> str: |
| | if not URL or not RUNPOD_TOKEN: |
| | return "❌ 未設定 RunPod 端點或 Bearer Token" |
| | try: |
| | r = requests.post(URL, json={"input": {"query": query}}, headers=HEAD, timeout=180) |
| | r.raise_for_status() |
| | data = r.json().get("output", r.json()) |
| | return data.get("answer") if isinstance(data, dict) else json.dumps(data, ensure_ascii=False) |
| | except Exception as e: |
| | return f"❌ 後端錯誤:{e}" |
| |
|
| | |
| |
|
| | def auth(password_entered): |
| | if password_entered == APP_PASSWORD: |
| | return gr.update(visible=False), gr.update(visible=True), "" |
| | else: |
| | return gr.update(value="❌ 密碼錯誤,請再試一次", visible=True), gr.update(visible=False), "" |
| |
|
| | def respond(msg, history): |
| | answer = call_backend(msg) |
| | history = history or [] |
| | history.append({"role": "user", "content": msg}) |
| | history.append({"role": "assistant", "content": answer}) |
| | return "", history |
| |
|
| | with gr.Blocks(title="RAG Demo – RunPod") as demo: |
| | gr.Markdown("""# 📚 私有 RAG Demo (需密碼)""") |
| |
|
| | pwd_box = gr.Textbox(type="password", placeholder="輸入密碼…", label="Password") |
| | pwd_err = gr.Markdown(visible=False) |
| | unlock = gr.Button("Unlock") |
| |
|
| | with gr.Column(visible=False) as chat_col: |
| | chatbot = gr.Chatbot(value=[], type="messages", show_copy_button=True) |
| | txt = gr.Textbox(placeholder="輸入問題…", show_label=False) |
| | send = gr.Button("送出", variant="primary") |
| | clear = gr.Button("清空對話") |
| |
|
| | unlock.click(auth, inputs=pwd_box, outputs=[pwd_err, chat_col, pwd_box]) |
| | send.click(respond, [txt, chatbot], [txt, chatbot]) |
| | clear.click(lambda: [], None, chatbot, queue=False) |
| |
|
| | if __name__ == "__main__": |
| | demo.launch() |
| |
|