Spaces:
Running
Running
Chandima Prabhath
commited on
Commit
·
40babb7
1
Parent(s):
1a71a94
upload edited images to imgbb
Browse files
flux_kontext_lib/image_generator.py
CHANGED
@@ -1,6 +1,7 @@
|
|
1 |
import requests
|
2 |
import base64
|
3 |
import json
|
|
|
4 |
from io import BytesIO
|
5 |
from typing import Optional, Dict
|
6 |
|
@@ -12,6 +13,41 @@ except ImportError:
|
|
12 |
print("Pillow library not found. Please install it using: pip install Pillow")
|
13 |
exit()
|
14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
def _download_image_from_url(image_url: str, save_path: str) -> bool:
|
16 |
"""
|
17 |
Downloads an image from a URL and saves it to a local path.
|
@@ -25,7 +61,7 @@ def _download_image_from_url(image_url: str, save_path: str) -> bool:
|
|
25 |
"""
|
26 |
print(f"Downloading generated image from: {image_url}")
|
27 |
try:
|
28 |
-
image_response = requests.get(image_url, stream=True)
|
29 |
# Check if the download request was successful.
|
30 |
if image_response.status_code == 200:
|
31 |
content_type = image_response.headers.get('Content-Type', '')
|
@@ -51,7 +87,8 @@ def generate_image(
|
|
51 |
download_path: Optional[str] = None
|
52 |
) -> Optional[Dict]:
|
53 |
"""
|
54 |
-
Sends a request to the image generation API
|
|
|
55 |
|
56 |
Args:
|
57 |
prompt_text: The instructional text for image modification.
|
@@ -59,7 +96,8 @@ def generate_image(
|
|
59 |
download_path: If provided, the path to save the generated image.
|
60 |
|
61 |
Returns:
|
62 |
-
A dictionary of the JSON response from the API,
|
|
|
63 |
"""
|
64 |
url = "https://kontext-chat.replicate.dev/generate-image"
|
65 |
|
@@ -101,19 +139,28 @@ def generate_image(
|
|
101 |
}
|
102 |
|
103 |
try:
|
104 |
-
response = requests.post(url, headers=headers, data=json.dumps(payload))
|
105 |
response.raise_for_status()
|
106 |
api_response_data = response.json()
|
107 |
|
108 |
-
|
|
|
|
|
109 |
if download_path and isinstance(api_response_data, dict):
|
110 |
image_url = api_response_data.get("imageUrl")
|
111 |
if image_url:
|
112 |
-
_download_image_from_url(image_url, download_path)
|
|
|
|
|
|
|
113 |
else:
|
114 |
-
print("Warning: 'imageUrl' not found in response,
|
|
|
|
|
|
|
|
|
115 |
|
116 |
return api_response_data
|
117 |
except requests.exceptions.RequestException as e:
|
118 |
print(f"API request failed: {e}")
|
119 |
-
return None
|
|
|
1 |
import requests
|
2 |
import base64
|
3 |
import json
|
4 |
+
import os
|
5 |
from io import BytesIO
|
6 |
from typing import Optional, Dict
|
7 |
|
|
|
13 |
print("Pillow library not found. Please install it using: pip install Pillow")
|
14 |
exit()
|
15 |
|
16 |
+
# --- Configuration ---
|
17 |
+
IMGBB_API_KEY = os.getenv("IMGBB_API_KEY")
|
18 |
+
|
19 |
+
def upload_to_imgbb(image_path: str, file_name: str) -> Optional[str]:
|
20 |
+
"""
|
21 |
+
Uploads the image at image_path to ImgBB.
|
22 |
+
Returns the public URL or None on failure.
|
23 |
+
"""
|
24 |
+
if not IMGBB_API_KEY:
|
25 |
+
print("Warning: IMGBB_API_KEY not set, skipping upload")
|
26 |
+
return None
|
27 |
+
|
28 |
+
print(f"Uploading {file_name} to ImgBB...")
|
29 |
+
try:
|
30 |
+
with open(image_path, 'rb') as f:
|
31 |
+
files = {"image": (file_name, f.read())}
|
32 |
+
resp = requests.post(
|
33 |
+
"https://api.imgbb.com/1/upload",
|
34 |
+
params={"key": IMGBB_API_KEY},
|
35 |
+
files=files,
|
36 |
+
timeout=20
|
37 |
+
)
|
38 |
+
resp.raise_for_status()
|
39 |
+
data = resp.json().get("data", {})
|
40 |
+
url = data.get("url")
|
41 |
+
if url:
|
42 |
+
print(f"Successfully uploaded to ImgBB: {url}")
|
43 |
+
return url
|
44 |
+
else:
|
45 |
+
print(f"Error: ImgBB API response missing 'url'. Response: {resp.json()}")
|
46 |
+
return None
|
47 |
+
except requests.exceptions.RequestException as e:
|
48 |
+
print(f"Error: ImgBB upload failed: {e}")
|
49 |
+
return None
|
50 |
+
|
51 |
def _download_image_from_url(image_url: str, save_path: str) -> bool:
|
52 |
"""
|
53 |
Downloads an image from a URL and saves it to a local path.
|
|
|
61 |
"""
|
62 |
print(f"Downloading generated image from: {image_url}")
|
63 |
try:
|
64 |
+
image_response = requests.get(image_url, stream=True, timeout=30)
|
65 |
# Check if the download request was successful.
|
66 |
if image_response.status_code == 200:
|
67 |
content_type = image_response.headers.get('Content-Type', '')
|
|
|
87 |
download_path: Optional[str] = None
|
88 |
) -> Optional[Dict]:
|
89 |
"""
|
90 |
+
Sends a request to the image generation API, optionally downloads the result,
|
91 |
+
and uploads it to ImgBB.
|
92 |
|
93 |
Args:
|
94 |
prompt_text: The instructional text for image modification.
|
|
|
96 |
download_path: If provided, the path to save the generated image.
|
97 |
|
98 |
Returns:
|
99 |
+
A dictionary of the JSON response from the API, including the ImgBB URL,
|
100 |
+
or None on error.
|
101 |
"""
|
102 |
url = "https://kontext-chat.replicate.dev/generate-image"
|
103 |
|
|
|
139 |
}
|
140 |
|
141 |
try:
|
142 |
+
response = requests.post(url, headers=headers, data=json.dumps(payload), timeout=45)
|
143 |
response.raise_for_status()
|
144 |
api_response_data = response.json()
|
145 |
|
146 |
+
imgbb_url = None # Initialize imgbb_url
|
147 |
+
|
148 |
+
# --- Download & Upload Logic ---
|
149 |
if download_path and isinstance(api_response_data, dict):
|
150 |
image_url = api_response_data.get("imageUrl")
|
151 |
if image_url:
|
152 |
+
if _download_image_from_url(image_url, download_path):
|
153 |
+
# If download is successful, upload the saved file to ImgBB
|
154 |
+
file_name = os.path.basename(download_path)
|
155 |
+
imgbb_url = upload_to_imgbb(download_path, file_name)
|
156 |
else:
|
157 |
+
print("Warning: 'imageUrl' not found in API response, cannot download or upload image.")
|
158 |
+
|
159 |
+
# Add the ImgBB URL to the response dictionary if it was generated
|
160 |
+
if isinstance(api_response_data, dict):
|
161 |
+
api_response_data['imgbb_url'] = imgbb_url
|
162 |
|
163 |
return api_response_data
|
164 |
except requests.exceptions.RequestException as e:
|
165 |
print(f"API request failed: {e}")
|
166 |
+
return None
|