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()