sarawork commited on
Commit
3b5c20d
·
verified ·
1 Parent(s): f263e9d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -0
app.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import TrOCRProcessor, VisionEncoderDecoderModel, pipeline
3
+ from PIL import Image
4
+
5
+ # Load OCR model (TrOCR for handwritten documents)
6
+ processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
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
+ # Step 1: OCR
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
+ # Step 2: Cleanup (optional)
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="text",
30
+ title="📜 Digitize Historical Records with AI",
31
+ description="Upload a scanned historical document (handwritten or printed). This app uses Hugging Face TrOCR to extract text and optionally clean it using a grammar-aware language model."
32
+ )
33
+
34
+ if __name__ == "__main__":
35
+ demo.launch()