Spaces:
Runtime error
Runtime error
Create ocr_engine.py
Browse files- ocr_engine.py +114 -0
ocr_engine.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from PIL import Image
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
import pytz
|
| 5 |
+
from ocr_engine import extract_weight, extract_unit_from_text
|
| 6 |
+
from simple_salesforce import Salesforce
|
| 7 |
+
import base64
|
| 8 |
+
import re
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
# Salesforce credentials
|
| 12 |
+
SF_USERNAME = "[email protected]"
|
| 13 |
+
SF_PASSWORD = "autoweight@32"
|
| 14 |
+
SF_TOKEN = "UgiHKWT0aoZRX9gvTYDjAiRY"
|
| 15 |
+
|
| 16 |
+
# Connect to Salesforce
|
| 17 |
+
sf = Salesforce(username=SF_USERNAME, password=SF_PASSWORD, security_token=SF_TOKEN)
|
| 18 |
+
|
| 19 |
+
def restore_decimal(text):
|
| 20 |
+
if re.fullmatch(r"\d{5}", text):
|
| 21 |
+
return f"{text[:2]}.{text[2:]}"
|
| 22 |
+
elif re.fullmatch(r"\d{4}", text):
|
| 23 |
+
return f"{text[:2]}.{text[2:]}"
|
| 24 |
+
return text
|
| 25 |
+
|
| 26 |
+
def process_image(image):
|
| 27 |
+
if image is None:
|
| 28 |
+
return "β No image provided", "", None, gr.update(visible=True)
|
| 29 |
+
try:
|
| 30 |
+
result = extract_weight(image)
|
| 31 |
+
weight, raw_text = result if isinstance(result, tuple) else (result, "")
|
| 32 |
+
|
| 33 |
+
print("π§ Final OCR Result:", weight)
|
| 34 |
+
print("π€ OCR Raw Text:", raw_text)
|
| 35 |
+
|
| 36 |
+
ist = pytz.timezone('Asia/Kolkata')
|
| 37 |
+
timestamp = datetime.now(ist).strftime("%Y-%m-%d %H:%M:%S IST")
|
| 38 |
+
|
| 39 |
+
if not weight or (isinstance(weight, str) and weight.startswith("Error")):
|
| 40 |
+
return f"β OCR Error: {weight}", "", image, gr.update(visible=True)
|
| 41 |
+
|
| 42 |
+
match = re.search(r'(\d{1,3}\.\d{1,3})\s*(kg|g)?', weight)
|
| 43 |
+
if match:
|
| 44 |
+
numeric_value = float(match.group(1))
|
| 45 |
+
unit = match.group(2) if match.group(2) else extract_unit_from_text(raw_text) or "kg"
|
| 46 |
+
else:
|
| 47 |
+
cleaned = re.sub(r"[^\d]", "", weight)
|
| 48 |
+
decimal_fixed = restore_decimal(cleaned)
|
| 49 |
+
try:
|
| 50 |
+
numeric_value = float(decimal_fixed)
|
| 51 |
+
unit = extract_unit_from_text(raw_text) or "kg"
|
| 52 |
+
except:
|
| 53 |
+
return f"β Could not extract number | OCR: {weight}", "", image, gr.update(visible=True)
|
| 54 |
+
|
| 55 |
+
image_path = "snapshot.jpg"
|
| 56 |
+
image.save(image_path)
|
| 57 |
+
|
| 58 |
+
record = sf.Weight_Log__c.create({
|
| 59 |
+
"Captured_Weight__c": numeric_value,
|
| 60 |
+
"Captured_Unit__c": unit,
|
| 61 |
+
"Captured_At__c": datetime.now(ist).isoformat(),
|
| 62 |
+
"Device_ID__c": "DEVICE-001",
|
| 63 |
+
"Status__c": "Confirmed"
|
| 64 |
+
})
|
| 65 |
+
|
| 66 |
+
with open(image_path, "rb") as f:
|
| 67 |
+
encoded_image = base64.b64encode(f.read()).decode("utf-8")
|
| 68 |
+
|
| 69 |
+
content = sf.ContentVersion.create({
|
| 70 |
+
"Title": f"Snapshot_{timestamp}",
|
| 71 |
+
"PathOnClient": "snapshot.jpg",
|
| 72 |
+
"VersionData": encoded_image
|
| 73 |
+
})
|
| 74 |
+
|
| 75 |
+
content_id = sf.query(
|
| 76 |
+
f"SELECT ContentDocumentId FROM ContentVersion WHERE Id = '{content['id']}'"
|
| 77 |
+
)['records'][0]['ContentDocumentId']
|
| 78 |
+
|
| 79 |
+
sf.ContentDocumentLink.create({
|
| 80 |
+
"ContentDocumentId": content_id,
|
| 81 |
+
"LinkedEntityId": record['id'],
|
| 82 |
+
"ShareType": "V",
|
| 83 |
+
"Visibility": "AllUsers"
|
| 84 |
+
})
|
| 85 |
+
|
| 86 |
+
return f"{numeric_value} {unit}", timestamp, image, gr.update(visible=False)
|
| 87 |
+
except Exception as e:
|
| 88 |
+
return f"Error: {str(e)}", "", None, gr.update(visible=True)
|
| 89 |
+
|
| 90 |
+
with gr.Blocks(css=".gr-button {background-color: #2e7d32 !important; color: white !important;}" ) as demo:
|
| 91 |
+
gr.Markdown("""
|
| 92 |
+
<h1 style='text-align: center; color: #2e7d32;'>π· Auto Weight Logger</h1>
|
| 93 |
+
<p style='text-align: center;'>Upload or capture a digital weight image. Detects weight using AI OCR.</p>
|
| 94 |
+
<hr style='border: 1px solid #ddd;' />
|
| 95 |
+
""")
|
| 96 |
+
|
| 97 |
+
with gr.Row():
|
| 98 |
+
image_input = gr.Image(type="pil", label="π Upload or Capture Image")
|
| 99 |
+
|
| 100 |
+
detect_btn = gr.Button("π Detect Weight")
|
| 101 |
+
|
| 102 |
+
with gr.Row():
|
| 103 |
+
weight_out = gr.Textbox(label="π¦ Detected Weight", placeholder="e.g., 75.5 kg", show_copy_button=True)
|
| 104 |
+
time_out = gr.Textbox(label="π Captured At (IST)", placeholder="e.g., 2025-07-01 12:00:00")
|
| 105 |
+
|
| 106 |
+
snapshot = gr.Image(label="πΈ Snapshot Preview")
|
| 107 |
+
retake_btn = gr.Button("π Retake / Try Again", visible=False)
|
| 108 |
+
|
| 109 |
+
detect_btn.click(fn=process_image, inputs=image_input, outputs=[weight_out, time_out, snapshot, retake_btn])
|
| 110 |
+
retake_btn.click(fn=lambda: ("", "", None, gr.update(visible=False)),
|
| 111 |
+
inputs=[], outputs=[weight_out, time_out, snapshot, retake_btn])
|
| 112 |
+
|
| 113 |
+
if __name__ == "__main__":
|
| 114 |
+
demo.launch()
|