Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# trocr_infer.py -- paste into your app.py and call ocr_with_trocr(pil_image)
|
| 2 |
+
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 6 |
+
|
| 7 |
+
# Model choices: "microsoft/trocr-base-printed" or "microsoft/trocr-base-handwritten"
|
| 8 |
+
MODEL_NAME = "microsoft/trocr-base-printed"
|
| 9 |
+
|
| 10 |
+
processor = TrOCRProcessor.from_pretrained(MODEL_NAME)
|
| 11 |
+
model = VisionEncoderDecoderModel.from_pretrained(MODEL_NAME).to(device)
|
| 12 |
+
model.eval()
|
| 13 |
+
|
| 14 |
+
def ocr_with_trocr(pil_image):
|
| 15 |
+
"""
|
| 16 |
+
Input: PIL.Image (RGB)
|
| 17 |
+
Returns: recognized text string
|
| 18 |
+
"""
|
| 19 |
+
# Preprocess
|
| 20 |
+
pixel_values = processor(images=pil_image, return_tensors="pt").pixel_values.to(device)
|
| 21 |
+
# Generate (greedy; tune generation params if desired)
|
| 22 |
+
generated_ids = model.generate(pixel_values, max_length=128, num_beams=1)
|
| 23 |
+
text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 24 |
+
return text.strip()
|