davidegato1 commited on
Commit
e1f9112
·
verified ·
1 Parent(s): 5c74dbf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -25
app.py CHANGED
@@ -8,33 +8,31 @@ import urllib.request
8
  import re
9
  import time
10
 
11
- # Configuration des paramètres
12
  HEADERS = {
13
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
14
  'Accept-Language': 'en-US,en;q=0.5'
15
  }
16
 
17
- # Fonction pour Bing
18
  def download_bing_images(search_query, limit, adult_filter_off):
19
  try:
20
- adult_filter = not adult_filter_off
21
  downloader.download(
22
  search_query,
23
  limit=limit,
24
- adult_filter_off=adult_filter,
25
  force_replace=False,
26
  timeout=60,
27
  filter_type='photo'
28
  )
29
-
30
  output_dir = os.path.join('dataset', search_query)
31
  return get_image_paths(output_dir)
32
-
33
  except Exception as e:
34
  print(f"Erreur Bing : {str(e)}")
35
  return []
36
 
37
- # Fonction pour Google (méthode sécurisée)
38
  def download_google_images(search_query, limit):
39
  try:
40
  output_dir = os.path.join('dataset', f'google_{search_query}')
@@ -62,42 +60,52 @@ def download_google_images(search_query, limit):
62
  print(f"Erreur Google : {str(e)}")
63
  return []
64
 
65
- # Téléchargement et sauvegarde des images
66
  def download_and_save(urls, output_dir):
67
  saved_paths = []
68
  for idx, url in enumerate(urls):
69
  try:
70
  filename = f"image_{idx+1}_{int(time.time())}.jpg"
71
  full_path = os.path.join(output_dir, filename)
72
-
73
  req = urllib.request.Request(url, headers=HEADERS)
74
  with urllib.request.urlopen(req, timeout=10) as response:
75
  with open(full_path, 'wb') as f:
76
  f.write(response.read())
77
- saved_paths.append(full_path)
78
  except Exception as e:
79
  print(f"Erreur téléchargement {url} : {str(e)}")
80
  return saved_paths
81
 
 
82
  def get_image_paths(directory):
83
  if os.path.exists(directory):
84
- return [os.path.join(directory, f) for f in os.listdir(directory)
85
  if f.lower().endswith(('png', 'jpg', 'jpeg'))]
86
  return []
87
 
88
- # Fonction principale
89
  def download_handler(source, query, limit, safe_mode):
90
- limit = max(1, min(limit, 100)) # Limite entre 1-100
 
91
  try:
92
  if source == "Bing":
93
- return download_bing_images(query, limit, safe_mode == "Off")
 
94
  elif source == "Google":
95
- return download_google_images(query, limit)
 
 
 
 
 
 
 
 
96
  except Exception as e:
97
  print(f"Erreur globale : {str(e)}")
98
- return []
99
 
100
- # Interface Gradio améliorée
101
  with gr.Blocks(theme=gr.themes.Soft(), title="Image Downloader") as app:
102
  gr.Markdown("# 📸 Téléchargeur d'Images Multi-Sources")
103
  gr.Markdown("Téléchargez des images depuis Bing ou Google (max 100)")
@@ -110,15 +118,10 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Image Downloader") as app:
110
 
111
  submit_btn = gr.Button("🚀 Lancer le téléchargement", variant="primary")
112
 
113
- gallery = gr.Gallery(
114
- label="Résultats",
115
- columns=5,
116
- object_fit="contain",
117
- height="auto"
118
- )
119
-
120
  status = gr.Textbox(label="Statut", interactive=False)
121
 
 
122
  submit_btn.click(
123
  fn=download_handler,
124
  inputs=[source, query, limit, safe_mode],
@@ -135,4 +138,5 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Image Downloader") as app:
135
  )
136
 
137
  if __name__ == "__main__":
138
- app.launch(server_port=7860, show_error=True)
 
 
8
  import re
9
  import time
10
 
11
+ # Configuration des headers HTTP
12
  HEADERS = {
13
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
14
  'Accept-Language': 'en-US,en;q=0.5'
15
  }
16
 
17
+ # Téléchargement via Bing
18
  def download_bing_images(search_query, limit, adult_filter_off):
19
  try:
20
+ # Ici, adult_filter_off est True si le mode sécurisé est désactivé ("Off")
21
  downloader.download(
22
  search_query,
23
  limit=limit,
24
+ adult_filter_off=adult_filter_off,
25
  force_replace=False,
26
  timeout=60,
27
  filter_type='photo'
28
  )
 
29
  output_dir = os.path.join('dataset', search_query)
30
  return get_image_paths(output_dir)
 
31
  except Exception as e:
32
  print(f"Erreur Bing : {str(e)}")
33
  return []
34
 
35
+ # Téléchargement via Google (méthode sécurisée)
36
  def download_google_images(search_query, limit):
37
  try:
38
  output_dir = os.path.join('dataset', f'google_{search_query}')
 
60
  print(f"Erreur Google : {str(e)}")
61
  return []
62
 
63
+ # Téléchargement et sauvegarde des images depuis une liste d'URLs
64
  def download_and_save(urls, output_dir):
65
  saved_paths = []
66
  for idx, url in enumerate(urls):
67
  try:
68
  filename = f"image_{idx+1}_{int(time.time())}.jpg"
69
  full_path = os.path.join(output_dir, filename)
 
70
  req = urllib.request.Request(url, headers=HEADERS)
71
  with urllib.request.urlopen(req, timeout=10) as response:
72
  with open(full_path, 'wb') as f:
73
  f.write(response.read())
74
+ saved_paths.append(full_path)
75
  except Exception as e:
76
  print(f"Erreur téléchargement {url} : {str(e)}")
77
  return saved_paths
78
 
79
+ # Récupérer les chemins des images dans un dossier
80
  def get_image_paths(directory):
81
  if os.path.exists(directory):
82
+ return [os.path.join(directory, f) for f in os.listdir(directory)
83
  if f.lower().endswith(('png', 'jpg', 'jpeg'))]
84
  return []
85
 
86
+ # Fonction principale appelée par l'interface Gradio
87
  def download_handler(source, query, limit, safe_mode):
88
+ # S'assurer que le nombre d'images est entre 1 et 100
89
+ limit = max(1, min(limit, 100))
90
  try:
91
  if source == "Bing":
92
+ # Si safe_mode est "Off", alors le filtre est désactivé (adult_filter_off=True)
93
+ image_paths = download_bing_images(query, limit, safe_mode == "Off")
94
  elif source == "Google":
95
+ image_paths = download_google_images(query, limit)
96
+ else:
97
+ image_paths = []
98
+
99
+ if image_paths:
100
+ status_msg = f"{len(image_paths)} image(s) téléchargée(s)."
101
+ else:
102
+ status_msg = "Aucune image téléchargée."
103
+ return image_paths, status_msg
104
  except Exception as e:
105
  print(f"Erreur globale : {str(e)}")
106
+ return [], f"Erreur: {str(e)}"
107
 
108
+ # Création de l'interface Gradio avec Blocks
109
  with gr.Blocks(theme=gr.themes.Soft(), title="Image Downloader") as app:
110
  gr.Markdown("# 📸 Téléchargeur d'Images Multi-Sources")
111
  gr.Markdown("Téléchargez des images depuis Bing ou Google (max 100)")
 
118
 
119
  submit_btn = gr.Button("🚀 Lancer le téléchargement", variant="primary")
120
 
121
+ gallery = gr.Gallery(label="Résultats", columns=5, object_fit="contain", height="auto")
 
 
 
 
 
 
122
  status = gr.Textbox(label="Statut", interactive=False)
123
 
124
+ # Liaison du bouton au gestionnaire de téléchargement (2 sorties attendues)
125
  submit_btn.click(
126
  fn=download_handler,
127
  inputs=[source, query, limit, safe_mode],
 
138
  )
139
 
140
  if __name__ == "__main__":
141
+ # Utilisation de server_name="0.0.0.0" pour Hugging Face Spaces
142
+ app.launch(server_name="0.0.0.0", server_port=7860, show_error=True)