Spaces:
Running
Running
import gradio as gr | |
from datetime import datetime | |
import pytz | |
from ocr_engine import extract_weight_from_image | |
from PIL import Image | |
import io | |
import base64 | |
from simple_salesforce import Salesforce | |
import logging | |
# Set up logging | |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
# Salesforce configuration (replace with your credentials) | |
SF_USERNAME = "your_salesforce_username" | |
SF_PASSWORD = "your_salesforce_password" | |
SF_SECURITY_TOKEN = "your_salesforce_security_token" | |
SF_DOMAIN = "login" # or "test" for sandbox | |
def connect_to_salesforce(): | |
try: | |
sf = Salesforce(username=SF_USERNAME, password=SF_PASSWORD, security_token=SF_SECURITY_TOKEN, domain=SF_DOMAIN) | |
logging.info("Connected to Salesforce successfully") | |
return sf | |
except Exception as e: | |
logging.error(f"Salesforce connection failed: {str(e)}") | |
return None | |
def resize_image(img, max_size_mb=5): | |
"""Resize image to ensure size < 5MB while preserving quality.""" | |
try: | |
img_bytes = io.BytesIO() | |
img.save(img_bytes, format="PNG") | |
size_mb = len(img_bytes.getvalue()) / (1024 * 1024) | |
if size_mb <= max_size_mb: | |
return img, img_bytes.getvalue() | |
# Resize proportionally | |
scale = 0.9 | |
while size_mb > max_size_mb: | |
w, h = img.size | |
img = img.resize((int(w * scale), int(h * scale)), Image.Resampling.LANCZOS) | |
img_bytes = io.BytesIO() | |
img.save(img_bytes, format="PNG") | |
size_mb = len(img_bytes.getvalue()) / (1024 * 1024) | |
scale *= 0.9 | |
logging.info(f"Resized image to {size_mb:.2f} MB") | |
return img, img_bytes.getvalue() | |
except Exception as e: | |
logging.error(f"Image resizing failed: {str(e)}") | |
return img, None | |
def process_image(img): | |
if img is None: | |
return "No image uploaded", None, None, None, gr.update(visible=False), gr.update(visible=False) | |
ist_time = datetime.now(pytz.timezone("Asia/Kolkata")).strftime("%d-%m-%Y %I:%M:%S %p") | |
img, img_bytes = resize_image(img) | |
weight, confidence = extract_weight_from_image(img) | |
if weight == "Not detected" or confidence < 70: | |
return f"{weight} (Confidence: {confidence}%)", ist_time, img, None, gr.update(visible=True), gr.update(visible=False) | |
# Encode image for preview | |
img_buffer = io.BytesIO(img_bytes) | |
img_base64 = base64.b64encode(img_buffer.getvalue()).decode() | |
return f"{weight} kg (Confidence: {confidence}%)", ist_time, img, img_base64, gr.update(visible=True), gr.update(visible=True) | |
def save_to_salesforce(weight_text, img_base64): | |
try: | |
sf = connect_to_salesforce() | |
if sf is None: | |
return "Failed to connect to Salesforce" | |
# Extract weight from text (remove "kg" and confidence) | |
weight = float(weight_text.split(" ")[0]) | |
ist_time = datetime.now(pytz.timezone("Asia/Kolkata")).strftime("%Y-%m-%d %H:%M:%S") | |
# Create custom object record (adjust object and fields as needed) | |
record = { | |
"Name": f"Weight_Log_{ist_time}", | |
"Weight__c": weight, | |
"Timestamp__c": ist_time, | |
"Image__c": img_base64 | |
} | |
result = sf.Weight_Log__c.create(record) | |
logging.info(f"Salesforce record created: {result}") | |
return "Successfully saved to Salesforce" | |
except Exception as e: | |
logging.error(f"Salesforce save failed: {str(e)}") | |
return f"Failed to save to Salesforce: {str(e)}" | |
with gr.Blocks(title="βοΈ Auto Weight Logger") as demo: | |
gr.Markdown("## βοΈ Auto Weight Logger") | |
gr.Markdown("π· Upload or capture an image of a digital weight scale (max 5MB).") | |
with gr.Row(): | |
image_input = gr.Image(type="pil", label="Upload / Capture Image") | |
output_weight = gr.Textbox(label="βοΈ Detected Weight (in kg)") | |
with gr.Row(): | |
timestamp = gr.Textbox(label="π Captured At (IST)") | |
snapshot = gr.Image(label="πΈ Snapshot Image") | |
with gr.Row(): | |
confirm_button = gr.Button("β Confirm and Save to Salesforce", visible=False) | |
status = gr.Textbox(label="Save Status", visible=False) | |
submit = gr.Button("π Detect Weight") | |
submit.click( | |
fn=process_image, | |
inputs=image_input, | |
outputs=[output_weight, timestamp, snapshot, gr.State(), confirm_button, status] | |
) | |
confirm_button.click( | |
fn=save_to_salesforce, | |
inputs=[output_weight, gr.State()], | |
outputs=status | |
) | |
gr.Markdown(""" | |
### Instructions | |
- Upload a clear, well-lit image of a digital weight scale display. | |
- Ensure the image is < 5MB (automatically resized if larger). | |
- Review the detected weight and click 'Confirm and Save to Salesforce' to log the data. | |
- The application works on both desktop and mobile browsers. | |
""") | |
demo.launch() |