Spaces:
Runtime error
Runtime error
Added App Folder
Browse filesFiles changed (15)
- app/__init__.pyAdded+16
- app/api.pyAdded+16
- app/routes/adhaarApi.pyAdded+70
- app/routes/panApi.pyAdded+70
- app/services/adhaarServices/adhaarDataExtractor.pyAdded+59
- app/services/adhaarServices/ocr.pyAdded+44
- app/services/panServices/panDataExtractor.pyAdded+61
- app/services/panServices/panOcr.pyAdded+52
- app/utils/1.pngAdded
- app/utils/2.pngAdded
- app/utils/3.pngAdded
- app/utils/4.pngAdded
- app/utils/azureOCR.pyAdded+42
- app/utils/imageUtils.pyAdded+51
- app/utils/seprator3.pngAdded
12345678910111213141516from flask import Flaskfrom ultralytics import YOLO
def create_app(): app = Flask(__name__) from .api import ocr_bp app.register_blueprint(ocr_bp)
with app.app_context(): # Load model once app.models = { 'adhaarModel': YOLO('models/aadhaarYolov8.pt'), 'panModel': YOLO('models/PanYolov8.pt') # Load additional models as needed }
return app12345678910111213141516from flask import Blueprintimport requestsimport osfrom .routes.adhaarApi import ocrAdhaarfrom .routes.panApi import ocrPanocr_bp = Blueprint('ocr', __name__)session = requests.Session()mode = os.getenv("PROJECT_MODE")
@ocr_bp.route('/ocrPan', methods=['POST'])def getResponse_Pan(): return ocrPan(mode, session)
@ocr_bp.route('/ocrAdhaar', methods=['POST'])def getResponse_Adhaar(): return ocrAdhaar(mode, session)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import refrom flask import request, jsonify, current_appfrom PIL import Image, UnidentifiedImageErrorfrom io import BytesIOimport base64import requestsfrom ..services.adhaarServices.ocr import process_resultsimport iodef ocrAdhaar(mode, session): try: print("API HIT ************* AADHAAROCR") data = request.get_json() if not data: return jsonify({"error": "Invalid request payload"}), 400 if mode == "prod": if not data.get('image'): return jsonify({"error": "Image data/buffer is required"}), 400 #removing 'data:image/png,base64 ' from buffer. imgBuffer = data.get('image') imgBuffer = re.sub("^data:image/.+;base64,", "", imgBuffer) # Adjust base64 string padding if len(imgBuffer) % 4: imgBuffer += '=' * (4 - len(imgBuffer) % 4) try: img_data = base64.b64decode(imgBuffer) img = Image.open(BytesIO(img_data)) img.verify() # Verify image format img = Image.open(io.BytesIO(img_data)) # Re-open image after verification except (base64.binascii.Error, ValueError) as decode_err: return jsonify({"error": f"Image decoding failed: {str(decode_err)}"}), 400 except UnidentifiedImageError: return jsonify({"error": "Unable to identify image format."}), 400
elif mode == "dev": if not data.get('imgUrl'): return jsonify({"error": "Image URL is required"}), 400 img_url = data.get('imgUrl') response = session.get(img_url) response.raise_for_status() img = Image.open(BytesIO(response.content)) img.verify() # Verify image format img = Image.open(BytesIO(response.content)) # Re-open image after verification
else: return jsonify({"error": "Invalid mode configuration"}), 500
# Check image format if img.format not in ['JPEG', 'JPG', 'PNG']: return jsonify({"error": "Invalid image format. Only JPG and PNG are supported."}), 400
# Run detection model = current_app.models.get('adhaarModel') results = model.predict(source=img, save=False) extracted_data = process_results(results, img) if extracted_data.get('statusCode') == 400: return jsonify(extracted_data), 400 return jsonify(extracted_data), 200 except requests.RequestException as req_err: return jsonify({"error": f"Image download failed: {str(req_err)}"}), 500 except UnidentifiedImageError: return jsonify({"error": "Unable to identify image format."}), 400 except Exception as e: current_app.logger.error(f"Unexpected error: {str(e)}") return jsonify({"error": "An unexpected error occurred."}), 50012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import refrom flask import request, jsonify, current_appfrom PIL import Image, UnidentifiedImageErrorfrom io import BytesIOimport base64import requestsfrom ..services.panServices.panOcr import process_resultsimport iodef ocrPan(mode, session): try: print("API HIT ************* PANOCR") data = request.get_json() if not data: return jsonify({"error": "Invalid request payload"}), 400 if mode == "prod": if not data.get('image'): return jsonify({"error": "Image data/buffer is required"}), 400 #removing 'data:image/png,base64 ' from buffer. imgBuffer = data.get('image') imgBuffer = re.sub("^data:image/.+;base64,", "", imgBuffer) # Adjust base64 string padding if len(imgBuffer) % 4: imgBuffer += '=' * (4 - len(imgBuffer) % 4) try: img_data = base64.b64decode(imgBuffer) img = Image.open(BytesIO(img_data)) img.verify() # Verify image format img = Image.open(io.BytesIO(img_data)) # Re-open image after verification except (base64.binascii.Error, ValueError) as decode_err: return jsonify({"error": f"Image decoding failed: {str(decode_err)}"}), 400 except UnidentifiedImageError: return jsonify({"error": "Unable to identify image format."}), 400
elif mode == "dev": if not data.get('imgUrl'): return jsonify({"error": "Image URL is required"}), 400 img_url = data.get('imgUrl') response = session.get(img_url) response.raise_for_status() img = Image.open(BytesIO(response.content)) img.verify() # Verify image format img = Image.open(BytesIO(response.content)) # Re-open image after verification
else: return jsonify({"error": "Invalid mode configuration"}), 500
# Check image format if img.format not in ['JPEG', 'JPG', 'PNG']: return jsonify({"error": "Invalid image format. Only JPG and PNG are supported."}), 400 # Run detection model = current_app.models.get('panModel') results = model.predict(source=img, save=False) extracted_data = process_results(results, img) if extracted_data.get('statusCode') == 400: return jsonify(extracted_data), 400 return jsonify(extracted_data), 200 except requests.RequestException as req_err: return jsonify({"error": f"Image download failed: {str(req_err)}"}), 500 except UnidentifiedImageError: return jsonify({"error": "Unable to identify image format."}), 400 except Exception as e: current_app.logger.error(f"Unexpected error: {str(e)}") return jsonify({"error": "An unexpected error occurred."}), 5001234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import datetime
def extract_details(texts): details = {'name': '', 'gender': '', 'dob': '', 'aadhaarNo': ''} current_year = datetime.datetime.now().year for text in texts: # Check if colon exists in text and split accordingly if ':' in text: text = text.split(':')[1].strip()
cleaned_text = text.replace(':', '').strip() # Remove leading non-alphabetic characters for gender detection and strip spaces cleaned_gender = cleaned_text.lstrip('.-/').strip() # Check if the text is the name (only alphabets, spaces, and possibly dots) if (all(char.isalpha() or char.isspace() or char == '.' for char in cleaned_text) and cleaned_gender.lower() not in ['male', 'female']): details['name'] = cleaned_text
# Check if the text is the DOB (format: dd/mm/yyyy or yyyy) elif (len(cleaned_text) == 4 and cleaned_text.isdigit() and 1900 < int(cleaned_text) < current_year): details['dob'] = cleaned_text
# Check if the text is the DOB (format: dd/mm/yyyy or dd-mm-yyyy) elif (len(cleaned_text) == 10 and (cleaned_text[2] in ['/', '-']) and (cleaned_text[5] in ['/', '-']) and cleaned_text.replace('/', '').replace('-', '').isdigit()): details['dob'] = cleaned_text
# Check if the text is the gender (either 'Male' or 'Female') elif cleaned_gender.lower() in ['male', 'female']: details['gender'] = cleaned_gender.capitalize()
# Check if the text is the Aadhaar number (12 digits after removing spaces) elif cleaned_text.replace(' ', '').isdigit() and len(cleaned_text.replace(' ', '')) == 12: details['aadhaarNo'] = cleaned_text # Check if any key's value is empty if any(value == '' for value in details.values()): error_key = next(key for key, value in details.items() if value == '') result = { 'statusCode': 400, 'result': details, 'error': f'{error_key} value is not found due to bad image.' } else: result = { 'statusCode': 200, 'result': details, 'error': '' } return result1234567891011121314151617181920212223242526272829303132333435363738394041424344from io import BytesIOfrom ...utils.azureOCR import analyze_imagefrom ...utils.imageUtils import resize_if_needed, all_cropped_images_to_one_imagefrom app.services.adhaarServices.adhaarDataExtractor import extract_details
def process_results(results, img): precision_data = {label: {"correct": 0, "total": 0} for label in ["aadharNo", "name", "dob", "gender", "address"]} confidence_threshold = 0.3 input_image_format = img.format if img.format else "PNG" valid_formats = ["JPEG", "PNG", "BMP", "GIF", "TIFF"] input_image_format = input_image_format if input_image_format in valid_formats else "PNG" label_to_image = {} extracted_data = {"adhaarNo": "", "dob": "", "gender": "", "name": "", "address": ""} for result in results: for bbox, cls, conf in zip(result.boxes.xyxy, result.boxes.cls, result.boxes.conf): label = ["aadharNo", "dob", "gender", "name", "address"][int(cls)] print(label, conf) if conf < confidence_threshold or label == "address": continue x1, y1, x2, y2 = map(int, bbox.tolist()) crop_img = img.crop((x1, y1, x2, y2)) crop_img = resize_if_needed(crop_img) if label not in label_to_image or label_to_image[label][1] < conf: label_to_image[label] = (crop_img, conf) precision_data[label]["total"] += 1 precision_data[label]["correct"] += 1 # Replace with actual OCR validation check
cropped_images = [img for label, (img, conf) in sorted(label_to_image.items()) if label != "address"] final_image = all_cropped_images_to_one_image(cropped_images, separator_image_path='app/utils/seprator3.png') buffer = BytesIO() final_image.save(buffer, format=input_image_format) buffer.seek(0) response = analyze_image(buffer.getvalue(), input_image_format) # print(response) lines = response['readResult']['blocks'][0]['lines'] texts = [line['text'] for line in lines] print(texts) extracted_data = extract_details(texts) return extracted_data12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061import re
def extract_panData(data): unwanted_words = ["Name","/Name", "Date of Birth", "/Date of Birth", "Permanent Account Number", "Father's Name", "14 /Name", "/Father's Name"] # Clean the array by removing unwanted words and invalid entries cleaned_data = [] combination_pattern = re.compile(r'(?=.*[A-Za-z])(?=.*[0-9])(?=.*[!@#$%^&*(),?":{}|<>])')
for item in data: if item not in unwanted_words and not combination_pattern.search(item): cleaned_data.append(item) # Initialize result object result = { "statusCode": 200, "error": '', "data": { "panNo": '', "name": '', "fatherName": '', "dob": '' } } # Check and extract PAN number print(cleaned_data) pan_pattern = re.compile(r'^[A-Z]{5}[0-9]{4}[A-Z]$') if len(cleaned_data) > 0 and pan_pattern.match(cleaned_data[3]): result["data"]["panNo"] = cleaned_data[3] else: result["data"]["panNo"] = '' # Check and extract name name_pattern = re.compile(r'^[A-Za-z .]+$') if len(cleaned_data) > 1 and name_pattern.match(cleaned_data[2]): result["data"]["name"] = cleaned_data[2] else: result["data"]["name"] = '' # Check and extract father's name if len(cleaned_data) > 2 and name_pattern.match(cleaned_data[1]): result["data"]["fatherName"] = cleaned_data[1] else: result["data"]["fatherName"] = '' # Check and extract date of birth dob_pattern = re.compile(r'^\d{2}[-/]\d{2}[-/]\d{4}$') if len(cleaned_data) > 3 and dob_pattern.match(cleaned_data[0]): result["data"]["dob"] = cleaned_data[0] else: result["data"]["dob"] = '' # Check if any value is empty and set error message for key, value in result["data"].items(): if value == '': result["statusCode"] = 400 result["error"] = f"{key} value is not found due to bad image." break return result12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152from io import BytesIOfrom ...utils.azureOCR import analyze_imagefrom ...utils.imageUtils import resize_if_needed, all_cropped_images_to_one_imagefrom .panDataExtractor import extract_panData
def process_results(results, img): label_indices = {"dob": 0, "father": 1, "name": 2, "pan_num": 3} confidence_threshold = 0.3 input_image_format = img.format if img.format else "PNG" valid_formats = ["JPEG", "PNG", "BMP", "GIF", "TIFF"] input_image_format = input_image_format if input_image_format in valid_formats else "PNG" cropped_images_with_labels = [] precision_data = {label: {"correct": 0, "total": 0} for label in label_indices.keys()} # extracted_data = {"pan_num": "", "name": "", "father": "", "dob": ""} for result in results: for bbox, cls, conf in zip(result.boxes.xyxy, result.boxes.cls, result.boxes.conf): label = ["dob", "father", "name", "pan_num"][int(cls)] print(label, conf) if conf < confidence_threshold: continue x1, y1, x2, y2 = map(int, bbox.tolist()) crop_img = img.crop((x1, y1, x2, y2)) crop_img = resize_if_needed(crop_img) crop_img.save(f"temp_{label}.png") cropped_images_with_labels.append((crop_img, label_indices[label], conf)) precision_data[label]["total"] += 1 precision_data[label]["correct"] += 1 # Replace with actual OCR validation check # Sort the images by their label indices in ascending order cropped_images_with_labels.sort(key=lambda x: x[1]) print(cropped_images_with_labels, "cropped images with labels") # Extract only the images for concatenation cropped_images = [img for img, _, _ in cropped_images_with_labels] # print(cropped_images, "cropped images") if not cropped_images: raise ValueError("No images were cropped.") final_image = all_cropped_images_to_one_image(cropped_images, separator_image_path='app/utils/seprator3.png') buffer = BytesIO() final_image.save(buffer, format=input_image_format) buffer.seek(0) response = analyze_image(buffer.getvalue(), input_image_format) print(response, "response") lines = response['readResult']['blocks'][0]['lines'] texts = [line['text'] for line in lines] print(texts, "text after microsoft ocr") extracted_data = extract_panData(texts) return extracted_data123456789101112131415161718192021222324252627282930313233343536373839404142import requests
def analyze_image(image_buffer, imgType): url = 'https://portal.vision.cognitive.azure.com/api/demo/analyze?features=read' headers = { 'Accept': '*/*', 'Accept-Language': 'en-GB,en;q=0.9,en-US;q=0.8', 'Connection': 'keep-alive', 'Cookie': 'ARRAffinity=ecee788152e01b1e3805dc3134d03cab01ed97f61e69beeb53fcc885e5d0e707; ARRAffinitySameSite=ecee788152e01b1e3805dc3134d03cab01ed97f61e69beeb53fcc885e5d0e707; ai_user=Hps6Ce/6zz/k9q5icFxuiU|2024-07-03T12:30:25.655Z; MicrosoftApplicationsTelemetryDeviceId=89ed4fb7-9ae7-4e71-af1e-add358e41b9e; MSFPC=GUID=cbf8cbf9ba1b48c69374f48574f06958&HASH=cbf8&LV=202407&V=4&LU=1720009794093; ai_session=ZABOsZ0VsIaPiorOXIr2B+|1720009825676|1720010022866', 'DNT': '1', 'Origin': 'https://portal.vision.cognitive.azure.com', 'Referer': 'https://portal.vision.cognitive.azure.com/demo/extract-text-from-images', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin', 'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Mobile Safari/537.36 Edg/125.0.0.0', 'api-call-origin': 'Microsoft.Cognitive.CustomVision.Portal', 'content-disposition': 'form-data; name=Foo', 'enctype': 'multipart/form-data', 'request-context': 'appId=cid-v1:e2fac58d-316d-4cf3-a225-11d998b143db', 'request-id': '|37e377d2a90c4c1ba78805dc901a47ac.fb0593645bfd456f', 'sec-ch-ua': '"Microsoft Edge";v="125", "Chromium";v="125", "Not.A/Brand";v="24"', 'sec-ch-ua-mobile': '?1', 'sec-ch-ua-platform': '"Android"', 'traceparent': '00-37e377d2a90c4c1ba78805dc901a47ac-fb0593645bfd456f-01'}
files = {'file': ( f"allimage.{imgType}", image_buffer, f"image/{imgType}")} response = requests.post(url, headers=headers, files=files) if response.status_code != 200: raise Exception(f"Failed to analyze image: {response.status_code} - {response.text}") else: return response.json()
# Example usage
# Example usage# file_path = '/path/to/your/image.png'# url = 'https://portal.vision.cognitive.azure.com/api/demo/analyze?features=read'# response = analyze_image(file_path, url)# print(response)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051from PIL import Imageimport cv2import numpy as np
def resize_if_needed(image): width, height = image.size if width < 50 or height < 50: scale = max(70 / width, 70 / height) elif width > 16000 or height > 16000: scale = min(16000 / width, 16000 / height) else: return image return image.resize((int(width * scale), int(height * scale)), Image.LANCZOS)
def center_on_white_background(image): width, height = image.size if width < 150 and height < 50: background = Image.new('RGB', (150, 150), (255, 255, 255)) x, y = (150 - width) // 2, (150 - height) // 2 background.paste(image, (x, y)) return background return image
def all_cropped_images_to_one_image(cropped_images, separator_image_path): separator_image = Image.open(separator_image_path) separator_height = separator_image.height total_height = sum(img.height for img in cropped_images) + (len(cropped_images) - 1) * separator_height print("Total Height:", total_height) max_width = max(max(img.width for img in cropped_images), separator_image.width) print("Max Width:", max_width) combined_image = Image.new('RGB', (max_width, total_height)) y = 0 print(cropped_images, "before combine") for i, img in enumerate(cropped_images): combined_image.paste(img, (0, y)) y += img.height if i < len(cropped_images) - 1: combined_image.paste(separator_image, (0, y)) y += separator_height combined_image.save("combinedImage.png") return combined_image
def preprocess_image(image): gray = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2GRAY) _, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) return Image.fromarray(binary)app/__init__.pyAdded+16
app/api.pyAdded+16
app/routes/adhaarApi.pyAdded+70
app/routes/panApi.pyAdded+70
app/services/adhaarServices/adhaarDataExtractor.pyAdded+59
app/services/adhaarServices/ocr.pyAdded+44
app/services/panServices/panDataExtractor.pyAdded+61
app/services/panServices/panOcr.pyAdded+52
app/utils/1.pngAdded

app/utils/2.pngAdded

app/utils/3.pngAdded

app/utils/4.pngAdded

app/utils/azureOCR.pyAdded+42
app/utils/imageUtils.pyAdded+51
app/utils/seprator3.pngAdded
