Sanjayraju30 commited on
Commit
8578b51
Β·
verified Β·
1 Parent(s): e667809

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +31 -29
src/streamlit_app.py CHANGED
@@ -3,79 +3,81 @@ from PIL import Image, UnidentifiedImageError
3
  import io
4
  import uuid
5
  import urllib.parse
6
- import pytz
7
  from datetime import datetime
8
- from ocr_engine import extract_weight_from_image # This must return (weight, confidence)
 
9
 
10
- # Page setup
11
  st.set_page_config(page_title="βš–οΈ Auto Weight Logger", layout="centered")
12
  st.title("βš–οΈ Auto Weight Logger")
13
 
14
- # Store keys/state
15
  if "camera_key" not in st.session_state:
16
  st.session_state.camera_key = str(uuid.uuid4())
17
  if "captured_time" not in st.session_state:
18
  st.session_state.captured_time = ""
19
 
20
- # Select input type
 
 
 
 
 
21
  input_mode = st.radio("πŸ“Έ Select Input Method", ["Camera", "Upload"], horizontal=True)
22
 
23
- # Clear/reset
24
  if st.button("πŸ” Clear / Retake"):
25
  st.session_state.camera_key = str(uuid.uuid4())
26
  st.session_state.captured_time = ""
27
  st.rerun()
28
 
29
- # Init
30
  image_bytes = None
31
  image = None
32
 
33
- # Capture time (IST)
34
- def get_current_ist_time():
35
- ist = pytz.timezone("Asia/Kolkata")
36
- return datetime.now(ist).strftime("%Y-%m-%d %I:%M:%S %p")
37
-
38
- # Handle camera
39
  if input_mode == "Camera":
40
- cam_photo = st.camera_input("πŸ“· Take a photo", key=st.session_state.camera_key)
41
  if cam_photo:
42
  image_bytes = cam_photo.getvalue()
43
  st.session_state.captured_time = get_current_ist_time()
44
 
45
- # Handle upload
46
  elif input_mode == "Upload":
47
  uploaded_file = st.file_uploader("πŸ“ Upload an image (JPG/PNG)", type=["jpg", "jpeg", "png"])
48
  if uploaded_file:
49
  image_bytes = uploaded_file.read()
50
  st.session_state.captured_time = get_current_ist_time()
51
 
52
- # Process if image exists
53
  if image_bytes:
54
  try:
55
  image = Image.open(io.BytesIO(image_bytes))
56
 
57
- st.subheader("πŸ–ΌοΈ Snapshot Image")
 
 
 
 
58
  st.image(image, use_column_width=True)
59
 
 
60
  if len(image_bytes) > 5 * 1024 * 1024:
61
- st.error("❌ Image is too large (>5MB).")
62
  st.stop()
63
 
64
- with st.spinner("πŸ” Running OCR..."):
65
  weight, confidence = extract_weight_from_image(image)
66
 
67
- # Show captured time
68
- st.markdown(f"### πŸ•’ Captured At (IST): `{st.session_state.captured_time}`")
69
-
70
- # Show weight
71
  if not weight or confidence < 80:
72
- st.markdown(f"### πŸ“¦ Captured Weight: `Not Detected`")
73
- st.warning(f"⚠️ OCR Confidence too low ({int(confidence)}%)")
74
  else:
75
- st.markdown(f"### πŸ“¦ Captured Weight: `{weight} g`")
76
- st.success(f"βœ… OCR Confidence: {int(confidence)}%")
77
 
78
- # Generate Salesforce URL
79
  device_id = "BAL-001"
80
  image_url = "" # optional
81
 
@@ -89,7 +91,7 @@ if image_bytes:
89
  st.markdown(f"[πŸ“€ Click to Log Weight in Salesforce]({salesforce_url})", unsafe_allow_html=True)
90
 
91
  except UnidentifiedImageError:
92
- st.error("❌ Invalid image file.")
93
  except Exception as e:
94
  st.error("❌ Unexpected error.")
95
  st.exception(e)
 
3
  import io
4
  import uuid
5
  import urllib.parse
 
6
  from datetime import datetime
7
+ import pytz
8
+ from ocr_engine import extract_weight_from_image # Make sure this returns (weight, confidence)
9
 
10
+ # Set up page
11
  st.set_page_config(page_title="βš–οΈ Auto Weight Logger", layout="centered")
12
  st.title("βš–οΈ Auto Weight Logger")
13
 
14
+ # Session state keys
15
  if "camera_key" not in st.session_state:
16
  st.session_state.camera_key = str(uuid.uuid4())
17
  if "captured_time" not in st.session_state:
18
  st.session_state.captured_time = ""
19
 
20
+ # Get IST time
21
+ def get_current_ist_time():
22
+ ist = pytz.timezone("Asia/Kolkata")
23
+ return datetime.now(ist).strftime("%Y-%m-%d %I:%M:%S %p")
24
+
25
+ # Input selection
26
  input_mode = st.radio("πŸ“Έ Select Input Method", ["Camera", "Upload"], horizontal=True)
27
 
28
+ # Retake button
29
  if st.button("πŸ” Clear / Retake"):
30
  st.session_state.camera_key = str(uuid.uuid4())
31
  st.session_state.captured_time = ""
32
  st.rerun()
33
 
34
+ # Image handling
35
  image_bytes = None
36
  image = None
37
 
38
+ # Webcam input
 
 
 
 
 
39
  if input_mode == "Camera":
40
+ cam_photo = st.camera_input("πŸ“· Capture Weight Display", key=st.session_state.camera_key)
41
  if cam_photo:
42
  image_bytes = cam_photo.getvalue()
43
  st.session_state.captured_time = get_current_ist_time()
44
 
45
+ # File upload
46
  elif input_mode == "Upload":
47
  uploaded_file = st.file_uploader("πŸ“ Upload an image (JPG/PNG)", type=["jpg", "jpeg", "png"])
48
  if uploaded_file:
49
  image_bytes = uploaded_file.read()
50
  st.session_state.captured_time = get_current_ist_time()
51
 
52
+ # Process and display
53
  if image_bytes:
54
  try:
55
  image = Image.open(io.BytesIO(image_bytes))
56
 
57
+ # 1. Show Captured At
58
+ st.markdown(f"### πŸ•’ Captured At (IST): `{st.session_state.captured_time}`")
59
+
60
+ # 2. Show Snapshot Image
61
+ st.markdown("### πŸ–ΌοΈ Snapshot Image")
62
  st.image(image, use_column_width=True)
63
 
64
+ # 3. Extract OCR and show result
65
  if len(image_bytes) > 5 * 1024 * 1024:
66
+ st.error("❌ Image too large (>5MB). Please upload a smaller image.")
67
  st.stop()
68
 
69
+ with st.spinner("πŸ” Extracting weight using OCR..."):
70
  weight, confidence = extract_weight_from_image(image)
71
 
72
+ st.markdown("### βš–οΈ Captured Weight & OCR Confidence")
 
 
 
73
  if not weight or confidence < 80:
74
+ st.error(f"⚠️ Low OCR Confidence ({int(confidence)}%). Please retake or upload a clearer image.")
75
+ st.markdown("**Detected Weight:** Not reliable")
76
  else:
77
+ st.success(f"βœ… Detected Weight: `{weight} g`")
78
+ st.markdown(f"**Confidence:** `{int(confidence)}%`")
79
 
80
+ # 4. Send to Salesforce
81
  device_id = "BAL-001"
82
  image_url = "" # optional
83
 
 
91
  st.markdown(f"[πŸ“€ Click to Log Weight in Salesforce]({salesforce_url})", unsafe_allow_html=True)
92
 
93
  except UnidentifiedImageError:
94
+ st.error("❌ Unable to process image. Please upload a valid JPG or PNG.")
95
  except Exception as e:
96
  st.error("❌ Unexpected error.")
97
  st.exception(e)