Sanjayraju30 commited on
Commit
1a5f8fd
·
verified ·
1 Parent(s): 86ef11b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -11
app.py CHANGED
@@ -1,23 +1,30 @@
1
  import gradio as gr
2
- from datetime import datetime
3
- import pytz
4
- from ocr_engine import extract_weight_from_image
5
  from PIL import Image
6
  import io
7
  import base64
 
 
8
  from simple_salesforce import Salesforce
9
  import logging
 
 
10
 
11
  # Set up logging
12
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
13
 
14
- # Salesforce configuration (replace with your credentials)
15
- SF_USERNAME = "your_salesforce_username"
16
- SF_PASSWORD = "your_salesforce_password"
17
- SF_SECURITY_TOKEN = "your_salesforce_security_token"
18
- SF_DOMAIN = "login" # or "test" for sandbox
 
 
 
19
 
20
  def connect_to_salesforce():
 
21
  try:
22
  sf = Salesforce(username=SF_USERNAME, password=SF_PASSWORD, security_token=SF_SECURITY_TOKEN, domain=SF_DOMAIN)
23
  logging.info("Connected to Salesforce successfully")
@@ -49,15 +56,44 @@ def resize_image(img, max_size_mb=5):
49
  logging.error(f"Image resizing failed: {str(e)}")
50
  return img, None
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  def process_image(img):
 
53
  if img is None:
54
  return "No image uploaded", None, None, None, gr.update(visible=False), gr.update(visible=False)
55
 
56
  ist_time = datetime.now(pytz.timezone("Asia/Kolkata")).strftime("%d-%m-%Y %I:%M:%S %p")
57
  img, img_bytes = resize_image(img)
58
- weight, confidence = extract_weight_from_image(img)
 
 
 
59
 
60
- if weight == "Not detected" or confidence < 70:
61
  return f"{weight} (Confidence: {confidence:.2f}%)", ist_time, img, None, gr.update(visible=True), gr.update(visible=False)
62
 
63
  img_buffer = io.BytesIO(img_bytes)
@@ -65,6 +101,7 @@ def process_image(img):
65
  return f"{weight} kg (Confidence: {confidence:.2f}%)", ist_time, img, img_base64, gr.update(visible=True), gr.update(visible=True)
66
 
67
  def save_to_salesforce(weight_text, img_base64):
 
68
  try:
69
  sf = connect_to_salesforce()
70
  if sf is None:
@@ -87,6 +124,7 @@ def save_to_salesforce(weight_text, img_base64):
87
  logging.error(f"Salesforce save failed: {str(e)}")
88
  return f"Failed to save to Salesforce: {str(e)}"
89
 
 
90
  with gr.Blocks(title="⚖️ Auto Weight Logger") as demo:
91
  gr.Markdown("## ⚖️ Auto Weight Logger")
92
  gr.Markdown("📷 Upload or capture an image of a digital weight scale (max 5MB).")
@@ -123,4 +161,5 @@ with gr.Blocks(title="⚖️ Auto Weight Logger") as demo:
123
  - Works on desktop and mobile browsers.
124
  """)
125
 
126
- demo.launch()
 
 
1
  import gradio as gr
2
+ import cv2
3
+ import pytesseract
 
4
  from PIL import Image
5
  import io
6
  import base64
7
+ from datetime import datetime
8
+ import pytz
9
  from simple_salesforce import Salesforce
10
  import logging
11
+ import numpy as np
12
+ import os
13
 
14
  # Set up logging
15
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
16
 
17
+ # Configure Tesseract path for Hugging Face
18
+ pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract'
19
+
20
+ # Salesforce configuration (use environment variables in production)
21
+ SF_USERNAME = os.getenv("SF_USERNAME", "your_salesforce_username")
22
+ SF_PASSWORD = os.getenv("SF_PASSWORD", "your_salesforce_password")
23
+ SF_SECURITY_TOKEN = os.getenv("SF_SECURITY_TOKEN", "your_salesforce_security_token")
24
+ SF_DOMAIN = os.getenv("SF_DOMAIN", "login") # or "test" for sandbox
25
 
26
  def connect_to_salesforce():
27
+ """Connect to Salesforce with error handling."""
28
  try:
29
  sf = Salesforce(username=SF_USERNAME, password=SF_PASSWORD, security_token=SF_SECURITY_TOKEN, domain=SF_DOMAIN)
30
  logging.info("Connected to Salesforce successfully")
 
56
  logging.error(f"Image resizing failed: {str(e)}")
57
  return img, None
58
 
59
+ def extract_weight(img):
60
+ """Extract weight from image using Tesseract OCR."""
61
+ try:
62
+ # Convert PIL image to OpenCV format
63
+ img_cv = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
64
+ gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
65
+ # Preprocess image for better OCR accuracy
66
+ _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
67
+ # Configure Tesseract for 7-segment display (digits only, single line)
68
+ config = '--psm 7 digits'
69
+ text = pytesseract.image_to_string(thresh, config=config)
70
+ # Extract numeric values (digits and decimal point)
71
+ weight = ''.join(filter(lambda x: x in '0123456789.', text))
72
+ # Validate weight (ensure it’s a valid number)
73
+ try:
74
+ weight_float = float(weight)
75
+ # Simplified confidence: 95% if valid number, else 0%
76
+ confidence = 95.0 if weight_float > 0 else 0.0
77
+ return weight, confidence
78
+ except ValueError:
79
+ return "Not detected", 0.0
80
+ except Exception as e:
81
+ logging.error(f"OCR processing failed: {str(e)}")
82
+ return "Not detected", 0.0
83
+
84
  def process_image(img):
85
+ """Process uploaded or captured image and extract weight."""
86
  if img is None:
87
  return "No image uploaded", None, None, None, gr.update(visible=False), gr.update(visible=False)
88
 
89
  ist_time = datetime.now(pytz.timezone("Asia/Kolkata")).strftime("%d-%m-%Y %I:%M:%S %p")
90
  img, img_bytes = resize_image(img)
91
+ if img_bytes is None:
92
+ return "Image processing failed", ist_time, img, None, gr.update(visible=False), gr.update(visible=False)
93
+
94
+ weight, confidence = extract_weight(img)
95
 
96
+ if weight == "Not detected" or confidence < 95.0:
97
  return f"{weight} (Confidence: {confidence:.2f}%)", ist_time, img, None, gr.update(visible=True), gr.update(visible=False)
98
 
99
  img_buffer = io.BytesIO(img_bytes)
 
101
  return f"{weight} kg (Confidence: {confidence:.2f}%)", ist_time, img, img_base64, gr.update(visible=True), gr.update(visible=True)
102
 
103
  def save_to_salesforce(weight_text, img_base64):
104
+ """Save weight and image to Salesforce Weight_Log__c object."""
105
  try:
106
  sf = connect_to_salesforce()
107
  if sf is None:
 
124
  logging.error(f"Salesforce save failed: {str(e)}")
125
  return f"Failed to save to Salesforce: {str(e)}"
126
 
127
+ # Gradio Interface
128
  with gr.Blocks(title="⚖️ Auto Weight Logger") as demo:
129
  gr.Markdown("## ⚖️ Auto Weight Logger")
130
  gr.Markdown("📷 Upload or capture an image of a digital weight scale (max 5MB).")
 
161
  - Works on desktop and mobile browsers.
162
  """)
163
 
164
+ if __name__ == "__main__":
165
+ demo.launch()