Create api.py
Browse files
api.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import io
|
2 |
+
import random
|
3 |
+
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
|
10 |
+
API_URL = "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-dev"
|
11 |
+
headers = {"Authorization": f"Bearer {os.getenv('HF')}"}
|
12 |
+
|
13 |
+
def query(payload):
|
14 |
+
response = requests.post(API_URL, headers=headers, json=payload)
|
15 |
+
if response.status_code != 200:
|
16 |
+
raise HTTPException(status_code=response.status_code, detail="API call failed")
|
17 |
+
return response.content
|
18 |
+
|
19 |
+
def generate_image(prompt: str) -> Image.Image:
|
20 |
+
# Generate a random seed so even the same prompt produces a new image.
|
21 |
+
random_seed = random.randint(0, 999999)
|
22 |
+
payload = {
|
23 |
+
"inputs": prompt,
|
24 |
+
"parameters": {"seed": random_seed}
|
25 |
+
}
|
26 |
+
image_bytes = query(payload)
|
27 |
+
return Image.open(io.BytesIO(image_bytes))
|
28 |
+
|
29 |
+
app = FastAPI()
|
30 |
+
|
31 |
+
@app.get("/")
|
32 |
+
def get_generated_image(text: str):
|
33 |
+
"""
|
34 |
+
API endpoint that returns the generated image directly.
|
35 |
+
Example usage:
|
36 |
+
https://bowozzz-gen.hf.space/api?text=jokowi
|
37 |
+
"""
|
38 |
+
try:
|
39 |
+
image = generate_image(text)
|
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")
|