mcuo
/

mcuo commited on
Commit
5e01dc4
·
verified ·
1 Parent(s): 7a7089b

Upload Krea-2_models/app(banana).py

Browse files
Files changed (1) hide show
  1. Krea-2_models/app(banana).py +559 -0
Krea-2_models/app(banana).py ADDED
@@ -0,0 +1,559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from gradio_client import Client, handle_file
3
+ from google import genai
4
+ from google.genai import types
5
+ import os
6
+ from typing import Optional, List, Tuple
7
+ import requests
8
+ from PIL import Image
9
+ from io import BytesIO
10
+ import tempfile
11
+ import ffmpeg
12
+ import sqlite3
13
+ from datetime import datetime, date
14
+ from pathlib import Path
15
+ from threading import Lock
16
+
17
+ # --- Database Setup ---
18
+ DATA_DIR = Path("/data")
19
+ DATA_DIR.mkdir(exist_ok=True)
20
+ DB_PATH = DATA_DIR / "usage_limits.db"
21
+
22
+ DAILY_LIMIT = 40
23
+ EXEMPTED_USERS = ["multimodalart"]
24
+ db_lock = Lock()
25
+
26
+ def init_db():
27
+ """Initialize the SQLite database (single global usage pool)."""
28
+ print(f"Initializing database at: {DB_PATH}")
29
+ try:
30
+ with sqlite3.connect(DB_PATH) as conn:
31
+ cursor = conn.cursor()
32
+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='usage'")
33
+ table_exists = cursor.fetchone()
34
+
35
+ if not table_exists:
36
+ cursor.execute('''
37
+ CREATE TABLE usage (
38
+ username TEXT PRIMARY KEY,
39
+ date TEXT NOT NULL,
40
+ count INTEGER NOT NULL DEFAULT 0
41
+ )
42
+ ''')
43
+ conn.commit()
44
+ print("Database initialized successfully")
45
+ return
46
+
47
+ cursor.execute("PRAGMA table_info(usage)")
48
+ columns = [col[1] for col in cursor.fetchall()]
49
+
50
+ if 'count_standard' in columns and 'count_pro' in columns:
51
+ print("Migrating to single-pool schema (count_standard + count_pro → count)...")
52
+ cursor.execute('''
53
+ CREATE TABLE usage_new (
54
+ username TEXT PRIMARY KEY,
55
+ date TEXT NOT NULL,
56
+ count INTEGER NOT NULL DEFAULT 0
57
+ )
58
+ ''')
59
+ cursor.execute('''
60
+ INSERT INTO usage_new (username, date, count)
61
+ SELECT username, date, count_standard + count_pro FROM usage
62
+ ''')
63
+ cursor.execute("DROP TABLE usage")
64
+ cursor.execute("ALTER TABLE usage_new RENAME TO usage")
65
+ conn.commit()
66
+ print("Migration completed successfully")
67
+ elif 'count' in columns:
68
+ print("Database schema is already up to date")
69
+ else:
70
+ print("Unknown schema — recreating table...")
71
+ cursor.execute("DROP TABLE usage")
72
+ cursor.execute('''
73
+ CREATE TABLE usage (
74
+ username TEXT PRIMARY KEY,
75
+ date TEXT NOT NULL,
76
+ count INTEGER NOT NULL DEFAULT 0
77
+ )
78
+ ''')
79
+ conn.commit()
80
+ except Exception as e:
81
+ print(f"Error initializing database: {e}")
82
+ import traceback
83
+ traceback.print_exc()
84
+
85
+ def check_and_update_usage(username: str, credits_to_use: int = 1) -> bool:
86
+ """
87
+ Check if user has enough credits for today and update usage.
88
+ Returns True if user can generate, False if limit reached.
89
+ """
90
+ if username in EXEMPTED_USERS:
91
+ print(f"User {username} is exempted from rate limits")
92
+ return True
93
+
94
+ with db_lock:
95
+ try:
96
+ with sqlite3.connect(DB_PATH) as conn:
97
+ today = str(date.today())
98
+ cursor = conn.cursor()
99
+
100
+ cursor.execute("SELECT date, count FROM usage WHERE username = ?", (username,))
101
+ result = cursor.fetchone()
102
+
103
+ if result is None:
104
+ cursor.execute("INSERT INTO usage (username, date, count) VALUES (?, ?, ?)",
105
+ (username, today, credits_to_use))
106
+ conn.commit()
107
+ print(f"New user {username}: {credits_to_use}/{DAILY_LIMIT}")
108
+ return True
109
+
110
+ user_date, user_count = result
111
+
112
+ if user_date != today:
113
+ cursor.execute("UPDATE usage SET date = ?, count = ? WHERE username = ?",
114
+ (today, credits_to_use, username))
115
+ conn.commit()
116
+ print(f"User {username} reset for new day: {credits_to_use}/{DAILY_LIMIT}")
117
+ return True
118
+
119
+ if user_count + credits_to_use > DAILY_LIMIT:
120
+ print(f"User {username} insufficient credits: needs {credits_to_use}, has {DAILY_LIMIT - user_count}/{DAILY_LIMIT} remaining")
121
+ return False
122
+
123
+ new_count = user_count + credits_to_use
124
+ cursor.execute("UPDATE usage SET count = ? WHERE username = ?", (new_count, username))
125
+ conn.commit()
126
+ print(f"User {username} usage: {new_count}/{DAILY_LIMIT} (used {credits_to_use} credits)")
127
+ return True
128
+
129
+ except Exception as e:
130
+ print(f"Error checking usage for {username}: {e}")
131
+ import traceback
132
+ traceback.print_exc()
133
+ # On error, allow the request (fail open)
134
+ return True
135
+
136
+ def get_remaining_generations(username: str) -> int:
137
+ """Get the number of remaining credits for today."""
138
+ if username in EXEMPTED_USERS:
139
+ return 999999
140
+
141
+ with db_lock:
142
+ try:
143
+ with sqlite3.connect(DB_PATH) as conn:
144
+ today = str(date.today())
145
+ cursor = conn.cursor()
146
+
147
+ cursor.execute("SELECT date, count FROM usage WHERE username = ?", (username,))
148
+ result = cursor.fetchone()
149
+
150
+ if result is None:
151
+ return DAILY_LIMIT
152
+
153
+ user_date, user_count = result
154
+
155
+ if user_date != today:
156
+ return DAILY_LIMIT
157
+
158
+ return max(0, DAILY_LIMIT - user_count)
159
+ except Exception as e:
160
+ print(f"Error getting remaining generations for {username}: {e}")
161
+ return DAILY_LIMIT
162
+
163
+ # Initialize database on module load
164
+ init_db()
165
+
166
+ # --- Google Gemini API Configuration ---
167
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY", "")
168
+ if not GOOGLE_API_KEY:
169
+ raise ValueError("GOOGLE_API_KEY environment variable not set.")
170
+ client = genai.Client(api_key=os.environ.get("GOOGLE_API_KEY"))
171
+
172
+ # Added Nano Banana 2 (3.1 flash) model definition
173
+ GEMINI_MODEL_NAME = 'gemini-2.5-flash-image'
174
+ GEMINI_PRO_MODEL_NAME = 'gemini-3-pro-image-preview'
175
+ GEMINI_NANO_BANANA_2_MODEL_NAME = 'gemini-3.1-flash-image-preview'
176
+
177
+ HF_USERINFO_URL = "https://huggingface.co/oauth/userinfo"
178
+
179
+ def get_user_info(token: Optional[gr.OAuthToken]) -> Optional[dict]:
180
+ """Fetch {username, is_pro} from the OAuth userinfo endpoint in a single call.
181
+ Returns None if the token is missing/invalid or the request fails."""
182
+ if not token:
183
+ return None
184
+ token_str = token.token if isinstance(token, gr.OAuthToken) else token
185
+ try:
186
+ resp = requests.get(
187
+ HF_USERINFO_URL,
188
+ headers={"Authorization": f"Bearer {token_str}"},
189
+ timeout=10,
190
+ )
191
+ resp.raise_for_status()
192
+ data = resp.json()
193
+ is_pro = (
194
+ data.get("isPro", False)
195
+ or any(org.get("plan") in ("team", "enterprise") for org in data.get("orgs", []))
196
+ )
197
+ return {
198
+ "username": data.get("preferred_username"),
199
+ "is_pro": is_pro,
200
+ }
201
+ except Exception as e:
202
+ print(f"Could not fetch OAuth userinfo: {e}")
203
+ return None
204
+
205
+ def get_credit_cost(resolution: str) -> int:
206
+ """Get the credit cost for a given resolution."""
207
+ if "4K" in resolution:
208
+ return 4
209
+ elif "2K" in resolution:
210
+ return 2
211
+ else: # 1K
212
+ return 1
213
+
214
+ def get_resolution_value(resolution: str) -> str:
215
+ """Extract the resolution value from the dropdown selection."""
216
+ if "4K" in resolution:
217
+ return "4K"
218
+ elif "2K" in resolution:
219
+ return "2K"
220
+ else:
221
+ return "1K"
222
+
223
+ def _extract_image_data_from_response(response) -> Optional[bytes]:
224
+ """Helper to extract image data from the model's response."""
225
+ if hasattr(response, 'candidates') and response.candidates:
226
+ for part in response.candidates[0].content.parts:
227
+ if hasattr(part, 'inline_data') and hasattr(part.inline_data, 'data'):
228
+ return part.inline_data.data
229
+ return None
230
+
231
+ def _get_video_info(video_path: str) -> Tuple[float, Tuple[int, int]]:
232
+ """Instantly gets the framerate and (width, height) of a video using ffprobe."""
233
+ probe = ffmpeg.probe(video_path)
234
+ video_stream = next((s for s in probe['streams'] if s['codec_type'] == 'video'), None)
235
+ if not video_stream:
236
+ raise ValueError("No video stream found in the file.")
237
+ framerate = eval(video_stream['avg_frame_rate'])
238
+ resolution = (int(video_stream['width']), int(video_stream['height']))
239
+ return framerate, resolution
240
+
241
+ def _resize_image(image_path: str, target_size: Tuple[int, int]) -> str:
242
+ """Resizes an image to a target size and saves it to a new temp file."""
243
+ with Image.open(image_path) as img:
244
+ if img.size == target_size:
245
+ return image_path
246
+ resized_img = img.resize(target_size, Image.Resampling.LANCZOS)
247
+ suffix = os.path.splitext(image_path)[1] or ".png"
248
+ with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp_file:
249
+ resized_img.save(tmp_file.name)
250
+ return tmp_file.name
251
+
252
+ def _trim_first_frame_fast(video_path: str) -> str:
253
+ """Removes exactly the first frame of a video without re-encoding."""
254
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp_output_file:
255
+ output_path = tmp_output_file.name
256
+ try:
257
+ framerate, _ = _get_video_info(video_path)
258
+ if framerate == 0: raise ValueError("Framerate cannot be zero.")
259
+ start_time = 1 / framerate
260
+ (
261
+ ffmpeg
262
+ .input(video_path, ss=start_time)
263
+ .output(output_path, c='copy', avoid_negative_ts='make_zero')
264
+ .run(overwrite_output=True, quiet=True)
265
+ )
266
+ return output_path
267
+ except Exception as e:
268
+ raise RuntimeError(f"FFmpeg trim error: {e}")
269
+
270
+ def _combine_videos_simple(video1_path: str, video2_path: str) -> str:
271
+ """Combines two videos using the fast concat demuxer."""
272
+ with tempfile.NamedTemporaryFile(delete=False, mode='w', suffix=".txt") as tmp_list_file:
273
+ tmp_list_file.write(f"file '{os.path.abspath(video1_path)}'\n")
274
+ tmp_list_file.write(f"file '{os.path.abspath(video2_path)}'\n")
275
+ list_file_path = tmp_list_file.name
276
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp_output_file:
277
+ output_path = tmp_output_file.name
278
+ try:
279
+ (
280
+ ffmpeg
281
+ .input(list_file_path, format='concat', safe=0)
282
+ .output(output_path, c='copy')
283
+ .run(overwrite_output=True, quiet=True)
284
+ )
285
+ return output_path
286
+ except ffmpeg.Error as e:
287
+ raise RuntimeError(f"FFmpeg combine error: {e.stderr.decode()}")
288
+ finally:
289
+ if os.path.exists(list_file_path):
290
+ os.remove(list_file_path)
291
+
292
+ def _generate_video_segment(input_image_path: str, output_image_path: str, prompt: str, token: str) -> str:
293
+ """Generates a single video segment using the external service."""
294
+ video_client = Client("multimodalart/wan-2-2-first-last-frame", token=token)
295
+ result = video_client.predict(
296
+ start_image_pil=handle_file(input_image_path),
297
+ end_image_pil=handle_file(output_image_path),
298
+ prompt=prompt, api_name="/generate_video"
299
+ )
300
+ return result[0]["video"]
301
+
302
+ def unified_image_generator(prompt: str, images: Optional[List[str]], previous_video_path: Optional[str], last_frame_path: Optional[str], aspect_ratio: str, model_selection: str, resolution: str, oauth_token: Optional[gr.OAuthToken]) -> tuple:
303
+ user_info = get_user_info(oauth_token)
304
+ if not user_info or not user_info["is_pro"]:
305
+ raise gr.Error("Access Denied.")
306
+ username = user_info["username"]
307
+ if not username:
308
+ raise gr.Error("Could not identify user.")
309
+
310
+ use_pro_model = (model_selection == "Nano Banana PRO")
311
+ use_banana_2 = (model_selection == "Nano Banana 2")
312
+
313
+ # Credit cost: Banana = 1, Banana 2 = 1/2/4 by resolution, PRO = 2× resolution (2/4/8)
314
+ if use_pro_model:
315
+ credits_to_use = get_credit_cost(resolution) * 2
316
+ elif use_banana_2:
317
+ credits_to_use = get_credit_cost(resolution)
318
+ else:
319
+ credits_to_use = 1
320
+
321
+ can_generate = check_and_update_usage(username, credits_to_use)
322
+
323
+ if not can_generate:
324
+ remaining = get_remaining_generations(username)
325
+ if (use_pro_model or use_banana_2) and remaining > 0 and remaining < credits_to_use:
326
+ gr.Info(f"You need {credits_to_use} credits for {get_resolution_value(resolution)} but only have {remaining} remaining. Try a lower resolution or use Nano Banana (1 credit/gen).")
327
+ raise gr.Error(f"Insufficient credits. You need {credits_to_use} but have {remaining}/{DAILY_LIMIT} remaining today.")
328
+
329
+ try:
330
+ contents = [Image.open(image_path[0]) for image_path in images] if images else []
331
+ contents.append(prompt)
332
+
333
+ # Select API model identifier based on selection
334
+ if use_pro_model:
335
+ model_name_api = GEMINI_PRO_MODEL_NAME
336
+ elif use_banana_2:
337
+ model_name_api = GEMINI_NANO_BANANA_2_MODEL_NAME
338
+ else:
339
+ model_name_api = GEMINI_MODEL_NAME
340
+
341
+ # Create config with aspect ratio and resolution
342
+ if use_pro_model or use_banana_2:
343
+ resolution_value = get_resolution_value(resolution)
344
+
345
+ img_config_kwargs = {"image_size": resolution_value}
346
+ if aspect_ratio != "Auto":
347
+ img_config_kwargs["aspect_ratio"] = aspect_ratio
348
+
349
+ gen_config_kwargs = {
350
+ "response_modalities": ["IMAGE", "TEXT"],
351
+ "image_config": types.ImageConfig(**img_config_kwargs)
352
+ }
353
+
354
+ # Apply Thinking Config uniquely for Nano Banana 2
355
+ if use_banana_2:
356
+ gen_config_kwargs["thinking_config"] = types.ThinkingConfig(thinking_level="MINIMAL")
357
+
358
+ generate_content_config = types.GenerateContentConfig(**gen_config_kwargs)
359
+ else:
360
+ # Standard model: only aspect_ratio
361
+ if aspect_ratio == "Auto":
362
+ generate_content_config = types.GenerateContentConfig(
363
+ response_modalities=["IMAGE", "TEXT"],
364
+ )
365
+ else:
366
+ generate_content_config = types.GenerateContentConfig(
367
+ response_modalities=["IMAGE", "TEXT"],
368
+ image_config=types.ImageConfig(
369
+ aspect_ratio=aspect_ratio,
370
+ ),
371
+ )
372
+
373
+ print(f"Generating image for user {username} with prompt {prompt} using {model_name_api}")
374
+ response = client.models.generate_content(
375
+ model=model_name_api,
376
+ contents=contents,
377
+ config=generate_content_config
378
+ )
379
+ image_data = _extract_image_data_from_response(response)
380
+ if not image_data: raise gr.Error("No image data in response")
381
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp:
382
+ Image.open(BytesIO(image_data)).save(tmp.name)
383
+ output_path = tmp.name
384
+
385
+ can_create_video = bool(images and len(images) == 1)
386
+ can_extend_video = False
387
+ if can_create_video and previous_video_path and last_frame_path:
388
+ # The crucial check for continuity
389
+ if images[0][0] == last_frame_path:
390
+ can_extend_video = True
391
+
392
+ print(f"Image generated at {output_path}")
393
+ return (output_path, gr.update(visible=can_create_video), gr.update(visible=can_extend_video), gr.update(visible=False))
394
+ except Exception as e:
395
+ raise gr.Error(f"Image generation failed: {e}. Rephrase your prompt to make image generation explicit and try again")
396
+
397
+ def create_new_video(input_image_gallery: List[str], prompt_input: str, output_image: str, oauth_token: Optional[gr.OAuthToken]) -> tuple:
398
+ user_info = get_user_info(oauth_token)
399
+ if not user_info or not user_info["is_pro"]: raise gr.Error("Access Denied.")
400
+ if not input_image_gallery or not output_image: raise gr.Error("Input/output images required.")
401
+ try:
402
+ new_segment_path = _generate_video_segment(input_image_gallery[0][0], output_image, prompt_input, oauth_token.token)
403
+ return new_segment_path, new_segment_path, output_image
404
+ except Exception as e:
405
+ raise gr.Error(f"Video creation failed: {e}")
406
+
407
+ def extend_existing_video(input_image_gallery: List[str], prompt_input: str, output_image: str, previous_video_path: str, oauth_token: Optional[gr.OAuthToken]) -> tuple:
408
+ user_info = get_user_info(oauth_token)
409
+ if not user_info or not user_info["is_pro"]: raise gr.Error("Access Denied.")
410
+ if not previous_video_path: raise gr.Error("No previous video to extend.")
411
+ if not input_image_gallery or not output_image: raise gr.Error("Input/output images required.")
412
+ try:
413
+ _, target_resolution = _get_video_info(previous_video_path)
414
+ resized_input_path = _resize_image(input_image_gallery[0][0], target_resolution)
415
+ resized_output_path = _resize_image(output_image, target_resolution)
416
+ new_segment_path = _generate_video_segment(resized_input_path, resized_output_path, prompt_input, oauth_token.token)
417
+ trimmed_segment_path = _trim_first_frame_fast(new_segment_path)
418
+ final_video_path = _combine_videos_simple(previous_video_path, trimmed_segment_path)
419
+ return final_video_path, final_video_path, output_image
420
+ except Exception as e:
421
+ raise gr.Error(f"Video extension failed: {e}")
422
+
423
+ css = '''
424
+ #sub_title{margin-top: -15px !important}
425
+ .tab-wrapper{margin-bottom: -33px !important}
426
+ .tabitem{padding: 0px !important}
427
+ .fillable{max-width: 980px !important}
428
+ .dark .progress-text {color: white}
429
+ .logo-dark{display: none}
430
+ .dark .logo-dark{display: block !important}
431
+ .dark .logo-light{display: none}
432
+ .grid-container img{object-fit: contain}
433
+ .grid-container {display: grid;grid-template-columns: repeat(2, 1fr)}
434
+ .grid-container:has(> .gallery-item:only-child) {grid-template-columns: 1fr}
435
+ #wan_ad p{text-align: center;padding: .5em}
436
+ '''
437
+
438
+ with gr.Blocks() as demo:
439
+ gr.HTML('''
440
+ <img class="logo-dark" src='https://huggingface.co/spaces/multimodalart/nano-banana/resolve/main/nano_banana_pros.png' style='margin: 0 auto; max-width: 650px' />
441
+ <img class="logo-light" src='https://huggingface.co/spaces/multimodalart/nano-banana/resolve/main/nano_banana_pros_light.png' style='margin: 0 auto; max-width: 650px' />
442
+ ''')
443
+ gr.HTML("<h3 style='text-align:center'>Hugging Face PRO users can use Google's Nano Banana and Nano Banana PRO on this Space. <a href='http://huggingface.co/subscribe/pro?source=nana_banana' target='_blank'>Subscribe to PRO</a></h3>", elem_id="sub_title")
444
+ pro_message = gr.Markdown(visible=False)
445
+ main_interface = gr.Column(visible=False)
446
+
447
+ previous_video_state = gr.State(None)
448
+ last_frame_of_video_state = gr.State(None)
449
+
450
+ with main_interface:
451
+ with gr.Row():
452
+ with gr.Column(scale=1):
453
+ image_input_gallery = gr.Gallery(label="Upload one or more images here. Leave empty for text-to-image", file_types=["image"], height="auto")
454
+ prompt_input = gr.Textbox(label="Prompt", placeholder="Turns this photo into a masterpiece")
455
+
456
+ # Added Nano Banana 2 choice here
457
+ model_radio = gr.Radio(
458
+ choices=["Nano Banana", "Nano Banana 2", "Nano Banana PRO"],
459
+ value="Nano Banana 2",
460
+ label="Model",
461
+ )
462
+
463
+ with gr.Row():
464
+ aspect_ratio_dropdown = gr.Dropdown(
465
+ label="Aspect Ratio",
466
+ choices=["Auto", "1:1", "9:16", "16:9", "3:4", "4:3", "3:2", "2:3", "5:4", "4:5", "21:9"],
467
+ value="Auto",
468
+ interactive=True
469
+ )
470
+
471
+ resolution_dropdown = gr.Dropdown(
472
+ label="Resolution",
473
+ choices=["1K", "2K", "4K"],
474
+ value="1K",
475
+ interactive=True,
476
+ visible=True
477
+ )
478
+
479
+ generate_button = gr.Button("Generate", variant="primary")
480
+ with gr.Column(scale=1):
481
+ output_image = gr.Image(label="Output", interactive=False, elem_id="output", type="filepath")
482
+ use_image_button = gr.Button("♻️ Use this Image for Next Edit", variant="primary")
483
+ with gr.Row():
484
+ create_video_button = gr.Button("Create video between the two images 🎥", variant="secondary", visible=False)
485
+ extend_video_button = gr.Button("Extend existing video with new scene 🎞️", variant="secondary", visible=False)
486
+ with gr.Group(visible=False) as video_group:
487
+ video_output = gr.Video(label="Generated Video", buttons=["download"], autoplay=True)
488
+ gr.Markdown("Generate more with [Wan 2.2 first-last-frame](https://huggingface.co/spaces/multimodalart/wan-2-2-first-last-frame)", elem_id="wan_ad")
489
+ gr.Markdown("<h2 style='text-align: center'>Thank you for being a PRO! 🤗</h2>")
490
+
491
+ login_button = gr.LoginButton()
492
+
493
+ # Show/hide resolution dropdown based on model selection (visible for PRO and Nano Banana 2)
494
+ def update_resolution_visibility(model_selection):
495
+ return gr.update(visible=(model_selection in ["Nano Banana PRO", "Nano Banana 2"]))
496
+
497
+ model_radio.change(
498
+ fn=update_resolution_visibility,
499
+ inputs=[model_radio],
500
+ outputs=[resolution_dropdown],
501
+ api_visibility="private"
502
+ )
503
+
504
+ gr.on(
505
+ triggers=[generate_button.click, prompt_input.submit],
506
+ fn=unified_image_generator,
507
+ inputs=[prompt_input, image_input_gallery, previous_video_state, last_frame_of_video_state, aspect_ratio_dropdown, model_radio, resolution_dropdown],
508
+ outputs=[output_image, create_video_button, extend_video_button, video_group],
509
+ api_visibility="private"
510
+ )
511
+ use_image_button.click(
512
+ fn=lambda img: (
513
+ [img] if img else None, None, gr.update(visible=False),
514
+ gr.update(visible=False), gr.update(visible=False)
515
+ ),
516
+ inputs=[output_image],
517
+ outputs=[image_input_gallery, output_image, create_video_button, extend_video_button, video_group],
518
+ api_visibility="private"
519
+ )
520
+ create_video_button.click(
521
+ fn=lambda: gr.update(visible=True), outputs=[video_group],
522
+ api_visibility="private"
523
+ ).then(
524
+ fn=create_new_video,
525
+ inputs=[image_input_gallery, prompt_input, output_image],
526
+ outputs=[video_output, previous_video_state, last_frame_of_video_state],
527
+ api_visibility="private"
528
+ )
529
+ extend_video_button.click(
530
+ fn=lambda: gr.update(visible=True), outputs=[video_group],
531
+ api_visibility="private"
532
+ ).then(
533
+ fn=extend_existing_video,
534
+ inputs=[image_input_gallery, prompt_input, output_image, previous_video_state],
535
+ outputs=[video_output, previous_video_state, last_frame_of_video_state],
536
+ api_visibility="private"
537
+ )
538
+
539
+ def control_access(profile: Optional[gr.OAuthProfile] = None, oauth_token: Optional[gr.OAuthToken] = None):
540
+ if not profile: return gr.update(visible=False), gr.update(visible=False)
541
+ user_info = get_user_info(oauth_token)
542
+ if user_info and user_info["is_pro"]:
543
+ return gr.update(visible=True), gr.update(visible=False)
544
+ else:
545
+ message = (
546
+ "## ✨ Exclusive Access for PRO Users\n\n"
547
+ "Thank you for your interest! This app is available exclusively for our Hugging Face **PRO** members.\n\n"
548
+ "To unlock this and many other cool stuff, please consider upgrading your account.\n\n"
549
+ "### [**Become a PRO Today!**](http://huggingface.co/subscribe/pro?source=nana_banana)"
550
+ )
551
+ return gr.update(visible=False), gr.update(visible=True, value=message)
552
+ demo.load(control_access, inputs=None, outputs=[main_interface, pro_message], api_visibility="private")
553
+
554
+ if __name__ == "__main__":
555
+ demo.queue(max_size=None, default_concurrency_limit=None, api_open=False).launch(
556
+ show_error=True,
557
+ theme=gr.themes.Citrus(),
558
+ css=css
559
+ )