Spaces:
Sleeping
Sleeping
Update ocr_engine.py
Browse files- ocr_engine.py +14 -32
ocr_engine.py
CHANGED
|
@@ -1,35 +1,17 @@
|
|
| 1 |
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 2 |
-
from PIL import Image
|
| 3 |
-
import
|
| 4 |
|
| 5 |
-
#
|
| 6 |
-
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-
|
| 7 |
-
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-
|
| 8 |
|
| 9 |
-
def extract_weight(image
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
generated_ids = model.generate(pixel_values, max_length=32)
|
| 19 |
-
full_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 20 |
-
print("OCR Output:", full_text)
|
| 21 |
-
|
| 22 |
-
# Step 3: Extract numeric value
|
| 23 |
-
cleaned = full_text.lower().replace(" ", "")
|
| 24 |
-
match = re.search(r"(\d+(\.\d+)?)", cleaned)
|
| 25 |
-
weight = match.group(1) if match else None
|
| 26 |
-
|
| 27 |
-
# Step 4: Determine unit
|
| 28 |
-
if any(u in cleaned for u in ["kg", "kgs", "kilo"]):
|
| 29 |
-
unit = "kg"
|
| 30 |
-
elif any(u in cleaned for u in ["g", "gram", "grams"]):
|
| 31 |
-
unit = "grams"
|
| 32 |
-
else:
|
| 33 |
-
unit = "kg" if weight and float(weight) >= 20 else "grams"
|
| 34 |
-
|
| 35 |
-
return f"{weight} {unit}" if weight else "No valid weight detected"
|
|
|
|
| 1 |
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import torch
|
| 4 |
|
| 5 |
+
# Load processor and model only once
|
| 6 |
+
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
|
| 7 |
+
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
|
| 8 |
|
| 9 |
+
def extract_weight(image):
|
| 10 |
+
try:
|
| 11 |
+
# Resize or preprocess if needed
|
| 12 |
+
pixel_values = processor(images=image, return_tensors="pt").pixel_values
|
| 13 |
+
generated_ids = model.generate(pixel_values)
|
| 14 |
+
text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 15 |
+
return text.strip()
|
| 16 |
+
except Exception as e:
|
| 17 |
+
return f"Error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|