BowoZZZ commited on
Commit
c5f541c
·
verified ·
1 Parent(s): 275acba

Update api.py

Browse files
Files changed (1) hide show
  1. api.py +7 -6
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
- # 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,
@@ -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 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")
 
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")