|
import gradio as gr |
|
import torch |
|
import os |
|
from diffusers import StableDiffusion3Pipeline |
|
from safetensors.torch import load_file |
|
from spaces import GPU |
|
|
|
|
|
model_id = "stabilityai/stable-diffusion-3.5-large" |
|
hf_token = os.getenv("HF_TOKEN") |
|
|
|
|
|
pipeline = None |
|
|
|
|
|
try: |
|
if hf_token: |
|
pipeline = StableDiffusion3Pipeline.from_pretrained( |
|
model_id, |
|
torch_dtype=torch.float16, |
|
cache_dir="./model_cache" |
|
) |
|
else: |
|
pipeline = StableDiffusion3Pipeline.from_pretrained( |
|
model_id, |
|
torch_dtype=torch.float16, |
|
cache_dir="./model_cache" |
|
) |
|
|
|
lora_filename = "lora_trained_model.safetensors" |
|
lora_path = os.path.join("./", lora_filename) |
|
|
|
if os.path.exists(lora_path): |
|
lora_weights = load_file(lora_path) |
|
text_encoder = pipeline.text_encoder |
|
text_encoder.load_state_dict(lora_weights, strict=False) |
|
print(f"LoRA loaded successfully from: {lora_path}") |
|
else: |
|
print(f"Error: LoRA file not found at: {lora_path}") |
|
exit() |
|
|
|
print("Stable Diffusion model loaded successfully!") |
|
|
|
except Exception as e: |
|
print(f"Error loading model or LoRA: {e}") |
|
exit() |
|
|
|
|
|
@GPU(duration=65) |
|
def generate_image(prompt): |
|
global pipeline |
|
if pipeline is None: |
|
return "Error: Model not loaded!" |
|
|
|
try: |
|
image = pipeline(prompt).images[0] |
|
return image |
|
except Exception as e: |
|
return f"Error generating image: {e}" |
|
|
|
|
|
with gr.Blocks() as demo: |
|
prompt_input = gr.Textbox(label="Prompt") |
|
image_output = gr.Image(label="Generated Image") |
|
generate_button = gr.Button("Generate") |
|
|
|
generate_button.click( |
|
fn=generate_image, |
|
inputs=prompt_input, |
|
outputs=image_output, |
|
) |
|
|
|
demo.launch() |