SyntheticVis-Umut commited on
Commit
e3a8a3d
·
1 Parent(s): 819742e

Enhance FastAPI application to support image generation with Inference API. Updated API title, added model configuration, and implemented a new endpoint for generating images from text prompts. Retained echo functionality for testing.

Browse files
Files changed (2) hide show
  1. app.py +39 -5
  2. requirements.txt +2 -0
app.py CHANGED
@@ -1,16 +1,50 @@
 
 
1
  from fastapi import FastAPI
 
2
  from pydantic import BaseModel
 
3
 
4
- app = FastAPI(title="Hello API")
5
 
6
- class Prompt(BaseModel):
7
- text: str
 
 
 
 
 
 
 
 
 
 
8
 
9
  @app.get("/")
10
  def root():
11
- return {"ok": True, "message": "API is live"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  @app.post("/echo")
14
  def echo(p: Prompt):
15
- # do your logic here
16
  return {"length": len(p.text), "upper": p.text.upper()}
 
1
+ import io, os
2
+ from typing import Optional
3
  from fastapi import FastAPI
4
+ from fastapi.responses import StreamingResponse, JSONResponse
5
  from pydantic import BaseModel
6
+ from huggingface_hub import InferenceClient
7
 
8
+ app = FastAPI(title="ImageGen API")
9
 
10
+ # Choose a model that supports text->image via Inference API.
11
+ # FLUX.1-schnell is fast; you can swap for SDXL or others later.
12
+ MODEL_ID = os.getenv("MODEL_ID", "black-forest-labs/FLUX.1-schnell")
13
+ HF_TOKEN = os.getenv("HF_TOKEN") # set in Space Secrets
14
+ client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)
15
+
16
+ class GenReq(BaseModel):
17
+ prompt: str
18
+ width: int = 768
19
+ height: int = 768
20
+ seed: Optional[int] = None
21
+ num_inference_steps: Optional[int] = None # some models ignore this
22
 
23
  @app.get("/")
24
  def root():
25
+ return {"ok": True, "message": "API is live", "model": MODEL_ID}
26
+
27
+ @app.post("/generate")
28
+ def generate(req: GenReq):
29
+ try:
30
+ # InferenceClient returns a PIL.Image for text_to_image
31
+ img = client.text_to_image(
32
+ prompt=req.prompt,
33
+ size=f"{req.width}x{req.height}",
34
+ seed=req.seed,
35
+ num_inference_steps=req.num_inference_steps
36
+ )
37
+ buf = io.BytesIO()
38
+ img.save(buf, format="PNG")
39
+ buf.seek(0)
40
+ return StreamingResponse(buf, media_type="image/png")
41
+ except Exception as e:
42
+ return JSONResponse({"error": str(e)}, status_code=500)
43
+
44
+ # Keep your original echo for testing
45
+ class Prompt(BaseModel):
46
+ text: str
47
 
48
  @app.post("/echo")
49
  def echo(p: Prompt):
 
50
  return {"length": len(p.text), "upper": p.text.upper()}
requirements.txt CHANGED
@@ -1,2 +1,4 @@
1
  fastapi
2
  uvicorn
 
 
 
1
  fastapi
2
  uvicorn
3
+ huggingface_hub
4
+ python-multipart