Spaces:
Sleeping

File size: 8,378 Bytes
fcc10cf
40e3ff5
99730e5
40e3ff5
79fb2c8
eff17b5
7371f3a
 
fcc10cf
09dd53d
624355e
fcc10cf
a067997
40e3ff5
 
09dd53d
a067997
dba936e
40e3ff5
dba936e
40e3ff5
dba936e
40e3ff5
cfc433d
091b467
fcc10cf
99730e5
35d0991
 
 
3e2fa12
35d0991
 
3e2fa12
35d0991
 
 
96fce02
35d0991
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a067997
ab08a12
99730e5
40e3ff5
 
0a07c56
99e77a0
 
 
8cd19f1
 
08019b0
99e77a0
08019b0
 
 
 
 
 
 
 
 
 
 
 
99e77a0
b474c86
 
 
 
 
 
b35c7e2
b474c86
 
b9713ee
 
10603aa
b9713ee
 
99e77a0
05c2fea
b9713ee
 
 
 
 
 
 
 
 
 
 
 
 
eff17b5
 
b9713ee
 
 
 
 
 
 
091b467
99e77a0
101f465
05c2fea
 
be60bdc
99e77a0
 
b9713ee
 
 
e7d875a
b9713ee
e7d875a
b9713ee
 
 
 
 
05c2fea
b9713ee
 
 
4b29243
 
 
f550997
 
b9713ee
 
 
 
 
 
 
 
 
 
 
 
05c2fea
 
b9713ee
05c2fea
b9713ee
 
 
 
 
f550997
4b29243
b9713ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
091b467
a067997
 
4973e55
1a3a365
 
afa3656
40e3ff5
eff17b5
a067997
 
 
 
9320321
 
 
 
 
 
 
99e77a0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
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(
                """
                <div style="
                    background-color: #f8d7da;
                    color: #721c24;
                    padding: 15px;
                    border-radius: 8px;
                    border: 1px solid #f5c6cb;
                    font-size: 16px;
                    width: 90%;
                    margin: 20px auto;
                    text-align: center;
                ">
                    ❌ <strong>No particles were detected.</strong><br>
                    The analysis was skipped because class <code>5</code> (particles) was not found among the detections.
                </div>
                """, 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(
                    """
                    <div style="
                        background-color: #FFF3CD;
                        color: #856404;
                        padding: 15px;
                        border-radius: 8px;
                        border: 1px solid #FFEEBA;
                        font-size: 16px;
                        width: 90%;
                    ">
                        <strong>Warning:</strong><br>
                        Scale bar not found.<br>
                        For optimal detection, please use a black scale bar on a white background as per the model's requirements.
                    </div>
                    """, 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)