Spaces:
Sleeping
Sleeping
Removed paddleOCR Code
Browse files
app.py
CHANGED
|
@@ -2,8 +2,7 @@ import uvicorn
|
|
| 2 |
from fastapi.staticfiles import StaticFiles
|
| 3 |
import hashlib
|
| 4 |
from enum import Enum
|
| 5 |
-
from fastapi import FastAPI,Header, Query,Depends,HTTPException
|
| 6 |
-
from paddleocr import PaddleOCR, PPStructure, save_structure_res
|
| 7 |
from PIL import Image
|
| 8 |
import io
|
| 9 |
import numpy as np
|
|
@@ -18,7 +17,6 @@ import traceback # For detailed traceback of errors
|
|
| 18 |
import re
|
| 19 |
import json
|
| 20 |
from dotenv import load_dotenv
|
| 21 |
-
import uvicorn
|
| 22 |
import base64
|
| 23 |
|
| 24 |
load_dotenv()
|
|
@@ -30,7 +28,7 @@ logger = logging.getLogger(__name__)
|
|
| 30 |
# MongoDB Configuration
|
| 31 |
MONGODB_URI = os.getenv("MONGODB_URI")
|
| 32 |
DATABASE_NAME = os.getenv("DATABASE_NAME")
|
| 33 |
-
COLLECTION_NAME = os.getenv("COLLECTION_NAME","invoice_collection")
|
| 34 |
|
| 35 |
app = FastAPI(docs_url='/')
|
| 36 |
use_gpu = False
|
|
@@ -43,7 +41,7 @@ if not MONGODB_URI:
|
|
| 43 |
# Initialize MongoDB Connection
|
| 44 |
client = MongoClient(MONGODB_URI)
|
| 45 |
db = client[DATABASE_NAME]
|
| 46 |
-
invoice_collection=db[COLLECTION_NAME]
|
| 47 |
|
| 48 |
@app.on_event("startup")
|
| 49 |
def startup_db():
|
|
@@ -55,9 +53,6 @@ def startup_db():
|
|
| 55 |
except Exception as e:
|
| 56 |
print("MongoDB connection failed:", str(e))
|
| 57 |
|
| 58 |
-
# Initialize PaddleOCR
|
| 59 |
-
ocr = PaddleOCR(use_angle_cls=True, lang='en')
|
| 60 |
-
|
| 61 |
# AWS S3 Configuration
|
| 62 |
API_KEY = os.getenv("API_KEY")
|
| 63 |
AWS_ACCESS_KEY = os.getenv("AWS_ACCESS_KEY")
|
|
@@ -75,7 +70,6 @@ s3_client = boto3.client(
|
|
| 75 |
)
|
| 76 |
|
| 77 |
# Function to fetch file from S3
|
| 78 |
-
|
| 79 |
def fetch_file_from_s3_file(file_key):
|
| 80 |
try:
|
| 81 |
response = s3_client.get_object(Bucket=S3_BUCKET_NAME, Key=file_key)
|
|
@@ -152,11 +146,11 @@ This JSON format will be used to store and manage invoices in a structured and u
|
|
| 152 |
response = openai.ChatCompletion.create(
|
| 153 |
model="gpt-4o-mini",
|
| 154 |
messages=[
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
)
|
| 161 |
content = response.choices[0].message.content.strip()
|
| 162 |
print("Before content:", content)
|
|
@@ -164,9 +158,6 @@ This JSON format will be used to store and manage invoices in a structured and u
|
|
| 164 |
cleaned_content = re.sub(r'\n```$', '', cleaned_content) # Remove '\n```' at the end
|
| 165 |
|
| 166 |
# Step 2: Parse the cleaned content as JSON
|
| 167 |
-
#parsed_content = json.loads(cleaned_content)
|
| 168 |
-
|
| 169 |
-
# Step 3: Print the parsed JSON object
|
| 170 |
try:
|
| 171 |
parsed_content = json.loads(cleaned_content)
|
| 172 |
return parsed_content
|
|
@@ -185,53 +176,37 @@ def verify_api_key(api_key: str = Header(...)):
|
|
| 185 |
|
| 186 |
@app.get("/")
|
| 187 |
def read_root():
|
| 188 |
-
return {"message": "Welcome to the
|
| 189 |
|
| 190 |
@app.get("/ocr/extraction")
|
| 191 |
-
def ocr_from_s3(api_key: str = Depends(verify_api_key),file_key: str = Query(..., description="S3 file key for the file")):
|
| 192 |
"""
|
| 193 |
Perform OCR on a file (PDF or Image) stored in S3 and summarize the text using GPT.
|
| 194 |
"""
|
| 195 |
try:
|
| 196 |
# Fetch file from S3
|
| 197 |
-
file_data, content_type,document_type,entityrefkey = fetch_file_from_s3_file(file_key)
|
| 198 |
|
| 199 |
extracted_text = []
|
| 200 |
base64Data = base64.b64encode(file_data).decode('utf-8')
|
| 201 |
-
|
|
|
|
| 202 |
if content_type.startswith("image/"): # Image file
|
| 203 |
image = Image.open(io.BytesIO(file_data)).convert("RGB") # Use BytesIO stream directly
|
| 204 |
image_np = np.array(image) # Convert to NumPy array
|
| 205 |
-
result = ocr.ocr(image_np, cls=True)
|
| 206 |
base64DataResp = f"data:image/{content_type.lower()};base64,{base64Data}"
|
| 207 |
-
# Extract text from OCR results
|
| 208 |
-
for line in result:
|
| 209 |
-
for word_info in line:
|
| 210 |
-
extracted_text.append(word_info[1][0])
|
| 211 |
-
|
| 212 |
elif content_type == "application/pdf": # PDF file
|
| 213 |
# Open PDF using PyMuPDF
|
| 214 |
pdf_document = fitz.open(stream=io.BytesIO(file_data), filetype="pdf")
|
| 215 |
-
|
| 216 |
extracted_text = []
|
| 217 |
-
|
| 218 |
# Process each page in the PDF
|
| 219 |
for page_number in range(len(pdf_document)):
|
| 220 |
page = pdf_document[page_number]
|
| 221 |
-
|
| 222 |
# Render the page as an image
|
| 223 |
pix = page.get_pixmap()
|
| 224 |
image = Image.open(io.BytesIO(pix.tobytes("png"))).convert("RGB")
|
| 225 |
-
|
| 226 |
-
# Convert Pillow image to NumPy array (for PaddleOCR compatibility)
|
| 227 |
image_np = np.array(image)
|
| 228 |
-
|
| 229 |
-
# Run OCR on the image
|
| 230 |
-
result = ocr.ocr(image_np, cls=True)
|
| 231 |
-
for line in result:
|
| 232 |
-
for word_info in line:
|
| 233 |
-
extracted_text.append(word_info[1][0])
|
| 234 |
-
|
| 235 |
pdf_document.close()
|
| 236 |
base64DataResp = f"data:application/pdf;base64,{base64Data}"
|
| 237 |
else:
|
|
@@ -244,11 +219,11 @@ def ocr_from_s3(api_key: str = Depends(verify_api_key),file_key: str = Query(...
|
|
| 244 |
summary = summarize_text(full_text)
|
| 245 |
|
| 246 |
return {
|
| 247 |
-
"entityrefkey":entityrefkey
|
| 248 |
"file_key": file_key,
|
| 249 |
"file_type": content_type,
|
| 250 |
-
"document_type":document_type,
|
| 251 |
-
"base64DataResp":base64DataResp,
|
| 252 |
"extracted_text": full_text,
|
| 253 |
"summary": summary
|
| 254 |
}
|
|
|
|
| 2 |
from fastapi.staticfiles import StaticFiles
|
| 3 |
import hashlib
|
| 4 |
from enum import Enum
|
| 5 |
+
from fastapi import FastAPI, Header, Query, Depends, HTTPException
|
|
|
|
| 6 |
from PIL import Image
|
| 7 |
import io
|
| 8 |
import numpy as np
|
|
|
|
| 17 |
import re
|
| 18 |
import json
|
| 19 |
from dotenv import load_dotenv
|
|
|
|
| 20 |
import base64
|
| 21 |
|
| 22 |
load_dotenv()
|
|
|
|
| 28 |
# MongoDB Configuration
|
| 29 |
MONGODB_URI = os.getenv("MONGODB_URI")
|
| 30 |
DATABASE_NAME = os.getenv("DATABASE_NAME")
|
| 31 |
+
COLLECTION_NAME = os.getenv("COLLECTION_NAME", "invoice_collection")
|
| 32 |
|
| 33 |
app = FastAPI(docs_url='/')
|
| 34 |
use_gpu = False
|
|
|
|
| 41 |
# Initialize MongoDB Connection
|
| 42 |
client = MongoClient(MONGODB_URI)
|
| 43 |
db = client[DATABASE_NAME]
|
| 44 |
+
invoice_collection = db[COLLECTION_NAME]
|
| 45 |
|
| 46 |
@app.on_event("startup")
|
| 47 |
def startup_db():
|
|
|
|
| 53 |
except Exception as e:
|
| 54 |
print("MongoDB connection failed:", str(e))
|
| 55 |
|
|
|
|
|
|
|
|
|
|
| 56 |
# AWS S3 Configuration
|
| 57 |
API_KEY = os.getenv("API_KEY")
|
| 58 |
AWS_ACCESS_KEY = os.getenv("AWS_ACCESS_KEY")
|
|
|
|
| 70 |
)
|
| 71 |
|
| 72 |
# Function to fetch file from S3
|
|
|
|
| 73 |
def fetch_file_from_s3_file(file_key):
|
| 74 |
try:
|
| 75 |
response = s3_client.get_object(Bucket=S3_BUCKET_NAME, Key=file_key)
|
|
|
|
| 146 |
response = openai.ChatCompletion.create(
|
| 147 |
model="gpt-4o-mini",
|
| 148 |
messages=[
|
| 149 |
+
{"role": "system", "content": system_prompt},
|
| 150 |
+
{"role": "user", "content": f"{text}"}
|
| 151 |
+
],
|
| 152 |
+
temperature=0.5,
|
| 153 |
+
max_tokens=16384
|
| 154 |
)
|
| 155 |
content = response.choices[0].message.content.strip()
|
| 156 |
print("Before content:", content)
|
|
|
|
| 158 |
cleaned_content = re.sub(r'\n```$', '', cleaned_content) # Remove '\n```' at the end
|
| 159 |
|
| 160 |
# Step 2: Parse the cleaned content as JSON
|
|
|
|
|
|
|
|
|
|
| 161 |
try:
|
| 162 |
parsed_content = json.loads(cleaned_content)
|
| 163 |
return parsed_content
|
|
|
|
| 176 |
|
| 177 |
@app.get("/")
|
| 178 |
def read_root():
|
| 179 |
+
return {"message": "Welcome to the Invoice Summarization API!"}
|
| 180 |
|
| 181 |
@app.get("/ocr/extraction")
|
| 182 |
+
def ocr_from_s3(api_key: str = Depends(verify_api_key), file_key: str = Query(..., description="S3 file key for the file")):
|
| 183 |
"""
|
| 184 |
Perform OCR on a file (PDF or Image) stored in S3 and summarize the text using GPT.
|
| 185 |
"""
|
| 186 |
try:
|
| 187 |
# Fetch file from S3
|
| 188 |
+
file_data, content_type, document_type, entityrefkey = fetch_file_from_s3_file(file_key)
|
| 189 |
|
| 190 |
extracted_text = []
|
| 191 |
base64Data = base64.b64encode(file_data).decode('utf-8')
|
| 192 |
+
|
| 193 |
+
# Process PDF or Image file
|
| 194 |
if content_type.startswith("image/"): # Image file
|
| 195 |
image = Image.open(io.BytesIO(file_data)).convert("RGB") # Use BytesIO stream directly
|
| 196 |
image_np = np.array(image) # Convert to NumPy array
|
|
|
|
| 197 |
base64DataResp = f"data:image/{content_type.lower()};base64,{base64Data}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
elif content_type == "application/pdf": # PDF file
|
| 199 |
# Open PDF using PyMuPDF
|
| 200 |
pdf_document = fitz.open(stream=io.BytesIO(file_data), filetype="pdf")
|
|
|
|
| 201 |
extracted_text = []
|
|
|
|
| 202 |
# Process each page in the PDF
|
| 203 |
for page_number in range(len(pdf_document)):
|
| 204 |
page = pdf_document[page_number]
|
|
|
|
| 205 |
# Render the page as an image
|
| 206 |
pix = page.get_pixmap()
|
| 207 |
image = Image.open(io.BytesIO(pix.tobytes("png"))).convert("RGB")
|
| 208 |
+
# Convert Pillow image to NumPy array
|
|
|
|
| 209 |
image_np = np.array(image)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
pdf_document.close()
|
| 211 |
base64DataResp = f"data:application/pdf;base64,{base64Data}"
|
| 212 |
else:
|
|
|
|
| 219 |
summary = summarize_text(full_text)
|
| 220 |
|
| 221 |
return {
|
| 222 |
+
"entityrefkey": entityrefkey,
|
| 223 |
"file_key": file_key,
|
| 224 |
"file_type": content_type,
|
| 225 |
+
"document_type": document_type,
|
| 226 |
+
"base64DataResp": base64DataResp,
|
| 227 |
"extracted_text": full_text,
|
| 228 |
"summary": summary
|
| 229 |
}
|