zaidulhassan79 commited on
Commit
7984522
·
verified ·
1 Parent(s): 175607e

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -0
app.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tempfile
3
+ import asyncio
4
+ from fastapi import FastAPI, UploadFile, File, Request, HTTPException
5
+ from fastapi.middleware.cors import CORSMiddleware
6
+ from paddleocr import PaddleOCR
7
+
8
+ MAX_FILE_SIZE = 900 * 1024
9
+ MAX_CONCURRENT_REQUESTS = 6
10
+
11
+ ALLOWED_ORIGINS = {
12
+ "https://delivqr.com",
13
+ "https://www.delivqr.com",
14
+ "https://kreeboo.com",
15
+ "https://www.kreeboo.com",
16
+ }
17
+
18
+ app = FastAPI(title="Paddle OCR API")
19
+
20
+ app.add_middleware(
21
+ CORSMiddleware,
22
+ allow_origins=list(ALLOWED_ORIGINS),
23
+ allow_credentials=True,
24
+ allow_methods=["POST"],
25
+ allow_headers=["*"],
26
+ )
27
+
28
+ semaphore = asyncio.Semaphore(MAX_CONCURRENT_REQUESTS)
29
+ ocr_models = {}
30
+
31
+ @app.on_event("startup")
32
+ def load_model():
33
+ ocr_models["en"] = PaddleOCR(
34
+ lang="en",
35
+ use_angle_cls=False,
36
+ show_log=False
37
+ )
38
+
39
+ @app.middleware("http")
40
+ async def restrict_domain(request: Request, call_next):
41
+ origin = request.headers.get("origin")
42
+ referer = request.headers.get("referer")
43
+
44
+ if origin not in ALLOWED_ORIGINS and not (
45
+ referer and any(referer.startswith(o) for o in ALLOWED_ORIGINS)
46
+ ):
47
+ raise HTTPException(status_code=403, detail="Access denied")
48
+
49
+ return await call_next(request)
50
+
51
+
52
+ @app.post("/ocr")
53
+ async def ocr_api(file: UploadFile = File(...)):
54
+ async with semaphore:
55
+
56
+ data = await file.read()
57
+
58
+ if len(data) > MAX_FILE_SIZE:
59
+ raise HTTPException(413, "Image too large")
60
+
61
+ if not file.content_type or not file.content_type.startswith("image/"):
62
+ raise HTTPException(400, "Only image files allowed")
63
+
64
+ with tempfile.NamedTemporaryFile(delete=False) as tmp:
65
+ tmp.write(data)
66
+ tmp_path = tmp.name
67
+
68
+ try:
69
+ result = ocr_models["en"].ocr(tmp_path)
70
+ except Exception as e:
71
+ raise HTTPException(500, f"OCR failed: {str(e)}")
72
+ finally:
73
+ os.remove(tmp_path)
74
+
75
+ return {
76
+ "language": "en",
77
+ "lines": [line[1][0] for line in result[0]]
78
+ }