Genzo1010 commited on
Commit
8377b76
·
verified ·
1 Parent(s): b93dc02

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile +20 -0
  2. app.py +80 -0
  3. requirements.txt +9 -0
Dockerfile ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use the official Python image as a base image
2
+ FROM python:3.9
3
+
4
+ # Set the working directory in the container
5
+ WORKDIR /app
6
+
7
+ # Copy the requirements file to the container
8
+ COPY requirements.txt .
9
+
10
+ # Install any necessary dependencies
11
+ RUN pip install --no-cache-dir -r requirements.txt
12
+
13
+ # Copy the rest of the application code to the container
14
+ COPY . .
15
+
16
+ # Expose the port that the FastAPI app will run on
17
+ EXPOSE 8000
18
+
19
+ # Command to run the FastAPI app using Uvicorn
20
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
app.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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=["*"],
20
+ allow_credentials=True,
21
+ allow_methods=["*"],
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"}
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ fastapi==0.112.2
2
+ uvicorn==0.30.6
3
+ Pillow==10.4.0
4
+ numpy==1.26.4
5
+ paddleocr==2.8.1
6
+ python-doctr==0.9.0
7
+ setuptools==74.0.0
8
+ requests==2.32.3
9
+ paddleocr