Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,24 +1,56 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
)
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
interface.launch()
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import threading
|
| 3 |
+
import time
|
| 4 |
+
import requests
|
| 5 |
+
from OCR_test import process_image
|
| 6 |
+
|
| 7 |
+
# ====== Keep-Alive Background Thread ======
|
| 8 |
+
def keep_alive_worker():
|
| 9 |
+
# 替换为你的 HF Space 实际访问 URL(注意格式!)
|
| 10 |
+
space_url = "https://fcu52005505--test.hf.space"
|
| 11 |
+
interval_sec = 60 # 1 分钟 = 60 秒
|
| 12 |
+
|
| 13 |
+
print(f"[Keep-Alive] Starting background pinger. Pinging {space_url} every {interval_sec} seconds...")
|
| 14 |
+
|
| 15 |
+
while True:
|
| 16 |
+
try:
|
| 17 |
+
# 发送 HEAD 请求(轻量,不下载内容)
|
| 18 |
+
response = requests.head(space_url, timeout=10)
|
| 19 |
+
status = response.status_code
|
| 20 |
+
print(f"[Keep-Alive] Pinged at {time.strftime('%Y-%m-%d %H:%M:%S')} | Status: {status}")
|
| 21 |
+
except Exception as e:
|
| 22 |
+
print(f"[Keep-Alive] ⚠️ Ping failed at {time.strftime('%Y-%m-%d %H:%M:%S')}: {e}")
|
| 23 |
+
|
| 24 |
+
time.sleep(interval_sec)
|
| 25 |
+
|
| 26 |
+
# 启动后台线程(daemon=True 保证主线程退出时它也退出)
|
| 27 |
+
threading.Thread(target=keep_alive_worker, daemon=True).start()
|
| 28 |
+
|
| 29 |
+
# ====== OCR Inference Function ======
|
| 30 |
+
def detect_objects(image):
|
| 31 |
+
try:
|
| 32 |
+
if image is None:
|
| 33 |
+
return "Error: No image uploaded."
|
| 34 |
+
# Call the `process_image` function with the image path
|
| 35 |
+
result = process_image(image)
|
| 36 |
+
return result
|
| 37 |
+
except Exception as e:
|
| 38 |
+
return f"Error: {e}"
|
| 39 |
+
|
| 40 |
+
# ====== Gradio Interface ======
|
| 41 |
+
interface = gr.Interface(
|
| 42 |
+
fn=detect_objects,
|
| 43 |
+
inputs=gr.Image(type="filepath", label="Upload Image"),
|
| 44 |
+
outputs=gr.Textbox(label="Detection Results"),
|
| 45 |
+
title="OCR Detection (Auto-Keep-Alive Enabled)",
|
| 46 |
+
description="Upload an image to get OCR results. This Space pings itself every 60s to avoid sleeping.",
|
| 47 |
+
examples=[
|
| 48 |
+
# 可选:添加示例图片路径(若你有放在 Space repo 的 example_images/)
|
| 49 |
+
# ["example_images/sample1.jpg"]
|
| 50 |
+
]
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# ====== Launch ======
|
| 54 |
+
if __name__ == "__main__":
|
| 55 |
+
# 注意:HF Spaces 会忽略 `server_name` 和 `server_port`
|
| 56 |
interface.launch()
|