Sanjayraju30 commited on
Commit
d22d28e
·
verified ·
1 Parent(s): ed22ec8

Update ocr_engine.py

Browse files
Files changed (1) hide show
  1. ocr_engine.py +9 -12
ocr_engine.py CHANGED
@@ -1,33 +1,30 @@
1
  from transformers import TrOCRProcessor, VisionEncoderDecoderModel
2
  from PIL import Image
 
3
 
4
- # Load OCR model once
5
  processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-stage1")
6
  model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-stage1")
7
 
8
  def extract_weight(image: Image.Image) -> str:
9
- # Ensure image is in RGB
10
  image = image.convert("RGB")
11
-
12
- # Process with Hugging Face OCR
13
  pixel_values = processor(images=image, return_tensors="pt").pixel_values
14
  generated_ids = model.generate(pixel_values)
15
  full_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
16
 
17
- # Normalize text
18
- full_text_cleaned = full_text.lower().replace(" ", "")
19
 
20
  # Detect unit
21
- if "kg" in full_text_cleaned:
22
  unit = "kg"
23
- elif "g" in full_text_cleaned or "gram" in full_text_cleaned:
24
  unit = "grams"
25
  else:
26
- unit = "grams" # default to grams if not clear
27
 
28
- # Extract number (includes decimals)
29
- import re
30
- match = re.search(r"(\d+(\.\d+)?)", full_text_cleaned)
31
  if match:
32
  weight = match.group(1)
33
  return f"{weight} {unit}"
 
1
  from transformers import TrOCRProcessor, VisionEncoderDecoderModel
2
  from PIL import Image
3
+ import re
4
 
5
+ # Load model + processor
6
  processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-stage1")
7
  model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-stage1")
8
 
9
  def extract_weight(image: Image.Image) -> str:
 
10
  image = image.convert("RGB")
 
 
11
  pixel_values = processor(images=image, return_tensors="pt").pixel_values
12
  generated_ids = model.generate(pixel_values)
13
  full_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
14
 
15
+ # Lowercase text but don't strip spacing before kg detection
16
+ full_text_lower = full_text.lower()
17
 
18
  # Detect unit
19
+ if "kg" in full_text_lower.replace(" ", ""):
20
  unit = "kg"
21
+ elif "g" in full_text_lower.replace(" ", "") or "gram" in full_text_lower:
22
  unit = "grams"
23
  else:
24
+ unit = "grams" # default
25
 
26
+ # Extract number using regex
27
+ match = re.search(r"(\d+(\.\d+)?)", full_text)
 
28
  if match:
29
  weight = match.group(1)
30
  return f"{weight} {unit}"