demo_app.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. import streamlit as st
  2. import requests
  3. from PIL import Image
  4. import io
  5. import base64
  6. # --- 1. Global Backend Check ---
  7. API_BASE_URL = "http://localhost:8000"
  8. def check_backend():
  9. try:
  10. res = requests.get(f"{API_BASE_URL}/get_confidence", timeout=2)
  11. return res.status_code == 200
  12. except:
  13. return False
  14. backend_active = check_backend()
  15. if not backend_active:
  16. st.error("⚠️ Backend API is offline!")
  17. st.info("Please start the backend server first (e.g., `python main.py`) to unlock AI features.")
  18. if st.button("🔄 Retry Connection"):
  19. st.rerun()
  20. st.stop() # Stops execution here, effectively disabling the app
  21. # --- 2. Main Page Config (Only rendered if backend is active) ---
  22. st.set_page_config(page_title="Palm Oil Ripeness AI", layout="wide")
  23. st.title("🌴 Palm Oil FFB Management System")
  24. st.markdown("### Production-Ready AI Analysis & Archival")
  25. # --- Sidebar ---
  26. st.sidebar.header("Backend Controls")
  27. def update_confidence():
  28. new_conf = st.session_state.conf_slider
  29. try:
  30. requests.post(f"{API_BASE_URL}/set_confidence", json={"threshold": new_conf})
  31. st.toast(f"Threshold updated to {new_conf}")
  32. except:
  33. st.sidebar.error("Failed to update threshold")
  34. # We already know backend is up here
  35. response = requests.get(f"{API_BASE_URL}/get_confidence")
  36. current_conf = response.json().get("current_confidence", 0.25)
  37. st.sidebar.success(f"Connected to API")
  38. # Synchronized Slider
  39. st.sidebar.slider(
  40. "Confidence Threshold",
  41. 0.1, 1.0,
  42. value=float(current_conf),
  43. key="conf_slider",
  44. on_change=update_confidence
  45. )
  46. # --- Tabs ---
  47. tab1, tab2, tab3 = st.tabs(["Single Analysis", "Batch Processing", "Similarity Search"])
  48. # --- Tab 1: Single Analysis ---
  49. with tab1:
  50. st.subheader("Analyze Single Bunch")
  51. uploaded_file = st.file_uploader("Upload a bunch image...", type=["jpg", "jpeg", "png"], key="single")
  52. if uploaded_file:
  53. col1, col2 = st.columns(2)
  54. with col1:
  55. st.image(uploaded_file, caption="Input", width=500)
  56. with col2:
  57. if st.button("Run Full Analysis"):
  58. with st.spinner("Processing... (Detecting + Vectorizing + Archiving)"):
  59. files = {"file": (uploaded_file.name, uploaded_file.getvalue(), uploaded_file.type)}
  60. res = requests.post(f"{API_BASE_URL}/analyze", files=files)
  61. if res.status_code == 200:
  62. data = res.json()
  63. st.success(f"✅ Record Archived! ID: {data['record_id']}")
  64. for det in data['detections']:
  65. st.info(f"**{det['class']}** - {det['confidence']:.2%} confidence")
  66. else:
  67. st.error(f"Analysis Failed: {res.text}")
  68. # --- Tab 2: Batch Processing ---
  69. with tab2:
  70. st.subheader("Bulk Analysis")
  71. # 1. Initialize Session State
  72. if "batch_uploader_key" not in st.session_state:
  73. st.session_state.batch_uploader_key = 0
  74. if "last_batch_results" not in st.session_state:
  75. st.session_state.last_batch_results = None
  76. # 2. Display Persisted Results (if any)
  77. if st.session_state.last_batch_results:
  78. res_data = st.session_state.last_batch_results
  79. with st.container(border=True):
  80. st.success(f"✅ Successfully processed {res_data['processed_count']} images.")
  81. st.write("Generated Record IDs:")
  82. st.code(res_data['record_ids'])
  83. if st.button("Clear Results & Start New Batch"):
  84. st.session_state.last_batch_results = None
  85. st.rerun()
  86. st.divider()
  87. # 3. Uploader UI
  88. col_batch1, col_batch2 = st.columns([4, 1])
  89. with col_batch1:
  90. uploaded_files = st.file_uploader(
  91. "Upload multiple images...",
  92. type=["jpg", "jpeg", "png"],
  93. accept_multiple_files=True,
  94. key=f"batch_{st.session_state.batch_uploader_key}"
  95. )
  96. with col_batch2:
  97. st.write("##") # Alignment
  98. if st.button("🗑️ Reset Uploader"):
  99. st.session_state.batch_uploader_key += 1
  100. st.rerun()
  101. if uploaded_files:
  102. if st.button(f"🚀 Process {len(uploaded_files)} Images"):
  103. with st.spinner("Batch Processing in progress..."):
  104. files = [("files", (f.name, f.getvalue(), f.type)) for f in uploaded_files]
  105. res = requests.post(f"{API_BASE_URL}/analyze_batch", files=files)
  106. if res.status_code == 200:
  107. # 4. Success: Store results and Clear Uploader automatically
  108. st.session_state.last_batch_results = res.json()
  109. st.session_state.batch_uploader_key += 1
  110. st.rerun()
  111. else:
  112. st.error(f"Batch Failed: {res.text}")
  113. # --- Tab 3: Similarity Search ---
  114. with tab3:
  115. st.subheader("Hybrid Semantic Search")
  116. st.markdown("Search records by either **Image Similarity** or **Natural Language Query**.")
  117. with st.form("hybrid_search_form"):
  118. col_input1, col_input2 = st.columns(2)
  119. with col_input1:
  120. search_file = st.file_uploader("Option A: Search Image...", type=["jpg", "jpeg", "png"], key="search")
  121. with col_input2:
  122. text_query = st.text_input("Option B: Natural Language Query", placeholder="e.g., 'ripe bunches with dark spots' or 'unripe fruit'")
  123. top_k = st.slider("Results Limit (Top K)", 1, 20, 3)
  124. submit_search = st.form_submit_button("Run Semantic Search")
  125. if submit_search:
  126. if not search_file and not text_query:
  127. st.warning("Please provide either an image or a text query.")
  128. else:
  129. with st.spinner("Searching Vector Index..."):
  130. payload = {"limit": top_k}
  131. # If an image is uploaded, it takes precedence for visual search
  132. if search_file:
  133. files = {"file": (search_file.name, search_file.getvalue(), search_file.type)}
  134. # Pass top_k as part of the data
  135. res = requests.post(f"{API_BASE_URL}/search_hybrid", files=files, data=payload)
  136. # Otherwise, use text query
  137. elif text_query:
  138. payload["text_query"] = text_query
  139. # Send as form-data (data=) to match FastAPI's Form(None)
  140. res = requests.post(f"{API_BASE_URL}/search_hybrid", data=payload)
  141. if res.status_code == 200:
  142. results = res.json().get("results", [])
  143. if not results:
  144. st.warning("No similar records found.")
  145. else:
  146. st.success(f"Found {len(results)} matches.")
  147. for item in results:
  148. with st.container(border=True):
  149. c1, c2 = st.columns([1, 2])
  150. # Fetch the image for this result
  151. rec_id = item["_id"]
  152. img_res = requests.get(f"{API_BASE_URL}/get_image/{rec_id}")
  153. with c1:
  154. if img_res.status_code == 200:
  155. img_b64 = img_res.json().get("image_data")
  156. if img_b64:
  157. st.image(base64.b64decode(img_b64), width=250)
  158. else:
  159. st.write("No image data found.")
  160. else:
  161. st.write("Failed to load image.")
  162. with c2:
  163. st.write(f"**Class:** {item['ripeness_class']}")
  164. st.write(f"**Similarity Score:** {item['score']:.4f}")
  165. st.write(f"**Timestamp:** {item['timestamp']}")
  166. st.write(f"**ID:** `{rec_id}`")
  167. else:
  168. st.error(f"Search failed: {res.text}")