jurgenbollo commited on
Commit
25b8bab
·
verified ·
1 Parent(s): b6e56ec

Update src/streamlit_app1.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app1.py +16 -51
src/streamlit_app1.py CHANGED
@@ -2,71 +2,30 @@ import streamlit as st
2
  import tensorflow as tf
3
  from PIL import Image
4
  import numpy as np
5
- from tensorflow.keras.applications.resnet50 import preprocess_input, ResNet50
6
 
7
  # Chargement des modèles avec message
8
  with st.spinner("Chargement des modèles..."):
9
  try:
10
  model_infect = tf.keras.models.load_model("src/exo1.keras")
11
  model_animals = tf.keras.models.load_model("src/exo2.keras")
12
- st.success("Modèles chargés avec succès ")
13
  except Exception as e:
14
  st.error(f"Erreur lors du chargement des modèles : {e}")
15
  st.stop()
16
 
17
- # Afficher résumé et input shape modèle infecté
18
- st.write("### Modèle Infecté - Résumé :")
19
- model_infect.summary(print_fn=lambda x: st.text(x))
20
- input_shape_infect = model_infect.input_shape # tuple
21
-
22
- st.write(f"**Input shape attendu (modèle infecté) :** {input_shape_infect}")
23
-
24
- # Initialisation extracteur features ResNet50 si besoin (pas de top, pooling avg)
25
- feature_extractor = ResNet50(weights='imagenet', include_top=False, pooling='avg')
26
-
27
  # Fonction de prédiction
28
  def predict(model, img_array, classes):
29
  prediction = model.predict(img_array)
30
  index = np.argmax(prediction)
31
  return classes[index], float(prediction[0][index])
32
 
33
- # Prétraitement pour le modèle infecté
34
- def preprocess_infect(image):
35
- # Si input shape 4D, exemple (None, 128, 128, 3)
36
- if len(input_shape_infect) == 4:
37
- # On adapte la taille selon ce que le modèle attend (sauf None)
38
- target_size = input_shape_infect[1:4]
39
- image = image.resize((target_size[1], target_size[0])) # (width, height)
40
- img_array = np.array(image) / 255.0
41
- img_array = np.expand_dims(img_array, axis=0)
42
- return img_array.astype(np.float32)
43
-
44
- # Si input shape 2D, exemple (None, 2048) => extraction features
45
- elif len(input_shape_infect) == 2:
46
- # On doit extraire les features avec ResNet50
47
- image = image.resize((224, 224))
48
- img_array = np.array(image)
49
- img_array = np.expand_dims(img_array, axis=0)
50
- img_array = preprocess_input(img_array)
51
- features = feature_extractor.predict(img_array)
52
- return features.astype(np.float32)
53
-
54
- else:
55
- st.error("Format d'entrée du modèle infecté non supporté.")
56
- st.stop()
57
-
58
- # Prétraitement pour modèle animaux (image classique)
59
- def preprocess_animals(image):
60
- image = image.resize((128, 128))
61
- img_array = np.array(image) / 255.0
62
- img_array = np.expand_dims(img_array, axis=0)
63
- return img_array.astype(np.float32)
64
-
65
  # Interface utilisateur
66
- st.title("🧠 Classification d’images")
67
 
 
68
  option = st.selectbox("Choisissez le modèle :", ("Infecté / Non Infecté", "Chat / Chien"))
69
 
 
70
  uploaded_file = st.file_uploader("Uploader une image", type=["jpg", "jpeg", "png"])
71
 
72
  if uploaded_file:
@@ -74,19 +33,25 @@ if uploaded_file:
74
  image = Image.open(uploaded_file).convert("RGB")
75
  st.image(image, caption="Image chargée", use_container_width=True)
76
 
 
77
  if st.button("Prédire"):
78
  with st.spinner("Prétraitement de l’image..."):
79
  if option == "Infecté / Non Infecté":
80
- img_array = preprocess_infect(image)
 
 
81
  else:
82
- img_array = preprocess_animals(image)
 
 
 
 
 
83
 
84
  with st.spinner("Prédiction en cours..."):
85
- if option == "Infecté / Non Infecté":
86
- label, confidence = predict(model_infect, img_array, ["Non Infecté", "Infecté"])
87
- else:
88
- label, confidence = predict(model_animals, img_array, ["Chat", "Chien"])
89
 
90
  st.success(f"✅ Classe prédite : **{label}** avec une confiance de **{confidence:.2f}**")
 
91
  except Exception as e:
92
  st.error(f"❌ Erreur lors du traitement : {e}")
 
2
  import tensorflow as tf
3
  from PIL import Image
4
  import numpy as np
 
5
 
6
  # Chargement des modèles avec message
7
  with st.spinner("Chargement des modèles..."):
8
  try:
9
  model_infect = tf.keras.models.load_model("src/exo1.keras")
10
  model_animals = tf.keras.models.load_model("src/exo2.keras")
11
+ st.success("Modèles chargés avec succès ")
12
  except Exception as e:
13
  st.error(f"Erreur lors du chargement des modèles : {e}")
14
  st.stop()
15
 
 
 
 
 
 
 
 
 
 
 
16
  # Fonction de prédiction
17
  def predict(model, img_array, classes):
18
  prediction = model.predict(img_array)
19
  index = np.argmax(prediction)
20
  return classes[index], float(prediction[0][index])
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  # Interface utilisateur
23
+ st.title("Classification d’images")
24
 
25
+ # Choix du modèle
26
  option = st.selectbox("Choisissez le modèle :", ("Infecté / Non Infecté", "Chat / Chien"))
27
 
28
+ # Upload d'image
29
  uploaded_file = st.file_uploader("Uploader une image", type=["jpg", "jpeg", "png"])
30
 
31
  if uploaded_file:
 
33
  image = Image.open(uploaded_file).convert("RGB")
34
  st.image(image, caption="Image chargée", use_container_width=True)
35
 
36
+ # Bouton pour déclencher la prédiction
37
  if st.button("Prédire"):
38
  with st.spinner("Prétraitement de l’image..."):
39
  if option == "Infecté / Non Infecté":
40
+ image = image.resize((50, 50))
41
+ model = model_infect
42
+ classes = ["Non Infecté", "Infecté"]
43
  else:
44
+ image = image.resize((128, 128))
45
+ model = model_animals
46
+ classes = ["Chat", "Chien"]
47
+
48
+ img_array = np.array(image) / 255.0
49
+ img_array = np.expand_dims(img_array, axis=0)
50
 
51
  with st.spinner("Prédiction en cours..."):
52
+ label, confidence = predict(model, img_array, classes)
 
 
 
53
 
54
  st.success(f"✅ Classe prédite : **{label}** avec une confiance de **{confidence:.2f}**")
55
+
56
  except Exception as e:
57
  st.error(f"❌ Erreur lors du traitement : {e}")