import streamlit as st from PIL import Image, UnidentifiedImageError import io import uuid import urllib.parse from datetime import datetime import pytz from ocr_engine import extract_weight_from_image # Make sure this returns (weight, confidence) # Set up page st.set_page_config(page_title="⚖️ Auto Weight Logger", layout="centered") st.title("⚖️ Auto Weight Logger") # Session state keys if "camera_key" not in st.session_state: st.session_state.camera_key = str(uuid.uuid4()) if "captured_time" not in st.session_state: st.session_state.captured_time = "" # Get IST time def get_current_ist_time(): ist = pytz.timezone("Asia/Kolkata") return datetime.now(ist).strftime("%Y-%m-%d %I:%M:%S %p") # Input selection input_mode = st.radio("📸 Select Input Method", ["Camera", "Upload"], horizontal=True) # Retake button if st.button("🔁 Clear / Retake"): st.session_state.camera_key = str(uuid.uuid4()) st.session_state.captured_time = "" st.rerun() # Image handling image_bytes = None image = None # Webcam input if input_mode == "Camera": cam_photo = st.camera_input("📷 Capture Weight Display", key=st.session_state.camera_key) if cam_photo: image_bytes = cam_photo.getvalue() st.session_state.captured_time = get_current_ist_time() # File upload elif input_mode == "Upload": uploaded_file = st.file_uploader("📁 Upload an image (JPG/PNG)", type=["jpg", "jpeg", "png"]) if uploaded_file: image_bytes = uploaded_file.read() st.session_state.captured_time = get_current_ist_time() # Process and display if image_bytes: try: image = Image.open(io.BytesIO(image_bytes)) # 1. Show Captured At st.markdown(f"### 🕒 Captured At (IST): `{st.session_state.captured_time}`") # 2. Show Snapshot Image st.markdown("### 🖼️ Snapshot Image") st.image(image, use_column_width=True) # 3. Extract OCR and show result if len(image_bytes) > 5 * 1024 * 1024: st.error("❌ Image too large (>5MB). Please upload a smaller image.") st.stop() with st.spinner("🔍 Extracting weight using OCR..."): weight, confidence = extract_weight_from_image(image) st.markdown("### ⚖️ Captured Weight & OCR Confidence") if not weight or confidence < 80: st.error(f"⚠️ Low OCR Confidence ({int(confidence)}%). Please retake or upload a clearer image.") st.markdown("**Detected Weight:** Not reliable") else: st.success(f"✅ Detected Weight: `{weight} g`") st.markdown(f"**Confidence:** `{int(confidence)}%`") # 4. Send to Salesforce device_id = "BAL-001" image_url = "" # optional salesforce_url = ( "https://autoweightlogger-dev-ed.my.salesforce-sites.com/" f"weight_logger_page?WeightInput={urllib.parse.quote(str(weight))}" f"&DeviceID={urllib.parse.quote(device_id)}&ImageURL={urllib.parse.quote(image_url)}" ) st.markdown("### ✅ Send to Salesforce") st.markdown(f"[📤 Click to Log Weight in Salesforce]({salesforce_url})", unsafe_allow_html=True) except UnidentifiedImageError: st.error("❌ Unable to process image. Please upload a valid JPG or PNG.") except Exception as e: st.error("❌ Unexpected error.") st.exception(e)