Update app.py
Browse files
app.py
CHANGED
|
@@ -1,35 +1,27 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 3 |
from PIL import Image
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
|
| 8 |
-
|
| 9 |
-
# Optional: grammar correction model
|
| 10 |
-
corrector = pipeline("text2text-generation", model="vennify/t5-base-grammar-correction")
|
| 11 |
-
|
| 12 |
|
| 13 |
def digitize_image(image):
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
| 15 |
pixel_values = processor(images=image, return_tensors="pt").pixel_values
|
| 16 |
generated_ids = model.generate(pixel_values)
|
| 17 |
raw_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 18 |
|
| 19 |
-
|
| 20 |
-
cleaned_text = corrector(raw_text, max_length=512)[0]['generated_text']
|
| 21 |
-
|
| 22 |
-
return f"π Raw OCR:\n{raw_text}\n\nβ
Cleaned Text:\n{cleaned_text}"
|
| 23 |
-
|
| 24 |
|
| 25 |
-
# Gradio UI
|
| 26 |
demo = gr.Interface(
|
| 27 |
fn=digitize_image,
|
| 28 |
-
inputs=gr.Image(type="pil"),
|
| 29 |
-
outputs="
|
| 30 |
-
title="π Digitize Historical Records
|
| 31 |
-
description="
|
| 32 |
)
|
| 33 |
|
| 34 |
-
|
| 35 |
-
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 3 |
from PIL import Image
|
| 4 |
|
| 5 |
+
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-printed")
|
| 6 |
+
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-printed")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
def digitize_image(image):
|
| 9 |
+
if image is None:
|
| 10 |
+
return "Please upload a valid image."
|
| 11 |
+
|
| 12 |
+
image = image.resize((768, 768)) # Optional: improve resolution
|
| 13 |
pixel_values = processor(images=image, return_tensors="pt").pixel_values
|
| 14 |
generated_ids = model.generate(pixel_values)
|
| 15 |
raw_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 16 |
|
| 17 |
+
return f"π OCR Result:\n{raw_text}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
|
|
|
| 19 |
demo = gr.Interface(
|
| 20 |
fn=digitize_image,
|
| 21 |
+
inputs=gr.Image(type="pil", label="Upload Document"),
|
| 22 |
+
outputs=gr.Textbox(label="Digitized Text"),
|
| 23 |
+
title="π Digitize Historical Records (Improved)",
|
| 24 |
+
description="Extract printed or handwritten text from historical documents using TrOCR."
|
| 25 |
)
|
| 26 |
|
| 27 |
+
demo.launch()
|
|
|