Spaces:
Running
Running
Create image_generation.py
Browse files
application/utils/image_generation.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# application/utils/image_generation.py - NEW FILE
|
2 |
+
from huggingface_hub import InferenceClient
|
3 |
+
import os
|
4 |
+
import base64
|
5 |
+
from io import BytesIO
|
6 |
+
|
7 |
+
def generate_image(prompt: str) -> str:
|
8 |
+
"""
|
9 |
+
Generates an image based on the given prompt using the Hugging Face Inference API.
|
10 |
+
|
11 |
+
Args:
|
12 |
+
prompt: The text prompt to generate the image from.
|
13 |
+
|
14 |
+
Returns:
|
15 |
+
The base64 encoded image data, or None if an error occurred.
|
16 |
+
"""
|
17 |
+
try:
|
18 |
+
api_key = os.environ.get('auth')
|
19 |
+
if not api_key:
|
20 |
+
raise ValueError("Hugging Face API key ('auth') not found in environment variables.")
|
21 |
+
|
22 |
+
client = InferenceClient(api_key=api_key)
|
23 |
+
image = client.text_to_image(
|
24 |
+
prompt,
|
25 |
+
model="black-forest-labs/FLUX.1-schnell"
|
26 |
+
)
|
27 |
+
|
28 |
+
# Convert PIL Image to base64 string
|
29 |
+
buffered = BytesIO()
|
30 |
+
image.save(buffered, format="PNG") # Or "JPEG" if appropriate
|
31 |
+
img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
|
32 |
+
return img_str
|
33 |
+
|
34 |
+
except Exception as e:
|
35 |
+
print(f"Error in image generation: {e}")
|
36 |
+
return None
|