Enoder commited on
Commit
ab4bd0c
·
verified ·
1 Parent(s): 7e864b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -122
app.py CHANGED
@@ -1,127 +1,99 @@
1
  import streamlit as st
2
  import numpy as np
3
  from PIL import Image
4
- import requests
5
- from io import BytesIO
6
  import random
7
  import time
8
-
9
- # Fonction pour télécharger une image aléatoire
10
- def download_random_image(animal):
11
- animal_images = {
12
- "chat": [
13
- "https://i.ibb.co/2FnDthw/IMG-6419.jpg",
14
- "https://i.ibb.co/QHpP9D4/IMG-6420.jpg",
15
- ],
16
- "chien": [
17
- "https://images.dog.ceo/breeds/hound-afghan/n02096585_1034.jpg",
18
- "https://dog.ceo/api/breeds/image/random"
19
- ],
20
- "cheval": [
21
- "https://cdn.pixabay.com/photo/2015/09/20/10/07/horse-557133_1280.jpg",
22
- "https://cdn.pixabay.com/photo/2018/05/07/17/24/horse-3380533_1280.jpg"
23
- ]
24
- }
25
-
26
- url = random.choice(animal_images[animal])
27
- try:
28
- response = requests.get(url)
29
- response.raise_for_status() # Vérifie si la requête a réussi
30
- img = Image.open(BytesIO(response.content)).resize((300, 300))
31
- return img
32
- except (requests.exceptions.RequestException, UnidentifiedImageError) as e:
33
- st.error(f"Erreur lors du téléchargement ou de l'ouverture de l'image : {e}")
34
- return None
35
-
36
- # Fonction pour transformer les pixels
37
- def transform_image(original_image, method):
38
- width, height = original_image.size
39
- img_array = np.array(original_image)
40
-
41
- # Crée une nouvelle image vide
42
- new_img_array = np.zeros_like(img_array)
43
-
44
- for x in range(width):
45
- for y in range(height):
46
- if method == "moyenne":
47
- # Moyenne des voisins
48
- neighbors = []
49
- for dx in [-1, 0, 1]:
50
- for dy in [-1, 0, 1]:
51
- if dx == 0 and dy == 0:
52
- continue
53
- nx, ny = x + dx, y + dy
54
- if 0 <= nx < width and 0 <= ny < height:
55
- neighbors.append(img_array[ny, nx])
56
- if neighbors:
57
- avg_color = np.mean(neighbors, axis=0)
58
- new_img_array[y, x] = avg_color
59
-
60
- elif method == "inversion":
61
- # Inversion des couleurs
62
- new_img_array[y, x] = 255 - img_array[y, x]
63
-
64
- elif method == "flou":
65
- # Filtre de flou simple
66
- neighbors = []
67
- for dx in [-1, 0, 1]:
68
- for dy in [-1, 0, 1]:
69
- nx, ny = x + dx, y + dy
70
- if 0 <= nx < width and 0 <= ny < height:
71
- neighbors.append(img_array[ny, nx])
72
- new_img_array[y, x] = np.mean(neighbors, axis=0)
73
-
74
- elif method == "luminosite":
75
- # Augmentation de la luminosité
76
- new_img_array[y, x] = np.clip(img_array[y, x] + 50, 0, 255)
77
-
78
- elif method == "detec_bords":
79
- # Détection des bords simple
80
- if x > 0 and y > 0 and x < width - 1 and y < height - 1:
81
- gx = (img_array[y-1, x+1] + 2 * img_array[y, x+1] + img_array[y+1, x+1] -
82
- img_array[y-1, x-1] - 2 * img_array[y, x-1] - img_array[y+1, x-1])
83
- gy = (img_array[y+1, x-1] + 2 * img_array[y+1, x] + img_array[y+1, x+1] -
84
- img_array[y-1, x-1] - 2 * img_array[y-1, x] - img_array[y-1, x+1])
85
- new_img_array[y, x] = np.clip(np.sqrt(gx**2 + gy**2), 0, 255)
86
-
87
- return Image.fromarray(new_img_array.astype('uint8'))
88
-
89
- # Interface Streamlit
90
- st.title("Transformateur d'Images")
91
- st.write("Choisissez un animal pour générer et transformer une image.")
92
-
93
- # Boutons pour les animaux
94
- col1, col2, col3 = st.columns(3)
95
-
96
- with col1:
97
- if st.button("Chat"):
98
- img = download_random_image("chat")
99
- if img:
100
- st.session_state.image = img
101
- st.image(img, caption="Image d'origine", use_column_width=True)
102
-
103
- with col2:
104
- if st.button("Chien"):
105
- img = download_random_image("chien")
106
- if img:
107
- st.session_state.image = img
108
- st.image(img, caption="Image d'origine", use_column_width=True)
109
-
110
- with col3:
111
- if st.button("Cheval"):
112
- img = download_random_image("cheval")
113
- if img:
114
- st.session_state.image = img
115
- st.image(img, caption="Image d'origine", use_column_width=True)
116
-
117
- # Sélection de la méthode de transformation
118
- method = st.selectbox("Choisissez une méthode de transformation", ["moyenne", "inversion", "flou", "luminosite", "detec_bords"])
119
-
120
- # Transformation de l'image
121
- if "image" in st.session_state:
122
- transformed_image = transform_image(st.session_state.image, method)
123
- st.image(transformed_image, caption="Image Transformée", use_column_width=True)
124
-
125
- # Bouton pour redémarrer le processus
126
- if st.button("Redémarrer"):
127
- st.session_state.image = None
 
1
  import streamlit as st
2
  import numpy as np
3
  from PIL import Image
 
 
4
  import random
5
  import time
6
+ import io
7
+
8
+ # Configuration de la page Streamlit
9
+ st.title("Générateur d'images d'animaux")
10
+ st.write("Choisissez un animal pour générer une image ou téléchargez une image à déchiffrer.")
11
+
12
+ # Initialisation des variables
13
+ image_data = []
14
+ validation_data = {}
15
+ auto_training_data = {}
16
+
17
+ # Fonction pour créer une image aléatoire
18
+ def create_image(label):
19
+ width, height = 300, 300
20
+ image = np.zeros((height, width, 3), dtype=np.uint8)
21
+
22
+ if label == "chat":
23
+ for i in range(height):
24
+ for j in range(width):
25
+ image[i, j] = [random.randint(150, 255), random.randint(150, 255), random.randint(150, 255)]
26
+ elif label == "chien":
27
+ for i in range(height):
28
+ for j in range(width):
29
+ image[i, j] = [random.randint(100, 200), random.randint(50, 150), random.randint(0, 100)]
30
+ elif label == "cheval":
31
+ for i in range(height):
32
+ for j in range(width):
33
+ image[i, j] = [random.randint(0, 50), random.randint(0, 50), random.randint(0, 50)]
34
+
35
+ return Image.fromarray(image)
36
+
37
+ # Fonction pour traiter l'image téléchargée
38
+ def process_uploaded_image(uploaded_file):
39
+ # Ouvrir l'image
40
+ image = Image.open(uploaded_file)
41
+ # Redimensionner l'image à 300x300
42
+ image = image.resize((300, 300))
43
+ return image
44
+
45
+ # Fonction pour gérer la validation des images
46
+ def validate_image(is_valid, label):
47
+ if is_valid:
48
+ validation_data[label] = validation_data.get(label, 0) + 1
49
+ else:
50
+ if label in validation_data:
51
+ del validation_data[label]
52
+
53
+ # Interface utilisateur
54
+ animal = st.radio("Sélectionnez un animal :", ("chat", "chien", "cheval"))
55
+ uploaded_file = st.file_uploader("Ou téléchargez une image (JPG, PNG)", type=["jpg", "jpeg", "png"])
56
+
57
+ if st.button("Générer une image"):
58
+ img = create_image(animal)
59
+ st.image(img, caption=f"Image générée pour un {animal}", use_column_width=True)
60
+
61
+ if st.button("Oui"):
62
+ validate_image(True, animal)
63
+ st.success("Image validée!")
64
+ elif st.button("Non"):
65
+ validate_image(False, animal)
66
+ st.error("Image rejetée!")
67
+
68
+ # Si une image est téléchargée, la traiter et l'afficher
69
+ if uploaded_file is not None:
70
+ uploaded_image = process_uploaded_image(uploaded_file)
71
+ st.image(uploaded_image, caption="Image téléchargée", use_column_width=True)
72
+
73
+ # Validation de l'image téléchargée
74
+ if st.button("Valider l'image téléchargée"):
75
+ validate_image(True, "image téléchargée")
76
+ st.success("Image téléchargée validée!")
77
+ if st.button("Rejeter l'image téléchargée"):
78
+ validate_image(False, "image téléchargée")
79
+ st.error("Image téléchargée rejetée!")
80
+
81
+ # Bouton pour réinitialiser le processus
82
+ if st.button("Réinitialiser"):
83
+ validation_data.clear()
84
+ st.success("Le processus a été réinitialisé.")
85
+
86
+ # Champ de texte pour données manuelles
87
+ if st.button("Don"):
88
+ don_text = st.text_area("Entrez vos données :", "")
89
+ if st.button("Envoyer"):
90
+ if don_text:
91
+ auto_training_data['data'] = don_text
92
+ st.success("Données envoyées!")
93
+ else:
94
+ st.error("Le champ de texte ne peut pas être vide.")
95
+
96
+ # Démarrer le processus automatiquement après 3 secondes si le champ 'Don' n'est pas rempli
97
+ if 'data' not in auto_training_data:
98
+ time.sleep(3)
99
+ st.success("Démarrage automatique du processus d'apprentissage...")