DranikKartofelniy commited on
Commit
50afb76
·
verified ·
1 Parent(s): 7dc760b

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -36
app.py CHANGED
@@ -2,72 +2,74 @@ import gradio as gr
2
  import os
3
  import time
4
 
5
- # --- СЕКРЕТЫ И НАСТРОЙКИ ---
6
  NANOBANANA_API_KEY = os.getenv("NANOBANANA_API_KEY")
7
  KLING_API_KEY = os.getenv("KLING_API_KEY")
8
 
9
  SYSTEM_PROMPT = """Hyper-realistic Instagram influencer lifestyle photo, shot on iPhone 15 Pro. The exact person [refer to subject images] is looking directly at the camera with a warm, highly attractive, and confident expression. Flawless, beautiful, glowing natural skin with a soft aesthetic finish (no harsh shadows, no rough textures). They are elegantly yet casually holding the product [refer to product images] close to the camera, showing it to the viewers. Flattering soft daylight from a window combined with a subtle ring-light glow on the face. Bright, aesthetic, cozy modern room background. High-end social media blogger vibe, perfect facial likeness, highly detailed but soft and visually pleasing."""
10
 
11
- # Используем генератор (yield), чтобы логи обновлялись в реальном времени
12
  def create_photo(blogger_images, product_images):
13
  logs = ""
 
14
  if not blogger_images or not product_images:
15
- raise gr.Error("Пожалуйста, загрузите фото блогера и товара!")
16
 
17
- logs += "[Система] Инициализация процесса...\n"
18
  yield logs, None
19
  time.sleep(1)
20
 
21
- logs += "[Storage] Загрузка изображений блогера и товара в облако...\n"
22
  yield logs, None
23
  time.sleep(1.5)
24
 
25
- logs += f"[NanoBanana Pro] Отправка API запроса. Промпт: {SYSTEM_PROMPT[:50]}...\n"
26
  yield logs, None
27
  time.sleep(1.5)
28
 
29
- logs += "[NanoBanana Pro] Генерация изображения (применение стиля и лица)...\n"
30
  yield logs, None
31
  time.sleep(2)
32
 
33
- logs += "[Успех] Фото сгенерировано! Загрузка в интерфейс...\n"
 
34
  photo_url = "https://images.unsplash.com/photo-1611162617474-5b21e879e113?q=80&w=1000&auto=format&fit=crop"
35
 
36
  yield logs, photo_url
37
 
38
  def create_video(blogger_images, product_images):
39
  logs = ""
 
40
  if not blogger_images or not product_images:
41
- raise gr.Error("Пожалуйста, загрузите фото блогера и товара!")
42
 
43
- logs += "[Система] Инициализация генерации видео...\n"
44
  yield logs, None
45
  time.sleep(1)
46
 
47
- logs += "[Kling API] POST /v1/videos/image2video -> Отправка данных...\n"
48
  yield logs, None
49
  time.sleep(1.5)
50
 
51
- logs += "[Kling API] Task ID: kl_9876543210ab. Статус: QUEUED...\n"
52
  yield logs, None
53
  time.sleep(2)
54
 
55
- logs += "[Kling API] Статус: PROCESSING (Рендеринг кадров)...\n"
56
  yield logs, None
57
  time.sleep(2.5)
58
 
59
- logs += "[Успех] Статус: SUCCEED. Видео готово к скачиванию!\n"
 
60
  video_url = "https://www.w3schools.com/html/mov_bbb.mp4"
61
 
62
  yield logs, video_url
63
 
64
- # --- НАСТРОЙКА КРАСИВОГО UI ---
65
  custom_css = """
66
  .container { max-width: 1100px; margin: auto; }
67
  .output-media { border-radius: 16px; box-shadow: 0 10px 25px rgba(0,0,0,0.1); }
68
  button.primary { background: linear-gradient(90deg, #6366f1, #a855f7); border: none; }
69
  button.primary:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(168, 85, 247, 0.4); transition: all 0.3s ease; }
70
- /* Стили для логов-терминала */
71
  .log-window textarea {
72
  background-color: #1e1e1e !important;
73
  color: #4ade80 !important;
@@ -76,44 +78,44 @@ button.primary:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(
76
  }
77
  """
78
 
79
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="violet"), css=custom_css) as demo:
 
80
  gr.Markdown("<h1 style='text-align: center;'>✨ AI Content Creator Pro</h1>")
81
- gr.Markdown("<p style='text-align: center; color: gray;'>Генерация гиперреалистичного UGC-контента: NanoBanana Pro (Фото) & Kling AI (Видео)</p>")
82
 
83
  with gr.Row():
84
- # ЛЕВАЯ КОЛОНКА (Инпуты)
85
  with gr.Column(scale=1):
86
- gr.Markdown("### 📥 Входные данные")
87
 
88
  with gr.Group():
89
- blogger_imgs = gr.File(label="📸 Блогер (1-5 фото)", file_count="multiple", file_types=["image"])
90
- product_imgs = gr.File(label="🛍️ Товар (1-5 фото)", file_count="multiple", file_types=["image"])
91
 
92
  with gr.Row():
93
- btn_photo = gr.Button("Создать Фото", variant="primary", size="lg")
94
- btn_video = gr.Button("Создать Видео", variant="primary", size="lg")
95
 
96
- # ОКНО ЛОГОВ ПОД КНОПКАМИ
97
  logs_output = gr.Textbox(
98
- label="🖥️ Системные логи",
99
  lines=6,
100
  interactive=False,
101
  elem_classes="log-window",
102
- placeholder="Здесь будут отображаться логи генерации..."
103
  )
104
 
105
- # ПРАВАЯ КОЛОНКА (Аутпуты)
106
  with gr.Column(scale=1):
107
- gr.Markdown("### 📤 Результат")
108
 
109
  with gr.Tabs():
110
- with gr.Tab("Фотография"):
111
- out_photo = gr.Image(label="Результат фото", elem_classes="output-media", show_download_button=True)
112
- with gr.Tab("Видео"):
113
- out_video = gr.Video(label="Результат видео", elem_classes="output-media", show_download_button=True)
114
 
115
- # Привязка кнопок к функциям
116
- # Обрати внимание: теперь функция возвращает 2 значения: логи и медиа (поэтому outputs=[logs_output, ...])
117
  btn_photo.click(
118
  fn=create_photo,
119
  inputs=[blogger_imgs, product_imgs],
@@ -127,4 +129,8 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="violet"
127
  )
128
 
129
  if __name__ == "__main__":
130
- demo.launch()
 
 
 
 
 
2
  import os
3
  import time
4
 
5
+ # --- SECRETS AND CONFIGURATION ---
6
  NANOBANANA_API_KEY = os.getenv("NANOBANANA_API_KEY")
7
  KLING_API_KEY = os.getenv("KLING_API_KEY")
8
 
9
  SYSTEM_PROMPT = """Hyper-realistic Instagram influencer lifestyle photo, shot on iPhone 15 Pro. The exact person [refer to subject images] is looking directly at the camera with a warm, highly attractive, and confident expression. Flawless, beautiful, glowing natural skin with a soft aesthetic finish (no harsh shadows, no rough textures). They are elegantly yet casually holding the product [refer to product images] close to the camera, showing it to the viewers. Flattering soft daylight from a window combined with a subtle ring-light glow on the face. Bright, aesthetic, cozy modern room background. High-end social media blogger vibe, perfect facial likeness, highly detailed but soft and visually pleasing."""
10
 
 
11
  def create_photo(blogger_images, product_images):
12
  logs = ""
13
+ # Check if images are uploaded
14
  if not blogger_images or not product_images:
15
+ raise gr.Error("Please upload photos of both the blogger and the product!")
16
 
17
+ logs += "[System] Initializing process...\n"
18
  yield logs, None
19
  time.sleep(1)
20
 
21
+ logs += "[Storage] Uploading blogger and product images to the cloud...\n"
22
  yield logs, None
23
  time.sleep(1.5)
24
 
25
+ logs += f"[NanoBanana Pro] Sending API request. Prompt: {SYSTEM_PROMPT[:50]}...\n"
26
  yield logs, None
27
  time.sleep(1.5)
28
 
29
+ logs += "[NanoBanana Pro] Generating image (applying style and likeness)...\n"
30
  yield logs, None
31
  time.sleep(2)
32
 
33
+ logs += "[Success] Photo generated! Loading into interface...\n"
34
+ # Placeholder realistic photo for demo purposes
35
  photo_url = "https://images.unsplash.com/photo-1611162617474-5b21e879e113?q=80&w=1000&auto=format&fit=crop"
36
 
37
  yield logs, photo_url
38
 
39
  def create_video(blogger_images, product_images):
40
  logs = ""
41
+ # Check if images are uploaded
42
  if not blogger_images or not product_images:
43
+ raise gr.Error("Please upload photos of both the blogger and the product!")
44
 
45
+ logs += "[System] Initializing video generation...\n"
46
  yield logs, None
47
  time.sleep(1)
48
 
49
+ logs += "[Kling API] POST /v1/videos/image2video -> Sending data...\n"
50
  yield logs, None
51
  time.sleep(1.5)
52
 
53
+ logs += "[Kling API] Task ID: kl_9876543210ab. Status: QUEUED...\n"
54
  yield logs, None
55
  time.sleep(2)
56
 
57
+ logs += "[Kling API] Status: PROCESSING (Rendering frames)...\n"
58
  yield logs, None
59
  time.sleep(2.5)
60
 
61
+ logs += "[Success] Status: SUCCEED. Video is ready!\n"
62
+ # Placeholder video for demo purposes
63
  video_url = "https://www.w3schools.com/html/mov_bbb.mp4"
64
 
65
  yield logs, video_url
66
 
67
+ # --- CUSTOM UI STYLES ---
68
  custom_css = """
69
  .container { max-width: 1100px; margin: auto; }
70
  .output-media { border-radius: 16px; box-shadow: 0 10px 25px rgba(0,0,0,0.1); }
71
  button.primary { background: linear-gradient(90deg, #6366f1, #a855f7); border: none; }
72
  button.primary:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(168, 85, 247, 0.4); transition: all 0.3s ease; }
 
73
  .log-window textarea {
74
  background-color: #1e1e1e !important;
75
  color: #4ade80 !important;
 
78
  }
79
  """
80
 
81
+ # App Layout setup
82
+ with gr.Blocks() as demo:
83
  gr.Markdown("<h1 style='text-align: center;'>✨ AI Content Creator Pro</h1>")
84
+ gr.Markdown("<p style='text-align: center; color: gray;'>Hyper-realistic UGC Generation: NanoBanana Pro (Photo) & Kling AI (Video)</p>")
85
 
86
  with gr.Row():
87
+ # LEFT COLUMN (Inputs)
88
  with gr.Column(scale=1):
89
+ gr.Markdown("### 📥 Inputs")
90
 
91
  with gr.Group():
92
+ blogger_imgs = gr.File(label="📸 Blogger (1-5 photos)", file_count="multiple", file_types=["image"])
93
+ product_imgs = gr.File(label="🛍️ Product (1-5 photos)", file_count="multiple", file_types=["image"])
94
 
95
  with gr.Row():
96
+ btn_photo = gr.Button("Create Photo", variant="primary", size="lg")
97
+ btn_video = gr.Button("Create Video", variant="primary", size="lg")
98
 
99
+ # TERMINAL LOGS
100
  logs_output = gr.Textbox(
101
+ label="🖥️ System Logs",
102
  lines=6,
103
  interactive=False,
104
  elem_classes="log-window",
105
+ placeholder="Generation logs will appear here..."
106
  )
107
 
108
+ # RIGHT COLUMN (Outputs)
109
  with gr.Column(scale=1):
110
+ gr.Markdown("### 📤 Output")
111
 
112
  with gr.Tabs():
113
+ with gr.Tab("Photo"):
114
+ out_photo = gr.Image(label="Photo Result", elem_classes="output-media")
115
+ with gr.Tab("Video"):
116
+ out_video = gr.Video(label="Video Result", elem_classes="output-media")
117
 
118
+ # Button triggers
 
119
  btn_photo.click(
120
  fn=create_photo,
121
  inputs=[blogger_imgs, product_imgs],
 
129
  )
130
 
131
  if __name__ == "__main__":
132
+ # Launching the app with custom theme and CSS
133
+ demo.launch(
134
+ theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="violet"),
135
+ css=custom_css
136
+ )