Galaxydude2 commited on
Commit
574a6ae
·
verified ·
1 Parent(s): a8e69b7

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. app.py +195 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import requests
4
+ import re
5
+ from urllib.parse import urljoin, urlparse
6
+ from pathlib import Path
7
+ import time
8
+ from bs4 import BeautifulSoup
9
+
10
+ def extract_images_from_url(url):
11
+ """Extrahiert alle Bild-URLs von einer Webseite."""
12
+ try:
13
+ # Hole die Webseite
14
+ response = requests.get(url, timeout=10)
15
+ response.raise_for_status()
16
+
17
+ # Parse HTML mit BeautifulSoup
18
+ soup = BeautifulSoup(response.content, 'html.parser')
19
+
20
+ # Finde alle Bild-Tags
21
+ img_tags = soup.find_all('img')
22
+
23
+ # Extrahiere URLs
24
+ img_urls = []
25
+ for img in img_tags:
26
+ src = img.get('src') or img.get('data-src')
27
+ if src:
28
+ # Erstelle absolute URL
29
+ absolute_url = urljoin(url, src)
30
+ img_urls.append(absolute_url)
31
+
32
+ # Entferne Duplikate und sortiere
33
+ img_urls = sorted(list(set(img_urls)))
34
+
35
+ return img_urls, len(img_urls)
36
+
37
+ except Exception as e:
38
+ raise gr.Error(f"Fehler beim Abrufen der URL: {str(e)}")
39
+
40
+ def download_image(url, folder, index):
41
+ """Lädt ein einzelnes Bild herunter."""
42
+ try:
43
+ # Hole den Dateinamen aus der URL
44
+ parsed = urlparse(url)
45
+ filename = os.path.basename(parsed.path)
46
+
47
+ # Wenn kein Dateiname vorhanden ist, generiere einen
48
+ if not filename:
49
+ filename = f"image_{index}.jpg"
50
+
51
+ # Erstelle den Dateipfad
52
+ filepath = os.path.join(folder, filename)
53
+
54
+ # Füge Index hinzu, falls Datei bereits existiert
55
+ counter = 1
56
+ while os.path.exists(filepath):
57
+ name, ext = os.path.splitext(filename)
58
+ filepath = os.path.join(folder, f"{name}_{counter}{ext}")
59
+ counter += 1
60
+
61
+ # Lade das Bild herunter
62
+ response = requests.get(url, timeout=30)
63
+ response.raise_for_status()
64
+
65
+ # Speichere das Bild
66
+ with open(filepath, 'wb') as f:
67
+ f.write(response.content)
68
+
69
+ return filepath, True
70
+
71
+ except Exception as e:
72
+ return str(e), False
73
+
74
+ def download_all_images(url, progress=gr.Progress()):
75
+ """Lädt alle Bilder von einer Webseite herunter."""
76
+ if not url:
77
+ raise gr.Error("Bitte geben Sie eine URL ein.")
78
+
79
+ # Validiere URL
80
+ if not url.startswith(('http://', 'https://')):
81
+ url = 'https://' + url
82
+
83
+ # Erstelle Download-Verzeichnis
84
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
85
+ folder_name = f"downloaded_images_{timestamp}"
86
+ download_folder = Path.cwd() / folder_name
87
+ download_folder.mkdir(exist_ok=True)
88
+
89
+ progress(0, desc="Rufe Bilder ab...")
90
+
91
+ # Extrahiere Bild-URLs
92
+ try:
93
+ img_urls, total_count = extract_images_from_url(url)
94
+ except Exception as e:
95
+ raise gr.Error(str(e))
96
+
97
+ if total_count == 0:
98
+ return None, f"Keine Bilder auf {url} gefunden."
99
+
100
+ progress(0.3, desc=f"Starte Download von {total_count} Bildern...")
101
+
102
+ # Download alle Bilder
103
+ downloaded_count = 0
104
+ failed_count = 0
105
+ results = []
106
+
107
+ for i, img_url in enumerate(progress.tqdm(img_urls, desc="Bilder herunterladen")):
108
+ try:
109
+ filepath, success = download_image(img_url, str(download_folder), i)
110
+
111
+ if success:
112
+ downloaded_count += 1
113
+ results.append(filepath)
114
+ else:
115
+ failed_count += 1
116
+
117
+ # Aktualisiere Fortschritt
118
+ progress((0.3 + 0.7 * (i + 1) / total_count),
119
+ desc=f"Bild {i+1}/{total_count}: {'✓' if success else '✗'}")
120
+
121
+ except Exception as e:
122
+ failed_count += 1
123
+ progress((0.3 + 0.7 * (i + 1) / total_count),
124
+ desc=f"Fehler bei Bild {i+1}: {str(e)}")
125
+
126
+ # Erstelle Ergebnis
127
+ message = f"✅ **Erfolgreich** {downloaded_count} Bilder heruntergeladen.\n"
128
+ if failed_count > 0:
129
+ message += f"⚠️ **Fehler** bei {failed_count} Bildern."
130
+
131
+ # Erstelle eine ZIP-Datei für den Download
132
+ import shutil
133
+ zip_path = download_folder.parent / f"{folder_name}.zip"
134
+ shutil.make_archive(str(zip_path.parent / zip_path.stem), 'zip', download_folder)
135
+
136
+ return str(zip_path), message
137
+
138
+ # Erstelle die Gradio-Anwendung
139
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="indigo")) as demo:
140
+ gr.Markdown("# 📷 Bild-Downloader")
141
+ gr.Markdown("Geben Sie eine URL ein, um **alle Bilder** von dieser Seite herunterzuladen.")
142
+
143
+ with gr.Row():
144
+ with gr.Column(scale=1):
145
+ url_input = gr.Textbox(
146
+ label="Web-URL",
147
+ placeholder="https://beispiel.de/seite",
148
+ info="Geben Sie die URL der Seite ein, von der Bilder heruntergeladen werden sollen."
149
+ )
150
+
151
+ download_btn = gr.Button(" Bilder herunterladen", variant="primary", icon="download")
152
+
153
+ gr.Markdown("""
154
+ ### ℹ️ Anleitung
155
+ 1. Geben Sie eine URL ein (z.B. eine Bildergalerie)
156
+ 2. Klicken Sie auf "Bilder herunterladen"
157
+ 3. Warten Sie, bis alle Bilder heruntergeladen wurden
158
+ 4. Laden Sie die ZIP-Datei mit allen Bildern herunter
159
+
160
+ ### 📌 Hinweise
161
+ - Die App extrahiert alle Bilder von `<img>`-Tags
162
+ - Bilder werden als ZIP-Archiv komprimiert
163
+ - Der Download kann einige Sekunden dauern
164
+ """)
165
+
166
+ with gr.Column(scale=1):
167
+ output_zip = gr.File(label="ZIP-Datei mit Bildern")
168
+ status_output = gr.Markdown(label="Status")
169
+
170
+ # Event Handler
171
+ download_btn.click(
172
+ fn=download_all_images,
173
+ inputs=url_input,
174
+ outputs=[output_zip, status_output],
175
+ api_visibility="public"
176
+ )
177
+
178
+ # Beispiele
179
+ gr.Examples(
180
+ examples=[
181
+ ["https://picsum.photos/"],
182
+ ["https://unsplash.com/s/photos/nature"],
183
+ ["https://www.flickr.com/"],
184
+ ],
185
+ inputs=url_input
186
+ )
187
+
188
+ # Starte die Anwendung
189
+ if __name__ == "__main__":
190
+ demo.launch(
191
+ theme=gr.themes.Soft(),
192
+ footer_links=[
193
+ {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}
194
+ ]
195
+ )
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ beautifulsoup4
2
+ gradio>=6.0.2
3
+ requests