Spaces:
Sleeping
Sleeping
Delete process_local_image.py
Browse files- process_local_image.py +0 -104
process_local_image.py
DELETED
|
@@ -1,104 +0,0 @@
|
|
| 1 |
-
from transformers import LayoutLMv3Processor, LayoutLMv3ForTokenClassification
|
| 2 |
-
import torch
|
| 3 |
-
from PIL import Image
|
| 4 |
-
import json
|
| 5 |
-
import pytesseract
|
| 6 |
-
|
| 7 |
-
# ===== Load pretrained LayoutLMv3 model and processor =====
|
| 8 |
-
MODEL_ID = "microsoft/layoutlmv3-base"
|
| 9 |
-
processor = LayoutLMv3Processor.from_pretrained(MODEL_ID, apply_ocr=False)
|
| 10 |
-
model = LayoutLMv3ForTokenClassification.from_pretrained(MODEL_ID)
|
| 11 |
-
|
| 12 |
-
# ===== Define label mapping (placeholders, adjust as needed) =====
|
| 13 |
-
labels = [
|
| 14 |
-
"O", # Outside any entity
|
| 15 |
-
"B-NAME", "I-NAME",
|
| 16 |
-
"B-DOB", "I-DOB",
|
| 17 |
-
"B-ADDRESS", "I-ADDRESS",
|
| 18 |
-
"B-LICENSE", "I-LICENSE"
|
| 19 |
-
]
|
| 20 |
-
|
| 21 |
-
def extract_driver_license_info(image_path):
|
| 22 |
-
print(f"π Processing image: {image_path}")
|
| 23 |
-
|
| 24 |
-
# Load image
|
| 25 |
-
image = Image.open(image_path).convert("RGB")
|
| 26 |
-
print(f"π Image size: {image.size[0]}x{image.size[1]} pixels")
|
| 27 |
-
|
| 28 |
-
# Step 1: Extract text using Tesseract OCR
|
| 29 |
-
print("π Extracting text with Tesseract OCR...")
|
| 30 |
-
full_text = pytesseract.image_to_string(image)
|
| 31 |
-
print(f"π Tesseract OCR extracted: {len(full_text)} characters")
|
| 32 |
-
print(f"π Raw OCR text:\n{full_text}")
|
| 33 |
-
|
| 34 |
-
# Step 2: Get bounding boxes from Tesseract for LayoutLMv3
|
| 35 |
-
print("π€ Processing with LayoutLMv3 for document understanding...")
|
| 36 |
-
|
| 37 |
-
try:
|
| 38 |
-
# Get detailed OCR data with bounding boxes
|
| 39 |
-
ocr_data = pytesseract.image_to_data(image, output_type=pytesseract.Output.DICT)
|
| 40 |
-
|
| 41 |
-
# Filter out empty words and get bounding boxes
|
| 42 |
-
words = []
|
| 43 |
-
boxes = []
|
| 44 |
-
img_width, img_height = image.size
|
| 45 |
-
|
| 46 |
-
for i in range(len(ocr_data['text'])):
|
| 47 |
-
word = ocr_data['text'][i].strip()
|
| 48 |
-
if word and int(ocr_data['conf'][i]) > 30: # Confidence threshold
|
| 49 |
-
words.append(word)
|
| 50 |
-
x, y, w, h = ocr_data['left'][i], ocr_data['top'][i], ocr_data['width'][i], ocr_data['height'][i]
|
| 51 |
-
# Normalize bounding boxes to 0-1000 range as required by LayoutLMv3
|
| 52 |
-
x_norm = int((x / img_width) * 1000)
|
| 53 |
-
y_norm = int((y / img_height) * 1000)
|
| 54 |
-
x2_norm = int(((x + w) / img_width) * 1000)
|
| 55 |
-
y2_norm = int(((y + h) / img_height) * 1000)
|
| 56 |
-
boxes.append([x_norm, y_norm, x2_norm, y2_norm])
|
| 57 |
-
|
| 58 |
-
print(f"π Found {len(words)} words with bounding boxes")
|
| 59 |
-
|
| 60 |
-
if len(words) > 0 and len(boxes) > 0:
|
| 61 |
-
# Process with LayoutLMv3 using Tesseract's bounding boxes
|
| 62 |
-
encoding = processor(image, words, boxes=boxes, return_tensors="pt")
|
| 63 |
-
|
| 64 |
-
with torch.no_grad():
|
| 65 |
-
outputs = model(**encoding)
|
| 66 |
-
logits = outputs.logits
|
| 67 |
-
predictions = logits.argmax(-1).squeeze().tolist()
|
| 68 |
-
|
| 69 |
-
print(f"π LayoutLMv3 processed {len(words)} words with bounding boxes")
|
| 70 |
-
print(f"π All predictions: {predictions}")
|
| 71 |
-
print(f"π All labels: {[labels[p] if p < len(labels) else f'UNKNOWN_{p}' for p in predictions]}")
|
| 72 |
-
print(f"π Word-prediction pairs: {list(zip(words, predictions))}")
|
| 73 |
-
|
| 74 |
-
# Extract entities using LayoutLMv3 predictions
|
| 75 |
-
extracted = {"name": "", "dob": "", "address": "", "license_number": "", "expiry": ""}
|
| 76 |
-
current_label = None
|
| 77 |
-
|
| 78 |
-
for word, pred_id in zip(words, predictions):
|
| 79 |
-
if pred_id < len(labels):
|
| 80 |
-
label = labels[pred_id]
|
| 81 |
-
if label.startswith("B-"):
|
| 82 |
-
current_label = label[2:].lower()
|
| 83 |
-
extracted[current_label] = word
|
| 84 |
-
elif label.startswith("I-") and current_label:
|
| 85 |
-
extracted[current_label] += " " + word
|
| 86 |
-
else:
|
| 87 |
-
current_label = None
|
| 88 |
-
|
| 89 |
-
print(f"π LayoutLMv3 extracted: {extracted}")
|
| 90 |
-
|
| 91 |
-
else:
|
| 92 |
-
print("β οΈ No valid words found by Tesseract")
|
| 93 |
-
extracted = {"name": "", "dob": "", "address": "", "license_number": "", "expiry": ""}
|
| 94 |
-
|
| 95 |
-
except Exception as e:
|
| 96 |
-
print(f"β οΈ LayoutLMv3 processing failed: {str(e)}")
|
| 97 |
-
extracted = {"name": "", "dob": "", "address": "", "license_number": "", "expiry": ""}
|
| 98 |
-
|
| 99 |
-
return extracted
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
if __name__ == "__main__":
|
| 103 |
-
result = extract_driver_license_info("1.jpg")
|
| 104 |
-
print(json.dumps(result, indent=4))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|