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image import convert_from_path
|
| 7 |
+
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 8 |
+
from doctr.models import detection_predictor
|
| 9 |
+
import tempfile
|
| 10 |
+
|
| 11 |
+
MODEL_ID = "umangchaudhari/gujarati-ocr"
|
| 12 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 13 |
+
PAD = 4
|
| 14 |
+
MIN_SCORE = 0.4
|
| 15 |
+
|
| 16 |
+
print("Loading models...")
|
| 17 |
+
processor = TrOCRProcessor.from_pretrained(MODEL_ID)
|
| 18 |
+
model = VisionEncoderDecoderModel.from_pretrained(MODEL_ID).to(DEVICE)
|
| 19 |
+
model.eval()
|
| 20 |
+
|
| 21 |
+
detector = detection_predictor(
|
| 22 |
+
arch='db_resnet50',
|
| 23 |
+
pretrained=True,
|
| 24 |
+
assume_straight_pages=True,
|
| 25 |
+
preserve_aspect_ratio=True,
|
| 26 |
+
symmetric_pad=True,
|
| 27 |
+
).to(DEVICE)
|
| 28 |
+
print("Models ready.")
|
| 29 |
+
|
| 30 |
+
def recognize_batch(crops):
|
| 31 |
+
if not crops:
|
| 32 |
+
return []
|
| 33 |
+
pixel_values = processor(
|
| 34 |
+
images=[c.convert("RGB") for c in crops],
|
| 35 |
+
return_tensors="pt"
|
| 36 |
+
).pixel_values.to(DEVICE)
|
| 37 |
+
with torch.no_grad():
|
| 38 |
+
generated = model.generate(pixel_values, max_new_tokens=64)
|
| 39 |
+
return [t.strip() for t in processor.batch_decode(generated, skip_special_tokens=True)]
|
| 40 |
+
|
| 41 |
+
def ocr_image(page_image):
|
| 42 |
+
W, H = page_image.width, page_image.height
|
| 43 |
+
page_np = np.array(page_image.convert("RGB"))
|
| 44 |
+
|
| 45 |
+
with torch.no_grad():
|
| 46 |
+
result = detector([page_np])
|
| 47 |
+
|
| 48 |
+
raw = result[0].get("words", np.zeros((0, 5)))
|
| 49 |
+
if raw.shape[0] == 0:
|
| 50 |
+
return ""
|
| 51 |
+
|
| 52 |
+
raw = raw[raw[:, 4] >= MIN_SCORE]
|
| 53 |
+
|
| 54 |
+
boxes_abs = []
|
| 55 |
+
for det in raw:
|
| 56 |
+
xmin, ymin, xmax, ymax, score = det
|
| 57 |
+
x0 = max(0, int(xmin * W) - PAD)
|
| 58 |
+
y0 = max(0, int(ymin * H) - PAD)
|
| 59 |
+
x1 = min(W, int(xmax * W) + PAD)
|
| 60 |
+
y1 = min(H, int(ymax * H) + PAD)
|
| 61 |
+
if x1 - x0 < 5 or y1 - y0 < 5:
|
| 62 |
+
continue
|
| 63 |
+
boxes_abs.append((y0, x0, x1, y1))
|
| 64 |
+
|
| 65 |
+
boxes_abs.sort(key=lambda b: (b[0] // 15, b[1]))
|
| 66 |
+
|
| 67 |
+
crops = []
|
| 68 |
+
valid_pos = []
|
| 69 |
+
for (y0, x0, x1, y1) in boxes_abs:
|
| 70 |
+
crops.append(page_image.crop((x0, y0, x1, y1)))
|
| 71 |
+
valid_pos.append((y0, x0))
|
| 72 |
+
|
| 73 |
+
all_texts = []
|
| 74 |
+
for i in range(0, len(crops), 64):
|
| 75 |
+
all_texts.extend(recognize_batch(crops[i:i+64]))
|
| 76 |
+
|
| 77 |
+
lines = {}
|
| 78 |
+
for (y, x), text in zip(valid_pos, all_texts):
|
| 79 |
+
if not text:
|
| 80 |
+
continue
|
| 81 |
+
row_key = y // 15
|
| 82 |
+
if row_key not in lines:
|
| 83 |
+
lines[row_key] = []
|
| 84 |
+
lines[row_key].append((x, text))
|
| 85 |
+
|
| 86 |
+
result_lines = []
|
| 87 |
+
for key in sorted(lines.keys()):
|
| 88 |
+
words = [t for _, t in sorted(lines[key], key=lambda z: z[0])]
|
| 89 |
+
result_lines.append(" ".join(words))
|
| 90 |
+
|
| 91 |
+
return "\n".join(result_lines)
|
| 92 |
+
|
| 93 |
+
def process_pdf(pdf_file):
|
| 94 |
+
if pdf_file is None:
|
| 95 |
+
return "Please upload a PDF or image."
|
| 96 |
+
try:
|
| 97 |
+
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp:
|
| 98 |
+
tmp.write(open(pdf_file.name, "rb").read())
|
| 99 |
+
tmp_path = tmp.name
|
| 100 |
+
|
| 101 |
+
pages = convert_from_path(tmp_path, dpi=200)
|
| 102 |
+
all_text = []
|
| 103 |
+
for i, page in enumerate(pages):
|
| 104 |
+
text = ocr_image(page)
|
| 105 |
+
all_text.append(f"--- Page {i+1} ---\n{text}")
|
| 106 |
+
return "\n\n".join(all_text)
|
| 107 |
+
except Exception as e:
|
| 108 |
+
return f"Error: {str(e)}"
|
| 109 |
+
|
| 110 |
+
def process_image(image):
|
| 111 |
+
if image is None:
|
| 112 |
+
return "Please upload an image."
|
| 113 |
+
try:
|
| 114 |
+
return ocr_image(image)
|
| 115 |
+
except Exception as e:
|
| 116 |
+
return f"Error: {str(e)}"
|
| 117 |
+
|
| 118 |
+
with gr.Blocks(title="Gujarati OCR") as demo:
|
| 119 |
+
gr.Markdown("""
|
| 120 |
+
# 🔤 Gujarati OCR
|
| 121 |
+
Extract text from Gujarati documents and images.
|
| 122 |
+
Fine-tuned TrOCR model trained on 80,000+ Gujarati word samples — **96.2% accuracy**.
|
| 123 |
+
""")
|
| 124 |
+
|
| 125 |
+
with gr.Tab("PDF"):
|
| 126 |
+
pdf_input = gr.File(label="Upload PDF", file_types=[".pdf"])
|
| 127 |
+
pdf_button = gr.Button("Extract Text", variant="primary")
|
| 128 |
+
pdf_output = gr.Textbox(label="Extracted Text", lines=20)
|
| 129 |
+
pdf_button.click(process_pdf, inputs=pdf_input, outputs=pdf_output)
|
| 130 |
+
|
| 131 |
+
with gr.Tab("Image"):
|
| 132 |
+
img_input = gr.Image(label="Upload Image", type="pil")
|
| 133 |
+
img_button = gr.Button("Extract Text", variant="primary")
|
| 134 |
+
img_output = gr.Textbox(label="Extracted Text", lines=20)
|
| 135 |
+
img_button.click(process_image, inputs=img_input, outputs=img_output)
|
| 136 |
+
|
| 137 |
+
gr.Markdown("""
|
| 138 |
+
**Model:** [umangchaudhari/gujarati-ocr](https://huggingface.co/umangchaudhari/gujarati-ocr)
|
| 139 |
+
**Detection:** docTR db_resnet50
|
| 140 |
+
**Recognition:** Fine-tuned Microsoft TrOCR
|
| 141 |
+
""")
|
| 142 |
+
|
| 143 |
+
demo.launch()
|