Spaces:
Sleeping
Sleeping
File size: 5,334 Bytes
ddbe87b |
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 |
import gradio as gr
import requests
import os
import zipfile
import shutil
from PIL import Image
import io
def download_images(image_links, image_names, directory):
# Links und Namen aufteilen und leere Zeilen entfernen
links = [link.strip() for link in image_links.strip().split('\n') if link.strip()]
names = [name.strip() for name in image_names.strip().split('\n') if name.strip()]
# Ergebnistext und Bildvorschauen
result_text = ""
previews = []
# Verzeichnis erstellen, falls nicht vorhanden
if directory.strip():
directory = directory.strip()
os.makedirs(directory, exist_ok=True)
else:
directory = "images"
os.makedirs(directory, exist_ok=True)
# Prüfen, ob Links und Namen verfügbar sind
if not links:
return "Keine Links angegeben.", [], None
# Falls weniger Namen als Links, fülle mit generischen Namen auf
while len(names) < len(links):
names.append(f"image_{len(names) + 1}.jpg")
# Bilder herunterladen
successful = 0
failed = 0
downloaded_files = []
for i, (link, name) in enumerate(zip(links, names)):
try:
# Prüfen, ob der Name eine Dateiendung hat
if not any(name.lower().endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.gif', '.webp']):
name = name + '.jpg' # Standard-Endung hinzufügen
filepath = os.path.join(directory, name)
# Bild herunterladen
response = requests.get(link, timeout=15)
if response.status_code == 200:
with open(filepath, 'wb') as f:
f.write(response.content)
successful += 1
downloaded_files.append(filepath)
# Bildvorschau für die Anzeige erstellen (alle Bilder)
try:
img = Image.open(io.BytesIO(response.content))
previews.append(img)
except Exception as e:
# Wenn Vorschau fehlschlägt, überspringen
pass
else:
failed += 1
result_text += f"Fehler bei {link} -> {name}: HTTP Status {response.status_code}\n"
except Exception as e:
failed += 1
result_text += f"Fehler bei {link} -> {name}: {str(e)}\n"
# ZIP-Datei erstellen, wenn mindestens ein Bild erfolgreich heruntergeladen wurde
zip_path = None
if successful > 0:
try:
zip_filename = f"{directory}.zip"
with zipfile.ZipFile(zip_filename, 'w') as zipf:
for file in downloaded_files:
zipf.write(file)
result_text += f"\nAlle Bilder wurden in {zip_filename} gepackt.\n"
zip_path = zip_filename
except Exception as e:
result_text += f"\nFehler beim Erstellen der ZIP-Datei: {str(e)}\n"
# Zusammenfassung
summary = f"Download abgeschlossen! {successful} Bilder erfolgreich, {failed} fehlgeschlagen.\n"
result_text = summary + result_text
return result_text, previews, zip_path
# Gradio-Interface erstellen
with gr.Blocks(title="Bild-Download-App") as app:
gr.Markdown("# Bild-Downloader")
gr.Markdown("Geben Sie Bildlinks und gewünschte Dateinamen ein (jeweils ein Link/Name pro Zeile)")
with gr.Row():
with gr.Column(scale=1):
image_links = gr.Textbox(
placeholder="https://example.com/image1.jpg\nhttps://example.com/image2.jpg",
label="Bildlinks (ein Link pro Zeile)",
lines=10
)
image_names = gr.Textbox(
placeholder="strand.jpg\nberg.jpg",
label="Dateinamen (ein Name pro Zeile)",
lines=10
)
directory = gr.Textbox(
placeholder="images",
label="Verzeichnis (leer lassen für 'images')",
value="images"
)
download_button = gr.Button("Bilder herunterladen")
with gr.Column(scale=1):
result_output = gr.Textbox(label="Ergebnis", lines=10)
zip_download = gr.File(label="ZIP-Datei zum Download")
gr.Markdown("### Bildvorschau")
image_gallery = gr.Gallery(label="Heruntergeladene Bilder")
# Beispiele hinzufügen
gr.Examples(
[
[
"https://images.unsplash.com/photo-1599982890963-3aabd60064d2\nhttps://images.unsplash.com/photo-1530122037265-a5f1f91d3b99",
"munich-skyline.jpg\nswiss-alps.jpg",
"destinations"
],
[
"https://images.unsplash.com/photo-1436491865332-7a61a109cc05\nhttps://images.unsplash.com/photo-1519494026892-80bbd2d6fd0d",
"airport-transfer.jpg\nmedical-tourism.jpg",
"services"
]
],
[image_links, image_names, directory],
"Beispiele"
)
download_button.click(
fn=download_images,
inputs=[image_links, image_names, directory],
outputs=[result_output, image_gallery, zip_download]
)
# App starten
if __name__ == "__main__":
app.launch()
|