demo_app.py 42 KB

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