import gradio as gr from PIL import Image from datetime import datetime import pytz from ocr_engine import extract_weight from simple_salesforce import Salesforce import base64 import os # Salesforce credentials SF_USERNAME = "Autoweightlogger@sathkrutha.com" SF_PASSWORD = "autoweight@32" SF_TOKEN = "UgiHKWT0aoZRX9gvTYDjAiRY" # Connect to Salesforce sf = Salesforce(username=SF_USERNAME, password=SF_PASSWORD, security_token=SF_TOKEN) def process_image(image): if image is None: return "❌ No image provided", "", None, gr.update(visible=True) try: weight = extract_weight(image) ist = pytz.timezone('Asia/Kolkata') timestamp = datetime.now(ist).strftime("%Y-%m-%d %H:%M:%S IST") if not weight or "No valid" in weight: return "❌ Unable to detect. Try again with a clearer image.", "", image, gr.update(visible=True) # Save image temporarily image_path = "snapshot.jpg" image.save(image_path) # Create Weight_Log__c record first record = sf.Weight_Log__c.create({ "Captured_Weight__c": float(weight.replace("kg", "").strip()), "Captured_At__c": datetime.now(ist).isoformat(), "Device_ID__c": "DEVICE-001", "Status__c": "Confirmed" # ✅ Must match picklist values }) # Upload image as ContentVersion with open(image_path, "rb") as f: encoded_image = base64.b64encode(f.read()).decode("utf-8") content = sf.ContentVersion.create({ "Title": f"Snapshot_{timestamp}", "PathOnClient": "snapshot.jpg", "VersionData": encoded_image }) # Get ContentDocumentId content_id = sf.query( f"SELECT ContentDocumentId FROM ContentVersion WHERE Id = '{content['id']}'" )['records'][0]['ContentDocumentId'] # Link file to Weight_Log__c record via ContentDocumentLink sf.ContentDocumentLink.create({ "ContentDocumentId": content_id, "LinkedEntityId": record['id'], "ShareType": "V", "Visibility": "AllUsers" }) return weight, timestamp, image, gr.update(visible=False) except Exception as e: return f"Error: {str(e)}", "", None, gr.update(visible=True) with gr.Blocks(css=".gr-button {background-color: #2e7d32 !important; color: white !important;}") as demo: gr.Markdown("""

📷 Auto Weight Logger

Upload or capture a digital weight image. Detects weight using AI OCR and logs it into Salesforce.


""") with gr.Row(): image_input = gr.Image(type="pil", label="📁 Upload or Capture Image") detect_btn = gr.Button("🚀 Detect Weight") with gr.Row(): weight_out = gr.Textbox(label="📦 Detected Weight", placeholder="e.g., 97.9 kg", show_copy_button=True) time_out = gr.Textbox(label="🕒 Captured At (IST)", placeholder="e.g., 2025-07-01 12:00:00") snapshot = gr.Image(label="📸 Snapshot Preview") retake_btn = gr.Button("🔁 Retake / Try Again", visible=False) detect_btn.click(fn=process_image, inputs=image_input, outputs=[weight_out, time_out, snapshot, retake_btn]) retake_btn.click(fn=lambda: ("", "", None, gr.update(visible=False)), inputs=[], outputs=[weight_out, time_out, snapshot, retake_btn]) demo.launch()