demo_app.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. import streamlit as st
  2. import requests
  3. from ultralytics import YOLO
  4. import numpy as np
  5. from PIL import Image
  6. import io
  7. import base64
  8. import pandas as pd
  9. import plotly.express as px
  10. import plotly.graph_objects as go
  11. import json
  12. import os
  13. from datetime import datetime
  14. from fpdf import FPDF
  15. # --- 1. Global Backend Check ---
  16. API_BASE_URL = "http://localhost:8000"
  17. def check_backend():
  18. try:
  19. res = requests.get(f"{API_BASE_URL}/get_confidence", timeout=2)
  20. return res.status_code == 200
  21. except:
  22. return False
  23. backend_active = check_backend()
  24. # LOCAL MODEL LOADING REMOVED (YOLO26 Clean Sweep)
  25. # UI now relies entirely on Backend API for NMS-Free inference.
  26. if not backend_active:
  27. st.error("⚠️ Backend API is offline!")
  28. st.info("Please start the backend server first (e.g., `python main.py`) to unlock AI features.")
  29. if st.button("🔄 Retry Connection"):
  30. st.rerun()
  31. st.stop() # Stops execution here, effectively disabling the app
  32. # --- 2. Main Page Config (Only rendered if backend is active) ---
  33. st.set_page_config(page_title="Palm Oil Ripeness AI (YOLO26)", layout="wide")
  34. st.title("🌴 Palm Oil FFB Management System")
  35. st.markdown("### Production-Ready AI Analysis & Archival")
  36. # --- Sidebar ---
  37. st.sidebar.header("Backend Controls")
  38. def update_confidence():
  39. new_conf = st.session_state.conf_slider
  40. try:
  41. requests.post(f"{API_BASE_URL}/set_confidence", json={"threshold": new_conf})
  42. st.toast(f"Threshold updated to {new_conf}")
  43. except:
  44. st.sidebar.error("Failed to update threshold")
  45. # We already know backend is up here
  46. response = requests.get(f"{API_BASE_URL}/get_confidence")
  47. current_conf = response.json().get("current_confidence", 0.25)
  48. st.sidebar.success(f"Connected to API")
  49. st.sidebar.info("Engine: YOLO26 NMS-Free (Inference: ~39ms)")
  50. # Synchronized Slider
  51. st.sidebar.slider(
  52. "Confidence Threshold",
  53. 0.1, 1.0,
  54. value=float(current_conf),
  55. key="conf_slider",
  56. on_change=update_confidence
  57. )
  58. st.sidebar.markdown("---")
  59. st.sidebar.subheader("Inference Engine")
  60. engine_choice = st.sidebar.selectbox(
  61. "Select Model Engine",
  62. ["YOLO26 (ONNX - High Speed)", "YOLO26 (PyTorch - Native)"],
  63. index=0,
  64. help="ONNX is optimized for latency. PyTorch provides native object handling."
  65. )
  66. model_type = "onnx" if "ONNX" in engine_choice else "pytorch"
  67. if model_type == "pytorch":
  68. st.sidebar.warning("PyTorch Engine: Higher Memory Usage")
  69. else:
  70. st.sidebar.info("ONNX Engine: ~39ms Latency")
  71. # Helper to reset results when files change
  72. def reset_single_results():
  73. st.session_state.last_detection = None
  74. def reset_batch_results():
  75. st.session_state.last_batch_results = None
  76. # MPOB Color Map for Overlays (Global for consistency)
  77. overlay_colors = {
  78. 'Ripe': '#22c55e', # Industrial Green
  79. 'Underripe': '#fbbf24', # Industrial Orange
  80. 'Unripe': '#3b82f6', # Industrial Blue
  81. 'Abnormal': '#dc2626', # Critical Red
  82. 'Empty_Bunch': '#64748b',# Waste Gray
  83. 'Overripe': '#7c2d12' # Dark Brown/Orange
  84. }
  85. def display_interactive_results(image, detections, key=None):
  86. """Renders image with interactive hover-boxes using Plotly."""
  87. img_width, img_height = image.size
  88. fig = go.Figure()
  89. # Add the palm image as the background
  90. fig.add_layout_image(
  91. dict(source=image, x=0, y=img_height, sizex=img_width, sizey=img_height,
  92. sizing="stretch", opacity=1, layer="below", xref="x", yref="y")
  93. )
  94. # Configure axes to match image dimensions
  95. fig.update_xaxes(showgrid=False, range=(0, img_width), zeroline=False, visible=False)
  96. fig.update_yaxes(showgrid=False, range=(0, img_height), zeroline=False, visible=False, scaleanchor="x")
  97. # Add interactive boxes
  98. for i, det in enumerate(detections):
  99. x1, y1, x2, y2 = det['box']
  100. # Plotly y-axis is inverted relative to PIL, so we flip y
  101. y_top, y_bottom = img_height - y1, img_height - y2
  102. color = overlay_colors.get(det['class'], "#ffeb3b")
  103. # The 'Hover' shape
  104. bunch_id = det.get('bunch_id', i+1)
  105. fig.add_trace(go.Scatter(
  106. x=[x1, x2, x2, x1, x1],
  107. y=[y_top, y_top, y_bottom, y_bottom, y_top],
  108. fill="toself",
  109. fillcolor=color,
  110. opacity=0.3, # Semi-transparent until hover
  111. mode='lines',
  112. line=dict(color=color, width=3),
  113. name=f"Bunch #{bunch_id}",
  114. text=f"<b>ID: #{bunch_id}</b><br>Grade: {det['class']}<br>Score: {det['confidence']:.2f}<br>Alert: {det['is_health_alert']}",
  115. hoverinfo="text"
  116. ))
  117. fig.update_layout(width=800, height=600, margin=dict(l=0, r=0, b=0, t=0), showlegend=False)
  118. st.plotly_chart(fig, use_container_width=True, key=key)
  119. def annotate_image(image, detections):
  120. """Draws high-visibility boxes and background-shaded labels."""
  121. from PIL import ImageDraw, ImageFont
  122. draw = ImageDraw.Draw(image)
  123. # Dynamic font size based on image resolution
  124. font_size = max(20, image.width // 40)
  125. try:
  126. font_path = "C:\\Windows\\Fonts\\arial.ttf"
  127. if os.path.exists(font_path):
  128. font = ImageFont.truetype(font_path, font_size)
  129. else:
  130. font = ImageFont.load_default()
  131. except:
  132. font = ImageFont.load_default()
  133. for det in detections:
  134. box = det['box'] # [x1, y1, x2, y2]
  135. cls = det['class']
  136. conf = det['confidence']
  137. bunch_id = det.get('bunch_id', '?')
  138. color = overlay_colors.get(cls, '#ffffff')
  139. # 1. Draw Bold Bounding Box
  140. draw.rectangle(box, outline=color, width=max(4, image.width // 200))
  141. # 2. Draw Label Background (High Contrast)
  142. label = f"#{bunch_id} {cls} {conf:.2f}"
  143. try:
  144. # textbbox provides precise coordinates for background rectangle
  145. l, t, r, b = draw.textbbox((box[0], box[1] - font_size - 10), label, font=font)
  146. draw.rectangle([l-5, t-5, r+5, b+5], fill=color)
  147. draw.text((l, t), label, fill="white", font=font)
  148. except:
  149. # Fallback for basic text drawing
  150. draw.text((box[0], box[1] - 25), label, fill=color)
  151. return image
  152. def generate_batch_report(data, uploaded_files_map=None):
  153. """Generates a professional PDF report for batch results with visual evidence."""
  154. from PIL import ImageDraw
  155. pdf = FPDF()
  156. pdf.add_page()
  157. pdf.set_font("Arial", "B", 16)
  158. pdf.cell(190, 10, "Palm Oil FFB Harvest Quality Report", ln=True, align="C")
  159. pdf.set_font("Arial", "", 12)
  160. pdf.cell(190, 10, f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align="C")
  161. pdf.ln(10)
  162. # 1. Summary Table
  163. pdf.set_font("Arial", "B", 14)
  164. pdf.cell(190, 10, "1. Batch Summary", ln=True)
  165. pdf.set_font("Arial", "", 12)
  166. summary = data.get('industrial_summary', {})
  167. total_bunches = data.get('total_count', 0)
  168. pdf.cell(95, 10, "Metric", border=1)
  169. pdf.cell(95, 10, "Value", border=1, ln=True)
  170. pdf.cell(95, 10, "Total Bunches Detected", border=1)
  171. pdf.cell(95, 10, str(total_bunches), border=1, ln=True)
  172. for grade, count in summary.items():
  173. if count > 0:
  174. pdf.cell(95, 10, f"Grade: {grade}", border=1)
  175. pdf.cell(95, 10, str(count), border=1, ln=True)
  176. pdf.ln(10)
  177. # 2. Strategic Insights
  178. pdf.set_font("Arial", "B", 14)
  179. pdf.cell(190, 10, "2. Strategic Yield Insights", ln=True)
  180. pdf.set_font("Arial", "", 12)
  181. unripe = summary.get('Unripe', 0)
  182. underripe = summary.get('Underripe', 0)
  183. loss = unripe + underripe
  184. if loss > 0:
  185. pdf.multi_cell(190, 10, f"WARNING: {loss} bunches were harvested before peak ripeness. "
  186. "This directly impacts the Oil Extraction Rate (OER) and results in potential yield loss.")
  187. else:
  188. pdf.multi_cell(190, 10, "EXCELLENT: All detected bunches meet prime ripeness standards. Harvest efficiency is 100%.")
  189. # Critical Alerts
  190. abnormal = summary.get('Abnormal', 0)
  191. empty = summary.get('Empty_Bunch', 0)
  192. if abnormal > 0 or empty > 0:
  193. pdf.ln(5)
  194. pdf.set_text_color(220, 0, 0)
  195. pdf.set_font("Arial", "B", 12)
  196. pdf.cell(190, 10, "CRITICAL HEALTH ALERTS:", ln=True)
  197. pdf.set_font("Arial", "", 12)
  198. if abnormal > 0:
  199. pdf.cell(190, 10, f"- {abnormal} Abnormal Bunches detected (Requires immediate field inspection).", ln=True)
  200. if empty > 0:
  201. pdf.cell(190, 10, f"- {empty} Empty Bunches detected (Waste reduction needed).", ln=True)
  202. pdf.set_text_color(0, 0, 0)
  203. # 3. Visual Evidence Section
  204. if 'detailed_results' in data and uploaded_files_map:
  205. pdf.add_page()
  206. pdf.set_font("Arial", "B", 14)
  207. pdf.cell(190, 10, "3. Visual Batch Evidence (AI Overlay)", ln=True)
  208. pdf.ln(5)
  209. # Group detections by filename
  210. results_by_file = {}
  211. for res in data['detailed_results']:
  212. fname = res['filename']
  213. if fname not in results_by_file:
  214. results_by_file[fname] = []
  215. results_by_file[fname].append(res['detection'])
  216. for fname, detections in results_by_file.items():
  217. if fname in uploaded_files_map:
  218. img_bytes = uploaded_files_map[fname]
  219. img = Image.open(io.BytesIO(img_bytes)).convert("RGB")
  220. draw = ImageDraw.Draw(img)
  221. # Drawing annotated boxes for PDF using high-visibility utility
  222. annotate_image(img, detections)
  223. # Save to temp file for PDF
  224. temp_img_path = f"temp_report_{fname}"
  225. img.save(temp_img_path)
  226. # Check if we need a new page based on image height (rough estimate)
  227. if pdf.get_y() > 200:
  228. pdf.add_page()
  229. pdf.image(temp_img_path, x=10, w=150)
  230. pdf.set_font("Arial", "I", 10)
  231. pdf.cell(190, 10, f"Annotated: {fname}", ln=True)
  232. pdf.ln(5)
  233. os.remove(temp_img_path)
  234. # Footer
  235. pdf.set_y(-15)
  236. pdf.set_font("Arial", "I", 8)
  237. pdf.cell(190, 10, "Generated by Palm Oil AI Desktop PoC - YOLO26 Engine", align="C")
  238. return pdf.output(dest='S')
  239. # --- Tabs ---
  240. tab1, tab2, tab3, tab4 = st.tabs(["Single Analysis", "Batch Processing", "Similarity Search", "History Vault"])
  241. # --- Tab 1: Single Analysis ---
  242. with tab1:
  243. st.subheader("Analyze Single Bunch")
  244. uploaded_file = st.file_uploader(
  245. "Upload a bunch image...",
  246. type=["jpg", "jpeg", "png"],
  247. key="single",
  248. on_change=reset_single_results
  249. )
  250. if uploaded_file:
  251. # State initialization
  252. if "last_detection" not in st.session_state:
  253. st.session_state.last_detection = None
  254. # 1. Auto-Detection Trigger
  255. if uploaded_file and st.session_state.last_detection is None:
  256. with st.spinner(f"Processing with {model_type.upper()} Engine..."):
  257. files = {"file": (uploaded_file.name, uploaded_file.getvalue(), uploaded_file.type)}
  258. payload = {"model_type": model_type}
  259. res = requests.post(f"{API_BASE_URL}/analyze", files=files, data=payload)
  260. if res.status_code == 200:
  261. st.session_state.last_detection = res.json()
  262. st.rerun() # Refresh to show results immediately
  263. else:
  264. st.error(f"Detection Failed: {res.text}")
  265. # 2. Results Layout
  266. if st.session_state.last_detection:
  267. st.divider()
  268. # PRIMARY ANNOTATED VIEW
  269. st.write("### 🔍 AI Analytical View")
  270. data = st.session_state.last_detection
  271. img = Image.open(uploaded_file).convert("RGB")
  272. display_interactive_results(img, data['detections'], key="main_viewer")
  273. # Visual Legend
  274. st.write("#### 🎨 Ripeness Legend")
  275. l_cols = st.columns(len(overlay_colors))
  276. for i, (grade, color) in enumerate(overlay_colors.items()):
  277. with l_cols[i]:
  278. st.markdown(f'<div style="background-color:{color}; padding:10px; border-radius:5px; text-align:center; color:white; font-weight:bold;">{grade}</div>', unsafe_allow_html=True)
  279. st.divider()
  280. st.write("### 📈 Manager's Dashboard")
  281. m_col1, m_col2, m_col3, m_col4 = st.columns(4)
  282. with m_col1:
  283. st.metric("Total Bunches", data.get('total_count', 0))
  284. with m_col2:
  285. st.metric("Healthy (Ripe)", data['industrial_summary'].get('Ripe', 0))
  286. with m_col3:
  287. abnormal = data['industrial_summary'].get('Abnormal', 0)
  288. st.metric("Abnormal Alerts", abnormal, delta=-abnormal, delta_color="inverse")
  289. with m_col4:
  290. st.metric("Inference Speed", f"{data.get('inference_ms', 0):.1f} ms")
  291. col1, col2 = st.columns([1.5, 1]) # Keep original col structure for summary below
  292. with col1:
  293. with st.expander("🛠️ Technical Evidence: Raw Output Tensor", expanded=False):
  294. st.write("First 5 detections from raw output tensor:")
  295. st.json(data.get('raw_array_sample', []))
  296. with st.container(border=True):
  297. st.write("### 🏷️ Detection Results")
  298. if not data['detections']:
  299. st.warning("No Fresh Fruit Bunches detected.")
  300. else:
  301. for det in data['detections']:
  302. st.info(f"### Bunch #{det['bunch_id']}: {det['class']} ({det['confidence']:.2%})")
  303. st.write("### 📊 Harvest Quality Mix")
  304. # Convert industrial_summary dictionary to a DataFrame for charting
  305. summary_df = pd.DataFrame(
  306. list(data['industrial_summary'].items()),
  307. columns=['Grade', 'Count']
  308. )
  309. # Filter out classes with 0 count for a cleaner chart
  310. summary_df = summary_df[summary_df['Count'] > 0]
  311. if not summary_df.empty:
  312. # Create a Pie Chart to show the proportion of each grade
  313. fig = px.pie(summary_df, values='Count', names='Grade',
  314. color='Grade',
  315. color_discrete_map={
  316. 'Ripe': '#22c55e', # Industrial Green
  317. 'Underripe': '#fbbf24', # Industrial Orange
  318. 'Unripe': '#3b82f6', # Industrial Blue
  319. 'Abnormal': '#dc2626', # Critical Red
  320. 'Empty_Bunch': '#64748b' # Waste Gray
  321. },
  322. hole=0.4)
  323. fig.update_layout(margin=dict(t=0, b=0, l=0, r=0), height=300)
  324. st.plotly_chart(fig, width='stretch', key="single_pie")
  325. # 💡 Strategic R&D Insight: Harvest Efficiency
  326. st.write("---")
  327. st.write("#### 💡 Strategic R&D Insight")
  328. unripe_count = data['industrial_summary'].get('Unripe', 0)
  329. underripe_count = data['industrial_summary'].get('Underripe', 0)
  330. total_non_prime = unripe_count + underripe_count
  331. st.write(f"🌑 **Unripe (Mentah):** {unripe_count}")
  332. st.write(f"🌗 **Underripe (Kurang Masak):** {underripe_count}")
  333. if total_non_prime > 0:
  334. st.warning(f"🚨 **Potential Yield Loss:** {total_non_prime} bunches harvested too early. This will reduce OER (Oil Extraction Rate).")
  335. else:
  336. st.success("✅ **Harvest Efficiency:** 100% Prime Ripeness detected.")
  337. # High-Priority Health Alert
  338. if data['industrial_summary'].get('Abnormal', 0) > 0:
  339. st.error(f"🚨 CRITICAL: {data['industrial_summary']['Abnormal']} Abnormal Bunches Detected!")
  340. if data['industrial_summary'].get('Empty_Bunch', 0) > 0:
  341. st.warning(f"⚠️ ALERT: {data['industrial_summary']['Empty_Bunch']} Empty Bunches Detected.")
  342. # 3. Cloud Actions (Only if detections found)
  343. st.write("---")
  344. st.write("#### ✨ Cloud Archive")
  345. if st.button("🚀 Save to Atlas (Vectorize)", width='stretch'):
  346. with st.spinner("Archiving..."):
  347. import json
  348. primary_det = data['detections'][0]
  349. payload = {"detection_data": json.dumps(primary_det)}
  350. files_cloud = {"file": (uploaded_file.name, uploaded_file.getvalue(), uploaded_file.type)}
  351. res_cloud = requests.post(f"{API_BASE_URL}/vectorize_and_store", files=files_cloud, data=payload)
  352. if res_cloud.status_code == 200:
  353. res_json = res_cloud.json()
  354. if res_json["status"] == "success":
  355. st.success(f"Archived! ID: `{res_json['record_id'][:8]}...`")
  356. else:
  357. st.error(f"Cloud Error: {res_json['message']}")
  358. else:
  359. st.error("Failed to connect to cloud service")
  360. if st.button("🚩 Flag Misclassification", width='stretch', type="secondary"):
  361. # Save to local feedback folder
  362. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  363. feedback_id = f"fb_{timestamp}"
  364. img_path = f"feedback/{feedback_id}.jpg"
  365. json_path = f"feedback/{feedback_id}.json"
  366. # Save image
  367. Image.open(uploaded_file).save(img_path)
  368. # Save metadata
  369. feedback_data = {
  370. "original_filename": uploaded_file.name,
  371. "timestamp": timestamp,
  372. "detections": data['detections'],
  373. "threshold_used": data['current_threshold']
  374. }
  375. with open(json_path, "w") as f:
  376. json.dump(feedback_data, f, indent=4)
  377. st.toast("✅ Feedback saved to local vault!", icon="🚩")
  378. if st.button("💾 Local History Vault (Auto-Saved)", width='stretch', type="secondary", disabled=True):
  379. pass
  380. st.caption("✅ This analysis was automatically archived to the local vault.")
  381. # --- Tab 2: Batch Processing ---
  382. with tab2:
  383. st.subheader("Bulk Analysis")
  384. # 1. Initialize Session State
  385. if "batch_uploader_key" not in st.session_state:
  386. st.session_state.batch_uploader_key = 0
  387. if "last_batch_results" not in st.session_state:
  388. st.session_state.last_batch_results = None
  389. # 2. Display Persisted Results (if any)
  390. if st.session_state.last_batch_results:
  391. res_data = st.session_state.last_batch_results
  392. with st.container(border=True):
  393. st.success(f"✅ Successfully processed {res_data['processed_count']} images.")
  394. # Batch Summary Dashboard
  395. st.write("### 📈 Batch Quality Overview")
  396. batch_summary = res_data.get('industrial_summary', {})
  397. if batch_summary:
  398. sum_df = pd.DataFrame(list(batch_summary.items()), columns=['Grade', 'Count'])
  399. sum_df = sum_df[sum_df['Count'] > 0]
  400. b_col1, b_col2 = st.columns([1, 1])
  401. with b_col1:
  402. st.dataframe(sum_df, hide_index=True, width='stretch')
  403. with b_col2:
  404. if not sum_df.empty:
  405. fig_batch = px.bar(sum_df, x='Grade', y='Count', color='Grade',
  406. color_discrete_map={
  407. 'Ripe': '#22c55e',
  408. 'Underripe': '#fbbf24',
  409. 'Unripe': '#3b82f6',
  410. 'Abnormal': '#dc2626',
  411. 'Empty_Bunch': '#64748b'
  412. })
  413. fig_batch.update_layout(margin=dict(t=0, b=0, l=0, r=0), height=200, showlegend=False)
  414. st.plotly_chart(fig_batch, width='stretch', key="batch_bar")
  415. if batch_summary.get('Abnormal', 0) > 0:
  416. st.error(f"🚨 BATCH CRITICAL: {batch_summary['Abnormal']} Abnormal Bunches found in this batch!")
  417. st.write("Generated Record IDs:")
  418. st.code(res_data['record_ids'])
  419. # --- 4. Batch Evidence Gallery ---
  420. st.write("### 🖼️ Detailed Detection Evidence")
  421. if 'detailed_results' in res_data:
  422. # Group results by filename for gallery
  423. gallery_map = {}
  424. for res in res_data['detailed_results']:
  425. fname = res['filename']
  426. if fname not in gallery_map:
  427. gallery_map[fname] = []
  428. gallery_map[fname].append(res['detection'])
  429. # Show images with overlays using consistent utility
  430. for up_file in uploaded_files:
  431. if up_file.name in gallery_map:
  432. with st.container(border=True):
  433. g_img = Image.open(up_file).convert("RGB")
  434. g_annotated = annotate_image(g_img, gallery_map[up_file.name])
  435. st.image(g_annotated, caption=f"Evidence: {up_file.name}", use_container_width=True)
  436. # PDF Export Button (Pass images map)
  437. files_map = {f.name: f.getvalue() for f in uploaded_files}
  438. pdf_bytes = generate_batch_report(res_data, files_map)
  439. st.download_button(
  440. label="📄 Download Executive Batch Report (PDF)",
  441. data=pdf_bytes,
  442. file_name=f"PalmOil_BatchReport_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf",
  443. mime="application/pdf",
  444. width='stretch'
  445. )
  446. if st.button("Clear Results & Start New Batch", width='stretch'):
  447. st.session_state.last_batch_results = None
  448. st.rerun()
  449. st.divider()
  450. # 3. Uploader UI
  451. col_batch1, col_batch2 = st.columns([4, 1])
  452. with col_batch1:
  453. uploaded_files = st.file_uploader(
  454. "Upload multiple images...",
  455. type=["jpg", "jpeg", "png"],
  456. accept_multiple_files=True,
  457. key=f"batch_{st.session_state.batch_uploader_key}",
  458. on_change=reset_batch_results
  459. )
  460. with col_batch2:
  461. st.write("##") # Alignment
  462. if st.session_state.last_batch_results is None and uploaded_files:
  463. if st.button("🔍 Process Batch", type="primary", width='stretch'):
  464. with st.spinner(f"Analyzing {len(uploaded_files)} images with {model_type.upper()}..."):
  465. files = [("files", (f.name, f.getvalue(), f.type)) for f in uploaded_files]
  466. payload = {"model_type": model_type}
  467. res = requests.post(f"{API_BASE_URL}/process_batch", files=files, data=payload)
  468. if res.status_code == 200:
  469. data = res.json()
  470. if data["status"] == "success":
  471. st.session_state.last_batch_results = data
  472. st.session_state.batch_uploader_key += 1
  473. st.rerun()
  474. elif data["status"] == "partial_success":
  475. st.warning(data["message"])
  476. st.info(f"Successfully detected {data['detections_count']} bunches locally.")
  477. else:
  478. st.error(f"Batch Error: {data['message']}")
  479. else:
  480. st.error(f"Batch Processing Failed: {res.text}")
  481. if st.button("🗑️ Reset Uploader"):
  482. st.session_state.batch_uploader_key += 1
  483. st.session_state.last_batch_results = None
  484. st.rerun()
  485. # --- Tab 3: Similarity Search ---
  486. with tab3:
  487. st.subheader("Hybrid Semantic Search")
  488. st.markdown("Search records by either **Image Similarity** or **Natural Language Query**.")
  489. with st.form("hybrid_search_form"):
  490. col_input1, col_input2 = st.columns(2)
  491. with col_input1:
  492. search_file = st.file_uploader("Option A: Search Image...", type=["jpg", "jpeg", "png"], key="search")
  493. with col_input2:
  494. text_query = st.text_input("Option B: Natural Language Query", placeholder="e.g., 'ripe bunches with dark spots' or 'unripe fruit'")
  495. top_k = st.slider("Results Limit (Top K)", 1, 20, 3)
  496. submit_search = st.form_submit_button("Run Semantic Search")
  497. if submit_search:
  498. if not search_file and not text_query:
  499. st.warning("Please provide either an image or a text query.")
  500. else:
  501. with st.spinner("Searching Vector Index..."):
  502. payload = {"limit": top_k}
  503. # If an image is uploaded, it takes precedence for visual search
  504. if search_file:
  505. files = {"file": (search_file.name, search_file.getvalue(), search_file.type)}
  506. # Pass top_k as part of the data
  507. res = requests.post(f"{API_BASE_URL}/search_hybrid", files=files, data=payload)
  508. # Otherwise, use text query
  509. elif text_query:
  510. payload["text_query"] = text_query
  511. # Send as form-data (data=) to match FastAPI's Form(None)
  512. res = requests.post(f"{API_BASE_URL}/search_hybrid", data=payload)
  513. if res.status_code == 200:
  514. results = res.json().get("results", [])
  515. if not results:
  516. st.warning("No similar records found.")
  517. else:
  518. st.success(f"Found {len(results)} matches.")
  519. for item in results:
  520. with st.container(border=True):
  521. c1, c2 = st.columns([1, 2])
  522. # Fetch the image for this result
  523. rec_id = item["_id"]
  524. img_res = requests.get(f"{API_BASE_URL}/get_image/{rec_id}")
  525. with c1:
  526. if img_res.status_code == 200:
  527. img_b64 = img_res.json().get("image_data")
  528. if img_b64:
  529. st.image(base64.b64decode(img_b64), width=250)
  530. else:
  531. st.write("No image data found.")
  532. else:
  533. st.write("Failed to load image.")
  534. with c2:
  535. st.write(f"**Class:** {item['ripeness_class']}")
  536. st.write(f"**Similarity Score:** {item['score']:.4f}")
  537. st.write(f"**Timestamp:** {item['timestamp']}")
  538. st.write(f"**ID:** `{rec_id}`")
  539. else:
  540. st.error(f"Search failed: {res.text}")
  541. # --- Tab 4: History Vault ---
  542. with tab4:
  543. st.subheader("📜 Local History Vault")
  544. if "selected_history_id" not in st.session_state:
  545. st.session_state.selected_history_id = None
  546. try:
  547. res = requests.get(f"{API_BASE_URL}/get_history")
  548. if res.status_code == 200:
  549. history_data = res.json().get("history", [])
  550. if not history_data:
  551. st.info("No saved records found.")
  552. else:
  553. if st.session_state.selected_history_id is None:
  554. # ListView Mode
  555. st.write("### 📋 Record List")
  556. df_history = pd.DataFrame(history_data)[['id', 'filename', 'timestamp', 'inference_ms']]
  557. st.dataframe(df_history, hide_index=True, use_container_width=True)
  558. id_to_select = st.number_input("Enter Record ID to view details:", min_value=int(df_history['id'].min()), max_value=int(df_history['id'].max()), step=1)
  559. if st.button("Deep Dive Analysis", type="primary"):
  560. st.session_state.selected_history_id = id_to_select
  561. st.rerun()
  562. else:
  563. # Detail View Mode
  564. record = next((item for item in history_data if item["id"] == st.session_state.selected_history_id), None)
  565. if not record:
  566. st.error("Record not found.")
  567. if st.button("Back to List"):
  568. st.session_state.selected_history_id = None
  569. st.rerun()
  570. else:
  571. if st.button("⬅️ Back to History List"):
  572. st.session_state.selected_history_id = None
  573. st.rerun()
  574. st.divider()
  575. st.write(f"## 🔍 Deep Dive: Record #{record['id']} ({record['filename']})")
  576. detections = json.loads(record['detections'])
  577. summary = json.loads(record['summary'])
  578. # Metrics Row
  579. h_col1, h_col2, h_col3, h_col4 = st.columns(4)
  580. with h_col1:
  581. st.metric("Total Bunches", sum(summary.values()))
  582. with h_col2:
  583. st.metric("Healthy (Ripe)", summary.get('Ripe', 0))
  584. with h_col3:
  585. st.metric("Abnormal Alerts", summary.get('Abnormal', 0))
  586. with h_col4:
  587. st.metric("Inference Speed", f"{record.get('inference_ms', 0) or 0:.1f} ms")
  588. # Image View
  589. if os.path.exists(record['archive_path']):
  590. with open(record['archive_path'], "rb") as f:
  591. hist_img = Image.open(f).convert("RGB")
  592. display_interactive_results(hist_img, detections, key=f"hist_{record['id']}")
  593. else:
  594. st.error(f"Archive file not found: {record['archive_path']}")
  595. # Technical Evidence Expander
  596. with st.expander("🛠️ Technical Evidence: Raw Output Tensor"):
  597. raw_data = record.get('raw_array_sample')
  598. if raw_data:
  599. try:
  600. st.json(json.loads(raw_data))
  601. except:
  602. st.text(raw_data)
  603. else:
  604. st.info("No raw tensor data available for this record.")
  605. else:
  606. st.error(f"Failed to fetch history: {res.text}")
  607. except Exception as e:
  608. st.error(f"Error loading history: {str(e)}")