BowoZZZ commited on
Commit
a8df29c
Β·
verified Β·
1 Parent(s): 437062b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -35
app.py CHANGED
@@ -4,70 +4,94 @@ import io
4
  import random
5
  from PIL import Image
6
  import os
 
7
 
8
- # API Configuration
 
 
 
 
 
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
- # Function to query the Hugging Face API
13
  def query(payload):
14
  response = requests.post(API_URL, headers=headers, json=payload)
 
 
15
  return response.content
16
 
17
- # Check for 'text' parameter in URL
18
- query_params = st.query_params
19
- prompt_from_url = query_params.get('text')
20
-
21
- def generate_image(prompt):
22
- # Generate a random seed to force a new image
23
  random_seed = random.randint(0, 999999)
24
  payload = {
25
  "inputs": prompt,
26
- "parameters": {
27
- "seed": random_seed
28
- }
29
  }
30
  image_bytes = query(payload)
31
  return Image.open(io.BytesIO(image_bytes))
32
 
33
- if prompt_from_url:
34
- # If 'text' parameter is present, generate and display the image only
35
- prompt = prompt_from_url
36
- image = generate_image(prompt)
37
- st.image(image, caption="Generated Image", use_container_width=True)
38
 
39
- # Provide download link
 
 
 
 
 
 
 
 
 
40
  img_buffer = io.BytesIO()
41
  image.save(img_buffer, format="PNG")
42
  img_buffer.seek(0)
43
- st.download_button(
44
- label="Download Image πŸ“₯",
45
- data=img_buffer,
46
- file_name="generated_image.png",
47
- mime="image/png"
48
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  else:
50
- # Standard interface with prompt input
51
  st.title("AI Image Generator πŸŽ¨πŸš€")
52
  st.write("Enter a prompt below and generate an AI-generated image using Hugging Face!")
53
-
54
- # User Input
55
  prompt = st.text_input("Enter your prompt:", "Astronaut riding a horse")
56
-
57
  if st.button("Generate Image"):
58
  if prompt:
59
  st.write("Generating image... Please wait ⏳")
60
  image = generate_image(prompt)
61
-
62
- # Display Image
63
  st.image(image, caption="Generated Image", use_container_width=True)
64
-
65
- # Convert Image to Bytes for Download
66
  img_buffer = io.BytesIO()
67
  image.save(img_buffer, format="PNG")
68
  img_buffer.seek(0)
69
-
70
- # Download Button
71
  st.download_button(
72
  label="Download Image πŸ“₯",
73
  data=img_buffer,
@@ -76,7 +100,6 @@ else:
76
  )
77
  else:
78
  st.warning("Please enter a prompt before generating an image.")
79
-
80
- # Footer
81
  st.write("---")
82
  st.write("Powered by [Hugging Face](https://huggingface.co/) πŸš€")
 
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
+ # Function to query the Hugging Face API and generate an image
19
  def query(payload):
20
  response = requests.post(API_URL, headers=headers, json=payload)
21
+ if response.status_code != 200:
22
+ raise HTTPException(status_code=response.status_code, detail="API call failed")
23
  return response.content
24
 
25
+ def generate_image(prompt: str) -> Image.Image:
26
+ # Use a random seed so even identical prompts produce different images.
 
 
 
 
27
  random_seed = random.randint(0, 999999)
28
  payload = {
29
  "inputs": prompt,
30
+ "parameters": {"seed": random_seed}
 
 
31
  }
32
  image_bytes = query(payload)
33
  return Image.open(io.BytesIO(image_bytes))
34
 
35
+ # --- FastAPI App for API endpoint ---
36
+ api_app = FastAPI()
 
 
 
37
 
38
+ @api_app.get("/api")
39
+ def get_generated_image(text: str):
40
+ """
41
+ API endpoint that returns the generated image directly.
42
+ Example: https://your-domain/?text=jokowi will eventually call this endpoint.
43
+ """
44
+ try:
45
+ image = generate_image(text)
46
+ except Exception as e:
47
+ raise HTTPException(status_code=500, detail=str(e))
48
  img_buffer = io.BytesIO()
49
  image.save(img_buffer, format="PNG")
50
  img_buffer.seek(0)
51
+ return StreamingResponse(img_buffer, media_type="image/png")
52
+
53
+ # Run FastAPI in a separate thread so it runs alongside Streamlit
54
+ def run_api():
55
+ uvicorn.run(api_app, host="0.0.0.0", port=8000)
56
+
57
+ threading.Thread(target=run_api, daemon=True).start()
58
+
59
+ # --- Streamlit UI ---
60
+
61
+ # Use st.query_params (a property) to check for a query parameter.
62
+ query_params = st.query_params
63
+ prompt_from_url = query_params.get('text')
64
+
65
+ if prompt_from_url:
66
+ # If a query parameter "text" is present, assume this is an API request.
67
+ # For API clients, we don't want to show UI elements like buttons.
68
+ # Instead, we offer a clickable link or instructions so that they know
69
+ # they can fetch the image directly from our FastAPI endpoint.
70
+ st.write("A request with a text query parameter was detected. To get the raw image data, please use the API endpoint:")
71
+ # Construct the API URL (adjust the host/domain and port as needed)
72
+ api_endpoint = f"{st.experimental_get_url()[:-1]}/api?text={prompt_from_url}"
73
+ st.write("API Endpoint:", api_endpoint)
74
+
75
+ # Optionally, you can also show 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,
 
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/) πŸš€")