Fix: lazy-load OCR model and smart URL auto-detection
Browse files- index.html +8 -2
- main.py +20 -10
index.html
CHANGED
|
@@ -345,9 +345,15 @@
|
|
| 345 |
const copyApiKeyBtn = document.getElementById('copyApiKeyBtn');
|
| 346 |
|
| 347 |
// Auto-detect the correct API URL based on where this page is being served from
|
| 348 |
-
// Works both locally and on HuggingFace/Render/any public host
|
| 349 |
const apiUrlInput = document.getElementById('apiUrl');
|
| 350 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
apiUrlInput.value = baseUrl + '/ocr';
|
| 352 |
|
| 353 |
let selectedFile = null;
|
|
|
|
| 345 |
const copyApiKeyBtn = document.getElementById('copyApiKeyBtn');
|
| 346 |
|
| 347 |
// Auto-detect the correct API URL based on where this page is being served from
|
|
|
|
| 348 |
const apiUrlInput = document.getElementById('apiUrl');
|
| 349 |
+
const host = window.location.hostname;
|
| 350 |
+
let baseUrl;
|
| 351 |
+
if (host === 'localhost' || host === '127.0.0.1') {
|
| 352 |
+
baseUrl = 'http://localhost:4002';
|
| 353 |
+
} else {
|
| 354 |
+
// On HuggingFace Spaces or any other public host, use same origin
|
| 355 |
+
baseUrl = window.location.protocol + '//' + window.location.host;
|
| 356 |
+
}
|
| 357 |
apiUrlInput.value = baseUrl + '/ocr';
|
| 358 |
|
| 359 |
let selectedFile = null;
|
main.py
CHANGED
|
@@ -2,8 +2,6 @@ from fastapi import FastAPI, Depends, HTTPException, status, UploadFile, File
|
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from fastapi.responses import HTMLResponse, FileResponse
|
| 4 |
from fastapi.security import APIKeyHeader
|
| 5 |
-
from PIL import Image
|
| 6 |
-
import easyocr
|
| 7 |
import io
|
| 8 |
import os
|
| 9 |
|
|
@@ -12,16 +10,26 @@ app = FastAPI(title="Image OCR API")
|
|
| 12 |
# Add CORS middleware to allow other websites to connect
|
| 13 |
app.add_middleware(
|
| 14 |
CORSMiddleware,
|
| 15 |
-
allow_origins=["*"],
|
| 16 |
allow_credentials=True,
|
| 17 |
-
allow_methods=["*"],
|
| 18 |
-
allow_headers=["*"],
|
| 19 |
)
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
|
|
|
| 23 |
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
# You can override this securely in HuggingFace Settings -> Secrets
|
| 26 |
API_KEY = os.environ.get("API_KEY", "xkLm9Qz4BvWtUa2Nf8PjX1")
|
| 27 |
API_KEY_NAME = "x-api-key"
|
|
@@ -43,7 +51,7 @@ async def serve_ui():
|
|
| 43 |
try:
|
| 44 |
return FileResponse("index.html")
|
| 45 |
except Exception:
|
| 46 |
-
raise HTTPException(status_code=404, detail="index.html not found.
|
| 47 |
|
| 48 |
@app.post("/ocr", tags=["OCR"])
|
| 49 |
async def perform_ocr(
|
|
@@ -60,6 +68,9 @@ async def perform_ocr(
|
|
| 60 |
try:
|
| 61 |
contents = await file.read()
|
| 62 |
|
|
|
|
|
|
|
|
|
|
| 63 |
# Perform OCR extraction using EasyOCR
|
| 64 |
result = reader.readtext(contents, detail=0)
|
| 65 |
extracted_text = "\n".join(result)
|
|
@@ -74,6 +85,5 @@ async def perform_ocr(
|
|
| 74 |
|
| 75 |
if __name__ == "__main__":
|
| 76 |
import uvicorn
|
| 77 |
-
# If Render or another platform injects a specific port, use it, otherwise use our local 4002
|
| 78 |
port = int(os.environ.get("PORT", 4002))
|
| 79 |
uvicorn.run("main:app", host="0.0.0.0", port=port, reload=True)
|
|
|
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from fastapi.responses import HTMLResponse, FileResponse
|
| 4 |
from fastapi.security import APIKeyHeader
|
|
|
|
|
|
|
| 5 |
import io
|
| 6 |
import os
|
| 7 |
|
|
|
|
| 10 |
# Add CORS middleware to allow other websites to connect
|
| 11 |
app.add_middleware(
|
| 12 |
CORSMiddleware,
|
| 13 |
+
allow_origins=["*"],
|
| 14 |
allow_credentials=True,
|
| 15 |
+
allow_methods=["*"],
|
| 16 |
+
allow_headers=["*"],
|
| 17 |
)
|
| 18 |
|
| 19 |
+
# Lazy-load the OCR reader — only initializes on first use, not at startup
|
| 20 |
+
# This prevents the app from crashing on HuggingFace before it can accept requests
|
| 21 |
+
_reader = None
|
| 22 |
|
| 23 |
+
def get_reader():
|
| 24 |
+
global _reader
|
| 25 |
+
if _reader is None:
|
| 26 |
+
import easyocr
|
| 27 |
+
print("Loading OCR Model for the first time... Please wait!")
|
| 28 |
+
_reader = easyocr.Reader(['en'])
|
| 29 |
+
print("OCR Model loaded successfully!")
|
| 30 |
+
return _reader
|
| 31 |
+
|
| 32 |
+
# Define the API Key (strong 0-9, a-z, A-Z pattern)
|
| 33 |
# You can override this securely in HuggingFace Settings -> Secrets
|
| 34 |
API_KEY = os.environ.get("API_KEY", "xkLm9Qz4BvWtUa2Nf8PjX1")
|
| 35 |
API_KEY_NAME = "x-api-key"
|
|
|
|
| 51 |
try:
|
| 52 |
return FileResponse("index.html")
|
| 53 |
except Exception:
|
| 54 |
+
raise HTTPException(status_code=404, detail="index.html not found.")
|
| 55 |
|
| 56 |
@app.post("/ocr", tags=["OCR"])
|
| 57 |
async def perform_ocr(
|
|
|
|
| 68 |
try:
|
| 69 |
contents = await file.read()
|
| 70 |
|
| 71 |
+
# Get reader (lazy-loaded on first call)
|
| 72 |
+
reader = get_reader()
|
| 73 |
+
|
| 74 |
# Perform OCR extraction using EasyOCR
|
| 75 |
result = reader.readtext(contents, detail=0)
|
| 76 |
extracted_text = "\n".join(result)
|
|
|
|
| 85 |
|
| 86 |
if __name__ == "__main__":
|
| 87 |
import uvicorn
|
|
|
|
| 88 |
port = int(os.environ.get("PORT", 4002))
|
| 89 |
uvicorn.run("main:app", host="0.0.0.0", port=port, reload=True)
|