Pranavpai0309/TextExtraction_Payment_Screenshot
0
1from fastapi import FastAPI, File, UploadFile , HTTPException2from pydantic import BaseModel3import pytesseract4from PIL import Image5import io6import re7 8app = FastAPI()9 10class ExtractionResult(BaseModel):11 upi_handle: str | None = None12 upi_transaction_id: str | None = None13 google_transaction_id: str | None = None14 15image_types = ["image/jpeg", "image/png", "image/jpg"]16 17pytesseract.pytesseract.tesseract_cmd = "/usr/bin/tesseract"18 19def parse_transaction_ids(input_text: str):20 norm = input_text.replace('\r', '\n')21 lower = norm.lower()22 23 upi_txn = None24 m = re.search(r'upi transaction id[:\s]*([0-9]{5,20})', lower, flags=re.IGNORECASE)25 26 if m:27 upi_txn = m.group(1)28 29 else:30 m2 = re.search(r'upi[^ \n]{0,40}([0-9]{6,20})', lower, flags=re.IGNORECASE)31 32 if m2:33 upi_txn = m2.group(1)34 35 google_txn = None36 37 mg = re.search(r'google transaction id[:\s]*([^\s,;]+)', norm, flags=re.IGNORECASE)38 39 if mg:40 google_txn = mg.group(1).strip()41 42 upi_handle = None43 handles = re.findall(r'([^\s,;]+@[^\s,;]+)', norm)44 45 if handles:46 best = None47 for h in handles:48 pos = norm.find(h)49 window = norm[max(0, pos-40): pos+len(h)+40].lower()50 51 if 'upi' in window or 'pay' in window or 'gpay' in window or 'google' in window or 'paytm' in window:52 best = h53 break54 55 upi_handle = best or handles[0]56 57 return {58 "upi_handle": upi_handle,59 "upi_transaction_id": upi_txn,60 "google_transaction_id": google_txn61 }62 63@app.get("/")64def root():65 return {"Message" : "FastAPI is running smoothly ..."}66 67 68@app.post("/text-extraction", tags=["Text Extraction "], response_model=ExtractionResult)69async def upload_and_extract(file: UploadFile = File(...)):70 """71 72 Args:73 Input image file (jpg,jpeg and png)74 75 Raises:76 HTTPException: 400 - if not of image format ..77 78 Returns:79 80 extracted text in the format :81 {82 "upi_handle": upi_handle,83 "upi_transaction_id": upi_txn,84 "google_transaction_id": google_txn85 }86 """87 88 if file.content_type not in image_types:89 raise HTTPException(status_code=400,detail="Only images of format jpg,jpeg,png are allowed. Try uploading a valid image ...")90 91 image_contents = await file.read()92 93 image = Image.open(io.BytesIO(image_contents)).convert("RGB")94 95 extracted_text = pytesseract.image_to_string(image)96 97 parsed = parse_transaction_ids(extracted_text)98 99 return ExtractionResult(100 upi_handle=parsed["upi_handle"],101 upi_transaction_id=parsed["upi_transaction_id"],102 google_transaction_id=parsed["google_transaction_id"]103 )