File size: 1,751 Bytes
06bd65a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from src.api.routes import router
from src.services.ocr_engine import ocr_service
import urllib.request
import threading
import time

app = FastAPI(
    title="PaddleOCR API Service",
    description="High-performance, CPU-optimized API backend for PaddleOCR",
    version="1.0.0"
)

# Enable CORS (Cross-Origin Resource Sharing)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Register routes
app.include_router(router)

def ping_webrtc_loop():
    """Background loop that pings the WebRTC space every 3 hours to prevent it from sleeping."""
    time.sleep(30)  # Wait for startup
    while True:
        try:
            req = urllib.request.Request(
                "https://webrtc.blindtechcommunity.com/health",
                headers={"User-Agent": "Mozilla/5.0"}
            )
            with urllib.request.urlopen(req, timeout=15) as response:
                print(f"[Keep-Alive] Pinged WebRTC signaling server. Status: {response.status}")
        except Exception as e:
            print(f"[Keep-Alive] Failed to ping WebRTC signaling server: {e}")
        time.sleep(10800)  # Ping every 3 hours

@app.on_event("startup")
def startup_event():
    """Warm up the English OCR engine on startup so the first request is instant."""
    print("Startup: Warming up default OCR engine...")
    ocr_service.get_engine("en")
    print("Startup: Default OCR engine is warm and ready.")
    
    # Start background keep-alive ping for the WebRTC space
    threading.Thread(target=ping_webrtc_loop, daemon=True).start()