ebraam1 commited on
Commit
990c5ce
·
verified ·
1 Parent(s): f87b0f7

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File
2
+ from pydantic import BaseModel
3
+ from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline
4
+ import torch
5
+ from PIL import Image
6
+ import io
7
+ from fastapi.responses import StreamingResponse
8
+
9
+ app = FastAPI()
10
+
11
+ MODEL_PATH = "Interior.safetensors"
12
+ LORA_PATH = "Interior_lora.safetensors"
13
+
14
+ print("Loading base model...")
15
+
16
+ txt2img = StableDiffusionPipeline.from_single_file(
17
+ MODEL_PATH,
18
+ torch_dtype=torch.float16,
19
+ safety_checker=None
20
+ ).to("cpu") # هنرجعها GPU لو متاح لاحقًا
21
+
22
+ img2img = StableDiffusionImg2ImgPipeline.from_single_file(
23
+ MODEL_PATH,
24
+ torch_dtype=torch.float16,
25
+ safety_checker=None
26
+ ).to("cpu")
27
+
28
+ print("Loading LoRA...")
29
+
30
+ txt2img.load_lora_weights(LORA_PATH)
31
+ img2img.load_lora_weights(LORA_PATH)
32
+
33
+ print("LoRA loaded 🔥")
34
+
35
+ class Prompt(BaseModel):
36
+ prompt: str
37
+
38
+
39
+ def to_bytes(img):
40
+ buf = io.BytesIO()
41
+ img.save(buf, format="PNG")
42
+ buf.seek(0)
43
+ return buf
44
+
45
+
46
+ @app.post("/txt2img")
47
+ def generate(data: Prompt):
48
+
49
+ image = txt2img(
50
+ data.prompt,
51
+ cross_attention_kwargs={"scale": 0.8}
52
+ ).images[0]
53
+
54
+ return StreamingResponse(to_bytes(image), media_type="image/png")
55
+
56
+
57
+ @app.post("/img2img")
58
+ async def img2img_api(file: UploadFile = File(...), prompt: str = ""):
59
+
60
+ img = Image.open(io.BytesIO(await file.read())).convert("RGB").resize((512,512))
61
+
62
+ image = img2img(
63
+ prompt=prompt,
64
+ image=img,
65
+ cross_attention_kwargs={"scale": 0.8}
66
+ ).images[0]
67
+
68
+ return StreamingResponse(to_bytes(image), media_type="image/png")