Spaces:
Running
Running
Update ocr_engine.py
Browse files- ocr_engine.py +5 -4
ocr_engine.py
CHANGED
@@ -3,20 +3,21 @@ from PIL import Image
|
|
3 |
import torch
|
4 |
import re
|
5 |
|
6 |
-
# Load TrOCR model and processor
|
7 |
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
|
8 |
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
|
9 |
|
10 |
def extract_weight(image):
|
11 |
try:
|
12 |
-
# OCR
|
13 |
pixel_values = processor(images=image, return_tensors="pt").pixel_values
|
14 |
generated_ids = model.generate(pixel_values)
|
15 |
text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
|
16 |
print("OCR Output:", text)
|
17 |
|
18 |
-
#
|
19 |
-
|
|
|
20 |
|
21 |
if match:
|
22 |
value = match.group(1)
|
|
|
3 |
import torch
|
4 |
import re
|
5 |
|
6 |
+
# Load TrOCR model and processor
|
7 |
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
|
8 |
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
|
9 |
|
10 |
def extract_weight(image):
|
11 |
try:
|
12 |
+
# Step 1: OCR with TrOCR
|
13 |
pixel_values = processor(images=image, return_tensors="pt").pixel_values
|
14 |
generated_ids = model.generate(pixel_values)
|
15 |
text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
|
16 |
print("OCR Output:", text)
|
17 |
|
18 |
+
# Step 2: Search for weight pattern (g or kg)
|
19 |
+
pattern = r'(\d{1,5}(?:\.\d{1,3})?)\s*(kg|g)' # e.g., 75.25 g, 98.78kg
|
20 |
+
match = re.search(pattern, text.lower())
|
21 |
|
22 |
if match:
|
23 |
value = match.group(1)
|