# ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ # ┃ Step0: モンキーパッチ (絶対に一番上) ┃ # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ import huggingface_hub # dynamic_modules_utils が cached_download を import してくるので、 # hf_hub_download を alias しておく if not hasattr(huggingface_hub, "cached_download"): huggingface_hub.cached_download = huggingface_hub.hf_hub_download # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ # ┃ 以下、これまで通りのコード ┃ # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ import gradio as gr import torch from diffusers import StableDiffusionPipeline, DPMSolverMultistepScheduler # モデル設定 model_id = "runwayml/stable-diffusion-v1-5" device = "cuda" if torch.cuda.is_available() else "cpu" torch_dtype = torch.float16 if device == "cuda" else torch.float32 # スケジューラー読み込み scheduler = DPMSolverMultistepScheduler.from_pretrained( model_id, subfolder="scheduler" ) # パイプライン読み込み pipe = StableDiffusionPipeline.from_pretrained( model_id, scheduler=scheduler, torch_dtype=torch_dtype, safety_checker=None ).to(device) # メモリ最適化 if device == "cuda": pipe.enable_attention_slicing() # 画像生成関数 def generate_image( prompt, negative_prompt, num_steps, guidance_scale, width, height, seed ): generator = ( torch.Generator(device=device).manual_seed(seed) if seed and seed > 0 else None ) return pipe( prompt=prompt, negative_prompt=negative_prompt, num_inference_steps=num_steps, guidance_scale=guidance_scale, width=width, height=height, generator=generator, ).images[0] # Gradio UI with gr.Blocks(css="footer {visibility: hidden}") as demo: gr.Markdown("# Simple Stable Diffusion") gr.Markdown("テキストから画像を生成するシンプルなアプリです。") with gr.Row(): with gr.Column(): prompt = gr.Textbox( label="プロンプト", lines=3, placeholder="画像にしたい内容を入力してください…", ) negative_prompt = gr.Textbox( label="ネガティブプロンプト", lines=2, value="低品質, 汚い, 粗い, ぼやけた, 歪んだ", ) num_steps = gr.Slider( minimum=5, maximum=50, step=1, value=25, label="ステップ数" ) guidance_scale = gr.Slider( minimum=1, maximum=15, step=0.1, value=7.5, label="ガイダンススケール" ) width = gr.Slider( minimum=384, maximum=768, step=32, value=512, label="幅" ) height = gr.Slider( minimum=384, maximum=768, step=32, value=512, label="高さ" ) seed = gr.Number(label="シード値(0=ランダム)", value=0) generate_btn = gr.Button("生成", variant="primary") with gr.Column(): result = gr.Image(label="生成結果") generate_btn.click( generate_image, inputs=[ prompt, negative_prompt, num_steps, guidance_scale, width, height, seed, ], outputs=result, ) gr.Examples( examples=[ ["富士山と桜、春の風景", "低品質, イラスト", 25, 7.5, 512, 512, 42], ["サイバーパンク都市、夜景、ネオン", "人物, ぼやけ", 30, 7.5, 512, 512, 123], ["ラーメン、湯気の食べ物写真", "変形, 不自然", 25, 7.5, 512, 512, 456], ], inputs=[ prompt, negative_prompt, num_steps, guidance_scale, width, height, seed, ], ) gr.Markdown("### 使い方\n1. プロンプト入力\n2. 設定調整\n3. 「生成」クリック") demo.launch()