File size: 10,156 Bytes
85a57d9
 
 
 
0b47556
 
 
7acea35
0b47556
 
 
 
 
da457da
0b47556
 
 
 
 
 
 
 
 
 
 
 
 
 
e5d9054
0b47556
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5d9054
 
0b47556
e5d9054
0b47556
 
 
da457da
 
9442e1b
 
da457da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9442e1b
 
 
9190d9d
9442e1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9190d9d
 
dced319
 
9190d9d
 
 
 
 
 
 
9eace46
9190d9d
 
 
 
 
 
 
 
 
 
 
 
dced319
 
c56c9e3
 
dced319
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b47556
7ad609c
 
 
 
 
 
 
c56c9e3
 
54793f1
c56c9e3
 
 
 
 
 
 
 
da457da
c56c9e3
 
 
 
 
 
 
 
e751817
 
113496e
 
 
def7607
113496e
c56c9e3
1cb0811
c56c9e3
 
54793f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b872464
3139489
54793f1
 
744139f
3139489
432c2f5
54793f1
 
 
f757536
5b383d0
c56c9e3
9442e1b
0b47556
e751817
5b383d0
c56c9e3
0b47556
 
 
 
c846ff6
0b47556
 
c56c9e3
0b47556
1549d07
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import gradio as gr
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.figure import Figure

# Charger ton modèle
model = tf.keras.models.load_model("MobileNetV2_UL_ML_c3_l0_acc97_auc100_20251012_161415.keras")

# Classes
classes = ["Cubisme", "Expressionnisme", "Post-impressionnisme"]

# Fonction de prédiction avec graphique personnalisé
"""def predire(image):
    # Prédiction
    image_resized = tf.image.resize(image, (224, 224)) / 255.0
    preds = model.predict(tf.expand_dims(image_resized, axis=0))[0]
    
    # Créer le graphique avec matplotlib
    fig = Figure(figsize=(10, 6))
    ax = fig.add_subplot(111)
    
    # Trier par probabilité décroissante
    sorted_indices = np.argsort(preds)[::-1]
    sorted_classes = [classes[i] for i in sorted_indices]
    sorted_probs = [preds[i] for i in sorted_indices]
    
    # Définir les couleurs : vert si > 50%, bleu sinon
    colors = ['#2ecc71' if prob >= 0.5 else '#bdc3c7' for prob in sorted_probs]
    
    # Créer le bar plot horizontal
    bars = ax.barh(sorted_classes, sorted_probs, color=colors, edgecolor='black', linewidth=1.5)
    
    # Ajouter les pourcentages sur les barres
    for i, (bar, prob) in enumerate(zip(bars, sorted_probs)):
        width = bar.get_width()
        label_x = width + 0.02 if width < 0.9 else width - 0.02
        ha = 'left' if width < 0.9 else 'right'
        text_color = 'black' if width < 0.9 else 'white'
        ax.text(label_x, bar.get_y() + bar.get_height()/2, 
                f'{prob*100:.1f}%', 
                ha=ha, va='center', fontsize=12, fontweight='bold', color=text_color)
    
    # Configuration du graphique
    ax.set_xlabel('Probabilité', fontsize=12, fontweight='bold')
    ax.set_xlim(0, 1.0)
    ax.set_title('Probabilités par mouvement pictural', fontsize=14, fontweight='bold', pad=20)
    ax.grid(axis='x', alpha=0.3, linestyle='--')
    ax.set_axisbelow(True)
    
    # Légende
    from matplotlib.patches import Patch
    legend_elements = [
        Patch(facecolor='#2ecc71', edgecolor='black', label='≥ 50%'),
        Patch(facecolor='#bdc3c7', edgecolor='black', label='< 50%')
    ]
    ax.legend(handles=legend_elements, loc='upper right', fontsize=10)
    
    fig.tight_layout()
    
    return fig"""

# Solution 2
"""def predire(image):
    image_resized = tf.image.resize(image, (224, 224)) / 255.0
    preds = model.predict(tf.expand_dims(image_resized, axis=0))[0]

    sorted_indices = np.argsort(preds)[::-1]
    sorted_classes = [classes[i] for i in sorted_indices]
    sorted_probs = [preds[i] for i in sorted_indices]
    colors = ['#2ecc71' if prob >= 0.5 else '#bdc3c7' for prob in sorted_probs]

    fig = Figure(figsize=(4, 3))  # Format compact adapté mobile
    ax = fig.add_subplot(111)

    # Barres verticales
    bars = ax.bar(sorted_classes, sorted_probs, color=colors, edgecolor='black', linewidth=1.5)

    # Ajout pourcentages
    for bar, prob in zip(bars, sorted_probs):
        ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.03, 
                f"{prob*100:.1f}%", ha='center', va='bottom', fontsize=13, fontweight='bold', color='black')

    ax.set_ylabel('Probabilité', fontsize=15, fontweight='bold')
    ax.set_ylim(0, 1.0)
    ax.set_title('Probabilités par mouvement pictural', fontsize=16, fontweight='bold', pad=20)
    ax.grid(axis='y', alpha=0.15, linestyle='--')
    ax.set_axisbelow(True)

    # Titres inclinés à 45°
    ax.set_xticklabels(sorted_classes, rotation=45, ha='right', fontsize=15, fontweight='bold')
    fig.tight_layout()

    return fig"""

# Solution 3 : Passer par Plotly
"""import plotly.graph_objects as go

def predire(image):
    image_resized = tf.image.resize(image, (224, 224)) / 255.0
    preds = model.predict(tf.expand_dims(image_resized, axis=0))[0]

    sorted_indices = np.argsort(preds)[::-1]
    sorted_classes = [classes[i] for i in sorted_indices]
    sorted_probs = [preds[i] for i in sorted_indices]
    colors = ['#2ecc71' if prob >= 0.5 else '#bdc3c7' for prob in sorted_probs]

    fig = go.Figure(go.Bar(
        x=sorted_classes,
        y=sorted_probs,
        text=[f"{p*100:.1f}%" for p in sorted_probs],
        marker=dict(color=colors, line=dict(color='black', width=1)),
        textposition='auto',
    ))
    fig.update_layout(
        xaxis=dict(tickangle=45, tickfont=dict(size=17)),
        yaxis=dict(range=[0,1], title='Probabilité', tickfont=dict(size=17)),
        title="Probabilités par mouvement pictural",
        margin=dict(l=15, r=15, t=40, b=25),
        height=280,
        font=dict(size=17)
    )
    return fig"""

# Solution avec le graphique plus haut (ADAPTER LA HAUTEUR)
"""def predire(image):
    image_resized = tf.image.resize(image, (224, 224)) / 255.0
    preds = model.predict(tf.expand_dims(image_resized, axis=0))[0]
    sorted_indices = np.argsort(preds)[::-1]
    sorted_classes = [classes[i] for i in sorted_indices]
    sorted_probs = [preds[i] for i in sorted_indices]
    colors = ['#2ecc71' if prob >= 0.5 else '#bdc3c7' for prob in sorted_probs]

    fig = Figure(figsize=(12, 4.2))  # hauteur augmentée
    ax = fig.add_subplot(111)
    bars = ax.bar(sorted_classes, sorted_probs, color=colors, edgecolor='black', linewidth=1.5)

    for bar, prob in zip(bars, sorted_probs):
        ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.035, 
                f"{prob*100:.1f}%", ha='center', va='bottom', fontsize=12, color='black', fontweight='bold')

    ax.set_ylabel('Probabilité', fontsize=14, fontweight='bold')
    ax.set_ylim(0, 1)
    ax.set_title("Probabilités par mouvement pictural", fontsize=14, fontweight='bold', pad=20)
    ax.set_xticklabels(sorted_classes, rotation=45, ha='right', fontsize=13, fontweight='bold')
    fig.tight_layout(pad=2.0)
    return fig"""

# Façon 5 uniquement sur le texte mais ça donne une erreur
"""def predire(image):
    image_resized = tf.image.resize(image, (224, 224)) / 255.0
    preds = model.predict(tf.expand_dims(image_resized, axis=0))[0]
    sorted_indices = np.argsort(preds)[::-1]
    sorted_classes = [classes[i] for i in sorted_indices]
    sorted_probs = [preds[i] for i in sorted_indices]

    # HTML pour Gradio : barres remplies & label
    bars = []
    for cls, prob in zip(sorted_classes, sorted_probs):
        color = "#2ecc71" if prob >= 0.5 else "#bdc3c7"
        bars.append(f'''
        <div style="background:linear-gradient(90deg,{color} {prob*100:.1f}%,#fff {prob*100:.1f}%);padding:6px 0;margin:5px 0;border-radius:4px;">
            <span style="padding-left:12px;font-size:15px;font-weight:bold;">{cls} — {prob*100:.1f} %</span>
        </div>''')
    return gr.HTML("".join(bars))

demo = gr.Interface(
    fn=predire,
    inputs=gr.Image(type="numpy", label="Importer une œuvre"),
    outputs=[gr.Image(label="Input"), gr.HTML(label="Résultats")],
    title="🎨 Classification de style pictural",
    examples=None,
    theme=gr.themes.Soft()
)"""

"""import plotly.graph_objects as go

def predire(image):
    image_resized = tf.image.resize(image, (224, 224)) / 255.0
    preds = model.predict(tf.expand_dims(image_resized, axis=0))[0]
    sorted_indices = np.argsort(preds)[::-1]
    sorted_classes = [classes[i] for i in sorted_indices]
    sorted_probs = [preds[i] for i in sorted_indices]
    colors = ['#2ecc71' if p >= 0.5 else '#bdc3c7' for p in sorted_probs]

    fig = go.Figure(go.Bar(
        x=sorted_classes,
        y=sorted_probs,
        marker=dict(color=colors, line=dict(color='black', width=1)),
        text=[f"{p*100:.1f}%" for p in sorted_probs],
        textposition='auto'
    ))
    fig.update_layout(
        xaxis=dict(fixedrange=True, tickangle=45, tickfont=dict(size=15)),
        yaxis=dict(fixedrange=True, range=[0,1], title="Probabilité", tickfont=dict(size=14)),
        title=dict(
            text="Probabilités par mouvement pictural",
            y=0.95,  # remonte le titre pour laisser de l’espace
            pad=dict(b=50)  # espace (en px) sous le titre, ajuste à volonté
        ),
        margin=dict(l=20, r=20, t=32, b=46),
        height=500,
        font=dict(size=16)
    )


    # Pour placer le texte à l’intérieur des barres
    fig.show(config={'displayModeBar': False})
    return fig
"""

import plotly.graph_objects as go

def predire(image):
    image_resized = tf.image.resize(image, (224, 224)) / 255.0
    preds = model.predict(tf.expand_dims(image_resized, axis=0))[0]
    sorted_indices = np.argsort(preds)[::-1]
    sorted_classes = [classes[i] for i in sorted_indices]
    sorted_probs = [preds[i] for i in sorted_indices]
    colors = ['#2ecc71' if p >= 0.5 else '#bdc3c7' for p in sorted_probs]

    fig = go.Figure(go.Bar(
        x=sorted_classes,
        y=sorted_probs,
        marker=dict(color=colors, line=dict(color='black', width=1)),
        text=[f"{p*100:.1f}%" for p in sorted_probs],
        textposition='auto'
    ))

    fig.update_layout(
        xaxis=dict(fixedrange=True, tickangle=45, tickfont=dict(size=15), automargin=True),
        yaxis=dict(fixedrange=True, range=[0, 1], title="Probabilité", tickfont=dict(size=14)),
        title=dict(
            text="Probabilités par <br>mouvement pictural",
            y=0.90,
            pad=dict(b=30)
        ),
        margin=dict(l=20, r=20, t=0, b=60),  # marge top plus haute et bottom plus grande
        height=600,
        font=dict(size=13)
    )

    # Pour placer le texte à l’intérieur des barres
    fig.data[0].textfont = dict(color='black', size=14, family="Arial")
    fig.show(config={'displayModeBar': False})
    return fig

# Interface Gradio
# Exemple pour Plotly hors Gradio :

demo = gr.Interface(
    fn=predire,
    inputs=gr.Image(type="numpy", label="Importer une œuvre"),
    outputs=gr.Plot(label="Résultats de la classification"),
    title="🎨 Classification de style pictural",
    description="Upload une image et découvre le mouvement pictural estimé par le CNN. Les barres vertes indiquent une probabilité supérieure ou égale à 50%.",
    examples=None,
    theme=gr.themes.Soft()
)

demo.launch()