Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import threading | |
| import time | |
| import requests | |
| from OCR_test import process_image | |
| # ====== Keep-Alive Background Thread ====== | |
| def keep_alive_worker(): | |
| # 替换为你的 HF Space 实际访问 URL(注意格式!) | |
| space_url = "https://fcu52005505-test.hf.space" | |
| interval_sec = 86400 # 1 分钟 = 60 秒 | |
| print(f"[Keep-Alive] Starting background pinger. Pinging {space_url} every {interval_sec} seconds...") | |
| while True: | |
| try: | |
| # 发送 HEAD 请求(轻量,不下载内容) | |
| response = requests.head(space_url, timeout=10) | |
| status = response.status_code | |
| print(f"[Keep-Alive] Pinged at {time.strftime('%Y-%m-%d %H:%M:%S')} | Status: {status}") | |
| except Exception as e: | |
| print(f"[Keep-Alive] ⚠️ Ping failed at {time.strftime('%Y-%m-%d %H:%M:%S')}: {e}") | |
| time.sleep(interval_sec) | |
| # 启动后台线程(daemon=True 保证主线程退出时它也退出) | |
| threading.Thread(target=keep_alive_worker, daemon=True).start() | |
| # ====== OCR Inference Function ====== | |
| def detect_objects(image): | |
| try: | |
| if image is None: | |
| return "Error: No image uploaded." | |
| # Call the `process_image` function with the image path | |
| result = process_image(image) | |
| return result | |
| except Exception as e: | |
| return f"Error: {e}" | |
| # ====== Gradio Interface ====== | |
| interface = gr.Interface( | |
| fn=detect_objects, | |
| inputs=gr.Image(type="filepath", label="Upload Image"), | |
| outputs=gr.Textbox(label="Detection Results"), | |
| title="OCR Detection", | |
| description="Upload an image to get OCR results.", | |
| examples=[ | |
| # 可选:添加示例图片路径(若你有放在 Space repo 的 example_images/) | |
| # ["example_images/sample1.jpg"] | |
| ] | |
| ) | |
| # ====== Launch ====== | |
| if __name__ == "__main__": | |
| # 注意:HF Spaces 会忽略 `server_name` 和 `server_port` | |
| interface.launch() |