Sanjayraju30 commited on
Commit
83f2f91
·
verified ·
1 Parent(s): f50878a

Update ocr_engine.py

Browse files
Files changed (1) hide show
  1. ocr_engine.py +10 -17
ocr_engine.py CHANGED
@@ -3,37 +3,30 @@ from PIL import Image
3
  import torch
4
  import re
5
 
6
- # Load TrOCR processor and model once
7
  processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
8
  model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
9
 
10
  def clean_ocr_text(text):
11
- # Fix common OCR mistakes
12
- text = text.replace(",", ".") # comma to dot
13
- text = re.sub(r"[^\d\.kg]", "", text.lower()) # keep only digits, dot, k, g
 
14
  return text
15
 
16
  def extract_weight(image):
17
  try:
18
- # TrOCR inference
19
  pixel_values = processor(images=image, return_tensors="pt").pixel_values
20
  generated_ids = model.generate(pixel_values)
21
  raw_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
22
- print("OCR Raw Output:", raw_text)
23
 
24
- # Clean and normalize text
25
- cleaned_text = clean_ocr_text(raw_text)
26
- print("Cleaned OCR:", cleaned_text)
27
-
28
- # Flexible regex to catch even minor issues (e.g., 52.2g, 98.7kg)
29
- pattern = r'(\d{1,5}(?:\.\d{1,3})?)\s*(kg|g)'
30
- match = re.search(pattern, cleaned_text)
31
 
 
 
32
  if match:
33
- value = match.group(1)
34
- unit = match.group(2)
35
- return f"{value} {unit}"
36
  else:
37
- return "No valid weight found"
38
  except Exception as e:
39
  return f"Error: {str(e)}"
 
3
  import torch
4
  import re
5
 
6
+ # Load TrOCR once
7
  processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
8
  model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
9
 
10
  def clean_ocr_text(text):
11
+ print("[RAW OCR]", text)
12
+ text = text.replace(",", ".").replace("s", "5").replace("o", "0").lower()
13
+ text = re.sub(r"[^\d\.kg]", "", text) # Keep only digits, dot, k, g
14
+ print("[CLEANED OCR]", text)
15
  return text
16
 
17
  def extract_weight(image):
18
  try:
 
19
  pixel_values = processor(images=image, return_tensors="pt").pixel_values
20
  generated_ids = model.generate(pixel_values)
21
  raw_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
 
22
 
23
+ cleaned = clean_ocr_text(raw_text)
 
 
 
 
 
 
24
 
25
+ # Regex for weight
26
+ match = re.search(r'(\d{1,5}(?:\.\d{1,3})?)\s*(kg|g)', cleaned)
27
  if match:
28
+ return f"{match.group(1)} {match.group(2)}"
 
 
29
  else:
30
+ return f"No valid weight found | OCR: {cleaned}"
31
  except Exception as e:
32
  return f"Error: {str(e)}"