openfree commited on
Commit
6a5d0ee
·
verified ·
1 Parent(s): 7c63bcd

Delete app-backup.py

Browse files
Files changed (1) hide show
  1. app-backup.py +0 -392
app-backup.py DELETED
@@ -1,392 +0,0 @@
1
- import gradio as gr
2
- import replicate
3
- import os
4
- from PIL import Image
5
- import requests
6
- from io import BytesIO
7
- import time
8
- import tempfile
9
- import base64
10
-
11
- # Set up Replicate API key from environment variable
12
- os.environ['REPLICATE_API_TOKEN'] = os.getenv('REPLICATE_API_TOKEN')
13
-
14
- def upload_image_to_hosting(image):
15
- """
16
- Upload image to multiple hosting services with fallback
17
- """
18
- # Method 1: Try imgbb.com (more reliable than Imgur)
19
- try:
20
- buffered = BytesIO()
21
- image.save(buffered, format="PNG")
22
- buffered.seek(0)
23
- img_base64 = base64.b64encode(buffered.getvalue()).decode()
24
-
25
- # imgbb API (free tier)
26
- response = requests.post(
27
- "https://api.imgbb.com/1/upload",
28
- data={
29
- 'key': '6d207e02198a847aa98d0a2a901485a5', # Free API key
30
- 'image': img_base64,
31
- }
32
- )
33
-
34
- if response.status_code == 200:
35
- data = response.json()
36
- if data.get('success'):
37
- return data['data']['url']
38
- except Exception as e:
39
- print(f"imgbb upload failed: {e}")
40
-
41
- # Method 2: Try freeimage.host
42
- try:
43
- buffered = BytesIO()
44
- image.save(buffered, format="PNG")
45
- buffered.seek(0)
46
-
47
- files = {'source': buffered}
48
- response = requests.post(
49
- "https://freeimage.host/api/1/upload",
50
- files=files,
51
- data={'key': '6d207e02198a847aa98d0a2a901485a5'}
52
- )
53
-
54
- if response.status_code == 200:
55
- data = response.json()
56
- if 'image' in data and 'url' in data['image']:
57
- return data['image']['url']
58
- except Exception as e:
59
- print(f"freeimage.host upload failed: {e}")
60
-
61
- # Method 3: Try 0x0.st (simple and reliable)
62
- try:
63
- buffered = BytesIO()
64
- image.save(buffered, format="PNG")
65
- buffered.seek(0)
66
-
67
- files = {'file': ('image.png', buffered, 'image/png')}
68
- response = requests.post(
69
- "https://0x0.st",
70
- files=files
71
- )
72
-
73
- if response.status_code == 200:
74
- return response.text.strip()
75
- except Exception as e:
76
- print(f"0x0.st upload failed: {e}")
77
-
78
- # Method 4: Original Imgur as last resort
79
- try:
80
- buffered = BytesIO()
81
- image.save(buffered, format="PNG")
82
- buffered.seek(0)
83
- img_base64 = base64.b64encode(buffered.getvalue()).decode()
84
-
85
- headers = {
86
- 'Authorization': 'Client-ID 0d90e8a3e7d8b4e'
87
- }
88
-
89
- response = requests.post(
90
- 'https://api.imgur.com/3/image',
91
- headers=headers,
92
- data={'image': img_base64}
93
- )
94
-
95
- if response.status_code == 200:
96
- data = response.json()
97
- if data.get('success'):
98
- return data['data']['link']
99
- except Exception as e:
100
- print(f"Imgur upload failed: {e}")
101
-
102
- return None
103
-
104
- def save_temp_image(image):
105
- """
106
- Save image temporarily and return file path
107
- """
108
- with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp:
109
- image.save(tmp.name, 'PNG')
110
- return tmp.name
111
-
112
- def process_images(prompt, image1, image2=None):
113
- """
114
- Process uploaded images with Replicate API
115
- """
116
- if not image1:
117
- return None, "❌ Please upload at least one image"
118
-
119
- # Check if API token is set
120
- if not os.getenv('REPLICATE_API_TOKEN'):
121
- return None, "⚠️ Please set REPLICATE_API_TOKEN environment variable"
122
-
123
- try:
124
- # Prepare image URLs list
125
- image_urls = []
126
-
127
- # Upload first image
128
- print("Uploading first image...")
129
- url1 = upload_image_to_hosting(image1)
130
- if url1:
131
- image_urls.append(url1)
132
- print(f"Image 1 uploaded: {url1}")
133
- else:
134
- # If all hosting services fail, use base64 data URI as fallback
135
- buffered = BytesIO()
136
- image1.save(buffered, format="PNG")
137
- buffered.seek(0)
138
- img_base64 = base64.b64encode(buffered.getvalue()).decode()
139
- data_uri = f"data:image/png;base64,{img_base64}"
140
- image_urls.append(data_uri)
141
- print("Using base64 data URI for image 1")
142
-
143
- # Upload second image if provided
144
- if image2:
145
- print("Uploading second image...")
146
- url2 = upload_image_to_hosting(image2)
147
- if url2:
148
- image_urls.append(url2)
149
- print(f"Image 2 uploaded: {url2}")
150
- else:
151
- buffered = BytesIO()
152
- image2.save(buffered, format="PNG")
153
- buffered.seek(0)
154
- img_base64 = base64.b64encode(buffered.getvalue()).decode()
155
- data_uri = f"data:image/png;base64,{img_base64}"
156
- image_urls.append(data_uri)
157
- print("Using base64 data URI for image 2")
158
-
159
- # Prepare input exactly as shown in the reference
160
- input_data = {
161
- "prompt": prompt,
162
- "image_input": image_urls
163
- }
164
-
165
- print(f"Sending to Replicate: prompt='{prompt}', images={len(image_urls)}")
166
-
167
- # Run the model
168
- output = replicate.run(
169
- "google/nano-banana",
170
- input=input_data
171
- )
172
-
173
- # Process output
174
- if output is None:
175
- return None, "❌ No output received from model"
176
-
177
- # Try different methods to get the image
178
- try:
179
- # Method 1: Using read() method
180
- if hasattr(output, 'read'):
181
- img_data = output.read()
182
- img = Image.open(BytesIO(img_data))
183
- return img, "✅ Free Nano Banana generated your image successfully! 🍌"
184
- except:
185
- pass
186
-
187
- try:
188
- # Method 2: Using url() method and downloading
189
- if hasattr(output, 'url'):
190
- output_url = output.url()
191
- response = requests.get(output_url, timeout=30)
192
- if response.status_code == 200:
193
- img = Image.open(BytesIO(response.content))
194
- return img, "✅ Free Nano Banana generated your image successfully! 🍌"
195
- except:
196
- pass
197
-
198
- # Method 3: If output is a URL string or list
199
- output_url = None
200
- if isinstance(output, str):
201
- output_url = output
202
- elif isinstance(output, list) and len(output) > 0:
203
- output_url = output[0]
204
-
205
- if output_url:
206
- response = requests.get(output_url, timeout=30)
207
- if response.status_code == 200:
208
- img = Image.open(BytesIO(response.content))
209
- return img, "✅ Free Nano Banana generated your image successfully! 🍌"
210
-
211
- return None, f"❌ Could not process output. Output type: {type(output)}"
212
-
213
- except replicate.exceptions.ReplicateError as e:
214
- error_msg = str(e)
215
- if "502" in error_msg:
216
- return None, "❌ Server error (502). The nano-banana model might be temporarily unavailable."
217
- elif "404" in error_msg:
218
- return None, "❌ Model 'google/nano-banana' not found. Please verify the model exists."
219
- elif "401" in error_msg or "403" in error_msg:
220
- return None, "❌ Authentication error. Please check your REPLICATE_API_TOKEN."
221
- elif "402" in error_msg:
222
- return None, "❌ Payment required. Please check your Replicate billing status."
223
- else:
224
- return None, f"❌ Replicate Error: {error_msg}"
225
- except Exception as e:
226
- return None, f"❌ Error: {str(e)}"
227
-
228
- # Create Gradio interface with gradient theme
229
- css = """
230
- .gradio-container {
231
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
232
- font-family: 'Inter', sans-serif;
233
- }
234
- .gr-button {
235
- background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
236
- border: none;
237
- color: white;
238
- font-weight: bold;
239
- transition: transform 0.2s;
240
- }
241
- .gr-button:hover {
242
- transform: scale(1.05);
243
- box-shadow: 0 10px 20px rgba(0,0,0,0.2);
244
- }
245
- .gr-input {
246
- border-radius: 10px;
247
- border: 2px solid rgba(255,255,255,0.3);
248
- background: rgba(255,255,255,0.9);
249
- }
250
- .header-text {
251
- background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
252
- -webkit-background-clip: text;
253
- -webkit-text-fill-color: transparent;
254
- background-clip: text;
255
- font-size: 2.5em;
256
- font-weight: bold;
257
- text-align: center;
258
- margin-bottom: 20px;
259
- }
260
- .description-text {
261
- color: white;
262
- text-align: center;
263
- font-size: 1.1em;
264
- margin-bottom: 30px;
265
- text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
266
- }
267
- """
268
-
269
- # Build the Gradio interface
270
- with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
271
- gr.HTML("""
272
- <div class="header-text">🍌 Free Nano Banana</div>
273
- <div class="description-text">
274
- Upload 1-2 images and describe how you want them styled.
275
- The AI will create a beautiful transformation using nano-banana model!
276
- </div>
277
- """)
278
-
279
- with gr.Row():
280
- with gr.Column(scale=1):
281
- gr.Markdown("### 📤 Input Section")
282
-
283
- prompt = gr.Textbox(
284
- label="✏️ Style Prompt",
285
- placeholder="Describe how you want to style your images...",
286
- lines=3,
287
- value="Make the sheets in the style of the logo. Make the scene natural."
288
- )
289
-
290
- with gr.Row():
291
- image1 = gr.Image(
292
- label="Image 1 (Required)",
293
- type="pil",
294
- height=200
295
- )
296
- image2 = gr.Image(
297
- label="Image 2 (Optional)",
298
- type="pil",
299
- height=200
300
- )
301
-
302
- generate_btn = gr.Button(
303
- "🚀 Generate Styled Image",
304
- variant="primary",
305
- size="lg"
306
- )
307
-
308
- gr.Markdown("""
309
- #### 💡 Tips:
310
- - Upload high-quality images for best results
311
- - Be specific in your style description
312
- - Model: google/nano-banana 🍌
313
- - Free image hosting included!
314
- """)
315
-
316
- with gr.Column(scale=1):
317
- gr.Markdown("### 🎯 Output Section")
318
-
319
- output_image = gr.Image(
320
- label="Generated Image",
321
- type="pil",
322
- height=400
323
- )
324
-
325
- status = gr.Textbox(
326
- label="Status",
327
- interactive=False,
328
- lines=2
329
- )
330
-
331
- # Examples section
332
- with gr.Row():
333
- gr.Examples(
334
- examples=[
335
- ["Make the sheets in the style of the logo. Make the scene natural.", None, None],
336
- ["Transform into watercolor painting style", None, None],
337
- ["Make it look like a vintage photograph", None, None],
338
- ["Apply cyberpunk neon style", None, None],
339
- ],
340
- inputs=[prompt, image1, image2],
341
- label="Example Prompts"
342
- )
343
-
344
- # Event handlers
345
- generate_btn.click(
346
- fn=process_images,
347
- inputs=[prompt, image1, image2],
348
- outputs=[output_image, status],
349
- api_name="generate"
350
- )
351
-
352
- # Additional information
353
- gr.Markdown("""
354
- ---
355
- ### ⚙️ Setup Instructions:
356
-
357
- 1. **Set Environment Variable:**
358
- ```bash
359
- export REPLICATE_API_TOKEN="r8_your_token_here"
360
- ```
361
- Get your token from: https://replicate.com/account/api-tokens
362
-
363
- 2. **Install Required Packages:**
364
- ```bash
365
- pip install gradio replicate pillow requests
366
- ```
367
-
368
- 3. **Model Information:**
369
- - Model: `google/nano-banana`
370
- - Input format:
371
- - `prompt`: Text description
372
- - `image_input`: List of image URLs
373
- - Output: Generated/styled image
374
-
375
- 4. **Important Notes:**
376
- - Images must be hosted with public URLs
377
- - Currently using Imgur for free image hosting
378
- - If model returns 502 error, it may be temporarily unavailable
379
-
380
- ### 🔒 Security:
381
- - API keys are managed through environment variables
382
- - Never commit API keys to version control
383
- """)
384
-
385
- # Launch the app
386
- if __name__ == "__main__":
387
- demo.launch(
388
- share=True,
389
- server_name="0.0.0.0",
390
- server_port=7860,
391
- show_error=True
392
- )