amirkhanbloch commited on
Commit
1991e47
·
verified ·
1 Parent(s): ed5acad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -8
app.py CHANGED
@@ -18,7 +18,6 @@ if not HUGGINGFACE_TOKEN:
18
  raise ValueError("Hugging Face API token not found. Please set it in the environment variables.")
19
 
20
  headers = {"Authorization": f"Bearer {HUGGINGFACE_TOKEN}"}
21
- print(HUGGINGFACE_TOKEN)
22
 
23
  # Function to query Hugging Face model API
24
  def query(payload):
@@ -34,7 +33,7 @@ def query(payload):
34
  def generate_image():
35
  try:
36
  # Send a request to the Hugging Face model
37
- image_bytes = query({"inputs": "cat with dog"})
38
 
39
  # Open the image
40
  image = Image.open(io.BytesIO(image_bytes))
@@ -49,9 +48,18 @@ def generate_image():
49
  except Exception as e:
50
  raise HTTPException(status_code=500, detail=str(e))
51
 
52
- # Define a root route to handle requests to "/"
53
- @app.get("/")
54
- def read_root(logs: str = None):
55
- if logs == "container":
56
- return {"logs": "Container logs not available."}
57
- return {"message": "Welcome to the API! Use /generate-image to generate images."}
 
 
 
 
 
 
 
 
 
 
18
  raise ValueError("Hugging Face API token not found. Please set it in the environment variables.")
19
 
20
  headers = {"Authorization": f"Bearer {HUGGINGFACE_TOKEN}"}
 
21
 
22
  # Function to query Hugging Face model API
23
  def query(payload):
 
33
  def generate_image():
34
  try:
35
  # Send a request to the Hugging Face model
36
+ image_bytes = query({"inputs": "dog with cat"})
37
 
38
  # Open the image
39
  image = Image.open(io.BytesIO(image_bytes))
 
48
  except Exception as e:
49
  raise HTTPException(status_code=500, detail=str(e))
50
 
51
+ # Event handler to generate the image on startup
52
+ @app.on_event("startup")
53
+ async def startup_event():
54
+ try:
55
+ # Automatically call the generate image logic on startup
56
+ print("Generating image on startup...")
57
+ image_bytes = query({"inputs": "dog with cat"})
58
+
59
+ # Save the image locally as 'generated_image.png' for verification
60
+ with open("generated_image.png", "wb") as f:
61
+ f.write(image_bytes)
62
+ print("Image generated and saved as 'generated_image.png'.")
63
+
64
+ except Exception as e:
65
+ print(f"Error during image generation: {e}")