import streamlit as st from PIL import Image, UnidentifiedImageError import io import uuid import urllib.parse import pytz from datetime import datetime from ocr_engine import extract_weight_from_image # Make sure this returns (weight, confidence) # Setup st.set_page_config(page_title="⚖️ Auto Weight Logger", layout="centered") st.title("⚖️ Auto Weight Logger") # Session states if "camera_key" not in st.session_state: st.session_state.camera_key = str(uuid.uuid4()) # Input method input_mode = st.radio("📸 Select Input Method", ["Camera", "Upload"], horizontal=True) # Clear button if st.button("🔁 Clear / Retake"): st.session_state.camera_key = str(uuid.uuid4()) st.rerun() # Image bytes and capture image_bytes = None image = None 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() elif input_mode == "Upload": uploaded_file = st.file_uploader("📁 Upload Image (JPG/PNG)", type=["jpg", "jpeg", "png"]) if uploaded_file: image_bytes = uploaded_file.read() # Process image if image_bytes: try: image = Image.open(io.BytesIO(image_bytes)) # Timestamp ist = pytz.timezone("Asia/Kolkata") captured_time = datetime.now(ist).strftime("%Y-%m-%d %I:%M:%S %p") st.subheader("🖼️ Snapshot Image") st.image(image, use_column_width=True) if len(image_bytes) > 5 * 1024 * 1024: st.error("❌ Image too large (>5MB). Please use a smaller image.") st.stop() with st.spinner("🔍 Extracting weight..."): weight, confidence = extract_weight_from_image(image) # Output regardless of confidence st.markdown(f"### 📦 Captured Weight: `{weight if weight else 'Not Detected'}`") st.markdown(f"### 🕒 Captured At (IST): `{captured_time}`") if not weight or confidence < 80: st.warning(f"⚠️ Low OCR Confidence ({int(confidence)}%). You may retry.") else: st.success(f"✅ High Confidence: {int(confidence)}%") # Salesforce redirect link 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("❌ Invalid image format.") except Exception as e: st.error("❌ Something went wrong while processing the image.") st.exception(e)