Spaces:
Runtime error
Runtime error
pawandev commited on
Commit ·
6368900
1
Parent(s): 37c2aa4
Added PanOCR refined code to do Pan Card ocr
Browse filesFiles changed (5)
12env.env1234env.env*.pyc*.DS_Store
9 unmodified lines101112131415169 unmodified lines# Load model onceapp.models = {'adhaarModel': YOLO('models/aadhaarYolov8.pt'),'panModel': YOLO('models/PanYolov8.pt') # Load additional models as needed}return app9 unmodified lines101112131415169 unmodified lines# Load model onceapp.models = {'adhaarModel': YOLO('models/aadhaarYolov8.pt'),'panModel': YOLO('models/PanModal_v3.pt') # Load additional models as needed}return app
54 unmodified lines555657585960615 unmodified lines6768697054 unmodified lines# Run detectionmodel = 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), 4005 unmodified linesreturn jsonify({"error": "Unable to identify image format."}), 400except Exception as e:current_app.logger.error(f"Unexpected error: {str(e)}")return jsonify({"error": "An unexpected error occurred."}), 50054 unmodified lines5556575859606162635 unmodified lines6970717254 unmodified lines# Run detectionmodel = current_app.models.get('panModel')results = model.predict(source=img, save=False)# print(results,"model result")extracted_data = process_results(results, img)# print(extracted_data, "extracted data")if extracted_data.get('statusCode') == 400:return jsonify(extracted_data), 4005 unmodified linesreturn jsonify({"error": "Unable to identify image format."}), 400except Exception as e:current_app.logger.error(f"Unexpected error: {str(e)}")return jsonify({"error": "An unexpected error occurred on api call."}), 500
123456716 unmodified lines242526272829303132333435363738394041424344454647484950515253import redef 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 entriescleaned_data = []16 unmodified lines}# Check and extract PAN numberprint(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 namename_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 nameif 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 birthdob_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"] = ''1234567816 unmodified lines252627282930313233343536373839404142434445464748495051525354import redef extract_panData(data):unwanted_words = ["Name","/Name",'Permanent', 'Account', 'Number', 'Card', 'नाम', '/Name',"पिता का नाम",'नाम / Name', "पिता का नाम/ Father's Name", 'नाम /Name',"पिता का नाम / Father's Name", 'जन्म का वाराज़', 'Date of Birth', 'Permanent Account Number Card', "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 entriescleaned_data = []16 unmodified lines}# Check and extract PAN numberprint(cleaned_data, "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[0]):result["data"]["panNo"] = cleaned_data[0]else:result["data"]["panNo"] = ''# Check and extract namename_pattern = re.compile(r'^[A-Za-z .]+$')if len(cleaned_data) > 1 and name_pattern.match(cleaned_data[1]):result["data"]["name"] = cleaned_data[1]else:result["data"]["name"] = ''# Check and extract father's nameif len(cleaned_data) > 2 and name_pattern.match(cleaned_data[2]):result["data"]["fatherName"] = cleaned_data[2]else:result["data"]["fatherName"] = ''# Check and extract date of birthdob_pattern = re.compile(r'^\d{2}[-/]\d{2}[-/]\d{4}$')if len(cleaned_data) > 3 and dob_pattern.match(cleaned_data[3]):result["data"]["dob"] = cleaned_data[3]else:result["data"]["dob"] = ''
1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041426 unmodified lines495051521 unmodified linefrom ...utils.azureOCR import analyze_imagefrom ...utils.imageUtils import resize_if_needed, all_cropped_images_to_one_imagefrom .panDataExtractor import extract_panDatadef process_results(results, img):label_indices = {"dob": 0, "father": 1, "name": 2, "pan_num": 3}confidence_threshold = 0.3input_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:continuex1, 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"] += 1precision_data[label]["correct"] += 1 # Replace with actual OCR validation check# Sort the images by their label indices in ascending ordercropped_images_with_labels.sort(key=lambda x: x[1])print(cropped_images_with_labels, "cropped images with labels")# Extract only the images for concatenationcropped_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()6 unmodified linestexts = [line['text'] for line in lines]print(texts, "text after microsoft ocr")extracted_data = extract_panData(texts)return extracted_data1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455566 unmodified lines636465661 unmodified linefrom ...utils.azureOCR import analyze_imagefrom ...utils.imageUtils import resize_if_needed, all_cropped_images_to_one_imagefrom .panDataExtractor import extract_panDatafrom collections import defaultdictdef process_results(results, img):label_indices = {"pan_num": 0, "name": 1, "father": 2, "dob": 3}confidence_threshold = 0.3input_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"best_crops = {label: (None, -1) for label in label_indices.keys()} # Store best (image, confidence) pairsprecision_data = {label: {"correct": 0, "total": 0} for label in label_indices.keys()}for result in results:for bbox, cls, conf in zip(result.boxes.xyxy, result.boxes.cls, result.boxes.conf):# Ensure the class index is within the bounds of the label listif int(cls) >= len(label_indices):print(f"Warning: Class index {cls} is out of range. Skipping this bbox.")continuelabel = list(label_indices.keys())[int(cls)]print(label, conf)if conf < confidence_threshold:continuex1, 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")# Replace old crop if new one has higher confidence_, best_conf = best_crops[label]if conf > best_conf:best_crops[label] = (crop_img, conf)precision_data[label]["total"] += 1precision_data[label]["correct"] += 1 # Replace with actual OCR validation check# Extract the images for final processingcropped_images_with_labels = [(img, label_indices[label], conf) for label, (img, conf) in best_crops.items() if img is not None]# Sort the images by their label indices in ascending ordercropped_images_with_labels.sort(key=lambda x: x[1])print(cropped_images_with_labels, "cropped images with labels")if not cropped_images_with_labels:raise ValueError("No images were cropped.")# Extract only the images for concatenationcropped_images = [img for img, _, _ in cropped_images_with_labels]final_image = all_cropped_images_to_one_image(cropped_images, separator_image_path='app/utils/seprator3.png')buffer = BytesIO()6 unmodified linestexts = [line['text'] for line in lines]print(texts, "text after microsoft ocr")extracted_data = extract_panData(texts)return extracted_data
.gitignore+3-1
app/__init__.py+1-1
app/routes/panApi.py+3-1
app/services/panServices/panDataExtractor.py+11-10
app/services/panServices/panOcr.py+27-13