demo_app.py 34 KB

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