Spaces:
Runtime error
Runtime error
Jamiiwej2903
commited on
Create main.py
Browse files
main.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI
|
2 |
+
from pydantic import BaseModel
|
3 |
+
from huggingface_hub import InferenceClient
|
4 |
+
import uvicorn
|
5 |
+
from fastapi.responses import StreamingResponse
|
6 |
+
import io
|
7 |
+
|
8 |
+
app = FastAPI()
|
9 |
+
|
10 |
+
client = InferenceClient("stabilityai/stable-diffusion-2-1")
|
11 |
+
|
12 |
+
class Item(BaseModel):
|
13 |
+
prompt: str
|
14 |
+
negative_prompt: str = ""
|
15 |
+
num_inference_steps: int = 50
|
16 |
+
guidance_scale: float = 7.5
|
17 |
+
width: int = 512
|
18 |
+
height: int = 512
|
19 |
+
|
20 |
+
def generate_image(item: Item):
|
21 |
+
image = client.image_to_image(
|
22 |
+
image=None, # We're using text-to-image, so this is None
|
23 |
+
prompt=item.prompt,
|
24 |
+
negative_prompt=item.negative_prompt,
|
25 |
+
num_inference_steps=item.num_inference_steps,
|
26 |
+
guidance_scale=item.guidance_scale,
|
27 |
+
width=item.width,
|
28 |
+
height=item.height,
|
29 |
+
)
|
30 |
+
return image
|
31 |
+
|
32 |
+
@app.post("/generate_image/")
|
33 |
+
async def generate_image_api(item: Item):
|
34 |
+
image = generate_image(item)
|
35 |
+
|
36 |
+
# Convert the image to a byte stream
|
37 |
+
img_byte_arr = io.BytesIO()
|
38 |
+
image.save(img_byte_arr, format='PNG')
|
39 |
+
img_byte_arr.seek(0)
|
40 |
+
|
41 |
+
# Return the image as a streaming response
|
42 |
+
return StreamingResponse(img_byte_arr, media_type="image/png")
|
43 |
+
|
44 |
+
if __name__ == "__main__":
|
45 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|