Sanjayraju30 commited on
Commit
fb27fac
·
verified ·
1 Parent(s): 556d23e

Update ocr_engine.py

Browse files
Files changed (1) hide show
  1. ocr_engine.py +19 -13
ocr_engine.py CHANGED
@@ -9,24 +9,30 @@ model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-stage1")
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}"
31
  else:
32
  return "No valid weight detected"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, max_length=20)
13
  full_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
14
 
15
+ # For debugging (optional):
16
+ print("OCR Output:", full_text)
17
 
18
+ # Extract number (weight)
 
 
 
 
 
 
 
 
19
  match = re.search(r"(\d+(\.\d+)?)", full_text)
20
  if match:
21
  weight = match.group(1)
 
22
  else:
23
  return "No valid weight detected"
24
+
25
+ # Detect unit — smarter match
26
+ text_lower = full_text.lower().replace(" ", "")
27
+ if any(unit in text_lower for unit in ["kg", "kgs", "kilogram", "kilo", "k.g"]):
28
+ unit = "kg"
29
+ elif any(unit in text_lower for unit in ["g", "gram", "grams"]):
30
+ unit = "grams"
31
+ else:
32
+ # Smart fallback: use value
33
+ if float(weight) >= 5:
34
+ unit = "kg"
35
+ else:
36
+ unit = "grams"
37
+
38
+ return f"{weight} {unit}"