Update main.py
Browse files
main.py
CHANGED
|
@@ -4,12 +4,12 @@ import json
|
|
| 4 |
import easyocr
|
| 5 |
import uvicorn
|
| 6 |
import numpy as np
|
| 7 |
-
from pyzbar import pyzbar
|
| 8 |
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 9 |
from fastapi.responses import Response
|
| 10 |
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
|
| 12 |
-
app = FastAPI(title="Aadhaar
|
| 13 |
|
| 14 |
app.add_middleware(
|
| 15 |
CORSMiddleware,
|
|
@@ -19,8 +19,10 @@ app.add_middleware(
|
|
| 19 |
allow_headers=["*"],
|
| 20 |
)
|
| 21 |
|
| 22 |
-
# Initialize
|
|
|
|
| 23 |
reader = easyocr.Reader(['en'], gpu=False)
|
|
|
|
| 24 |
|
| 25 |
def get_clean_digits(text):
|
| 26 |
text = text.upper().replace('O','0').replace('I','1').replace('L','1').replace('|','1')
|
|
@@ -31,35 +33,40 @@ def apply_mask(img, bbox, ratio=0.7):
|
|
| 31 |
p3 = tuple(map(int, bbox[2]))
|
| 32 |
width = p3[0] - p1[0]
|
| 33 |
mask_width = int(width * ratio)
|
|
|
|
| 34 |
cv2.rectangle(img, p1, (p1[0] + mask_width, p3[1]), (0, 0, 0), -1)
|
| 35 |
return img
|
| 36 |
|
| 37 |
def mask_qr_with_zbar(img):
|
| 38 |
"""
|
| 39 |
-
|
| 40 |
-
|
| 41 |
"""
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
return img
|
| 52 |
|
| 53 |
@app.post("/v1/aadhaar/process")
|
| 54 |
async def process_document(file: UploadFile = File(...)):
|
| 55 |
try:
|
| 56 |
contents = await file.read()
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
# 1. Mask QR Code
|
| 60 |
img = mask_qr_with_zbar(img)
|
| 61 |
|
| 62 |
-
# 2. Resize
|
| 63 |
h, w = img.shape[:2]
|
| 64 |
img = cv2.resize(img, (1200, int(h * (1200/w))))
|
| 65 |
|
|
@@ -71,29 +78,26 @@ async def process_document(file: UploadFile = File(...)):
|
|
| 71 |
clean = get_clean_digits(text)
|
| 72 |
text_upper = text.upper()
|
| 73 |
|
| 74 |
-
#
|
| 75 |
if len(clean) == 12 and not clean.startswith(('0','1')):
|
| 76 |
extracted["aadhaar"] = clean
|
| 77 |
-
img = apply_mask(img, bbox, 0.
|
| 78 |
continue
|
| 79 |
|
| 80 |
-
#
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
target_bbox = bbox
|
| 84 |
-
target_clean = clean
|
| 85 |
|
| 86 |
-
#
|
| 87 |
if len(clean) < 12 and i + 1 < len(results):
|
| 88 |
next_bbox, next_text, _ = results[i+1]
|
| 89 |
next_clean = get_clean_digits(next_text)
|
| 90 |
if len(next_clean) >= 12:
|
| 91 |
-
target_bbox = next_bbox
|
| 92 |
-
target_clean = next_clean
|
| 93 |
|
| 94 |
if len(target_clean) >= 12:
|
| 95 |
extracted["vid"] = target_clean
|
| 96 |
-
img = apply_mask(img, target_bbox, 0.
|
| 97 |
|
| 98 |
_, buffer = cv2.imencode('.jpg', img)
|
| 99 |
return Response(
|
|
@@ -106,7 +110,8 @@ async def process_document(file: UploadFile = File(...)):
|
|
| 106 |
)
|
| 107 |
|
| 108 |
except Exception as e:
|
|
|
|
| 109 |
raise HTTPException(status_code=500, detail=str(e))
|
| 110 |
|
| 111 |
if __name__ == "__main__":
|
| 112 |
-
uvicorn.run(app, host="0.0.0.0", port=
|
|
|
|
| 4 |
import easyocr
|
| 5 |
import uvicorn
|
| 6 |
import numpy as np
|
| 7 |
+
from pyzbar import pyzbar
|
| 8 |
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 9 |
from fastapi.responses import Response
|
| 10 |
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
|
| 12 |
+
app = FastAPI(title="Aadhaar Masking HF Edition")
|
| 13 |
|
| 14 |
app.add_middleware(
|
| 15 |
CORSMiddleware,
|
|
|
|
| 19 |
allow_headers=["*"],
|
| 20 |
)
|
| 21 |
|
| 22 |
+
# Initialize once. Using English only to prevent memory crashes on HF Free Tier
|
| 23 |
+
print("Loading OCR Engine...")
|
| 24 |
reader = easyocr.Reader(['en'], gpu=False)
|
| 25 |
+
print("Engine Loaded.")
|
| 26 |
|
| 27 |
def get_clean_digits(text):
|
| 28 |
text = text.upper().replace('O','0').replace('I','1').replace('L','1').replace('|','1')
|
|
|
|
| 33 |
p3 = tuple(map(int, bbox[2]))
|
| 34 |
width = p3[0] - p1[0]
|
| 35 |
mask_width = int(width * ratio)
|
| 36 |
+
# Applying a black mask
|
| 37 |
cv2.rectangle(img, p1, (p1[0] + mask_width, p3[1]), (0, 0, 0), -1)
|
| 38 |
return img
|
| 39 |
|
| 40 |
def mask_qr_with_zbar(img):
|
| 41 |
"""
|
| 42 |
+
Detects actual QR patterns. If pyzbar is missing system libs,
|
| 43 |
+
this fails gracefully instead of crashing.
|
| 44 |
"""
|
| 45 |
+
try:
|
| 46 |
+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
| 47 |
+
qr_codes = pyzbar.decode(gray)
|
| 48 |
+
for qr in qr_codes:
|
| 49 |
+
(x, y, w, h) = qr.rect
|
| 50 |
+
# Mask with slight padding
|
| 51 |
+
cv2.rectangle(img, (x-10, y-10), (x+w+10, y+h+10), (0, 0, 0), -1)
|
| 52 |
+
except Exception as e:
|
| 53 |
+
print(f"QR detection skipped: {e}")
|
| 54 |
return img
|
| 55 |
|
| 56 |
@app.post("/v1/aadhaar/process")
|
| 57 |
async def process_document(file: UploadFile = File(...)):
|
| 58 |
try:
|
| 59 |
contents = await file.read()
|
| 60 |
+
nparr = np.frombuffer(contents, np.uint8)
|
| 61 |
+
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
|
| 62 |
+
|
| 63 |
+
if img is None:
|
| 64 |
+
raise HTTPException(status_code=400, detail="Invalid image file")
|
| 65 |
|
| 66 |
+
# 1. Mask QR Code specifically (No more full-black image)
|
| 67 |
img = mask_qr_with_zbar(img)
|
| 68 |
|
| 69 |
+
# 2. Resize for OCR (Standardize 1200px width)
|
| 70 |
h, w = img.shape[:2]
|
| 71 |
img = cv2.resize(img, (1200, int(h * (1200/w))))
|
| 72 |
|
|
|
|
| 78 |
clean = get_clean_digits(text)
|
| 79 |
text_upper = text.upper()
|
| 80 |
|
| 81 |
+
# AADHAAR: 12 digits, must not start with 0 or 1
|
| 82 |
if len(clean) == 12 and not clean.startswith(('0','1')):
|
| 83 |
extracted["aadhaar"] = clean
|
| 84 |
+
img = apply_mask(img, bbox, 0.72)
|
| 85 |
continue
|
| 86 |
|
| 87 |
+
# VID: 16 digits or text context
|
| 88 |
+
if "VID" in text_upper or len(clean) == 16:
|
| 89 |
+
target_bbox, target_clean = bbox, clean
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
# Check next block if VID label is separate from numbers
|
| 92 |
if len(clean) < 12 and i + 1 < len(results):
|
| 93 |
next_bbox, next_text, _ = results[i+1]
|
| 94 |
next_clean = get_clean_digits(next_text)
|
| 95 |
if len(next_clean) >= 12:
|
| 96 |
+
target_bbox, target_clean = next_bbox, next_clean
|
|
|
|
| 97 |
|
| 98 |
if len(target_clean) >= 12:
|
| 99 |
extracted["vid"] = target_clean
|
| 100 |
+
img = apply_mask(img, target_bbox, 0.78)
|
| 101 |
|
| 102 |
_, buffer = cv2.imencode('.jpg', img)
|
| 103 |
return Response(
|
|
|
|
| 110 |
)
|
| 111 |
|
| 112 |
except Exception as e:
|
| 113 |
+
print(f"Error: {e}")
|
| 114 |
raise HTTPException(status_code=500, detail=str(e))
|
| 115 |
|
| 116 |
if __name__ == "__main__":
|
| 117 |
+
uvicorn.run(app, host="0.0.0.0", port=7860) # Port 7860 is default for HF Spaces
|