-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
68 lines (59 loc) · 2.1 KB
/
Copy pathmain.py
File metadata and controls
68 lines (59 loc) · 2.1 KB
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
from fastapi import FastAPI, Query
from fastapi.middleware.cors import CORSMiddleware
import torch
from diffusers import StableDiffusionPipeline
from fastapi.responses import Response
import io
import peft
app = FastAPI()
# Configure CORS (Allow all origins for testing)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Load Stable Diffusion model on CPU
model_id = "sd-legacy/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float32)
pipe = pipe.to("cpu")
# Load LoRA Model
lora_model_path = "./Super Ani ver2_v2.0.safetensors"
try:
pipe.load_lora_weights(lora_model_path, weights=1.2)
pipe.fuse_lora()
pipe.unet.set_default_attn_processor()
print("LoRA model loaded successfully.")
except Exception as e:
print(f"Failed to load LoRA model: {e}")
@app.get("/")
def generate(
prompt: str,
cfg_scale: float = Query(5, description="How strictly the image follows the prompt"),
steps: int = Query(50, description="Number of sampling steps"),
width: int = Query(512, description="Image width"),
height: int = Query(512, description="Image height"),
sampler: str = Query("DPM++ 2M Karras", description="Sampling method"),
seed: int = Query(None, description="Random seed")
):
# Apply LoRA trigger word (if applicable)
prompt = f"by Super Ani, {prompt}"
# If seed is provided, set the generator to control randomness
if seed is not None:
generator = torch.manual_seed(seed)
else:
generator = None # No seed, let the RNG generate a random one
# Generate image
image = pipe(prompt,
guidance_scale=cfg_scale,
num_inference_steps=steps,
height=height,
width=width,
sampler=sampler,
generator=generator).images[0]
# Convert image to bytes
img_io = io.BytesIO()
image.save(img_io, format="PNG")
img_io.seek(0)
return Response(content=img_io.getvalue(), media_type="image/png")