from ultralytics import YOLO
from PIL import Image
import numpy as np
import pandas as pd
import cv2
import os
import zipfile
import math
import time
import shutil
from collections import Counter
from datetime import datetime
import gradio as gr
import matplotlib.pyplot as plt
import matplotlib
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
matplotlib.use('Agg') #using non-interactive backend
import seaborn as sns
# =========================
# MODEL SETUP
# =========================
MODEL_PATHS = {
"strawberry_UAV": "weights/strawberry_UAV_best.pt",
"strawberry_Ground": "weights/strawberry_Ground_best.pt",
"blueberry": "weights/blueberry_best.pt",
}
MODELS = {name: YOLO(path) for name, path in MODEL_PATHS.items()}
# =========================
# COLOR MAP
# =========================
color_map = {
0: (0, 255, 255), # Yellow
1: (0, 255, 0), # Green
2: (0, 0, 255), # Red
3: (203, 192, 255) # Pink
}
# =========================
# TILING HELPERS
# =========================
def split_horizontally_into_three(image: Image.Image):
#Strawberry UAV
width, height = image.size
tile_height = height // 3
return [image.crop((0, i * tile_height, width, (i + 1) * tile_height)) for i in range(3)]
def split_dynamic(image: Image.Image, base_tile_size=640):
width, height = image.size
cols = math.ceil(width // base_tile_size)
rows = math.ceil(height // base_tile_size)
tile_w = width // cols
tile_h = height // rows
tiles = []
for row in range(rows):
for col in range(cols):
left = col * tile_w
upper = row * tile_h
right = (col + 1) * tile_w
lower = (row + 1) * tile_h
tiles.append(image.crop((left, upper, right, lower)))
return tiles
# =========================
# DRAW BOXES
# =========================
def draw_boxes(image, results):
img = np.array(image.convert("RGB"))
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
for box in results[0].boxes:
cls = int(box.cls[0])
label = results[0].names[cls]
x1, y1, x2, y2 = map(int, box.xyxy[0].tolist())
color = color_map.get(cls, (255, 255, 255))
cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)
(tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)
cv2.rectangle(img, (x1, y1 - th - 10), (x1 + tw, y1), color, -1)
cv2.putText(img, label, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 2)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return Image.fromarray(img)
# =============================================
# CLEAR OLD OUTPUTS TO PREVENT SERVER CLUTTER
# =============================================
def cleanup_old_outputs(path="output", age_minutes=60):
now = time.time()
threshold = age_minutes * 60
if not os.path.exists(path):
return
for item in os.listdir(path):
full_path = os.path.join(path, item)
if os.path.isdir(full_path):
if now - os.path.getmtime(full_path) > threshold:
shutil.rmtree(full_path, ignore_errors=True)
# ================================================
# COMPLETELY CLEAR ALL OLD OUTPUTS BEFORE EACH RUN
# ================================================
def clear_output_dir(path="output"):
if os.path.exists(path):
for item in os.listdir(path):
item_path = os.path.join(path, item)
if os.path.isdir(item_path):
shutil.rmtree(item_path, ignore_errors=True)
elif os.path.isfile(item_path):
os.remove(item_path)
else:
os.makedirs(path)
# =========================
# VISUALIZATION FUNCTIONS
# =========================
def create_single_image_chart(class_counts, title="Flower and fruit counts", model_name=None):
"""Create a stacked bar chart for single image detection results"""
if not class_counts:
# Return empty plot if no detections
fig, ax = plt.subplots(figsize=(8, 6))
ax.text(0.5, 0.5, 'No detections found', ha='center', va='center',
transform=ax.transAxes, fontsize=14)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_xticks([])
ax.set_yticks([])
ax.set_title(title, fontsize=16, fontweight='bold')
plt.tight_layout()
return fig
# Prepare data for stacked bar chart
labels = list(class_counts.keys())
counts = list(class_counts.values())
# Calculate ripeness ratio for blueberry model and add to title
chart_title = title
if model_name == "blueberry" and ('Ripe' in class_counts or 'Unripe' in class_counts):
ripe = class_counts.get('Ripe', 0)
unripe = class_counts.get('Unripe', 0)
total = ripe + unripe
if total > 0:
ripeness_ratio = (ripe / total) * 100
chart_title = f"Blueberry Detection Results\nšÆ Ripeness Ratio: {ripeness_ratio:.1f}%"
else:
chart_title = "Blueberry Detection Results"
# Define specific colors for each class
color_mapping = {
'Red': '#DC143C', # Red color for Red class
'Green': '#32CD32', # Green color for Green class
'Turning': '#FFC0CB', # Pink color for Turning class
'Flower': '#FFD700', # Yellow color for Flower class
'Ripe': '#663399', # Dark purple for Ripe blueberries
'Unripe': '#32CD32' # Green for Unripe blueberries
}
# Default colors for any unknown classes
default_colors = ['#87CEEB', '#DDA0DD', '#FFA500', '#98FB98']
# Get colors for each label
bar_colors = []
for i, label in enumerate(labels):
if label in color_mapping:
bar_colors.append(color_mapping[label])
else:
bar_colors.append(default_colors[i % len(default_colors)])
fig, ax = plt.subplots(figsize=(8, 6))
# Create stacked bar chart
bottom = 0
bars = []
for i, (label, count) in enumerate(zip(labels, counts)):
bar = ax.bar('Counts', count, bottom=bottom, label=label,
color=bar_colors[i], alpha=0.8)
bars.append(bar)
# Add count text on each segment
if count > 0:
ax.text(0, bottom + count/2, str(count), ha='center', va='center',
fontweight='bold', fontsize=12)
bottom += count
# Customize the chart
ax.set_title(chart_title, fontsize=16, fontweight='bold', pad=20)
ax.set_ylabel('Count', fontsize=12)
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
# Remove x-axis ticks since we only have one bar
ax.set_xticks([])
# Set y-axis to start from 0
ax.set_ylim(0, sum(counts) * 1.1)
plt.tight_layout()
return fig
def create_class_histogram(df, selected_class, title=None):
"""Create interactive histogram for selected class with hover functionality"""
if df.empty or selected_class not in df.columns:
# Return empty plot
fig = go.Figure()
fig.add_annotation(
text="No data available for selected class",
xref="paper", yref="paper",
x=0.5, y=0.5, xanchor='center', yanchor='middle',
showarrow=False, font=dict(size=16)
)
fig.update_layout(
title=title or f"{selected_class} Count Distribution",
showlegend=False,
height=500
)
return fig
# Sort by selected class count (descending)
df_sorted = df.sort_values(by=selected_class, ascending=False)
# Prepare data
image_names = df_sorted['image'].tolist()
counts = df_sorted[selected_class].tolist()
# Create hover text with all class information for each image
hover_text = []
for _, row in df_sorted.iterrows():
text_lines = [f"{row['image']}"]
for col in df.columns:
if col != 'image':
text_lines.append(f"{col}: {row[col]}")
hover_text.append("
".join(text_lines))
# Create the histogram
fig = go.Figure(data=[
go.Bar(
x=image_names,
y=counts,
name=selected_class,
hovertemplate="%{customdata}",
customdata=hover_text,
marker=dict(
color=counts,
colorscale='Viridis',
showscale=True,
colorbar=dict(title=f"{selected_class} Count")
)
)
])
fig.update_layout(
title=title or f"{selected_class} Count Distribution (Descending Order)",
xaxis_title="Images",
yaxis_title=f"{selected_class} Count",
height=500,
hovermode='closest',
xaxis=dict(tickangle=45)
)
return fig
def create_individual_image_stacked_chart(df, image_name, title=None):
"""Create stacked chart for individual image (for hover display)"""
if df.empty:
fig = go.Figure()
fig.add_annotation(text="No data available", x=0.5, y=0.5)
return fig
# Find the row for this image
image_row = df[df['image'] == image_name]
if image_row.empty:
fig = go.Figure()
fig.add_annotation(text=f"No data for {image_name}", x=0.5, y=0.5)
return fig
# Get class counts (exclude 'image' column)
class_columns = [col for col in df.columns if col != 'image']
counts = [image_row[col].iloc[0] for col in class_columns]
# Filter out zero counts
non_zero_data = [(col, count) for col, count in zip(class_columns, counts) if count > 0]
if not non_zero_data:
fig = go.Figure()
fig.add_annotation(text="No detections in this image", x=0.5, y=0.5)
return fig
labels, values = zip(*non_zero_data)
# Create stacked bar
colors = ['#FFD700', '#32CD32', '#DC143C', '#FFC0CB', '#87CEEB', '#DDA0DD']
fig = go.Figure()
bottom = 0
for i, (label, value) in enumerate(non_zero_data):
fig.add_trace(go.Bar(
x=['Counts'],
y=[value],
name=label,
base=bottom,
marker_color=colors[i % len(colors)],
text=str(value),
textposition='inside'
))
bottom += value
fig.update_layout(
title=title or f"Detection Counts for {image_name}",
barmode='stack',
height=400,
showlegend=True,
xaxis=dict(showticklabels=False)
)
return fig
# Global variable to store batch data
batch_dataframe = None
def store_batch_data(df):
"""Store batch DataFrame for visualization tab"""
global batch_dataframe
batch_dataframe = df.copy()
def get_batch_data():
"""Retrieve stored batch DataFrame"""
global batch_dataframe
return batch_dataframe if batch_dataframe is not None else pd.DataFrame()
def debug_batch_data():
"""Debug function to check batch data status"""
df = get_batch_data()
if df.empty:
return "ā No batch data found"
else:
available_classes = [col for col in df.columns if col != 'image']
return f"ā
Batch data found: {len(df)} images, classes: {available_classes}"
def force_initialize_batch_visualization():
"""Force initialize batch visualization with current data"""
df = get_batch_data()
if df.empty:
return (
gr.update(choices=[], visible=False, value=None),
gr.update(choices=[], visible=False, value=None),
go.Figure().add_annotation(text="No batch data", x=0.5, y=0.5).update_layout(title="No Data", height=400),
go.Figure().add_annotation(text="No batch data", x=0.5, y=0.5).update_layout(title="No Data", height=400),
"ā ļø **No batch data available**\n\nPlease run batch detection first."
)
# Get available classes dynamically from actual data (Ripe/Unripe for blueberry, etc.)
available_classes = [col for col in df.columns if col != 'image']
if available_classes:
default_class = available_classes[0]
# Create initial charts
choices = create_batch_dropdown_choices(default_class)
histogram = create_batch_histogram_plotly(default_class) # Use Plotly version
detail_chart = create_batch_detail_chart(None)
metrics = create_batch_metrics()
# Return with actual detected classes (Ripe/Unripe for blueberry)
return (
gr.update(choices=available_classes, value=default_class, visible=True),
gr.update(choices=choices, value=choices[0] if choices else None, visible=True),
histogram,
detail_chart,
metrics
)
return (
gr.update(choices=[], visible=False, value=None),
gr.update(choices=[], visible=False, value=None),
go.Figure().add_annotation(text="No classes detected", x=0.5, y=0.5).update_layout(title="No Data", height=400),
go.Figure().add_annotation(text="No classes detected", x=0.5, y=0.5).update_layout(title="No Data", height=400),
"No classes detected in batch data"
)
# Add these functions after the get_batch_data() function in detect.py
def get_model_classes(model_name):
"""Get the expected classes for each model"""
class_mapping = {
"strawberry_UAV": ["Flower", "Green", "Red", "Turning"],
"strawberry_Ground": ["Flower", "Green", "Red", "Turning"],
"blueberry": ["Ripe", "Unripe"]
}
return class_mapping.get(model_name, [])
def create_enhanced_histogram(selected_class, highlighted_image=None):
"""Create enhanced histogram with highlighting"""
df = get_batch_data()
if df.empty or selected_class not in df.columns:
# Return empty plot
fig = go.Figure()
fig.add_annotation(
text="No data available for selected class",
xref="paper", yref="paper",
x=0.5, y=0.5, xanchor='center', yanchor='middle',
showarrow=False, font=dict(size=16)
)
fig.update_layout(
title=f"{selected_class} Distribution",
showlegend=False,
height=400
)
return fig
df_sorted = df.sort_values(by=selected_class, ascending=False)
# Create colors - highlight selected image
colors = []
for img in df_sorted['image']:
if img == highlighted_image:
colors.append('#FF6B6B') # Red for selected
else:
colors.append('#4ECDC4') # Teal for others
fig = go.Figure(data=[
go.Bar(
x=df_sorted['image'],
y=df_sorted[selected_class],
marker_color=colors,
text=df_sorted[selected_class],
textposition='outside',
hovertemplate='%{x}
' +
f'{selected_class}: %{{y}}
' +
''
)
])
fig.update_layout(
title=f'{selected_class} Distribution (Red = Selected Image)',
xaxis_title='Images',
yaxis_title=f'{selected_class} Count',
height=400,
xaxis=dict(tickangle=45),
showlegend=False
)
return fig
def create_enhanced_detail_chart(image_name):
"""Create enhanced stacked bar chart for selected image"""
df = get_batch_data()
if df.empty:
fig = go.Figure()
fig.add_annotation(
text="No data available",
xref="paper", yref="paper",
x=0.5, y=0.5, xanchor='center', yanchor='middle',
showarrow=False, font=dict(size=16)
)
fig.update_layout(title="Image Breakdown", height=400)
return fig
if not image_name:
fig = go.Figure()
fig.add_annotation(
text="š Select an image from dropdown below
to see detailed breakdown",
xref="paper", yref="paper",
x=0.5, y=0.5, xanchor='center', yanchor='middle',
showarrow=False, font=dict(size=16, color='#666')
)
fig.update_layout(
title="Image Breakdown",
height=400,
showlegend=False
)
return fig
# Find the row for this image
image_row = df[df['image'] == image_name]
if image_row.empty:
fig = go.Figure()
fig.add_annotation(text=f"No data for {image_name}", x=0.5, y=0.5)
fig.update_layout(title=f"Breakdown: {image_name}", height=400)
return fig
# Get class counts (exclude 'image' column)
class_columns = [col for col in df.columns if col != 'image']
counts = [image_row[col].iloc[0] for col in class_columns]
# Filter out zero counts
non_zero_data = [(col, count) for col, count in zip(class_columns, counts) if count > 0]
if not non_zero_data:
fig = go.Figure()
fig.add_annotation(text="No detections in this image", x=0.5, y=0.5)
fig.update_layout(title=f"Breakdown: {image_name}", height=400)
return fig
labels, values = zip(*non_zero_data)
# Create stacked bar with appropriate colors
colors = ['#FFD700', '#32CD32', '#DC143C', '#FFC0CB', '#87CEEB', '#DDA0DD']
traces = []
bottom = 0
for i, (label, value) in enumerate(non_zero_data):
traces.append(go.Bar(
x=['Counts'],
y=[value],
name=label,
base=[bottom],
marker_color=colors[i % len(colors)],
text=[str(value)],
textposition='inside',
textfont=dict(color='white', weight='bold'),
hovertemplate=f'{label}: {value}'
))
bottom += value
fig = go.Figure(data=traces)
fig.update_layout(
title=f'Breakdown: {image_name}',
barmode='stack',
height=400,
showlegend=True,
xaxis=dict(showticklabels=False),
yaxis_title='Count',
legend=dict(
orientation='h',
yanchor='bottom',
y=1.02,
xanchor='center',
x=0.5
)
)
return fig
def create_blueberry_metrics(selected_image=None):
"""Create special metrics for blueberry model"""
df = get_batch_data()
if df.empty:
return "No data available"
if selected_image:
# Metrics for specific image
image_row = df[df['image'] == selected_image]
if image_row.empty:
return f"No data for {selected_image}"
ripe = image_row['Ripe'].iloc[0] if 'Ripe' in df.columns else 0
unripe = image_row['Unripe'].iloc[0] if 'Unripe' in df.columns else 0
total = ripe + unripe
if total == 0:
return f"**{selected_image}**\n\nNo blueberries detected"
ripe_pct = (ripe / total) * 100
unripe_pct = (unripe / total) * 100
return f"""**{selected_image} Metrics**
š« **Total Blueberries:** {total}
š¦ **Ripe:** {ripe} ({ripe_pct:.1f}%)
š¤ **Unripe:** {unripe} ({unripe_pct:.1f}%)
š **Ripeness Index:** {ripe_pct:.1f}%"""
else:
# Overall metrics for all images
if 'Ripe' not in df.columns or 'Unripe' not in df.columns:
return "No blueberry data available"
total_ripe = df['Ripe'].sum()
total_unripe = df['Unripe'].sum()
total_berries = total_ripe + total_unripe
if total_berries == 0:
return "No blueberries detected across all images"
ripe_pct = (total_ripe / total_berries) * 100
unripe_pct = (total_unripe / total_berries) * 100
return f"""**Overall Batch Metrics**
š **Total Images:** {len(df)}
š« **Total Blueberries:** {total_berries}
š¦ **Total Ripe:** {total_ripe} ({ripe_pct:.1f}%)
š¤ **Total Unripe:** {total_unripe} ({unripe_pct:.1f}%)
š **Average per Image:** {total_berries/len(df):.1f}
šÆ **Overall Ripeness:** {ripe_pct:.1f}%"""
def create_dropdown_choices_enhanced(selected_class):
"""Create dropdown choices with enhanced formatting"""
df = get_batch_data()
if df.empty or selected_class not in df.columns:
return []
df_sorted = df.sort_values(by=selected_class, ascending=False)
choices = []
for i, (_, row) in enumerate(df_sorted.iterrows()):
image_name = row['image']
count = row[selected_class]
choices.append(f"#{i+1} {image_name} ({selected_class}: {count})")
return choices
def extract_image_name_enhanced(dropdown_choice):
"""Extract actual image name from dropdown choice string"""
if not dropdown_choice:
return None
parts = dropdown_choice.split(' ')
if len(parts) >= 2:
return parts[1]
return None
def get_available_classes_dynamic():
"""Get available class names from batch data dynamically"""
df = get_batch_data()
if df.empty:
return []
return [col for col in df.columns if col != 'image']
def update_enhanced_class_selection(selected_class):
"""Enhanced update when class selection changes"""
df = get_batch_data()
if df.empty:
empty_fig = go.Figure()
empty_fig.add_annotation(text="No batch data available", x=0.5, y=0.5)
return (
gr.update(choices=[], visible=False),
empty_fig,
empty_fig,
"No data available"
)
choices = create_dropdown_choices_enhanced(selected_class)
histogram = create_enhanced_histogram(selected_class)
detail_chart = create_enhanced_detail_chart(None)
# Check if this is blueberry model
available_classes = get_available_classes_dynamic()
if set(available_classes) == {'Ripe', 'Unripe'}:
metrics = create_blueberry_metrics()
else:
metrics = "Select an image to see detailed breakdown"
return (
gr.update(choices=choices, value=choices[0] if choices else None, visible=True),
histogram,
detail_chart,
metrics
)
def update_enhanced_image_selection(selected_class, dropdown_choice):
"""Enhanced update when image selection changes"""
image_name = extract_image_name_enhanced(dropdown_choice)
histogram = create_enhanced_histogram(selected_class, image_name)
detail_chart = create_enhanced_detail_chart(image_name)
# Check if this is blueberry model for metrics
df = get_batch_data()
if not df.empty and set(df.columns) - {'image'} == {'Ripe', 'Unripe'}:
metrics = create_blueberry_metrics(image_name)
else:
metrics = f"Selected: {image_name}" if image_name else "No image selected"
return histogram, detail_chart, metrics
# =========================
# PROCESSING FUNCTIONS
# =========================
def process_single_image(model_name, file):
image = Image.open(file.name).convert("RGB")
filename = os.path.splitext(os.path.basename(file.name))[0]
if model_name == "strawberry_UAV":
tiles = split_horizontally_into_three(image)
iou, conf = 0.4, 0.3
elif model_name == "strawberry_Ground":
tiles = split_dynamic(image, 1280)
iou, conf = 0.5, 0.3
elif model_name == "blueberry":
tiles = split_dynamic(image)
iou, conf = 0.5, 0.3
else:
tiles = [image]
iou, conf = 0.5, 0.3
model = MODELS[model_name]
annotated_tiles = []
image_class_counts = Counter()
for i, tile in enumerate(tiles):
results = model.predict(tile, conf=conf, iou=iou)
annotated = draw_boxes(tile, results)
annotated_tiles.append(annotated)
if results[0].boxes.cls is not None:
cls_indices = results[0].boxes.cls.cpu().numpy().astype(int)
labels = [results[0].names[c] for c in cls_indices]
image_class_counts.update(labels)
summary_lines = [f"{filename}:"]
for label, count in image_class_counts.items():
summary_lines.append(f" - {label}: {count}")
# Add ripeness ratio for blueberry model
if model_name == "blueberry" and ('Ripe' in image_class_counts or 'Unripe' in image_class_counts):
ripe = image_class_counts.get('Ripe', 0)
unripe = image_class_counts.get('Unripe', 0)
total = ripe + unripe
if total > 0:
ripeness_ratio = (ripe / total) * 100
summary_lines.append(f"\nš« Total Blueberries: {total}")
summary_lines.append(f"šÆ Ripeness Ratio: {ripeness_ratio:.1f}%")
summary_text = "\n".join(summary_lines)
# Create visualization chart with model name for potential ratio display
chart_fig = create_single_image_chart(image_class_counts, model_name=model_name)
return annotated_tiles, summary_text, chart_fig
def process_directory_batch(model_name, files):
clear_output_dir()
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
base_output_dir = os.path.join("output", f"batch_{timestamp}")
os.makedirs(base_output_dir, exist_ok=True)
model = MODELS[model_name]
all_class_names = set()
image_class_counts = {}
for file in files:
image = Image.open(file.name).convert("RGB")
filename = os.path.splitext(os.path.basename(file.name))[0]
image_output_dir = os.path.join(base_output_dir, filename)
os.makedirs(image_output_dir, exist_ok=True)
# Tiling
if model_name == "strawberry_UAV":
tiles = split_horizontally_into_three(image)
iou, conf = 0.4, 0.3
elif model_name == "strawberry_Ground":
tiles = split_dynamic(image, 1280)
iou, conf = 0.5, 0.3
elif model_name == "blueberry":
tiles = split_dynamic(image)
iou, conf = 0.5, 0.3
else:
tiles = [image]
iou, conf = 0.5, 0.3
class_counter = Counter()
for i, tile in enumerate(tiles):
results = model.predict(tile, conf=conf, iou=iou)
annotated = draw_boxes(tile, results)
annotated.save(os.path.join(image_output_dir, f"{filename}_tile{i+1}.jpg"))
if results[0].boxes.cls is not None:
cls_indices = results[0].boxes.cls.cpu().numpy().astype(int)
labels = [results[0].names[c] for c in cls_indices]
class_counter.update(labels)
all_class_names.update(labels)
image_class_counts[filename + ".jpg"] = class_counter
# Build CSV dynamically
sorted_labels = sorted(all_class_names)
rows = []
for img_name, counter in image_class_counts.items():
row = {"image": img_name}
for label in sorted_labels:
row[label] = counter.get(label, 0)
rows.append(row)
df = pd.DataFrame(rows)
csv_filename = f"class_counts_{timestamp}.csv"
csv_path = os.path.join(base_output_dir, csv_filename)
df.to_csv(csv_path, index=False)
# Store DataFrame for visualization tab
store_batch_data(df)
# ZIP output
zip_filename = datetime.now().strftime("%Y%m%d_%H%M") + ".zip"
master_zip_path = os.path.join(base_output_dir, zip_filename)
with zipfile.ZipFile(master_zip_path, "w", allowZip64=True) as master_zip:
for subdir in os.listdir(base_output_dir):
full_path = os.path.join(base_output_dir, subdir)
if os.path.isdir(full_path):
for f in os.listdir(full_path):
master_zip.write(os.path.join(full_path, f), arcname=os.path.join(subdir, f))
master_zip.write(csv_path, arcname=csv_filename)
return [], "", master_zip_path
# =========================
# ENTRYPOINT FOR GRADIO
# =========================
def predict_entry(model_name, files):
is_single = len(files) == 1
is_blueberry = model_name == "blueberry"
if is_single:
images, summary, chart = process_single_image(model_name, files[0])
if is_blueberry:
# Save results to zip even for single image
_, _, zip_path = process_directory_batch(model_name, files)
return (
[], # No annotated image preview
summary,
zip_path,
chart, # Chart for single image
gr.update(visible=False), # Hide output_gallery
gr.update(visible=True), # Show summary
gr.update(visible=True), # Show ZIP
gr.update(visible=True), # Show chart
gr.update(visible=True), # Show preview
gr.update(value="ā
Done!", visible=True)
)
else:
return (
images,
summary,
None,
chart, # Chart for single image
gr.update(visible=True), # Show output_gallery
gr.update(visible=True), # Show summary
gr.update(visible=False), # No ZIP
gr.update(visible=True), # Show chart
gr.update(visible=True), # Show preview
gr.update(value="ā
Done!", visible=True)
)
else:
_, _, zip_path = process_directory_batch(model_name, files)
return (
[],
"",
zip_path,
None, # No chart for batch processing
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=True),
gr.update(visible=False), # Hide chart for batch
gr.update(visible=False),
gr.update(value="ā
Done!", visible=True)
)
# Add this global variable to track current selection
current_selected_class = "Red"
def update_class_histogram_with_selection(selected_class):
"""Update histogram and store current selection"""
global current_selected_class
current_selected_class = selected_class
df = get_batch_data()
if df.empty:
return None, gr.update(visible=False), gr.update(visible=False)
fig = create_class_histogram(df, selected_class)
return fig, gr.update(visible=True), gr.update(visible=False)
def handle_plot_click(evt: gr.SelectData):
"""Handle clicks on histogram bars"""
global current_selected_class
df = get_batch_data()
if df.empty or not evt.index:
return None, gr.update(visible=False)
# Sort by current selected class
df_sorted = df.sort_values(by=current_selected_class, ascending=False)
image_names = df_sorted['image'].tolist()
clicked_index = evt.index[0] if isinstance(evt.index, list) else evt.index
if clicked_index < len(image_names):
selected_image = image_names[clicked_index]
fig = create_individual_image_stacked_chart(df, selected_image)
return fig, gr.update(visible=True)
return None, gr.update(visible=False)
# Replace the enhanced functions in detect.py with these working versions
def create_batch_histogram_plotly(selected_class, highlighted_image=None):
"""Create clickable Plotly histogram for batch visualization"""
df = get_batch_data()
if df.empty or selected_class not in df.columns:
fig = go.Figure()
fig.add_annotation(
text="No data available",
xref="paper", yref="paper",
x=0.5, y=0.5, xanchor='center', yanchor='middle',
showarrow=False, font=dict(size=18, color='#666')
)
fig.update_layout(title="No Data", height=400)
return fig
df_sorted = df.sort_values(by=selected_class, ascending=False).copy()
# Clean image names - remove .jpg extension
df_sorted['clean_image'] = df_sorted['image'].str.replace('.jpg', '').str.replace('.jpeg', '').str.replace('.png', '')
# Create colors - highlight selected image
colors = []
for img in df_sorted['image']:
if img == highlighted_image:
colors.append('#FF4757') # Bright red for selected
else:
colors.append('#3742fa') # Beautiful blue for others
# Create hover text with all details
hover_text = []
for _, row in df_sorted.iterrows():
text_lines = [f"{row['clean_image']}"]
for col in df.columns:
if col != 'image':
text_lines.append(f"{col}: {row[col]}")
hover_text.append("
".join(text_lines))
fig = go.Figure(data=[
go.Bar(
x=df_sorted['clean_image'],
y=df_sorted[selected_class],
marker_color=colors,
text=df_sorted[selected_class],
textposition='outside',
hovertemplate='%{customdata}',
customdata=hover_text,
name=selected_class
)
])
# Update layout for better appearance
title_text = f'{selected_class} Distribution'
if highlighted_image:
title_text += ' (Red = Selected Image)'
# Determine if we need to rotate labels
rotation_angle = 45 if len(df_sorted) > 2 else 0
fig.update_layout(
title=dict(
text=title_text,
x=0.5,
xanchor='center',
font=dict(size=18, color='#2c3e50', family='Arial Black')
),
xaxis_title='Images',
yaxis_title=f'{selected_class} Count',
height=500,
showlegend=False,
xaxis=dict(
tickangle=rotation_angle,
tickfont=dict(size=10 if rotation_angle > 0 else 12)
),
yaxis=dict(
gridcolor='rgba(128,128,128,0.3)',
zerolinecolor='rgba(128,128,128,0.5)'
),
plot_bgcolor='rgba(248,249,250,0.8)',
paper_bgcolor='white',
margin=dict(
b=100 if rotation_angle > 0 else 60, # More bottom margin for rotated labels
t=80,
l=60,
r=60
)
)
return fig
def create_batch_detail_chart(image_name):
"""Create beautiful detail chart without text labels - hover shows the numbers"""
df = get_batch_data()
if df.empty:
fig = go.Figure()
fig.add_annotation(text="No data available", x=0.5, y=0.5,
font=dict(size=18, color='#666'))
fig.update_layout(title="No Data", height=450)
return fig
if not image_name:
fig = go.Figure()
fig.add_annotation(
text="š Select an image from dropdown below
to see detailed breakdown",
xref="paper", yref="paper",
x=0.5, y=0.5, xanchor='center', yanchor='middle',
showarrow=False, font=dict(size=18, color='#666')
)
fig.update_layout(
title="Image Breakdown",
height=450,
showlegend=False,
plot_bgcolor='rgba(248,249,250,0.8)',
paper_bgcolor='white'
)
return fig
# Get data for selected image
if image_name not in df['image'].values:
fig = go.Figure()
fig.add_annotation(text=f"Image {image_name} not found", x=0.5, y=0.5,
font=dict(size=18, color='#666'))
fig.update_layout(title="Image Not Found", height=450)
return fig
image_data = df[df['image'] == image_name].iloc[0]
# Get all class columns (exclude 'image')
class_columns = [col for col in df.columns if col != 'image']
# Beautiful color scheme
if set(class_columns) == {'Ripe', 'Unripe'}:
color_mapping = {
'Ripe': '#6c5ce7', # Beautiful purple for ripe
'Unripe': '#00b894' # Beautiful green for unripe
}
else:
color_mapping = {
'Flower': '#fdcb6e', # Golden yellow
'Green': '#00b894', # Emerald green
'Red': '#e17055', # Coral red
'Turning': '#fd79a8' # Pink
}
traces = []
bottom = 0
for cls in class_columns:
value = image_data[cls]
if value > 0:
traces.append(go.Bar(
x=['Counts'],
y=[value],
name=cls,
base=[bottom],
marker_color=color_mapping.get(cls, '#74b9ff'),
# Removed text and textposition - clean look with hover only
hovertemplate=f'{cls}: {value}'
))
bottom += value
if not traces:
fig = go.Figure()
fig.add_annotation(text=f"No detections in {image_name.replace('.jpg', '')}",
x=0.5, y=0.5, font=dict(size=18, color='#666'))
fig.update_layout(title=f'Breakdown: {image_name.replace(".jpg", "")}', height=450)
return fig
fig = go.Figure(data=traces)
# Create metrics text
metrics_text = ""
if 'Ripe' in df.columns and 'Unripe' in df.columns:
ripe = image_data['Ripe']
unripe = image_data['Unripe']
total = ripe + unripe
if total > 0:
ripe_pct = (ripe / total) * 100
metrics_text = f"šÆ Ripeness: {ripe_pct:.1f}%"
# Clean image name for title
clean_name = image_name.replace('.jpg', '').replace('.jpeg', '').replace('.png', '')
fig.update_layout(
title=dict(
text=f'Image: {clean_name}',
y=0.92,
x=0.5,
xanchor='center',
font=dict(size=12, color='#2c3e50', family='Arial Black')
),
barmode='stack',
height=450,
showlegend=True,
xaxis=dict(showticklabels=False),
yaxis_title='Count',
plot_bgcolor='rgba(248,249,250,0.8)',
paper_bgcolor='white',
font=dict(family='Arial', size=14, color='#2c3e50'),
legend=dict(
orientation='h',
yanchor='top',
y=1.15,
xanchor='center',
x=0.5,
bgcolor='rgba(255,255,255,0.9)',
bordercolor='rgba(116,185,255,0.5)',
borderwidth=1,
font=dict(size=12)
),
margin=dict(r=50, t=100, b=50, l=50)
)
# Add metrics annotation if available
if metrics_text:
fig.add_annotation(
text=metrics_text,
xref="paper", yref="paper",
x=0.02, y=0.02,
xanchor='left', yanchor='bottom',
showarrow=False,
font=dict(size=14, color='#2c3e50', family='Arial Black'),
bgcolor="rgba(255,255,255,0.9)",
bordercolor="rgba(116,185,255,0.5)",
borderwidth=2,
borderpad=8
)
return fig
def create_batch_dropdown_choices(selected_class):
"""Create dropdown choices for batch visualization"""
df = get_batch_data()
if df.empty or selected_class not in df.columns:
return []
df_sorted = df.sort_values(by=selected_class, ascending=False)
choices = []
for i, (_, row) in enumerate(df_sorted.iterrows()):
image_name = row['image']
count = row[selected_class]
choices.append(f"#{i+1} {image_name} ({selected_class}: {count})")
return choices
def extract_batch_image_name(dropdown_choice):
"""Extract image name from dropdown choice"""
if not dropdown_choice:
return None
parts = dropdown_choice.split(' ')
if len(parts) >= 2:
return parts[1]
return None
def create_batch_metrics(selected_image=None):
"""Create metrics for batch analysis"""
df = get_batch_data()
if df.empty:
return "No data available"
# Check if this is blueberry data (has Ripe/Unripe columns)
if 'Ripe' in df.columns and 'Unripe' in df.columns:
if selected_image:
# Metrics for specific image
image_row = df[df['image'] == selected_image]
if image_row.empty:
return f"No data for {selected_image}"
ripe = image_row['Ripe'].iloc[0]
unripe = image_row['Unripe'].iloc[0]
total = ripe + unripe
if total == 0:
return f"**{selected_image}**\n\nNo blueberries detected"
ripe_pct = (ripe / total) * 100
unripe_pct = (unripe / total) * 100
return f"""**{selected_image} Metrics**
š« **Total Blueberries:** {total}
š¦ **Ripe:** {ripe} ({ripe_pct:.1f}%)
š¤ **Unripe:** {unripe} ({unripe_pct:.1f}%)
š **Ripeness Index:** {ripe_pct:.1f}%"""
else:
# Overall metrics
total_ripe = df['Ripe'].sum()
total_unripe = df['Unripe'].sum()
total_berries = total_ripe + total_unripe
if total_berries == 0:
return "No blueberries detected"
ripe_pct = (total_ripe / total_berries) * 100
return f"""**Overall Blueberry Metrics**
š **Total Images:** {len(df)}
š« **Total Blueberries:** {total_berries}
š¦ **Total Ripe:** {total_ripe} ({ripe_pct:.1f}%)
š¤ **Total Unripe:** {total_unripe}
š **Average per Image:** {total_berries/len(df):.1f}
šÆ **Overall Ripeness:** {ripe_pct:.1f}%"""
else:
# Strawberry metrics
if selected_image:
return f"**Selected:** {selected_image}"
else:
return f"""**Strawberry Batch Analysis**
š **Total Images:** {len(df)}
š **Classes Available:** {', '.join([col for col in df.columns if col != 'image'])}"""
def update_batch_class_selection(selected_class):
"""Update everything when class selection changes (like test.py)"""
df = get_batch_data()
if df.empty:
empty_fig = go.Figure()
empty_fig.add_annotation(text="No batch data available", x=0.5, y=0.5)
empty_fig.update_layout(title="No Data", height=400)
return (
gr.update(choices=[], visible=False),
empty_fig,
empty_fig,
"ā ļø No batch data available. Please run batch detection first."
)
# Check if selected class exists in data
available_classes = get_available_classes_dynamic()
if selected_class not in available_classes:
if available_classes:
selected_class = available_classes[0] # Use first available class
else:
empty_fig = go.Figure()
empty_fig.add_annotation(text="No classes detected", x=0.5, y=0.5)
empty_fig.update_layout(title="No Data", height=400)
return (
gr.update(choices=[], visible=False),
empty_fig,
empty_fig,
"No classes detected in batch data"
)
choices = create_batch_dropdown_choices(selected_class)
histogram = create_batch_histogram_plotly(selected_class) # Use Plotly version
detail_chart = create_batch_detail_chart(None) # Start with placeholder
metrics = create_batch_metrics()
return (
gr.update(choices=choices, value=choices[0] if choices else None, visible=True),
histogram,
detail_chart,
metrics
)
def update_batch_image_selection(selected_class, dropdown_choice):
"""Update charts when image selection changes (like test.py)"""
if not dropdown_choice:
histogram = create_batch_histogram_plotly(selected_class) # Use Plotly version
detail_chart = create_batch_detail_chart(None)
metrics = create_batch_metrics()
return histogram, detail_chart, metrics
image_name = extract_batch_image_name(dropdown_choice)
histogram = create_batch_histogram_plotly(selected_class, image_name) # Use Plotly version
detail_chart = create_batch_detail_chart(image_name)
metrics = create_batch_metrics(image_name)
return histogram, detail_chart, metrics
def initialize_batch_visualization():
"""Initialize batch visualization after data is loaded"""
df = get_batch_data()
if df.empty:
return gr.update(visible=False), gr.update(visible=False)
# Get available classes dynamically from actual data
available_classes = [col for col in df.columns if col != 'image']
if available_classes:
default_class = available_classes[0]
# Use the actual detected classes directly (not hardcoded)
return (
gr.update(choices=available_classes, value=default_class, visible=True),
gr.update(visible=True)
)
return gr.update(visible=False), gr.update(visible=False)
def debug_create_batch_histogram(selected_class, highlighted_image=None):
"""Debug version of create histogram"""
print(f"š DEBUG: Creating histogram for class: {selected_class}")
df = get_batch_data()
print(f"š DEBUG: DataFrame shape: {df.shape}")
print(f"š DEBUG: DataFrame columns: {list(df.columns)}")
print(f"š DEBUG: DataFrame head:\n{df.head()}")
if df.empty:
print("ā DEBUG: DataFrame is empty!")
fig = go.Figure()
fig.add_annotation(text="DEBUG: No data available", x=0.5, y=0.5)
fig.update_layout(title="DEBUG: No Data", height=400)
return fig
if selected_class not in df.columns:
print(f"ā DEBUG: Class '{selected_class}' not in columns: {list(df.columns)}")
fig = go.Figure()
fig.add_annotation(text=f"DEBUG: Class {selected_class} not found", x=0.5, y=0.5)
fig.update_layout(title="DEBUG: Class Not Found", height=400)
return fig
print(f"ā
DEBUG: Class '{selected_class}' found in data")
df_sorted = df.sort_values(by=selected_class, ascending=False)
print(f"š DEBUG: Sorted data:\n{df_sorted[[selected_class, 'image']].head()}")
# Check if there are any non-zero values
non_zero_count = (df_sorted[selected_class] > 0).sum()
print(f"š DEBUG: Non-zero values in {selected_class}: {non_zero_count}")
print(f"š DEBUG: Value range: {df_sorted[selected_class].min()} to {df_sorted[selected_class].max()}")
# Create colors - highlight selected image
colors = []
for img in df_sorted['image']:
if img == highlighted_image:
colors.append('#FF6B6B') # Red for selected
else:
colors.append('#4ECDC4') # Teal for others
print(f"š DEBUG: Creating plotly figure with {len(df_sorted)} bars")
try:
fig = go.Figure(data=[
go.Bar(
x=df_sorted['image'].tolist(),
y=df_sorted[selected_class].tolist(),
marker_color=colors,
text=df_sorted[selected_class].tolist(),
textposition='outside',
hovertemplate='%{x}
' +
f'{selected_class}: %{{y}}
' +
''
)
])
fig.update_layout(
title=f'DEBUG: {selected_class} Distribution',
xaxis_title='Images',
yaxis_title=f'{selected_class} Count',
height=400,
xaxis=dict(tickangle=45),
showlegend=False
)
print("ā
DEBUG: Successfully created plotly figure")
return fig
except Exception as e:
print(f"ā DEBUG: Error creating plotly figure: {str(e)}")
fig = go.Figure()
fig.add_annotation(text=f"DEBUG ERROR: {str(e)}", x=0.5, y=0.5)
fig.update_layout(title="DEBUG: Error", height=400)
return fig