Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import requests | |
| import os # ✅ 用于读取 secret | |
| # ✅ 从 Hugging Face Secret 中获取 token | |
| API_TOKEN = os.getenv("HF_API_TOKEN") | |
| gr.Textbox(API_TOKEN, label="API Token", interactive=False) | |
| # ✅ 你私有后端的空间地址(注意大小写) | |
| BACKEND_URL = "https://dsbb0707-SpatialParseback.hf.space/api/predict/" | |
| def call_backend(input_text): | |
| try: | |
| # ✅ 加入 Authorization 头 | |
| headers = { | |
| "Authorization": f"Bearer {API_TOKEN}" | |
| } | |
| response = requests.post( | |
| BACKEND_URL, | |
| headers=headers, # ✅ 加入 header | |
| json={"data": [input_text]}, | |
| timeout=10 | |
| ) | |
| if response.status_code == 200: | |
| result = response.json()["data"][0] | |
| return f"✅ {result['result']}\n⏰ {result['timestamp']}" | |
| return f"❌ Backend Error (HTTP {response.status_code})" | |
| except Exception as e: | |
| return f"⚠️ Connection Error: {str(e)}" | |
| # ✅ Gradio 界面构建 | |
| with gr.Blocks() as demo: | |
| gr.Markdown("## 前端交互界面") | |
| with gr.Row(): | |
| input_box = gr.Textbox(label="输入文本", placeholder="请输入...") | |
| output_box = gr.Textbox(label="处理结果", interactive=False) | |
| submit_btn = gr.Button("提交", variant="primary") | |
| submit_btn.click( | |
| fn=call_backend, | |
| inputs=input_box, | |
| outputs=output_box | |
| ) | |
| # ✅ 正确的 Gradio 启动方式 | |
| if __name__ == "__main__": | |
| demo.launch(server_name="0.0.0.0", server_port=7860) | |