Sanjayraju30 commited on
Commit
750cb23
·
verified ·
1 Parent(s): 793e163

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -0
app.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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")
24
+ return sf
25
+ except Exception as e:
26
+ logging.error(f"Salesforce connection failed: {str(e)}")
27
+ return None
28
+
29
+ def resize_image(img, max_size_mb=5):
30
+ """Resize image to ensure size < 5MB while preserving quality."""
31
+ try:
32
+ img_bytes = io.BytesIO()
33
+ img.save(img_bytes, format="PNG")
34
+ size_mb = len(img_bytes.getvalue()) / (1024 * 1024)
35
+ if size_mb <= max_size_mb:
36
+ return img, img_bytes.getvalue()
37
+
38
+ scale = 0.9
39
+ while size_mb > max_size_mb:
40
+ w, h = img.size
41
+ img = img.resize((int(w * scale), int(h * scale)), Image.Resampling.LANCZOS)
42
+ img_bytes = io.BytesIO()
43
+ img.save(img_bytes, format="PNG")
44
+ size_mb = len(img_bytes.getvalue()) / (1024 * 1024)
45
+ scale *= 0.9
46
+ logging.info(f"Resized image to {size_mb:.2f} MB")
47
+ return img, img_bytes.getvalue()
48
+ except Exception as e:
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)
64
+ img_base64 = base64.b64encode(img_buffer.getvalue()).decode()
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:
71
+ return "Failed to connect to Salesforce"
72
+
73
+ weight = float(weight_text.split(" ")[0])
74
+ ist_time = datetime.now(pytz.timezone("Asia/Kolkata")).strftime("%Y-%m-%d %H:%M:%S")
75
+
76
+ record = {
77
+ "Name": f"Weight_Log_{ist_time}",
78
+ "Weight__c": weight,
79
+ "Timestamp__c": ist_time,
80
+ "Image__c": img_base64
81
+ }
82
+ result = sf.Weight_Log__c.create(record)
83
+ logging.info(f"Salesforce record created: {result}")
84
+ return "Successfully saved to Salesforce"
85
+ except Exception as e:
86
+ logging.error(f"Salesforce save failed: {str(e)}")
87
+ return f"Failed to save to Salesforce: {str(e)}"
88
+
89
+ with gr.Blocks(title="\u2696\ufe0f Auto Weight Logger") as demo:
90
+ gr.Markdown("## \u2696\ufe0f Auto Weight Logger")
91
+ gr.Markdown("\ud83d\udcf7 Upload or capture an image of a digital weight scale (max 5MB).")
92
+
93
+ with gr.Row():
94
+ image_input = gr.Image(type="pil", label="Upload / Capture Image")
95
+ output_weight = gr.Textbox(label="\u2696\ufe0f Detected Weight (in kg)")
96
+
97
+ with gr.Row():
98
+ timestamp = gr.Textbox(label="\ud83d\udd52 Captured At (IST)")
99
+ snapshot = gr.Image(label="\ud83d\udcf8 Snapshot Image")
100
+
101
+ with gr.Row():
102
+ confirm_button = gr.Button("\u2705 Confirm and Save to Salesforce", visible=False)
103
+ status = gr.Textbox(label="Save Status", visible=False)
104
+
105
+ submit = gr.Button("\ud83d\udd0d Detect Weight")
106
+ submit.click(
107
+ fn=process_image,
108
+ inputs=image_input,
109
+ outputs=[output_weight, timestamp, snapshot, gr.State(), confirm_button, status]
110
+ )
111
+ confirm_button.click(
112
+ fn=save_to_salesforce,
113
+ inputs=[output_weight, gr.State()],
114
+ outputs=status
115
+ )
116
+
117
+ gr.Markdown("""
118
+ ### Instructions
119
+ - Upload a clear, well-lit image of a digital weight scale display.
120
+ - Ensure the image is < 5MB (automatically resized if larger).
121
+ - Review the detected weight and click 'Confirm and Save to Salesforce' to log the data.
122
+ - Works on desktop and mobile browsers.
123
+ """)
124
+
125
+ demo.launch()