hakanwkwjbwbs commited on
Commit
c7bfd2e
·
1 Parent(s): 56a7c38

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -0
app.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from fastapi import FastAPI
3
+ from typing import List, Optional, Union
4
+ import io, uvicorn, gc
5
+ from fastapi.responses import StreamingResponse
6
+ import torch
7
+ import time
8
+ from diffusers import StableDiffusionPipeline, DPMSolverMultistepScheduler
9
+ from concurrent.futures import ThreadPoolExecutor
10
+
11
+ app = FastAPI()
12
+ app.POOL: ThreadPoolExecutor = None
13
+
14
+ @app.on_event("startup")
15
+ def startup_event():
16
+ app.POOL = ThreadPoolExecutor(max_workers=1)
17
+ @app.on_event("shutdown")
18
+ def shutdown_event():
19
+ app.POOL.shutdown(wait=False)
20
+
21
+ model_id = "stabilityai/stable-diffusion-2-1"
22
+ pipe_nsd = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
23
+ pipe_nsd.scheduler = DPMSolverMultistepScheduler.from_config(pipe_nsd.scheduler.config)
24
+ pipe_nsd = pipe_nsd.to("cuda")
25
+
26
+ @app.post("/getimage_nsd")
27
+ def get_image_nsd(
28
+ #prompt: Union[str, List[str]],
29
+ prompt: Optional[str] = "dog",
30
+ height: Optional[int] = 512,
31
+ width: Optional[int] = 512,
32
+ num_inference_steps: Optional[int] = 50,
33
+ guidance_scale: Optional[float] = 7.5,
34
+ negative_prompt: Optional[str] = None,):
35
+
36
+ image = app.POOL.submit(pipe_nsd,prompt,height,width,num_inference_steps,guidance_scale,negative_prompt).result().images
37
+ gc.collect()
38
+ torch.cuda.empty_cache()
39
+ filtered_image = io.BytesIO()
40
+ image[0].save(filtered_image, "JPEG")
41
+ filtered_image.seek(0)
42
+ return StreamingResponse(filtered_image, media_type="image/jpeg")
43
+
44
+ if __name__ == "__main__":
45
+ uvicorn.run(app, host="0.0.0.0", port=9000)