Update api.py
Browse files
api.py
CHANGED
@@ -4,6 +4,7 @@ import os
|
|
4 |
import requests
|
5 |
from fastapi import FastAPI, HTTPException
|
6 |
from fastapi.responses import StreamingResponse
|
|
|
7 |
from PIL import Image
|
8 |
|
9 |
# API Configuration for Hugging Face
|
@@ -17,7 +18,7 @@ def query(payload):
|
|
17 |
return response.content
|
18 |
|
19 |
def generate_image(prompt: str) -> Image.Image:
|
20 |
-
#
|
21 |
random_seed = random.randint(0, 999999)
|
22 |
payload = {
|
23 |
"inputs": prompt,
|
@@ -29,18 +30,18 @@ def generate_image(prompt: str) -> Image.Image:
|
|
29 |
app = FastAPI()
|
30 |
|
31 |
@app.get("/")
|
32 |
-
def get_generated_image(text: str):
|
33 |
"""
|
34 |
-
API endpoint that
|
35 |
Example usage:
|
36 |
-
|
37 |
"""
|
38 |
try:
|
39 |
-
|
|
|
40 |
except Exception as e:
|
41 |
raise HTTPException(status_code=500, detail=str(e))
|
42 |
img_buffer = io.BytesIO()
|
43 |
image.save(img_buffer, format="PNG")
|
44 |
img_buffer.seek(0)
|
45 |
-
# This call will block until the image is generated.
|
46 |
return StreamingResponse(img_buffer, media_type="image/png")
|
|
|
4 |
import requests
|
5 |
from fastapi import FastAPI, HTTPException
|
6 |
from fastapi.responses import StreamingResponse
|
7 |
+
from fastapi.concurrency import run_in_threadpool
|
8 |
from PIL import Image
|
9 |
|
10 |
# API Configuration for Hugging Face
|
|
|
18 |
return response.content
|
19 |
|
20 |
def generate_image(prompt: str) -> Image.Image:
|
21 |
+
# Use a random seed so even identical prompts produce different images.
|
22 |
random_seed = random.randint(0, 999999)
|
23 |
payload = {
|
24 |
"inputs": prompt,
|
|
|
30 |
app = FastAPI()
|
31 |
|
32 |
@app.get("/")
|
33 |
+
async def get_generated_image(text: str):
|
34 |
"""
|
35 |
+
API endpoint that waits for the image to be generated and returns it.
|
36 |
Example usage:
|
37 |
+
https://bowozzz-gen.hf.space/api?text=jokowi
|
38 |
"""
|
39 |
try:
|
40 |
+
# Run the generate_image function in a threadpool so that this async endpoint waits for it.
|
41 |
+
image = await run_in_threadpool(generate_image, text)
|
42 |
except Exception as e:
|
43 |
raise HTTPException(status_code=500, detail=str(e))
|
44 |
img_buffer = io.BytesIO()
|
45 |
image.save(img_buffer, format="PNG")
|
46 |
img_buffer.seek(0)
|
|
|
47 |
return StreamingResponse(img_buffer, media_type="image/png")
|