BowoZZZ commited on
Commit
7748092
Β·
verified Β·
1 Parent(s): 8b6e883

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -79
app.py CHANGED
@@ -4,25 +4,16 @@ import io
4
  import random
5
  from PIL import Image
6
  import os
7
- import threading
8
-
9
- # Import FastAPI-related classes
10
- from fastapi import FastAPI, HTTPException
11
- from fastapi.responses import StreamingResponse
12
- import uvicorn
13
 
14
  # API Configuration for Hugging Face
15
  API_URL = "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-dev"
16
  headers = {"Authorization": f"Bearer {os.getenv('HF')}"}
17
 
18
- # Define your base URL here (adjust this for your deployment)
19
- BASE_URL = "https://bowozzz-gen.hf.space"
20
-
21
- # Function to query the Hugging Face API and generate an image
22
  def query(payload):
23
  response = requests.post(API_URL, headers=headers, json=payload)
24
  if response.status_code != 200:
25
- raise HTTPException(status_code=response.status_code, detail="API call failed")
 
26
  return response.content
27
 
28
  def generate_image(prompt: str) -> Image.Image:
@@ -35,71 +26,29 @@ def generate_image(prompt: str) -> Image.Image:
35
  image_bytes = query(payload)
36
  return Image.open(io.BytesIO(image_bytes))
37
 
38
- # --- FastAPI App for API endpoint ---
39
- api_app = FastAPI()
40
-
41
- @api_app.get("/api")
42
- def get_generated_image(text: str):
43
- """
44
- API endpoint that returns the generated image directly.
45
- Example: https://bowozzz-gen.hf.space/api?text=jokowi
46
- """
47
- try:
48
- image = generate_image(text)
49
- except Exception as e:
50
- raise HTTPException(status_code=500, detail=str(e))
51
- img_buffer = io.BytesIO()
52
- image.save(img_buffer, format="PNG")
53
- img_buffer.seek(0)
54
- return StreamingResponse(img_buffer, media_type="image/png")
55
-
56
- # Run FastAPI in a separate thread so it runs alongside Streamlit
57
- def run_api():
58
- uvicorn.run(api_app, host="0.0.0.0", port=8000)
59
-
60
- threading.Thread(target=run_api, daemon=True).start()
61
-
62
- # --- Streamlit UI ---
63
-
64
- # Use st.query_params to check for a query parameter.
65
- query_params = st.query_params
66
- prompt_from_url = query_params.get('text')
67
-
68
- if prompt_from_url:
69
- # If a query parameter "text" is present, assume this is an API request.
70
- # Provide the API endpoint URL that returns raw image data.
71
- st.write("A request with a text query parameter was detected. To get the raw image data, use the API endpoint below:")
72
- api_endpoint = f"{BASE_URL}/api?text={prompt_from_url}"
73
- st.write("API Endpoint:", api_endpoint)
74
-
75
- # Optionally, display the generated image in the UI:
76
- image = generate_image(prompt_from_url)
77
- st.image(image, caption="Generated Image", use_container_width=True)
78
- else:
79
- # Standard interactive UI
80
- st.title("AI Image Generator πŸŽ¨πŸš€")
81
- st.write("Enter a prompt below and generate an AI-generated image using Hugging Face!")
82
-
83
- prompt = st.text_input("Enter your prompt:", "Astronaut riding a horse")
84
-
85
- if st.button("Generate Image"):
86
- if prompt:
87
- st.write("Generating image... Please wait ⏳")
88
- image = generate_image(prompt)
89
- st.image(image, caption="Generated Image", use_container_width=True)
90
-
91
- # Convert image to bytes for download
92
- img_buffer = io.BytesIO()
93
- image.save(img_buffer, format="PNG")
94
- img_buffer.seek(0)
95
- st.download_button(
96
- label="Download Image πŸ“₯",
97
- data=img_buffer,
98
- file_name="generated_image.png",
99
- mime="image/png"
100
- )
101
- else:
102
- st.warning("Please enter a prompt before generating an image.")
103
-
104
- st.write("---")
105
- st.write("Powered by [Hugging Face](https://huggingface.co/) πŸš€")
 
4
  import random
5
  from PIL import Image
6
  import os
 
 
 
 
 
 
7
 
8
  # API Configuration for Hugging Face
9
  API_URL = "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-dev"
10
  headers = {"Authorization": f"Bearer {os.getenv('HF')}"}
11
 
 
 
 
 
12
  def query(payload):
13
  response = requests.post(API_URL, headers=headers, json=payload)
14
  if response.status_code != 200:
15
+ st.error("Error calling the Hugging Face API.")
16
+ st.stop()
17
  return response.content
18
 
19
  def generate_image(prompt: str) -> Image.Image:
 
26
  image_bytes = query(payload)
27
  return Image.open(io.BytesIO(image_bytes))
28
 
29
+ st.title("AI Image Generator πŸŽ¨πŸš€")
30
+ st.write("Enter a prompt below and generate an AI-generated image using Hugging Face!")
31
+
32
+ prompt = st.text_input("Enter your prompt:", "Astronaut riding a horse")
33
+
34
+ if st.button("Generate Image"):
35
+ if prompt:
36
+ st.write("Generating image... Please wait ⏳")
37
+ image = generate_image(prompt)
38
+ st.image(image, caption="Generated Image", use_container_width=True)
39
+
40
+ # Convert image to bytes for download
41
+ img_buffer = io.BytesIO()
42
+ image.save(img_buffer, format="PNG")
43
+ img_buffer.seek(0)
44
+ st.download_button(
45
+ label="Download Image πŸ“₯",
46
+ data=img_buffer,
47
+ file_name="generated_image.png",
48
+ mime="image/png"
49
+ )
50
+ else:
51
+ st.warning("Please enter a prompt before generating an image.")
52
+
53
+ st.write("---")
54
+ st.write("Powered by [Hugging Face](https://huggingface.co/) πŸš€")