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

Removed gradio

Browse files
Files changed (1) hide show
  1. app.py +48 -25
app.py CHANGED
@@ -1,20 +1,25 @@
1
- from fastapi import FastAPI, File, UploadFile
 
2
  from fastapi.middleware.cors import CORSMiddleware
3
- from fastapi.middleware.gzip import GZipMiddleware
4
- import numpy as np
5
- from PIL import Image
6
  from paddleocr import PaddleOCR
7
  from doctr.io import DocumentFile
8
  from doctr.models import ocr_predictor
 
 
9
  import io
10
 
 
 
 
 
11
  app = FastAPI()
 
12
  app.add_middleware(
13
  CORSMiddleware,
14
  allow_origins=["*"],
15
  allow_credentials=True,
16
  allow_methods=["*"],
17
- allow_headers=["*"]
18
  )
19
 
20
  # Initialize models once at startup
@@ -23,34 +28,52 @@ paddle_ocr = PaddleOCR(lang='en', use_angle_cls=True)
23
 
24
  def ocr_with_doctr(file):
25
  text_output = ''
26
- doc = DocumentFile.from_pdf(file)
27
- result = ocr_model(doc)
28
- for page in result.pages:
29
- for block in page.blocks:
30
- for line in block.lines:
31
- text_output += " ".join([word.value for word in line.words]) + "\n"
 
 
 
 
 
32
  return text_output
33
 
34
  def ocr_with_paddle(img):
35
  finaltext = ''
36
- result = paddle_ocr.ocr(img)
37
- for i in range(len(result[0])):
38
- text = result[0][i][1][0]
39
- finaltext += ' ' + text
 
 
 
 
 
40
  return finaltext
41
 
42
- def generate_text_from_image(img):
43
- return ocr_with_paddle(img)
44
-
45
  @app.post("/ocr/")
46
  async def perform_ocr(file: UploadFile = File(...)):
47
- file_bytes = await file.read()
48
- if file.filename.endswith('.pdf'):
49
- text_output = ocr_with_doctr(io.BytesIO(file_bytes))
50
- else:
51
- img = np.array(Image.open(io.BytesIO(file_bytes)))
52
- text_output = generate_text_from_image(img)
53
- return {"ocr_text": text_output}
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  @app.get("/test/")
56
  async def test_call():
 
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
 
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():