demo_app.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  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("### 🧠 1. The 'Thinking' Phase: The Raw Tensor [1, 300, 6]")
  18. st.write("""
  19. When the AI 'thinks' about an image, it doesn't see 'Ripe' or 'Unripe'. It populates a
  20. fixed-size memory buffer (Tensor) with **300 potential candidates**. Each candidate is
  21. represented by a row of 6 numbers.
  22. """)
  23. st.table({
  24. "Tensor Index": ["0, 1, 2, 3", "4", "5"],
  25. "AI Output": ["Coordinates", "Confidence Score", "Class ID"],
  26. "Programmer's Logic": ["`[x1, y1, x2, y2]`", "`float (0.0 - 1.0)`", "`int (0-5)`"]
  27. })
  28. st.write("#### 🎯 The Coordinate Paradox (Pixels vs. Ratios)")
  29. st.write("""
  30. Depending on the engine, the **Values at Index 0-3** speak different languages.
  31. This is why the raw numbers won't match if you swap engines:
  32. """)
  33. col_a, col_b = st.columns(2)
  34. with col_a:
  35. st.info("**PyTorch Pathway (.pt)**")
  36. st.write("- **Format**: Absolute Pixels")
  37. st.write("- **Logic**: The AI outputs numbers mapped to the photo's resolution (e.g., `245.0`).")
  38. with col_b:
  39. st.success("**ONNX Pathway (.onnx)**")
  40. st.write("- **Format**: Normalized Ratios")
  41. st.write("- **Logic**: The AI outputs percentages (0.0 to 1.0) relative to its internal 640x640 grid (e.g., `0.38`).")
  42. st.write("---")
  43. st.write("### 🎯 2. What is 'Confidence'? (The Probability Filter)")
  44. st.write("""
  45. Confidence is the AI's **mathematical certainty** that an object exists in a specific box.
  46. It is the product of *Objectness* (Is something there?) and *Class Probability* (What is it?).
  47. """)
  48. st.table({
  49. "Confidence Value": ["> 0.90", "0.50 - 0.89", "< 0.25 (Threshold)"],
  50. "Interpretation": ["**Certain**: Clear, unobstructed view.", "**Likely**: Valid, but possibly obscured by fronds.", "**Noise**: Discarded to prevent False Positives."]
  51. })
  52. st.write("---")
  53. st.write("### 🛠️ 3. The Custom Handler (The Translation Layer)")
  54. st.write("""
  55. Because ONNX returns raw ratios, we built a **Manual Scaling Handler**. It maps those
  56. `0.0 - 1.0` values back to your high-resolution photo pixels.
  57. This explains our two key metrics:
  58. - **Inference Speed**: The time the AI spent populating the Raw Tensor.
  59. - **Post-Processing**: The time our code spent 'translating' that Tensor into labels and pixels.
  60. """)
  61. st.write("---")
  62. st.write("### 🧠 4. Model Benchmarking: YOLO26 vs YOLOv5")
  63. st.write("""
  64. We have included **YOLOv5** as an industry-standard baseline to validate the performance of our custom **YOLO26** model.
  65. **Key Comparison Points:**
  66. - **NMS-Free Architecture**: YOLO26 is designed to be NMS-Free, meaning it doesn't require a secondary 'cleaning' step to remove overlapping boxes, making it more efficient in post-processing.
  67. - **Accuracy vs. Latency**: While YOLOv5 is a robust general-purpose model, YOLO26 is fine-tuned specifically for Palm Oil FFB features, providing superior ripeness grading.
  68. - **Real-Time Efficiency**: By comparing the 'Inference Speed' and 'Post-Processing' metrics, you can see how the architectural differences impact real-world performance.
  69. """)
  70. # --- 1. Global Backend Check ---
  71. API_BASE_URL = "http://localhost:8000"
  72. # MPOB Color Map for Overlays (Global for consistency)
  73. overlay_colors = {
  74. 'Ripe': '#22c55e', # Industrial Green
  75. 'Underripe': '#fbbf24', # Industrial Orange
  76. 'Unripe': '#3b82f6', # Industrial Blue
  77. 'Abnormal': '#dc2626', # Critical Red
  78. 'Empty_Bunch': '#64748b',# Waste Gray
  79. 'Overripe': '#7c2d12' # Dark Brown/Orange
  80. }
  81. # Helper to reset results when files change or engine switches
  82. def reset_single_results():
  83. st.session_state.last_detection = None
  84. def reset_batch_results():
  85. st.session_state.last_batch_results = None
  86. def reset_all_analysis():
  87. """Global reset for all active analysis views."""
  88. st.session_state.last_detection = None
  89. st.session_state.last_batch_results = None
  90. # Increment uploader keys to 'forget' current files (Clear Canvas)
  91. if "single_uploader_key" not in st.session_state:
  92. st.session_state.single_uploader_key = 0
  93. st.session_state.single_uploader_key += 1
  94. if "batch_uploader_key" not in st.session_state:
  95. st.session_state.batch_uploader_key = 0
  96. st.session_state.batch_uploader_key += 1
  97. def check_backend():
  98. try:
  99. res = requests.get(f"{API_BASE_URL}/get_confidence", timeout=2)
  100. return res.status_code == 200
  101. except:
  102. return False
  103. backend_active = check_backend()
  104. # LOCAL MODEL LOADING REMOVED (YOLO26 Clean Sweep)
  105. # UI now relies entirely on Backend API for NMS-Free inference.
  106. if not backend_active:
  107. st.error("⚠️ Backend API is offline!")
  108. st.info("Please start the backend server first (e.g., `python main.py`) to unlock AI features.")
  109. if st.button("🔄 Retry Connection"):
  110. st.rerun()
  111. st.stop() # Stops execution here, effectively disabling the app
  112. # --- 2. Main Page Config (Only rendered if backend is active) ---
  113. st.set_page_config(page_title="Palm Oil Ripeness AI (YOLO26)", layout="wide")
  114. st.title("🌴 Palm Oil FFB Management System")
  115. st.markdown("### Production-Ready AI Analysis & Archival")
  116. # --- Sidebar ---
  117. st.sidebar.header("Backend Controls")
  118. def update_confidence():
  119. new_conf = st.session_state.conf_slider
  120. try:
  121. requests.post(f"{API_BASE_URL}/set_confidence", json={"threshold": new_conf})
  122. st.toast(f"Threshold updated to {new_conf}")
  123. except:
  124. st.sidebar.error("Failed to update threshold")
  125. # We already know backend is up here
  126. response = requests.get(f"{API_BASE_URL}/get_confidence")
  127. current_conf = response.json().get("current_confidence", 0.25)
  128. st.sidebar.success(f"Connected to API")
  129. st.sidebar.info("Engine: YOLO26 NMS-Free (Inference: ~39ms)")
  130. # Synchronized Slider
  131. st.sidebar.slider(
  132. "Confidence Threshold",
  133. 0.1, 1.0,
  134. value=float(current_conf),
  135. key="conf_slider",
  136. on_change=update_confidence
  137. )
  138. st.sidebar.markdown("---")
  139. # Inference Engine
  140. engine_choice = st.sidebar.selectbox(
  141. "Select Model Engine",
  142. ["YOLO26 (PyTorch - Native)", "YOLO26 (ONNX - High Speed)", "YOLOv5 (Benchmarking Mode)"],
  143. index=0,
  144. help="ONNX is optimized for latency. PyTorch provides native object handling. YOLOv5 is the benchmark baseline.",
  145. on_change=reset_all_analysis # Clear canvas on engine switch
  146. )
  147. st.sidebar.markdown("---")
  148. if "ONNX" in engine_choice:
  149. model_type = "onnx"
  150. elif "YOLOv5" in engine_choice:
  151. model_type = "yolov5"
  152. else:
  153. model_type = "pytorch"
  154. if st.sidebar.button("❓ How to read results?", icon="📘", width='stretch'):
  155. show_tech_guide()
  156. # Function definitions moved to top
  157. def display_interactive_results(image, detections, key=None):
  158. """Renders image with interactive hover-boxes using Plotly."""
  159. img_width, img_height = image.size
  160. fig = go.Figure()
  161. # Add the palm image as the background
  162. fig.add_layout_image(
  163. dict(source=image, x=0, y=img_height, sizex=img_width, sizey=img_height,
  164. sizing="stretch", opacity=1, layer="below", xref="x", yref="y")
  165. )
  166. # Configure axes to match image dimensions
  167. fig.update_xaxes(showgrid=False, range=(0, img_width), zeroline=False, visible=False)
  168. fig.update_yaxes(showgrid=False, range=(0, img_height), zeroline=False, visible=False, scaleanchor="x")
  169. # Add interactive boxes
  170. for i, det in enumerate(detections):
  171. x1, y1, x2, y2 = det['box']
  172. # Plotly y-axis is inverted relative to PIL, so we flip y
  173. y_top, y_bottom = img_height - y1, img_height - y2
  174. color = overlay_colors.get(det['class'], "#ffeb3b")
  175. # The 'Hover' shape
  176. bunch_id = det.get('bunch_id', i+1)
  177. fig.add_trace(go.Scatter(
  178. x=[x1, x2, x2, x1, x1],
  179. y=[y_top, y_top, y_bottom, y_bottom, y_top],
  180. fill="toself",
  181. fillcolor=color,
  182. opacity=0.3, # Semi-transparent until hover
  183. mode='lines',
  184. line=dict(color=color, width=3),
  185. name=f"ID: #{bunch_id}", # Unified ID Tag
  186. text=f"<b>ID: #{bunch_id}</b><br>Grade: {det['class']}<br>Score: {det['confidence']:.2f}<br>Alert: {det['is_health_alert']}",
  187. hoverinfo="text"
  188. ))
  189. fig.update_layout(width=800, height=600, margin=dict(l=0, r=0, b=0, t=0), showlegend=False)
  190. st.plotly_chart(fig, width='stretch', key=key)
  191. def annotate_image(image, detections):
  192. """Draws high-visibility 'Plated Labels' and boxes on the image."""
  193. from PIL import ImageDraw, ImageFont
  194. draw = ImageDraw.Draw(image)
  195. # 1. Dynamic Font Scaling (width // 40 as requested)
  196. font_size = max(20, image.width // 40)
  197. try:
  198. # standard Windows font paths for agent environment
  199. font_path = "C:\\Windows\\Fonts\\arialbd.ttf" # Bold for higher visibility
  200. if not os.path.exists(font_path):
  201. font_path = "C:\\Windows\\Fonts\\arial.ttf"
  202. if os.path.exists(font_path):
  203. font = ImageFont.truetype(font_path, font_size)
  204. else:
  205. font = ImageFont.load_default()
  206. except:
  207. font = ImageFont.load_default()
  208. for det in detections:
  209. box = det['box'] # [x1, y1, x2, y2]
  210. cls = det['class']
  211. conf = det['confidence']
  212. bunch_id = det.get('bunch_id', '?')
  213. color = overlay_colors.get(cls, '#ffffff')
  214. # 2. Draw Heavy-Duty Bounding Box
  215. line_width = max(4, image.width // 150)
  216. draw.rectangle(box, outline=color, width=line_width)
  217. # 3. Draw 'Plated Label' (Background Shaded)
  218. label = f"#{bunch_id} {cls} {conf:.2f}"
  219. try:
  220. # Precise background calculation using textbbox
  221. l, t, r, b = draw.textbbox((box[0], box[1]), label, font=font)
  222. # Shift background up so it doesn't obscure the fruit
  223. bg_rect = [l - 2, t - (b - t) - 10, r + 2, t - 6]
  224. draw.rectangle(bg_rect, fill=color)
  225. # Draw text inside the plate
  226. draw.text((l, t - (b - t) - 8), label, fill="white", font=font)
  227. except:
  228. # Simple fallback
  229. draw.text((box[0], box[1] - font_size), label, fill=color)
  230. return image
  231. def generate_batch_report(data, uploaded_files_map=None):
  232. """Generates a professional PDF report for batch results with visual evidence."""
  233. from PIL import ImageDraw
  234. pdf = FPDF()
  235. pdf.add_page()
  236. pdf.set_font("Arial", "B", 16)
  237. pdf.cell(190, 10, "Palm Oil FFB Harvest Quality Report", ln=True, align="C")
  238. pdf.set_font("Arial", "", 12)
  239. pdf.cell(190, 10, f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align="C")
  240. pdf.ln(10)
  241. # 1. Summary Table
  242. pdf.set_font("Arial", "B", 14)
  243. pdf.cell(190, 10, "1. Batch Summary", ln=True)
  244. pdf.set_font("Arial", "", 12)
  245. summary = data.get('industrial_summary', {})
  246. total_bunches = data.get('total_count', 0)
  247. pdf.cell(95, 10, "Metric", border=1)
  248. pdf.cell(95, 10, "Value", border=1, ln=True)
  249. pdf.cell(95, 10, "Total Bunches Detected", border=1)
  250. pdf.cell(95, 10, str(total_bunches), border=1, ln=True)
  251. for grade, count in summary.items():
  252. if count > 0:
  253. pdf.cell(95, 10, f"Grade: {grade}", border=1)
  254. pdf.cell(95, 10, str(count), border=1, ln=True)
  255. pdf.ln(10)
  256. # 2. Strategic Insights
  257. pdf.set_font("Arial", "B", 14)
  258. pdf.cell(190, 10, "2. Strategic Yield Insights", ln=True)
  259. pdf.set_font("Arial", "", 12)
  260. unripe = summary.get('Unripe', 0)
  261. underripe = summary.get('Underripe', 0)
  262. loss = unripe + underripe
  263. if loss > 0:
  264. pdf.multi_cell(190, 10, f"WARNING: {loss} bunches were harvested before peak ripeness. "
  265. "This directly impacts the Oil Extraction Rate (OER) and results in potential yield loss.")
  266. else:
  267. pdf.multi_cell(190, 10, "EXCELLENT: All detected bunches meet prime ripeness standards. Harvest efficiency is 100%.")
  268. # Critical Alerts
  269. abnormal = summary.get('Abnormal', 0)
  270. empty = summary.get('Empty_Bunch', 0)
  271. if abnormal > 0 or empty > 0:
  272. pdf.ln(5)
  273. pdf.set_text_color(220, 0, 0)
  274. pdf.set_font("Arial", "B", 12)
  275. pdf.cell(190, 10, "CRITICAL HEALTH ALERTS:", ln=True)
  276. pdf.set_font("Arial", "", 12)
  277. if abnormal > 0:
  278. pdf.cell(190, 10, f"- {abnormal} Abnormal Bunches detected (Requires immediate field inspection).", ln=True)
  279. if empty > 0:
  280. pdf.cell(190, 10, f"- {empty} Empty Bunches detected (Waste reduction needed).", ln=True)
  281. pdf.set_text_color(0, 0, 0)
  282. # 3. Visual Evidence Section
  283. if 'detailed_results' in data and uploaded_files_map:
  284. pdf.add_page()
  285. pdf.set_font("Arial", "B", 14)
  286. pdf.cell(190, 10, "3. Visual Batch Evidence (AI Overlay)", ln=True)
  287. pdf.ln(5)
  288. # Group detections by filename
  289. results_by_file = {}
  290. for res in data['detailed_results']:
  291. fname = res['filename']
  292. if fname not in results_by_file:
  293. results_by_file[fname] = []
  294. results_by_file[fname].append(res['detection'])
  295. for fname, detections in results_by_file.items():
  296. if fname in uploaded_files_map:
  297. img_bytes = uploaded_files_map[fname]
  298. img = Image.open(io.BytesIO(img_bytes)).convert("RGB")
  299. draw = ImageDraw.Draw(img)
  300. # Drawing annotated boxes for PDF using high-visibility utility
  301. annotate_image(img, detections)
  302. # Save to temp file for PDF
  303. temp_img_path = f"temp_report_{fname}"
  304. img.save(temp_img_path)
  305. # Check if we need a new page based on image height (rough estimate)
  306. if pdf.get_y() > 200:
  307. pdf.add_page()
  308. pdf.image(temp_img_path, x=10, w=150)
  309. pdf.set_font("Arial", "I", 10)
  310. pdf.cell(190, 10, f"Annotated: {fname}", ln=True)
  311. pdf.ln(5)
  312. os.remove(temp_img_path)
  313. # Footer
  314. pdf.set_y(-15)
  315. pdf.set_font("Arial", "I", 8)
  316. pdf.cell(190, 10, "Generated by Palm Oil AI Desktop PoC - YOLO26 Engine", align="C")
  317. return pdf.output(dest='S')
  318. # --- Tabs ---
  319. tab1, tab2, tab3, tab4 = st.tabs(["Single Analysis", "Batch Processing", "Similarity Search", "History Vault"])
  320. # --- Tab 1: Single Analysis ---
  321. with tab1:
  322. st.subheader("Analyze Single Bunch")
  323. # 1. Initialize Uploader Key
  324. if "single_uploader_key" not in st.session_state:
  325. st.session_state.single_uploader_key = 0
  326. uploaded_file = st.file_uploader(
  327. "Upload a bunch image...",
  328. type=["jpg", "jpeg", "png"],
  329. key=f"single_{st.session_state.single_uploader_key}",
  330. on_change=reset_single_results
  331. )
  332. if uploaded_file:
  333. # State initialization
  334. if "last_detection" not in st.session_state:
  335. st.session_state.last_detection = None
  336. # 1. Auto-Detection Trigger
  337. if uploaded_file and st.session_state.last_detection is None:
  338. with st.spinner(f"Processing with {model_type.upper()} Engine..."):
  339. files = {"file": (uploaded_file.name, uploaded_file.getvalue(), uploaded_file.type)}
  340. payload = {"model_type": model_type}
  341. res = requests.post(f"{API_BASE_URL}/analyze", files=files, data=payload)
  342. if res.status_code == 200:
  343. st.session_state.last_detection = res.json()
  344. detections = st.session_state.last_detection.get('detections', [])
  345. if model_type == "yolov5" and not detections:
  346. st.warning("⚠️ YOLOv5 Benchmarking model failed to load on the backend. Results are empty.")
  347. st.rerun() # Refresh to show results immediately
  348. else:
  349. st.error(f"Detection Failed: {res.text}")
  350. # 2. Results Layout
  351. if st.session_state.last_detection:
  352. # Redo Button at the top for easy access
  353. if st.button("🔄 Re-analyze Image", width='stretch', type="primary", help="Force a fresh detection (useful if threshold changed)."):
  354. st.session_state.last_detection = None
  355. st.rerun()
  356. data = st.session_state.last_detection
  357. st.divider()
  358. st.write("### 📈 Manager's Dashboard")
  359. m_col1, m_col2, m_col3, m_col4 = st.columns(4)
  360. with m_col1:
  361. st.metric("Total Bunches", data.get('total_count', 0))
  362. with m_col2:
  363. st.metric("Healthy (Ripe)", data['industrial_summary'].get('Ripe', 0))
  364. with m_col3:
  365. # Refined speed label based on engine
  366. speed_label = "Raw Speed (Unlabeled)" if model_type == "onnx" else "Wrapped Speed (Auto-Labeled)"
  367. st.metric("Inference Speed", f"{data.get('inference_ms', 0):.1f} ms", help=speed_label)
  368. with m_col4:
  369. st.metric("Post-Processing", f"{data.get('processing_ms', 0):.1f} ms", help="Labeling/Scaling overhead")
  370. st.divider()
  371. # Side-by-Side View (Technical Trace)
  372. img = Image.open(uploaded_file).convert("RGB")
  373. if st.session_state.get('tech_trace', False):
  374. t_col1, t_col2 = st.columns(2)
  375. with t_col1:
  376. st.subheader("🔢 Raw Output Tensor (The Math)")
  377. st.caption("First 5 rows of the 1x300x6 detection tensor.")
  378. st.json(data.get('raw_array_sample', []))
  379. with t_col2:
  380. st.subheader("🎨 AI Interpretation")
  381. img_annotated = annotate_image(img.copy(), data['detections'])
  382. st.image(img_annotated, width='stretch')
  383. else:
  384. # Regular View
  385. st.write("### 🔍 AI Analytical View")
  386. display_interactive_results(img, data['detections'], key="main_viewer")
  387. col1, col2 = st.columns([1.5, 1]) # Keep original col structure for summary below
  388. with col1:
  389. col_tech_h1, col_tech_h2 = st.columns([1, 1])
  390. with col_tech_h1:
  391. st.write("#### 🛠️ Technical Evidence")
  392. with col_tech_h2:
  393. st.session_state.tech_trace = st.toggle("🔬 Side-by-Side Trace", value=st.session_state.get('tech_trace', False))
  394. with st.expander("Raw Output Tensor (NMS-Free)", expanded=False):
  395. coord_type = "Absolute Pixels" if model_type == "pytorch" else "Normalized Ratios (0.0-1.0)"
  396. st.warning(f"Engine detected: {model_type.upper()} | Coordinate System: {coord_type}")
  397. st.json(data.get('raw_array_sample', []))
  398. with st.container(border=True):
  399. st.write("### 🏷️ Detection Results")
  400. if not data['detections']:
  401. st.warning("No Fresh Fruit Bunches detected.")
  402. else:
  403. for det in data['detections']:
  404. st.info(f"### Bunch #{det['bunch_id']}: {det['class']} ({det['confidence']:.2%})")
  405. st.write("### 📊 Harvest Quality Mix")
  406. # Convert industrial_summary dictionary to a DataFrame for charting
  407. summary_df = pd.DataFrame(
  408. list(data['industrial_summary'].items()),
  409. columns=['Grade', 'Count']
  410. )
  411. # Filter out classes with 0 count for a cleaner chart
  412. summary_df = summary_df[summary_df['Count'] > 0]
  413. if not summary_df.empty:
  414. # Create a Pie Chart to show the proportion of each grade
  415. fig = px.pie(summary_df, values='Count', names='Grade',
  416. color='Grade',
  417. color_discrete_map={
  418. 'Ripe': '#22c55e', # Industrial Green
  419. 'Underripe': '#fbbf24', # Industrial Orange
  420. 'Unripe': '#3b82f6', # Industrial Blue
  421. 'Abnormal': '#dc2626', # Critical Red
  422. 'Empty_Bunch': '#64748b' # Waste Gray
  423. },
  424. hole=0.4)
  425. fig.update_layout(margin=dict(t=0, b=0, l=0, r=0), height=300)
  426. st.plotly_chart(fig, width='stretch', key="single_pie")
  427. # 💡 Strategic R&D Insight: Harvest Efficiency
  428. st.write("---")
  429. st.write("#### 💡 Strategic R&D Insight")
  430. unripe_count = data['industrial_summary'].get('Unripe', 0)
  431. underripe_count = data['industrial_summary'].get('Underripe', 0)
  432. total_non_prime = unripe_count + underripe_count
  433. st.write(f"🌑 **Unripe (Mentah):** {unripe_count}")
  434. st.write(f"🌗 **Underripe (Kurang Masak):** {underripe_count}")
  435. if total_non_prime > 0:
  436. st.warning(f"🚨 **Potential Yield Loss:** {total_non_prime} bunches harvested too early. This will reduce OER (Oil Extraction Rate).")
  437. else:
  438. st.success("✅ **Harvest Efficiency:** 100% Prime Ripeness detected.")
  439. # High-Priority Health Alert
  440. if data['industrial_summary'].get('Abnormal', 0) > 0:
  441. st.error(f"🚨 CRITICAL: {data['industrial_summary']['Abnormal']} Abnormal Bunches Detected!")
  442. if data['industrial_summary'].get('Empty_Bunch', 0) > 0:
  443. st.warning(f"⚠️ ALERT: {data['industrial_summary']['Empty_Bunch']} Empty Bunches Detected.")
  444. # 3. Cloud Actions (Only if detections found)
  445. st.write("---")
  446. st.write("#### ✨ Cloud Archive")
  447. if st.button("🚀 Save to Atlas (Vectorize)", width='stretch'):
  448. with st.spinner("Archiving..."):
  449. import json
  450. primary_det = data['detections'][0]
  451. payload = {"detection_data": json.dumps(primary_det)}
  452. files_cloud = {"file": (uploaded_file.name, uploaded_file.getvalue(), uploaded_file.type)}
  453. res_cloud = requests.post(f"{API_BASE_URL}/vectorize_and_store", files=files_cloud, data=payload)
  454. if res_cloud.status_code == 200:
  455. res_json = res_cloud.json()
  456. if res_json["status"] == "success":
  457. st.success(f"Archived! ID: `{res_json['record_id'][:8]}...`")
  458. else:
  459. st.error(f"Cloud Error: {res_json['message']}")
  460. else:
  461. st.error("Failed to connect to cloud service")
  462. if st.button("🚩 Flag Misclassification", width='stretch', type="secondary"):
  463. # Save to local feedback folder
  464. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  465. feedback_id = f"fb_{timestamp}"
  466. img_path = f"feedback/{feedback_id}.jpg"
  467. json_path = f"feedback/{feedback_id}.json"
  468. # Save image
  469. Image.open(uploaded_file).save(img_path)
  470. # Save metadata
  471. feedback_data = {
  472. "original_filename": uploaded_file.name,
  473. "timestamp": timestamp,
  474. "detections": data['detections'],
  475. "threshold_used": data['current_threshold']
  476. }
  477. with open(json_path, "w") as f:
  478. json.dump(feedback_data, f, indent=4)
  479. st.toast("✅ Feedback saved to local vault!", icon="🚩")
  480. if st.button("💾 Local History Vault (Auto-Saved)", width='stretch', type="secondary", disabled=True):
  481. pass
  482. st.caption("✅ This analysis was automatically archived to the local vault.")
  483. # --- Tab 2: Batch Processing ---
  484. with tab2:
  485. st.subheader("Bulk Analysis")
  486. # 1. Initialize Session State
  487. if "batch_uploader_key" not in st.session_state:
  488. st.session_state.batch_uploader_key = 0
  489. if "last_batch_results" not in st.session_state:
  490. st.session_state.last_batch_results = None
  491. # 2. Display Persisted Results (if any)
  492. if st.session_state.last_batch_results:
  493. res_data = st.session_state.last_batch_results
  494. with st.container(border=True):
  495. st.success(f"✅ Successfully processed {res_data['processed_count']} images.")
  496. # Batch Summary Dashboard
  497. st.write("### 📈 Batch Quality Overview")
  498. batch_summary = res_data.get('industrial_summary', {})
  499. if batch_summary:
  500. sum_df = pd.DataFrame(list(batch_summary.items()), columns=['Grade', 'Count'])
  501. sum_df = sum_df[sum_df['Count'] > 0]
  502. b_col1, b_col2 = st.columns([1, 1])
  503. with b_col1:
  504. st.dataframe(sum_df, hide_index=True, width='stretch')
  505. with b_col2:
  506. if not sum_df.empty:
  507. fig_batch = px.bar(sum_df, x='Grade', y='Count', color='Grade',
  508. color_discrete_map={
  509. 'Ripe': '#22c55e',
  510. 'Underripe': '#fbbf24',
  511. 'Unripe': '#3b82f6',
  512. 'Abnormal': '#dc2626',
  513. 'Empty_Bunch': '#64748b'
  514. })
  515. fig_batch.update_layout(margin=dict(t=0, b=0, l=0, r=0), height=200, showlegend=False)
  516. st.plotly_chart(fig_batch, width='stretch', key="batch_bar")
  517. if batch_summary.get('Abnormal', 0) > 0:
  518. st.error(f"🚨 BATCH CRITICAL: {batch_summary['Abnormal']} Abnormal Bunches found in this batch!")
  519. st.write("Generated Record IDs:")
  520. st.code(res_data['record_ids'])
  521. # --- 4. Batch Evidence Gallery ---
  522. st.write("### 🖼️ Detailed Detection Evidence")
  523. if 'detailed_results' in res_data:
  524. # Group results by filename for gallery
  525. gallery_map = {}
  526. for res in res_data['detailed_results']:
  527. fname = res['filename']
  528. if fname not in gallery_map:
  529. gallery_map[fname] = []
  530. gallery_map[fname].append(res['detection'])
  531. # Show images with overlays using consistent utility
  532. for up_file in uploaded_files:
  533. if up_file.name in gallery_map:
  534. with st.container(border=True):
  535. g_img = Image.open(up_file).convert("RGB")
  536. g_annotated = annotate_image(g_img, gallery_map[up_file.name])
  537. st.image(g_annotated, caption=f"Evidence: {up_file.name}", width='stretch')
  538. # PDF Export Button (Pass images map)
  539. files_map = {f.name: f.getvalue() for f in uploaded_files}
  540. pdf_bytes = generate_batch_report(res_data, files_map)
  541. st.download_button(
  542. label="📄 Download Executive Batch Report (PDF)",
  543. data=pdf_bytes,
  544. file_name=f"PalmOil_BatchReport_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf",
  545. mime="application/pdf",
  546. width='stretch'
  547. )
  548. if st.button("Clear Results & Start New Batch", width='stretch'):
  549. st.session_state.last_batch_results = None
  550. st.rerun()
  551. st.divider()
  552. # 3. Uploader UI
  553. col_batch1, col_batch2 = st.columns([4, 1])
  554. with col_batch1:
  555. uploaded_files = st.file_uploader(
  556. "Upload multiple images...",
  557. type=["jpg", "jpeg", "png"],
  558. accept_multiple_files=True,
  559. key=f"batch_{st.session_state.batch_uploader_key}",
  560. on_change=reset_batch_results
  561. )
  562. with col_batch2:
  563. st.write("##") # Alignment
  564. if st.session_state.last_batch_results is None and uploaded_files:
  565. if st.button("🔍 Process Batch", type="primary", width='stretch'):
  566. with st.spinner(f"Analyzing {len(uploaded_files)} images with {model_type.upper()}..."):
  567. files = [("files", (f.name, f.getvalue(), f.type)) for f in uploaded_files]
  568. payload = {"model_type": model_type}
  569. res = requests.post(f"{API_BASE_URL}/process_batch", files=files, data=payload)
  570. if res.status_code == 200:
  571. data = res.json()
  572. if data["status"] == "success":
  573. st.session_state.last_batch_results = data
  574. st.session_state.batch_uploader_key += 1
  575. st.rerun()
  576. elif data["status"] == "partial_success":
  577. st.warning(data["message"])
  578. st.info(f"Successfully detected {data['detections_count']} bunches locally.")
  579. else:
  580. st.error(f"Batch Error: {data['message']}")
  581. else:
  582. st.error(f"Batch Processing Failed: {res.text}")
  583. if st.button("🗑️ Reset Uploader"):
  584. st.session_state.batch_uploader_key += 1
  585. st.session_state.last_batch_results = None
  586. st.rerun()
  587. # --- Tab 3: Similarity Search ---
  588. with tab3:
  589. st.subheader("Hybrid Semantic Search")
  590. st.markdown("Search records by either **Image Similarity** or **Natural Language Query**.")
  591. with st.form("hybrid_search_form"):
  592. col_input1, col_input2 = st.columns(2)
  593. with col_input1:
  594. search_file = st.file_uploader("Option A: Search Image...", type=["jpg", "jpeg", "png"], key="search")
  595. with col_input2:
  596. text_query = st.text_input("Option B: Natural Language Query", placeholder="e.g., 'ripe bunches with dark spots' or 'unripe fruit'")
  597. top_k = st.slider("Results Limit (Top K)", 1, 20, 3)
  598. submit_search = st.form_submit_button("Run Semantic Search")
  599. if submit_search:
  600. if not search_file and not text_query:
  601. st.warning("Please provide either an image or a text query.")
  602. else:
  603. with st.spinner("Searching Vector Index..."):
  604. payload = {"limit": top_k}
  605. # If an image is uploaded, it takes precedence for visual search
  606. if search_file:
  607. files = {"file": (search_file.name, search_file.getvalue(), search_file.type)}
  608. # Pass top_k as part of the data
  609. res = requests.post(f"{API_BASE_URL}/search_hybrid", files=files, data=payload)
  610. # Otherwise, use text query
  611. elif text_query:
  612. payload["text_query"] = text_query
  613. # Send as form-data (data=) to match FastAPI's Form(None)
  614. res = requests.post(f"{API_BASE_URL}/search_hybrid", data=payload)
  615. if res.status_code == 200:
  616. results = res.json().get("results", [])
  617. if not results:
  618. st.warning("No similar records found.")
  619. else:
  620. st.success(f"Found {len(results)} matches.")
  621. for item in results:
  622. with st.container(border=True):
  623. c1, c2 = st.columns([1, 2])
  624. # Fetch the image for this result
  625. rec_id = item["_id"]
  626. img_res = requests.get(f"{API_BASE_URL}/get_image/{rec_id}")
  627. with c1:
  628. if img_res.status_code == 200:
  629. img_b64 = img_res.json().get("image_data")
  630. if img_b64:
  631. st.image(base64.b64decode(img_b64), width=250)
  632. else:
  633. st.write("No image data found.")
  634. else:
  635. st.write("Failed to load image.")
  636. with c2:
  637. st.write(f"**Class:** {item['ripeness_class']}")
  638. st.write(f"**Similarity Score:** {item['score']:.4f}")
  639. st.write(f"**Timestamp:** {item['timestamp']}")
  640. st.write(f"**ID:** `{rec_id}`")
  641. else:
  642. st.error(f"Search failed: {res.text}")
  643. # --- Tab 4: History Vault ---
  644. with tab4:
  645. st.subheader("📜 Local History Vault")
  646. st.caption("Industrial-grade audit log of all past AI harvest scans.")
  647. if "selected_history_id" not in st.session_state:
  648. st.session_state.selected_history_id = None
  649. try:
  650. res = requests.get(f"{API_BASE_URL}/get_history")
  651. if res.status_code == 200:
  652. history_data = res.json().get("history", [])
  653. if not history_data:
  654. st.info("No saved records found in the vault.")
  655. else:
  656. if st.session_state.selected_history_id is None:
  657. # --- 1. ListView Mode (Management Dashboard) ---
  658. st.write("### 📋 Audit Log")
  659. # Prepare searchable dataframe
  660. df_history = pd.DataFrame(history_data)
  661. # Clean up for display
  662. display_df = df_history[['id', 'timestamp', 'engine', 'filename', 'inference_ms']].copy()
  663. display_df.columns = ['ID', 'Date/Time', 'Engine', 'Filename', 'Inference (ms)']
  664. st.dataframe(
  665. display_df,
  666. hide_index=True,
  667. width='stretch',
  668. column_config={
  669. "ID": st.column_config.NumberColumn(width="small"),
  670. "Inference (ms)": st.column_config.NumberColumn(format="%.1f ms")
  671. }
  672. )
  673. # Industrial Selection UI
  674. hist_col1, hist_col2 = st.columns([3, 1])
  675. with hist_col1:
  676. target_id = st.selectbox(
  677. "Select Record for Deep Dive Analysis",
  678. options=df_history['id'].tolist(),
  679. format_func=lambda x: f"Record #{x} - {df_history[df_history['id']==x]['filename'].values[0]}"
  680. )
  681. with hist_col2:
  682. st.write("##") # Alignment
  683. if st.button("🔬 Start Deep Dive", type="primary", width='stretch'):
  684. st.session_state.selected_history_id = target_id
  685. st.rerun()
  686. else:
  687. # --- 2. Detail View Mode (Technical Auditor) ---
  688. record = next((item for item in history_data if item["id"] == st.session_state.selected_history_id), None)
  689. if not record:
  690. st.error("Audit record not found.")
  691. if st.button("Back to List"):
  692. st.session_state.selected_history_id = None
  693. st.rerun()
  694. else:
  695. st.button("⬅️ Back to Audit Log", on_click=lambda: st.session_state.update({"selected_history_id": None}))
  696. st.divider()
  697. st.write(f"## 🔍 Deep Dive: Record #{record['id']}")
  698. engine_val = record.get('engine', 'Unknown')
  699. st.caption(f"Original Filename: `{record['filename']}` | Processed: `{record['timestamp']}` | Engine: `{engine_val.upper()}`")
  700. detections = json.loads(record['detections'])
  701. summary = json.loads(record['summary'])
  702. # Metrics Executive Summary
  703. h_col1, h_col2, h_col3, h_col4 = st.columns(4)
  704. with h_col1:
  705. st.metric("Total Bunches", sum(summary.values()))
  706. with h_col2:
  707. st.metric("Healthy (Ripe)", summary.get('Ripe', 0))
  708. with h_col3:
  709. st.metric("Engine Performance", f"{record.get('inference_ms', 0) or 0:.1f} ms")
  710. with h_col4:
  711. st.metric("Labeling Overhead", f"{record.get('processing_ms', 0) or 0:.1f} ms")
  712. # Re-Annotate Archived Image
  713. if os.path.exists(record['archive_path']):
  714. with open(record['archive_path'], "rb") as f:
  715. hist_img = Image.open(f).convert("RGB")
  716. # Side-by-Side: Interactive vs Static Plate
  717. v_tab1, v_tab2 = st.tabs(["Interactive Plotly View", "Static Annotated Evidence"])
  718. with v_tab1:
  719. display_interactive_results(hist_img, detections, key=f"hist_plotly_{record['id']}")
  720. with v_tab2:
  721. img_plate = annotate_image(hist_img.copy(), detections)
  722. st.image(img_plate, width='stretch', caption="Point-of-Harvest AI Interpretation")
  723. else:
  724. st.warning(f"Technical Error: Archive file missing at `{record['archive_path']}`")
  725. # Technical Evidence Expander (Mathematical Audit)
  726. st.divider()
  727. st.write("### 🛠️ Technical Audit Trail")
  728. with st.expander("🔬 View Raw Mathematical Tensor", expanded=False):
  729. st.info("This is the exact numerical output from the AI engine prior to human-readable transformation.")
  730. raw_data = record.get('raw_tensor')
  731. if raw_data:
  732. try:
  733. st.json(json.loads(raw_data))
  734. except:
  735. st.code(raw_data)
  736. else:
  737. st.warning("No raw tensor trace was archived for this legacy record.")
  738. else:
  739. st.error(f"Vault Connection Failed: {res.text}")
  740. except Exception as e:
  741. st.error(f"Audit System Error: {str(e)}")