demo_app.py 40 KB

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