Spaces:
Sleeping
Sleeping
Update utils/image_utils.py
Browse files- utils/image_utils.py +27 -0
utils/image_utils.py
CHANGED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# genesis/utils/image_utils.py
|
2 |
+
import os
|
3 |
+
import requests
|
4 |
+
|
5 |
+
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
6 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
7 |
+
|
8 |
+
def generate_image(prompt, output_file="generated.png"):
|
9 |
+
"""Try Gemini first, then OpenAI if Gemini fails."""
|
10 |
+
try:
|
11 |
+
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={GEMINI_API_KEY}"
|
12 |
+
r = requests.post(url, json={"contents": [{"parts": [{"text": prompt}]}]})
|
13 |
+
r.raise_for_status()
|
14 |
+
# Save the image binary
|
15 |
+
with open(output_file, "wb") as f:
|
16 |
+
f.write(r.content)
|
17 |
+
return output_file
|
18 |
+
except Exception:
|
19 |
+
url = "https://api.openai.com/v1/images/generations"
|
20 |
+
headers = {"Authorization": f"Bearer {OPENAI_API_KEY}"}
|
21 |
+
r = requests.post(url, json={"model": "gpt-4o-mini", "prompt": prompt, "size": "1024x1024"}, headers=headers)
|
22 |
+
r.raise_for_status()
|
23 |
+
image_url = r.json()["data"][0]["url"]
|
24 |
+
img_data = requests.get(image_url).content
|
25 |
+
with open(output_file, "wb") as f:
|
26 |
+
f.write(img_data)
|
27 |
+
return output_file
|