import os
import sys
import streamlit as st
import numpy as np
from PIL import Image
import cv2
import numpy as np
import matplotlib.pyplot as plt
MODEL_REPO = "FERJI/DetectNano2"
KF_API_KEY = os.getenv("KF_API_KEY")
# Clonage automatique du repo Hugging Face
if not os.path.exists("DetectNano2"):
os.system(f"git clone https://user:{KF_API_KEY}@huggingface.co/{MODEL_REPO}")
# Vérifier et importer le code caché
if os.path.exists("DetectNano2/detectnano_code2.py"):
sys.path.append("DetectNano2")
from detectnano_code2 import DetectNanoApp
else:
st.error("⚠️ Erreur : `detectnano_code2.py` introuvable dans le repository cloné !")
sys.exit(1)
with st.sidebar.expander("ℹ️ About This App", expanded=False):
st.markdown(
"""
🟢 **DetectNano - Version 2.0 (April 2025)**
An AI-powered tool for the automated detection of polymer nanostructures in TEM images.
➡️ **Try it now** for spherical morphology as a proof of concept!
---
⚠ **License:**
CC BY-NC-ND 4.0
⚠ **Disclaimer:**
- Due to the **limited and specific dataset used during training**, some detection errors may occur.
- A **more robust version** with improved accuracy and extended capabilities will be released **soon**.
---
🚀 **Future Developments:**
Follow our roadmap and updates on GitHub:
🔗 [GitHub Repository](https://github.com/ChemDoc/DetectNano)
📌 **Citation:**
**Zenodo DOI:** [https://doi.org/10.5281/zenodo.14995364](https://doi.org/10.5281/zenodo.14995364)
"""
)
# Interface utilisateur
st.header('DetectNano V.2')
uploaded_file = st.sidebar.file_uploader("📂 Upload an image...", type=["jpg", "png", "jpeg", "tif"])
scale_bar_length_nm = st.sidebar.number_input('Real scale bar length (nm)', min_value=1, value=200)
thresh = st.sidebar.slider('Detection Confidence Threshold', 0.1, 1.0, 0.3)
thickness = st.sidebar.slider("Square thickness", min_value=1, max_value=10, value=3)
st.sidebar.markdown("### Colors")
color_class_5 = st.sidebar.color_picker("Particles", "#0000FF")
color_class_4 = st.sidebar.color_picker("Scale bar", "#FF0000")
def hex_to_bgr(hex_color: str) -> tuple:
"""Convertit un code couleur hexadécimal (#RRGGBB) en BGR pour OpenCV."""
hex_color = hex_color.strip().lstrip('#')
if len(hex_color) != 6:
raise ValueError(f"Couleur hex invalide : '{hex_color}'")
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
return (b, g, r) # BGR pour OpenCV
button_container = st.sidebar.empty()
run_button = button_container.button(
'🚀 Run Detection',
key='run_button',
help='Click to run detection',
disabled=False
)
def denormalize_box(box, width, height):
x1, y1, x2, y2 = box
return [int(x1 * width), int(y1 * height), int(x2 * width), int(y2 * height)]
def visualize_and_analyze(image, labels, boxes, scores, scale_bar_length_nm, scale_bar_pixels,thickness,class_colors):
if 5 not in labels:
st.markdown(
"""
❌ No particles were detected.
The analysis was skipped because class 5 (particles) was not found among the detections.
""", unsafe_allow_html=True)
return
height, width, _ = image.shape
image1 = image.copy()
# Définir les couleurs et labels des classes
#class_colors = {5: (0, 0, 255), 4: (255, 0, 0)}
class_labels = {5: "P", 4: "scal_bar"}
for i in range(len(boxes)):
box = denormalize_box(boxes[i], width, height)
label = int(labels[i])
color = class_colors.get(label, (255, 255, 255))
cv2.rectangle(image, (box[0], box[1]), (box[2], box[3]), color , thickness)
col1, col2 = st.columns(2)
image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB)
col1.image(image1, caption='Uploaded Image.', use_container_width=True)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
col2.image(image, caption='Analyzed Image', use_container_width=True)
# Histogramme de confiance
sphere_scores = [s for l, s in zip(labels, scores) if l == 5]
fig, ax = plt.subplots(figsize=(10, 6))
mean_score = np.mean(sphere_scores)
std_dev = np.std(sphere_scores)
bgr = class_colors[5]
rgb = (bgr[2], bgr[1], bgr[0]) # BGR → RGB
normalized_rgb = tuple(c / 255 for c in rgb)
ax.hist(sphere_scores, bins=10, color=normalized_rgb, alpha=1, range=(0, 1))
ax.set_xlim(0, 1)
ax.set_ylim(0, max(10, len(sphere_scores) // 2))
ax.set_title(f"{len(sphere_scores)} particles detected\nConfidence Score Distribution: {mean_score:.2f} ± {std_dev:.2f}")
ax.set_xlabel("Confidence Score")
ax.set_ylabel("Frequency")
ax.grid(axis='y', linestyle='--', alpha=0.1)
plt.tight_layout()
st.pyplot(fig)
if scale_bar_pixels:
pixel_to_nm = scale_bar_length_nm / scale_bar_pixels
object_sizes_nm = {cls: [] for cls in set(labels) if cls != 4}
for i, label in enumerate(labels):
if label != 4:
x1, y1, x2, y2 = denormalize_box(boxes[i], width, height)
dim = ((x2 - x1) + (y2 - y1)) / 2 * pixel_to_nm
object_sizes_nm[label].append(dim)
fig2, ax2 = plt.subplots(figsize=(10, 6))
for cls, values in object_sizes_nm.items():
ax2.hist(values, bins=10, width=4, alpha=1, color=normalized_rgb)
ax2.set_xlabel("Diameter (nm)")
ax2.set_ylabel("Number of Detections")
mean_size = np.mean([v for l in object_sizes_nm.values() for v in l])
std_size = np.std([v for l in object_sizes_nm.values() for v in l])
ax2.set_title(f"Diameter: {mean_size:.1f} ± {std_size:.1f} nm")
ax2.legend()
ax2.grid(axis='y', linestyle='--', alpha=0.1)
plt.tight_layout()
st.pyplot(fig2)
else:
col1, col2 = st.columns([2, 3])
with col1:
st.markdown(
"""
Warning:
Scale bar not found.
For optimal detection, please use a black scale bar on a white background as per the model's requirements.
""", unsafe_allow_html=True)
with col2:
st.image("DetectNano2/proper_scale_bar.png", caption="Example of a proper scale bar", width=300)
app = DetectNanoApp()
if run_button and uploaded_file is not None:
image = np.array(Image.open(uploaded_file))
if image.shape[2] == 4:
image = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR)
height, width, _ = image.shape
image_name = os.path.splitext(uploaded_file.name)[0]
message, labels, boxes, scale_bar_pixels, scores= app.process(image, image_name, scale_bar_length_nm, thresh, height, width)
if message:
st.warning(message)
else:
class_colors = {
5: hex_to_bgr(color_class_5),
4: hex_to_bgr(color_class_4)
}
visualize_and_analyze(image, labels, boxes, scores, scale_bar_length_nm, scale_bar_pixels,thickness,class_colors)