Genzo1010 commited on
Commit
cf623b2
·
verified ·
1 Parent(s): 853d071

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -64
app.py CHANGED
@@ -1,19 +1,71 @@
1
- import logging
2
- from fastapi import FastAPI, File, UploadFile, HTTPException
3
  from fastapi.middleware.cors import CORSMiddleware
 
 
 
4
  from paddleocr import PaddleOCR
5
  from doctr.io import DocumentFile
6
  from doctr.models import ocr_predictor
7
- import numpy as np
8
- from PIL import Image
9
  import io
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- # Set up logging
12
- logging.basicConfig(level=logging.INFO)
13
- logger = logging.getLogger(__name__)
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- app = FastAPI()
 
 
 
 
 
 
 
 
 
 
 
16
 
 
 
 
 
 
 
 
17
  app.add_middleware(
18
  CORSMiddleware,
19
  allow_origins=["*"],
@@ -22,59 +74,5 @@ app.add_middleware(
22
  allow_headers=["*"],
23
  )
24
 
25
- # Initialize models once at startup
26
- ocr_model = ocr_predictor(pretrained=True)
27
- paddle_ocr = PaddleOCR(lang='en', use_angle_cls=True)
28
-
29
- def ocr_with_doctr(file):
30
- text_output = ''
31
- try:
32
- logger.info("Processing PDF with Doctr...")
33
- doc = DocumentFile.from_pdf(file)
34
- result = ocr_model(doc)
35
- for page in result.pages:
36
- for block in page.blocks:
37
- for line in block.lines:
38
- text_output += " ".join([word.value for word in line.words]) + "\n"
39
- except Exception as e:
40
- logger.error(f"Error processing PDF: {e}")
41
- raise HTTPException(status_code=500, detail=f"Error processing PDF: {e}")
42
- return text_output
43
-
44
- def ocr_with_paddle(img):
45
- finaltext = ''
46
- try:
47
- logger.info("Processing image with PaddleOCR...")
48
- result = paddle_ocr.ocr(img)
49
- for i in range(len(result[0])):
50
- text = result[0][i][1][0]
51
- finaltext += ' ' + text
52
- except Exception as e:
53
- logger.error(f"Error processing image: {e}")
54
- raise HTTPException(status_code=500, detail=f"Error processing image: {e}")
55
- return finaltext
56
-
57
- @app.post("/ocr/")
58
- async def perform_ocr(file: UploadFile = File(...)):
59
- try:
60
- logger.info(f"Received file: {file.filename}")
61
- file_bytes = await file.read()
62
-
63
- if file.filename.endswith('.pdf'):
64
- logger.info("Detected PDF file")
65
- text_output = ocr_with_doctr(io.BytesIO(file_bytes))
66
- else:
67
- logger.info("Detected image file")
68
- img = np.array(Image.open(io.BytesIO(file_bytes)))
69
- text_output = ocr_with_paddle(img)
70
-
71
- logger.info("OCR completed successfully")
72
- return {"ocr_text": text_output}
73
-
74
- except Exception as e:
75
- logger.error(f"Internal server error: {e}")
76
- raise HTTPException(status_code=500, detail=f"Internal server error: {e}")
77
-
78
- @app.get("/test/")
79
- async def test_call():
80
- return {"message": "Hi. I'm running"}
 
1
+ import uvicorn
2
+ from fastapi import FastAPI, UploadFile, File, HTTPException
3
  from fastapi.middleware.cors import CORSMiddleware
4
+ from typing import Optional
5
+ import numpy as np
6
+ from PIL import Image
7
  from paddleocr import PaddleOCR
8
  from doctr.io import DocumentFile
9
  from doctr.models import ocr_predictor
 
 
10
  import io
11
+ import logging
12
+
13
+ class OCRAPIApp:
14
+ def __init__(self):
15
+ self.app = FastAPI(
16
+ docs_url="/",
17
+ title="OCR API",
18
+ version="1.0",
19
+ )
20
+ self.setup_routes()
21
+ self.paddle_ocr = PaddleOCR(lang='en', use_angle_cls=True)
22
+ self.doctr_model = ocr_predictor(pretrained=True)
23
+
24
+ def ocr_with_paddle(self, img):
25
+ try:
26
+ logging.info("Processing image with PaddleOCR...")
27
+ result = self.paddle_ocr.ocr(img)
28
+ text_output = ' '.join([line[1][0] for line in result[0]])
29
+ return text_output
30
+ except Exception as e:
31
+ logging.error(f"Error with PaddleOCR: {e}")
32
+ raise HTTPException(status_code=500, detail="Error processing image")
33
 
34
+ def ocr_with_doctr(self, file):
35
+ try:
36
+ logging.info("Processing PDF with Doctr...")
37
+ doc = DocumentFile.from_pdf(file)
38
+ result = self.doctr_model(doc)
39
+ text_output = ''
40
+ for page in result.pages:
41
+ for block in page.blocks:
42
+ for line in block.lines:
43
+ text_output += ' '.join([word.value for word in line.words]) + "\n"
44
+ return text_output
45
+ except Exception as e:
46
+ logging.error(f"Error with Doctr: {e}")
47
+ raise HTTPException(status_code=500, detail="Error processing PDF")
48
 
49
+ async def ocr_endpoint(self, file: UploadFile = File(...)):
50
+ try:
51
+ file_bytes = await file.read()
52
+ if file.filename.endswith(".pdf"):
53
+ text_output = self.ocr_with_doctr(io.BytesIO(file_bytes))
54
+ else:
55
+ img = np.array(Image.open(io.BytesIO(file_bytes)))
56
+ text_output = self.ocr_with_paddle(img)
57
+ return {"ocr_text": text_output}
58
+ except Exception as e:
59
+ logging.error(f"Error processing file: {e}")
60
+ raise HTTPException(status_code=500, detail="Error processing file")
61
 
62
+ def setup_routes(self):
63
+ self.app.post("/ocr")(self.ocr_endpoint)
64
+
65
+ # Initialize the app
66
+ app = OCRAPIApp().app
67
+
68
+ # Add CORS middleware for cross-origin requests
69
  app.add_middleware(
70
  CORSMiddleware,
71
  allow_origins=["*"],
 
74
  allow_headers=["*"],
75
  )
76
 
77
+ if __name__ == "__main__":
78
+ uvicorn.run("your_file_name:app", host="0.0.0.0", port=8000, reload=True)