openfree commited on
Commit
bf74327
Β·
verified Β·
1 Parent(s): 65f0832

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -42
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
- import tempfile
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
- # Save and create file handles for upload
37
- with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp1:
38
- image1.save(tmp1.name, 'PNG')
39
- # Upload to Replicate (this creates a temporary URL)
40
- with open(tmp1.name, 'rb') as f:
41
- file_url = client.upload(f)
42
- image_urls.append(file_url)
43
- os.unlink(tmp1.name)
44
-
45
- if image2:
46
- with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp2:
47
- image2.save(tmp2.name, 'PNG')
48
- with open(tmp2.name, 'rb') as f:
49
- file_url = client.upload(f)
50
- image_urls.append(file_url)
51
- os.unlink(tmp2.name)
 
 
 
 
 
52
 
53
- status_message = "🎨 Processing your images with nano-banana model..."
54
 
55
- # Prepare input matching the exact format
56
  input_data = {
57
  "prompt": prompt,
58
- "image_input": image_urls # List of 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 the output based on the reference code
68
  output_url = None
69
 
70
- # The output object should have a url() method based on your example
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 image URL found in response"
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
- # Fallback to downloading from URL
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 with nano-banana!"
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 if the model exists on Replicate."
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. **Model Information:**
246
- - Using: `google/nano-banana` model
247
- - Input: `prompt` (text) and `image_input` (list of image URLs)
248
- - Output: Generated image based on the style transfer
249
 
250
- 4. **Note:**
251
- - The model requires actual URLs for images
252
- - Images are temporarily uploaded to Replicate's servers
253
- - Check if 'google/nano-banana' is available on your Replicate account
 
 
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