|
import gradio as gr |
|
import torch |
|
from transformers import pipeline, set_seed |
|
from diffusers import StableDiffusionPipeline |
|
import os |
|
import time |
|
|
|
|
|
|
|
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
print(f"Using device: {device}") |
|
|
|
|
|
asr_pipeline = None |
|
try: |
|
print("Loading ASR pipeline (Whisper)...") |
|
|
|
|
|
asr_pipeline = pipeline("automatic-speech-recognition", model="openai/whisper-base", device=device if device == "cuda" else -1) |
|
print("ASR pipeline loaded.") |
|
except Exception as e: |
|
print(f"Could not load ASR pipeline: {e}. Voice input will be disabled.") |
|
|
|
|
|
prompt_enhancer_pipeline = None |
|
try: |
|
print("Loading Prompt Enhancer pipeline (GPT-2)...") |
|
|
|
|
|
|
|
prompt_enhancer_pipeline = pipeline("text-generation", model="gpt2", device=device if device == "cuda" else -1) |
|
print("Prompt Enhancer pipeline loaded.") |
|
except Exception as e: |
|
print(f"Could not load Prompt Enhancer pipeline: {e}. Prompt enhancement might fail.") |
|
|
|
|
|
image_generator_pipe = None |
|
try: |
|
print("Loading Stable Diffusion pipeline (v1.5)...") |
|
model_id = "runwayml/stable-diffusion-v1-5" |
|
image_generator_pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16 if device == "cuda" else torch.float32) |
|
image_generator_pipe = image_generator_pipe.to(device) |
|
|
|
|
|
print("Stable Diffusion pipeline loaded.") |
|
except Exception as e: |
|
print(f"Could not load Stable Diffusion pipeline: {e}. Image generation will fail.") |
|
|
|
class DummyPipe: |
|
def __call__(self, *args, **kwargs): |
|
|
|
raise RuntimeError(f"Stable Diffusion model failed to load: {e}") |
|
image_generator_pipe = DummyPipe() |
|
|
|
|
|
|
|
|
|
|
|
def enhance_prompt(short_prompt, style_modifier="cinematic", quality_boost="photorealistic, highly detailed"): |
|
"""使用LLM增强简短描述""" |
|
if not prompt_enhancer_pipeline: |
|
return f"[Error: LLM not loaded] Original prompt: {short_prompt}" |
|
if not short_prompt: |
|
return "[Error: Input description is empty]" |
|
|
|
|
|
|
|
input_text = ( |
|
f"Generate a detailed and vivid prompt for an AI image generator based on the following description. " |
|
f"Incorporate the style '{style_modifier}' and quality boost '{quality_boost}'. " |
|
f"Focus on visual details, lighting, composition, and mood. " |
|
f"Description: \"{short_prompt}\"\n\n" |
|
f"Detailed Prompt:" |
|
) |
|
|
|
try: |
|
|
|
set_seed(int(time.time())) |
|
|
|
|
|
|
|
|
|
outputs = prompt_enhancer_pipeline( |
|
input_text, |
|
max_length=150, |
|
num_return_sequences=1, |
|
temperature=0.7, |
|
no_repeat_ngram_size=2, |
|
pad_token_id=prompt_enhancer_pipeline.tokenizer.eos_token_id |
|
) |
|
generated_text = outputs[0]['generated_text'] |
|
|
|
|
|
|
|
enhanced = generated_text.split("Detailed Prompt:")[-1].strip() |
|
|
|
if short_prompt in enhanced[:len(short_prompt)+5]: |
|
enhanced = enhanced.replace(short_prompt, "", 1).strip(' ,"') |
|
|
|
|
|
if style_modifier not in enhanced: |
|
enhanced += f", {style_modifier}" |
|
if quality_boost not in enhanced: |
|
enhanced += f", {quality_boost}" |
|
|
|
return enhanced |
|
|
|
except Exception as e: |
|
print(f"Error during prompt enhancement: {e}") |
|
return f"[Error: Prompt enhancement failed] Original prompt: {short_prompt}" |
|
|
|
|
|
def generate_image(prompt, negative_prompt, guidance_scale, num_inference_steps): |
|
"""使用Stable Diffusion生成图像""" |
|
if not isinstance(image_generator_pipe, StableDiffusionPipeline): |
|
raise gr.Error(f"Stable Diffusion model is not available. Load error: {image_generator_pipe}") |
|
if not prompt or "[Error:" in prompt: |
|
raise gr.Error("Cannot generate image due to invalid or missing prompt.") |
|
|
|
print(f"Generating image for prompt: {prompt}") |
|
print(f"Negative prompt: {negative_prompt}") |
|
print(f"Guidance scale: {guidance_scale}, Steps: {num_inference_steps}") |
|
|
|
try: |
|
|
|
generator = torch.Generator(device=device).manual_seed(int(time.time())) |
|
|
|
|
|
with torch.inference_mode(): |
|
image = image_generator_pipe( |
|
prompt=prompt, |
|
negative_prompt=negative_prompt, |
|
guidance_scale=float(guidance_scale), |
|
num_inference_steps=int(num_inference_steps), |
|
generator=generator |
|
).images[0] |
|
print("Image generated successfully.") |
|
return image |
|
except Exception as e: |
|
print(f"Error during image generation: {e}") |
|
|
|
raise gr.Error(f"Image generation failed: {e}") |
|
|
|
|
|
|
|
def transcribe_audio(audio_file_path): |
|
"""将音频文件转录为文本""" |
|
if not asr_pipeline: |
|
return "[Error: ASR model not loaded]", "" |
|
if audio_file_path is None: |
|
return "", "" |
|
|
|
print(f"Transcribing audio file: {audio_file_path}") |
|
try: |
|
|
|
transcription = asr_pipeline(audio_file_path)["text"] |
|
print(f"Transcription result: {transcription}") |
|
return transcription, audio_file_path |
|
except Exception as e: |
|
print(f"Error during audio transcription: {e}") |
|
return f"[Error: Transcription failed: {e}]", audio_file_path |
|
|
|
|
|
|
|
|
|
def process_input(input_text, audio_file, style_choice, quality_choice, neg_prompt, guidance, steps): |
|
"""处理输入(文本或语音),生成提示词和图像""" |
|
final_text_input = "" |
|
transcription_source = "" |
|
|
|
|
|
if input_text and input_text.strip(): |
|
final_text_input = input_text.strip() |
|
transcription_source = " (from text input)" |
|
|
|
elif audio_file is not None: |
|
transcribed_text, _ = transcribe_audio(audio_file) |
|
if transcribed_text and "[Error:" not in transcribed_text: |
|
final_text_input = transcribed_text |
|
transcription_source = " (from audio input)" |
|
elif "[Error:" in transcribed_text: |
|
|
|
return transcribed_text, None |
|
else: |
|
|
|
return "[Error: Please provide input via text or voice]", None |
|
else: |
|
|
|
return "[Error: Please provide input via text or voice]", None |
|
|
|
print(f"Using input: '{final_text_input}'{transcription_source}") |
|
|
|
|
|
enhanced_prompt = enhance_prompt(final_text_input, style_modifier=style_choice, quality_boost=quality_choice) |
|
print(f"Enhanced prompt: {enhanced_prompt}") |
|
|
|
|
|
generated_image = None |
|
if "[Error:" not in enhanced_prompt: |
|
try: |
|
generated_image = generate_image(enhanced_prompt, neg_prompt, guidance, steps) |
|
except gr.Error as e: |
|
|
|
enhanced_prompt = f"{enhanced_prompt}\n\n[Image Generation Error: {e}]" |
|
|
|
except Exception as e: |
|
|
|
enhanced_prompt = f"{enhanced_prompt}\n\n[Unexpected Image Generation Error: {e}]" |
|
|
|
|
|
return enhanced_prompt, generated_image |
|
|
|
|
|
|
|
|
|
|
|
style_options = ["cinematic", "photorealistic", "anime", "fantasy art", "cyberpunk", "steampunk", "watercolor"] |
|
quality_options = ["highly detailed", "sharp focus", "intricate details", "4k", "masterpiece", "best quality"] |
|
|
|
with gr.Blocks(theme=gr.themes.Soft()) as demo: |
|
gr.Markdown("# AI Image Generator: From Idea to Image") |
|
gr.Markdown("Enter a short description (or use voice input), and the app will enhance it into a detailed prompt and generate an image using Stable Diffusion.") |
|
|
|
with gr.Row(): |
|
with gr.Column(scale=1): |
|
|
|
inp_text = gr.Textbox(label="Enter short description here", placeholder="e.g., A magical treehouse in the sky") |
|
|
|
|
|
inp_audio = gr.Audio(sources=["microphone"], type="filepath", label="Or record your idea (clears text box if used)", visible=asr_pipeline is not None) |
|
|
|
|
|
|
|
inp_style = gr.Dropdown(label="Choose Base Style", choices=style_options, value="cinematic") |
|
|
|
|
|
inp_quality = gr.Radio(label="Quality Boost", choices=quality_options, value="highly detailed") |
|
|
|
|
|
inp_neg_prompt = gr.Textbox(label="Negative Prompt (optional)", placeholder="e.g., blurry, low quality, text, watermark") |
|
|
|
|
|
inp_guidance = gr.Slider(minimum=1.0, maximum=20.0, step=0.5, value=7.5, label="Guidance Scale (CFG)") |
|
|
|
|
|
inp_steps = gr.Slider(minimum=10, maximum=100, step=1, value=30, label="Inference Steps") |
|
|
|
|
|
btn_generate = gr.Button("Generate Image", variant="primary") |
|
|
|
with gr.Column(scale=1): |
|
|
|
out_prompt = gr.Textbox(label="Generated Prompt", interactive=False) |
|
out_image = gr.Image(label="Generated Image", type="pil") |
|
|
|
|
|
btn_generate.click( |
|
fn=process_input, |
|
inputs=[inp_text, inp_audio, inp_style, inp_quality, inp_neg_prompt, inp_guidance, inp_steps], |
|
outputs=[out_prompt, out_image] |
|
) |
|
|
|
|
|
if asr_pipeline: |
|
def clear_text_on_audio(audio_data): |
|
if audio_data is not None: |
|
return "" |
|
return gr.update() |
|
inp_audio.change(fn=clear_text_on_audio, inputs=inp_audio, outputs=inp_text) |
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
|
|
|
|
|
|
|
|
|
|
demo.launch(share=False) |