==== Application Startup at 2025-05-12 18:21:52 =====
Running on local URL: http://0.0.0.0:7860, with SSR ⚡ (experimental, to disable set ssr_mode=False in launch())
To create a public link, set share=True in launch().
Lade Modell: FLUX.1-schnell => black-forest-labs/FLUX.1-schnell auf cpu mit dtype=torch.float32
Fehler beim Laden von black-forest-labs/FLUX.1-schnell: 401 Client Error. (Request ID: Root=1-68223f73-324ef77531d2ab0234213af1;b907eb3b-4d43-4b02-9ab7-7cdd3b347479)
Cannot access gated repo for url https://huggingface.co/black-forest-labs/FLUX.1-schnell/resolve/main/model_index.json.
Access to model black-forest-labs/FLUX.1-schnell is restricted. You must have access to it and be authenticated to access it. Please log in.
Wechsel auf öffentliches Modell: runwayml/stable-diffusion-v1-5
Keyword arguments {'use_auth_token': None} are not expected by StableDiffusionPipeline and will be ignored.
/usr/local/lib/python3.10/site-packages/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py:899: FutureWarning: callback is deprecated and will be removed in version 1.0.0. Passing callback as an input argument to __call__ is deprecated, consider using callback_on_step_end
deprecate(
/usr/local/lib/python3.10/site-packages/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py:905: FutureWarning: callback_steps is deprecated and will be removed in version 1.0.0. Passing callback_steps as an input argument to __call__ is deprecated, consider using callback_on_step_end
deprecate(
Potential NSFW content was detected in one or more images. A black image will be returned instead. Try again with a different prompt and/or seed.
Potential NSFW content was detected in one or more images. A black image will be returned instead. Try again with a different prompt and/or seed.
Assistant
The log indicates the following key points and issues:
Model Loading Failure Due to Authentication:
User
Assistant
User
code vollständig ausgeben
Assistant
User
===== Application Startup at 2025-05-12 19:16:34 =====
Assistant
Der Fehler am Ende der Log-Ausgabe:
code
TypeError: infer.<locals>.progress_callback() takes 3 positional arguments but 4 were given
bedeutet, dass deine Callback-Funktion progress_callback im infer-Modul 3 Argumente deklariert hat, aber von der Pipeline übergeben werden.
User
ja
Assistant
Attempted to load the model black-forest-labs/FLUX.1-schnell from Hugging Face.
The request failed with a 401 Client Error, which means unauthorized access.
The model repository is gated (restricted), and the server process hasn't been authenticated against Hugging Face with valid credentials (an access token).
As a fallback, it switched to a publicly available model runwayml/stable-diffusion-v1-5.
Authentication Issue Solution:
To access gated (private/restricted) models on Hugging Face, you need to:
Have access rights to the repository.
Provide a valid authentication token.
When using diffusers or related pipelines, you should pass an access_token or set the environment variable HUGGINGFACE_TOKEN.
Example:
python
from diffusers import StableDiffusionPipeline
pipe = StableDiffusionPipeline.from_pretrained(
"black-forest-labs/FLUX.1-schnell",
use_auth_token="YOUR_HUGGINGFACE_ACCESS_TOKEN"
)
Or set environment variable before running your script:
Your code or the library is using deprecated arguments callback and callback_steps.
These will be removed soon; replace them with callback_on_step_end following the new API.
NSFW Content Detection:
The model detected potential NSFW content in one or more outputs.
As a safety measure, it replaced those with black images.
Suggestions:
Try different prompts or seed values.
If you want to disable NSFW filtering, be cautious of the risks, but some pipelines allow disabling or customizing this filtering.
Summary of Actions to Fix / Improve:
To fix the model loading error, authenticate your Hugging Face access by providing a valid use_auth_token.
Update your code to remove deprecated arguments.
Adjust prompts/seeds if you want to avoid NSFW filtering triggers.
Optionally, configure NSFW setting if you want to allow such outputs (with caution).
If you want me to help generate the exact updated code snippet or environment setup, feel free to ask!
import os
import gradio as gr
import numpy as np
import random
from diffusers import DiffusionPipeline
import torch
from huggingface_hub.utils import RepositoryNotFoundError, GatedRepoError
Token aus Umgebungsvariable (z.B. HF_TOKEN) laden
token = os.getenv("HF_TOKEN")
device = "cuda" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
Modell Liste mit Fallback
MODEL_MAP = {
"FLUX.1-schnell": "black-forest-labs/FLUX.1-schnell", # schnellstes, kleines Modell
"Stable Diffusion 1.5": "runwayml/stable-diffusion-v1-5", # Standardmodell, schnell und effizient
"DreamShaper v8": "Lykon/DreamShaper-v8", # künstlerisch, mittlere Geschwindigkeit
"Anything-v4": "andite/anything-v4", # mittlere bis langsame Geschwindigkeit
"Anything-v5": "andite/anything-v5", # größer als v4, etwas langsamer
"OpenJourney v4": "prompthero/openjourney-v4", # meist am langsamsten wegen Komplexität
}
with gr.Blocks(css=css, theme=gr.themes.Default(spacing_size="sm")) as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown("# 🖼️ AI Bildgenerator (mit automatischem Modell-Fallback)")
code
if name == "main":
demo.launch(debug=False, show_api=False)v
Dein Script sieht sehr gut aus und berücksichtigt den Token-Authentifizierungsprozess für gated Modelle.
Hier ein paar Hinweise und kleine Verbesserungen bzw. Fehlerbehebungen zu deinem Code:
1. Fix für use_auth_token-Warnung / Fehlermeldung in diffusers
In neueren Versionen der diffusers-Bibliothek wird erwartet, dass use_auth_token nicht mehr an DiffusionPipeline.from_pretrained() direkt übergeben wird, sondern stattdessen der HuggingFace-Login durch huggingface_hub.login() oder Setzen einer Umgebungsvariablen erfolgt.
Alternative:
Setze bitte vor dem Laden des Modells den Token über
python
from huggingface_hub import login
if token:
login(token)
Dann lade das Modell einfach ohne use_auth_token Argument:
Aktuell sieht dein Code so aus, dass use_auth_token=token if token else None benutzt wird. Das führt zwar nicht zwingend zu Fehlern, aber laut Logs in deiner ersten Nachricht wird es als nicht erwartet gemeldet.
2. Deprecation-Warning für callback und callback_steps
Diese Argumente sind in den aktuellen Versionen der Pipeline veraltet. Empfohlen ist, stattdessen callback_on_step_end zu verwenden.
3. Letzter Tipp: demo.launch() in der if __name__ == "__main__":-Sektion hat am Ende ein überflüssiges v
Du hast:
python
if __name__ == "__main__":
demo.launch(debug=False, show_api=False)v
Das v muss entfernt werden:
python
if __name__ == "__main__":
demo.launch(debug=False, show_api=False)
4. Optional: Einbindung des Tokens
Wenn du möchtest, kannst du den Token explizit laden und loggen einmal vor dem Laden der Modelle:
python
from huggingface_hub import login
if token:
print("Authentifiziere mit Hugging Face Token...")
login(token)
else:
print("Kein HF-Token gefunden, nur öffentlich zugängliche Modelle verfügbar.")
Das kannst du z.B. gleich an den Anfang deiner load_model Funktion oder direkt nach dem Laden der Umgebungsvariable machen.
Beispiel für deine load_model Funktion (angepasst)
python
from huggingface_hub import login
def load_model(model_name, enable_attention_slicing=True):
global token
model_repo_id = MODEL_MAP.get(model_name, MODEL_MAP["Stable Diffusion 1.5"])
print(f"Lade Modell: {model_name} => {model_repo_id} auf {device} mit dtype={torch_dtype}")
if token:
login(token)
try:
pipeline = DiffusionPipeline.from_pretrained(
model_repo_id,
torch_dtype=torch_dtype,
)
pipeline = pipeline.to(device)
if enable_attention_slicing:
pipeline.enable_attention_slicing()
return pipeline
except (RepositoryNotFoundError, GatedRepoError) as e:
print(f"Fehler beim Laden von {model_repo_id}: {e}")
# Fallback: Öffentliches Modell ohne Token
fallback_id = MODEL_MAP["Stable Diffusion 1.5"]
print(f"Wechsel auf öffentliches Modell: {fallback_id}")
pipeline = DiffusionPipeline.from_pretrained(
fallback_id,
torch_dtype=torch_dtype,
)
pipeline = pipeline.to(device)
if enable_attention_slicing:
pipeline.enable_attention_slicing()
return pipeline
Zusammenfassung
Entferne use_auth_token aus DiffusionPipeline.from_pretrained(), nutze stattdessen huggingface_hub.login(token)
Tausche callback und callback_steps gegen callback_on_step_end
Entferne das falsche v am Ende von demo.launch()
Damit sollte das Skript fehlerfrei und ohne Warnungen laufen.
Wenn du möchtest, kann ich dir den kompletten angepassten Code auch direkt generieren. Sag einfach Bescheid!
Hier ist dein vollständiger, überarbeiteter Code mit den besprochenen Anpassungen (Token-Login, aktualisierte Callback-Nutzung, Fehlerbehebung am Scriptende):
python
import os
import gradio as gr
import numpy as np
import random
from diffusers import DiffusionPipeline
import torch
from huggingface_hub import login
from huggingface_hub.utils import RepositoryNotFoundError, GatedRepoError
# Token aus Umgebungsvariable (z.B. HF_TOKEN) laden
token = os.getenv("HF_TOKEN")
device = "cuda" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
# Modell Liste mit Fallback
MODEL_MAP = {
"FLUX.1-schnell": "black-forest-labs/FLUX.1-schnell", # schnellstes, kleines Modell
"Stable Diffusion 1.5": "runwayml/stable-diffusion-v1-5", # Standardmodell, schnell und effizient
"DreamShaper v8": "Lykon/DreamShaper-v8", # künstlerisch, mittlere Geschwindigkeit
"Anything-v4": "andite/anything-v4", # mittlere bis langsame Geschwindigkeit
"Anything-v5": "andite/anything-v5", # größer als v4, etwas langsamer
"OpenJourney v4": "prompthero/openjourney-v4", # meist am langsamsten wegen Komplexität
}
DEFAULT_POSITIVE = (
"photorealistic, ultra detailed, 8K resolution, cinematic lighting, natural colors, sharp focus, "
"hyper-realistic, high-quality textures, intricate details, HDR, volumetric lighting, depth of field, "
"realistic reflections, dynamic composition, professional photography, soft shadows, vivid colors, "
"beautifully rendered, artistic masterpiece, lifelike portrayal"
)
DEFAULT_NEGATIVE = (
"low quality, blurry, bad anatomy, extra limbs, watermark, text, distorted proportions, unnatural colors, "
"heavy noise, pixelated, overexposed, inconsistent lighting, lack of detail, warped perspective, "
"unrealistic expressions, compression artifacts, harsh shadows, cluttered composition, exaggerated features, "
"unwanted text overlays"
)
pipe = None
current_model = None
def load_model(model_name, enable_attention_slicing=True):
global token
model_repo_id = MODEL_MAP.get(model_name, MODEL_MAP["Stable Diffusion 1.5"])
print(f"Lade Modell: {model_name} => {model_repo_id} auf {device} mit dtype={torch_dtype}")
if token:
print("Authentifiziere mit Hugging Face Token...")
login(token)
else:
print("Kein HF-Token gefunden, nur öffentlich zugängliche Modelle verfügbar.")
try:
pipeline = DiffusionPipeline.from_pretrained(
model_repo_id,
torch_dtype=torch_dtype,
)
pipeline = pipeline.to(device)
if enable_attention_slicing:
pipeline.enable_attention_slicing()
return pipeline
except (RepositoryNotFoundError, GatedRepoError) as e:
print(f"Fehler beim Laden von {model_repo_id}: {e}")
# Fallback: Öffentliches Modell ohne Token
fallback_id = MODEL_MAP["Stable Diffusion 1.5"]
print(f"Wechsel auf öffentliches Modell: {fallback_id}")
pipeline = DiffusionPipeline.from_pretrained(
fallback_id,
torch_dtype=torch_dtype,
)
pipeline = pipeline.to(device)
if enable_attention_slicing:
pipeline.enable_attention_slicing()
return pipeline
def infer(
model_name,
prompt,
positive_prompts,
negative_prompts,
base_seed,
randomize_seed,
width,
height,
guidance_scale,
num_inference_steps,
num_images,
enable_attention_slicing,
progress=gr.Progress(track_tqdm=True),
):
global pipe, current_model
num_images = int(num_images)
base_seed = int(base_seed) if base_seed is not None else 0
width = int(width)
height = int(height)
num_inference_steps = int(num_inference_steps)
guidance_scale = float(guidance_scale)
randomize_seed = bool(randomize_seed)
enable_attention_slicing = bool(enable_attention_slicing)
if current_model != model_name or pipe is None:
pipe = load_model(model_name, enable_attention_slicing)
current_model = model_name
full_prompt = prompt.strip()
if positive_prompts:
full_prompt += " " + positive_prompts.strip()
full_negative = negative_prompts.strip() if negative_prompts else ""
images = []
# Callback zum Aktualisieren des Gradio Fortschritts definieren
def progress_callback(step: int, timestep: int, latents):
# 'step' startet bei 0, deshalb +1; Normierung auf 0..1
progress((step + 1) / num_inference_steps)
for i in range(num_images):
if randomize_seed:
seed = random.randint(0, np.iinfo(np.int32).max)
else:
seed = base_seed + i
generator = torch.Generator(device=device).manual_seed(seed)
imgs = pipe(
prompt=full_prompt,
negative_prompt=full_negative,
width=width,
height=height,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
generator=generator,
callback_on_step_end=progress_callback, # angepasst
).images
images.extend(imgs)
return images
def reset_inputs():
return (
"FLUX.1-schnell",
"",
DEFAULT_POSITIVE,
DEFAULT_NEGATIVE,
1,
True,
512,
512,
0.6, # guidance standardmäßig 0.6
5, # inference standardmäßig 5
"1",
True,
)
css = """
#col-container {
max-width: 80%;
margin: 0 auto;
}
#output-gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
}
/* Dunklere Farbe für Range-Slider */
input[type=range] {
accent-color: #444444;
}
/* Responsive Text & Button Anpassungen */
@media (max-width: 768px) {
#col-container {
max-width: 95%;
}
}
"""
with gr.Blocks(css=css, theme=gr.themes.Default(spacing_size="sm")) as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown("# 🖼️ AI Bildgenerator (mit automatischem Modell-Fallback)")
gr.Markdown(
"""
**Achtung:** Falls ein Modell gated ist und du keinen Zugriff hast, wird
automatisch das öffentliche Stable Diffusion 1.5 Modell verwendet.
"""
)
with gr.Row():
with gr.Column(scale=2):
model_dropdown = gr.Dropdown(
label="Modell",
choices=list(MODEL_MAP.keys()),
value="FLUX.1-schnell",
interactive=True,
info="Gated Modelle benötigen ggf. Token & Freischaltung"
)
prompt = gr.Textbox(
label="Hauptprompt",
lines=4,
max_lines=10,
placeholder="Beschreibe das gewünschte Bild..."
)
positive_prompt = gr.Textbox(
label="Positiv-Prompts (durch Kommas getrennt)",
lines=2,
value=DEFAULT_POSITIVE
)
negative_prompt = gr.Textbox(
label="Negativ-Prompts (durch Kommas getrennt)",
lines=2,
value=DEFAULT_NEGATIVE
)
with gr.Accordion("Erweiterte Einstellungen", open=True):
with gr.Row():
seed_slider = gr.Slider(0, 2147483647, label="Seed", value=1, step=1)
randomize_seed_checkbox = gr.Checkbox(label="Zufälligen Seed", value=True)
with gr.Row():
width = gr.Slider(256, 512, value=512, step=64, label="Breite (max. 512 empfohlen)")
height = gr.Slider(256, 512, value=512, step=64, label="Höhe (max. 512 empfohlen)")
with gr.Row():
guidance_scale = gr.Slider(
0.0, 20.0, value=0.6, step=0.1, label="Guidance Scale"
)
num_inference_steps = gr.Slider(
1, 30, value=5, step=1, label="Inferenzschritte"
)
with gr.Row():
attention_slicing_checkbox = gr.Checkbox(
label="Speicheroptimierung (Attention Slicing) aktivieren",
value=True
)
num_images = gr.Dropdown(
label="Anzahl Bilder",
choices=[str(i) for i in range(1, 5)],
value="1",
interactive=True
)
with gr.Row():
generate_btn = gr.Button("Bild generieren", variant="primary")
reset_btn = gr.Button("Zurücksetzen")
# <-- hier keine Einrückung! Markdown außerhalb der Row:
gr.Markdown(
"""
**Hinweise:**
- *Guidance* bestimmt, wie strikt sich das Modell an den Prompt hält.
- *Inference* nutzt erlerntes Wissen, um Bilder zu generieren.
- Bei gated Modellen prüfe deinen Zugriff und Token.
- Für niedrige Hardware: max. 512x512 und Attention Slicing aktivieren.
"""
)
with gr.Column(scale=2):
output_gallery = gr.Gallery(
label="Ergebnisse",
show_label=False,
elem_id="output-gallery",
type="pil"
)
generate_btn.click(
fn=infer,
inputs=[
model_dropdown,
prompt,
positive_prompt,
negative_prompt,
seed_slider,
randomize_seed_checkbox,
width,
height,
guidance_scale,
num_inference_steps,
num_images,
attention_slicing_checkbox,
],
outputs=[output_gallery],
show_progress=True,
)
reset_btn.click(
fn=reset_inputs,
outputs=[
model_dropdown,
prompt,
positive_prompt,
negative_prompt,
seed_slider,
randomize_seed_checkbox,
width,
height,
guidance_scale,
num_inference_steps,
num_images,
attention_slicing_checkbox,
],
)
if __name__ == "__main__":
demo.launch(debug=False, show_api=False)
Falls du noch Fragen hast oder eine Erklärung zu einzelnen Stellen brauchst – gerne melden!
Running on local URL: http://0.0.0.0:7860, with SSR ⚡ (experimental, to disable set ssr_mode=False in launch())
To create a public link, set share=True in launch().
Lade Modell: FLUX.1-schnell => black-forest-labs/FLUX.1-schnell auf cpu mit dtype=torch.float32
Kein HF-Token gefunden, nur öffentlich zugängliche Modelle verfügbar.
Fehler beim Laden von black-forest-labs/FLUX.1-schnell: 401 Client Error. (Request ID: Root=1-68225411-23359dab473b09cd19ca3a36;12dd95d3-34e6-415e-857c-a4520bf90e3a)
Cannot access gated repo for url https://huggingface.co/black-forest-labs/FLUX.1-schnell/resolve/main/model_index.json.
Access to model black-forest-labs/FLUX.1-schnell is restricted. You must have access to it and be authenticated to access it. Please log in.
Wechsel auf öffentliches Modell: runwayml/stable-diffusion-v1-5
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/gradio/queueing.py", line 625, in process_events
response = await route_utils.call_process_api(
File "/usr/local/lib/python3.10/site-packages/gradio/route_utils.py", line 322, in call_process_api
output = await app.get_blocks().process_api(
File "/usr/local/lib/python3.10/site-packages/gradio/blocks.py", line 2136, in process_api
result = await self.call_function(
File "/usr/local/lib/python3.10/site-packages/gradio/blocks.py", line 1662, in call_function
prediction = await anyio.to_thread.run_sync( # type: ignore
File "/usr/local/lib/python3.10/site-packages/anyio/to_thread.py", line 56, in run_sync
return await get_async_backend().run_sync_in_worker_thread(
File "/usr/local/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 2470, in run_sync_in_worker_thread
return await future
File "/usr/local/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 967, in run
result = context.run(func, *args)
File "/usr/local/lib/python3.10/site-packages/gradio/utils.py", line 883, in wrapper
response = f(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/gradio/utils.py", line 883, in wrapper
response = f(*args, **kwargs)
File "/home/user/app/app.py", line 128, in infer
imgs = pipe(
File "/usr/local/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context
return func(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py", line 1066, in call
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
TypeError: infer..progress_callback() takes 3 positional arguments but 4 were given
4 Argumente
Ursache
Im aktuellen diffusers-Code wird das Callback für callback_on_step_end so aufgerufen: