Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -11,6 +11,36 @@ import base64
|
|
11 |
# Set up Replicate API key from environment variable
|
12 |
os.environ['REPLICATE_API_TOKEN'] = os.getenv('REPLICATE_API_TOKEN')
|
13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
def process_images(prompt, image1, image2=None):
|
15 |
"""
|
16 |
Process uploaded images with Replicate API
|
@@ -23,39 +53,39 @@ def process_images(prompt, image1, image2=None):
|
|
23 |
return None, "β οΈ Please set REPLICATE_API_TOKEN environment variable"
|
24 |
|
25 |
try:
|
26 |
-
|
27 |
-
from replicate.client import Client
|
28 |
-
|
29 |
-
# Initialize Replicate client
|
30 |
-
client = Client(api_token=os.getenv('REPLICATE_API_TOKEN'))
|
31 |
|
32 |
-
# Upload images to get URLs
|
33 |
-
# Replicate needs actual URLs, so we need to upload the images first
|
34 |
image_urls = []
|
35 |
|
36 |
-
|
37 |
-
|
38 |
-
image1
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
|
|
|
|
|
|
|
|
|
|
52 |
|
53 |
-
status_message = "π¨ Processing
|
54 |
|
55 |
-
# Prepare input matching the exact format
|
56 |
input_data = {
|
57 |
"prompt": prompt,
|
58 |
-
"image_input": image_urls
|
59 |
}
|
60 |
|
61 |
# Run the model
|
@@ -64,40 +94,49 @@ def process_images(prompt, image1, image2=None):
|
|
64 |
input=input_data
|
65 |
)
|
66 |
|
67 |
-
# Handle
|
68 |
output_url = None
|
69 |
|
70 |
-
#
|
71 |
if hasattr(output, 'url'):
|
72 |
output_url = output.url()
|
73 |
elif isinstance(output, str):
|
74 |
output_url = output
|
75 |
elif isinstance(output, list) and len(output) > 0:
|
76 |
output_url = output[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
|
78 |
if not output_url:
|
79 |
-
return None, "β Error: No
|
80 |
|
81 |
# Download the generated image
|
82 |
-
# Based on your example, we can also use output.read() if available
|
83 |
if hasattr(output, 'read'):
|
|
|
84 |
img_data = output.read()
|
85 |
img = Image.open(BytesIO(img_data))
|
86 |
else:
|
87 |
-
#
|
88 |
response = requests.get(output_url)
|
89 |
if response.status_code == 200:
|
90 |
img = Image.open(BytesIO(response.content))
|
91 |
else:
|
92 |
return None, f"β Error: Failed to download image (Status: {response.status_code})"
|
93 |
|
94 |
-
return img, "β
Image generated successfully
|
95 |
|
|
|
|
|
96 |
except Exception as e:
|
97 |
-
# If the model doesn't exist or other errors, provide helpful message
|
98 |
error_msg = str(e)
|
99 |
if "not found" in error_msg.lower():
|
100 |
-
return None, "β Model 'google/nano-banana' not found. Please check
|
101 |
elif "authentication" in error_msg.lower():
|
102 |
return None, "β Authentication failed. Please check your REPLICATE_API_TOKEN."
|
103 |
else:
|
@@ -242,15 +281,17 @@ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
|
|
242 |
pip install gradio replicate pillow requests
|
243 |
```
|
244 |
|
245 |
-
3. **
|
246 |
-
-
|
247 |
-
-
|
248 |
-
-
|
249 |
|
250 |
-
4. **
|
251 |
-
-
|
252 |
-
-
|
253 |
-
|
|
|
|
|
254 |
|
255 |
### π Security:
|
256 |
- API keys are managed through environment variables
|
|
|
11 |
# Set up Replicate API key from environment variable
|
12 |
os.environ['REPLICATE_API_TOKEN'] = os.getenv('REPLICATE_API_TOKEN')
|
13 |
|
14 |
+
def upload_to_imgur(image):
|
15 |
+
"""
|
16 |
+
Upload image to Imgur and return URL
|
17 |
+
Alternative: You can use other services like Cloudinary, imgbb, etc.
|
18 |
+
"""
|
19 |
+
import base64
|
20 |
+
import json
|
21 |
+
|
22 |
+
# Convert PIL image to base64
|
23 |
+
buffered = BytesIO()
|
24 |
+
image.save(buffered, format="PNG")
|
25 |
+
img_base64 = base64.b64encode(buffered.getvalue()).decode()
|
26 |
+
|
27 |
+
# Imgur API (anonymous upload)
|
28 |
+
headers = {
|
29 |
+
'Authorization': 'Client-ID 0d90e8a3e7d8b4e' # Public client ID for anonymous uploads
|
30 |
+
}
|
31 |
+
|
32 |
+
response = requests.post(
|
33 |
+
'https://api.imgur.com/3/image',
|
34 |
+
headers=headers,
|
35 |
+
data={'image': img_base64}
|
36 |
+
)
|
37 |
+
|
38 |
+
if response.status_code == 200:
|
39 |
+
data = response.json()
|
40 |
+
return data['data']['link']
|
41 |
+
else:
|
42 |
+
raise Exception(f"Failed to upload to Imgur: {response.status_code}")
|
43 |
+
|
44 |
def process_images(prompt, image1, image2=None):
|
45 |
"""
|
46 |
Process uploaded images with Replicate API
|
|
|
53 |
return None, "β οΈ Please set REPLICATE_API_TOKEN environment variable"
|
54 |
|
55 |
try:
|
56 |
+
status_message = "π€ Uploading images..."
|
|
|
|
|
|
|
|
|
57 |
|
58 |
+
# Upload images to get public URLs
|
|
|
59 |
image_urls = []
|
60 |
|
61 |
+
try:
|
62 |
+
# Try to upload to Imgur (or your preferred service)
|
63 |
+
url1 = upload_to_imgur(image1)
|
64 |
+
image_urls.append(url1)
|
65 |
+
|
66 |
+
if image2:
|
67 |
+
url2 = upload_to_imgur(image2)
|
68 |
+
image_urls.append(url2)
|
69 |
+
|
70 |
+
except Exception as upload_error:
|
71 |
+
# Fallback: Convert to base64 data URIs
|
72 |
+
buffered1 = BytesIO()
|
73 |
+
image1.save(buffered1, format="PNG")
|
74 |
+
img_base64_1 = base64.b64encode(buffered1.getvalue()).decode()
|
75 |
+
image_urls.append(f"data:image/png;base64,{img_base64_1}")
|
76 |
+
|
77 |
+
if image2:
|
78 |
+
buffered2 = BytesIO()
|
79 |
+
image2.save(buffered2, format="PNG")
|
80 |
+
img_base64_2 = base64.b64encode(buffered2.getvalue()).decode()
|
81 |
+
image_urls.append(f"data:image/png;base64,{img_base64_2}")
|
82 |
|
83 |
+
status_message = "π¨ Processing with nano-banana model..."
|
84 |
|
85 |
+
# Prepare input matching the exact format from your example
|
86 |
input_data = {
|
87 |
"prompt": prompt,
|
88 |
+
"image_input": image_urls
|
89 |
}
|
90 |
|
91 |
# Run the model
|
|
|
94 |
input=input_data
|
95 |
)
|
96 |
|
97 |
+
# Handle various output formats
|
98 |
output_url = None
|
99 |
|
100 |
+
# Check different possible output formats
|
101 |
if hasattr(output, 'url'):
|
102 |
output_url = output.url()
|
103 |
elif isinstance(output, str):
|
104 |
output_url = output
|
105 |
elif isinstance(output, list) and len(output) > 0:
|
106 |
output_url = output[0]
|
107 |
+
elif hasattr(output, '__iter__'):
|
108 |
+
try:
|
109 |
+
for item in output:
|
110 |
+
if isinstance(item, str) and item.startswith('http'):
|
111 |
+
output_url = item
|
112 |
+
break
|
113 |
+
except:
|
114 |
+
pass
|
115 |
|
116 |
if not output_url:
|
117 |
+
return None, f"β Error: No valid output URL found. Response type: {type(output)}"
|
118 |
|
119 |
# Download the generated image
|
|
|
120 |
if hasattr(output, 'read'):
|
121 |
+
# If output has a read method, use it
|
122 |
img_data = output.read()
|
123 |
img = Image.open(BytesIO(img_data))
|
124 |
else:
|
125 |
+
# Otherwise, download from URL
|
126 |
response = requests.get(output_url)
|
127 |
if response.status_code == 200:
|
128 |
img = Image.open(BytesIO(response.content))
|
129 |
else:
|
130 |
return None, f"β Error: Failed to download image (Status: {response.status_code})"
|
131 |
|
132 |
+
return img, f"β
Image generated successfully! Output URL: {output_url[:50]}..."
|
133 |
|
134 |
+
except replicate.exceptions.ModelError as e:
|
135 |
+
return None, f"β Model Error: {str(e)}\n\nMake sure 'google/nano-banana' exists and is accessible."
|
136 |
except Exception as e:
|
|
|
137 |
error_msg = str(e)
|
138 |
if "not found" in error_msg.lower():
|
139 |
+
return None, "β Model 'google/nano-banana' not found. Please check:\n1. Model name is correct\n2. Model is public or you have access\n3. Try format: 'owner/model-name'"
|
140 |
elif "authentication" in error_msg.lower():
|
141 |
return None, "β Authentication failed. Please check your REPLICATE_API_TOKEN."
|
142 |
else:
|
|
|
281 |
pip install gradio replicate pillow requests
|
282 |
```
|
283 |
|
284 |
+
3. **Image Hosting Options:**
|
285 |
+
- **Option A**: Uses Imgur for free image hosting (default)
|
286 |
+
- **Option B**: Falls back to base64 data URIs if upload fails
|
287 |
+
- **Option C**: Use your own image hosting service (Cloudinary, S3, etc.)
|
288 |
|
289 |
+
4. **Model Notes:**
|
290 |
+
- Using: `google/nano-banana` model
|
291 |
+
- If this model doesn't exist, try:
|
292 |
+
- `stability-ai/stable-diffusion`
|
293 |
+
- `pharmapsychotic/clip-interrogator`
|
294 |
+
- Check available models at: https://replicate.com/explore
|
295 |
|
296 |
### π Security:
|
297 |
- API keys are managed through environment variables
|