euiia commited on
Commit
f655f3b
·
verified ·
1 Parent(s): 2db91ab

Upload app (10).py

Browse files
Files changed (1) hide show
  1. app (10).py +289 -0
app (10).py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #Uma implementação aberta e funcional da arquitetura ADUC-SDR para geração de vídeo coerente.
2
+ # Copyright (C) 4 de Agosto de 2025 Carlos Rodrigues dos Santos
3
+ #
4
+ #Versao: 1.5.1
5
+ #
6
+ # Contato:
7
+ # Carlos Rodrigues dos Santos
8
+ # carlex22@gmail.com
9
+ #
10
+ # Repositórios e Projetos Relacionados:
11
+ # GitHub: https://github.com/carlex22/Aduc-sdr
12
+ # YouTube (Resultados): https://m.youtube.com/channel/UC3EgoJi_Fv7yuDpvfYNtoIQ
13
+ #
14
+ # Este programa é software livre: você pode redistribuí-lo e/ou modificá-lo
15
+ # sob os termos da Licença Pública Geral Affero da GNU como publicada pela
16
+ # Free Software Foundation, seja a versão 3 da Licença, ou
17
+ # (a seu critério) qualquer versão posterior.
18
+ #
19
+ # Este programa é distribuído na esperança de que seja útil,
20
+ # mas SEM QUALQUER GARANTIA; sem mesmo a garantia implícita de
21
+ # COMERCIALIZAÇÃO ou ADEQUAÇÃO A UM DETERMINADO FIM. Consulte a
22
+ # Licença Pública Geral Affero da GNU para mais detalhes.
23
+ #
24
+ # Você deve ter recebido uma cópia da Licença Pública Geral Affero da GNU
25
+ # junto com este programa. Se não, veja <https://www.gnu.org/licenses/>.
26
+ #
27
+ # AVISO DE PATENTE PENDENTE: O método e sistema ADUC implementado neste
28
+ # software está em processo de patenteamento. Consulte NOTICE.md.
29
+
30
+ import gradio as gr
31
+ import yaml
32
+ import logging
33
+ import os
34
+ import sys
35
+ import shutil
36
+ import time
37
+ import json
38
+
39
+ from aduc_orchestrator import AducOrchestrator
40
+
41
+ # --- 1. CONFIGURAÇÃO E INICIALIZAÇÃO ---
42
+
43
+ LOG_FILE_PATH = "aduc_log.txt"
44
+ if os.path.exists(LOG_FILE_PATH):
45
+ os.remove(LOG_FILE_PATH)
46
+
47
+ log_format = '%(asctime)s - %(levelname)s - [%(name)s:%(funcName)s] - %(message)s'
48
+ root_logger = logging.getLogger()
49
+ root_logger.setLevel(logging.INFO)
50
+ root_logger.handlers.clear()
51
+
52
+ stream_handler = logging.StreamHandler(sys.stdout)
53
+ stream_handler.setLevel(logging.INFO)
54
+ stream_handler.setFormatter(logging.Formatter(log_format))
55
+ root_logger.addHandler(stream_handler)
56
+
57
+ file_handler = logging.FileHandler(LOG_FILE_PATH, mode='w', encoding='utf-8')
58
+ file_handler.setLevel(logging.INFO)
59
+ file_handler.setFormatter(logging.Formatter(log_format))
60
+ root_logger.addHandler(file_handler)
61
+
62
+ logger = logging.getLogger(__name__)
63
+
64
+ i18n = {}
65
+ try:
66
+ with open("i18n.json", "r", encoding="utf-8") as f:
67
+ i18n = json.load(f)
68
+ except Exception as e:
69
+ logger.error(f"Erro ao carregar i18n.json: {e}")
70
+ i18n = {"pt": {}, "en": {}, "zh": {}}
71
+
72
+ if 'pt' not in i18n: i18n['pt'] = i18n.get('en', {})
73
+ if 'en' not in i18n: i18n['en'] = {}
74
+ if 'zh' not in i18n: i18n['zh'] = i18n.get('en', {})
75
+
76
+ try:
77
+ with open("config.yaml", 'r') as f: config = yaml.safe_load(f)
78
+ WORKSPACE_DIR = config['application']['workspace_dir']
79
+ aduc = AducOrchestrator(workspace_dir=WORKSPACE_DIR)
80
+ logger.info("Orquestrador ADUC e Especialistas inicializados com sucesso.")
81
+ except Exception as e:
82
+ logger.error(f"ERRO CRÍTICO ao inicializar: {e}", exc_info=True)
83
+ exit()
84
+
85
+ # --- 2. WRAPPERS DA UI ---
86
+
87
+ def run_mode_a_wrapper(prompt, num_keyframes, ref_files, resolution_str, duration_per_fragment, progress=gr.Progress()):
88
+ if not ref_files:
89
+ raise gr.Error("Por favor, forneça pelo menos uma imagem de referência.")
90
+
91
+ ref_paths = [aduc.process_image_for_story(f.name, 480, f"ref_processed_{i}.png") for i, f in enumerate(ref_files)]
92
+
93
+ progress(0.1, desc="Gerando roteiro...")
94
+ storyboard, initial_ref_path, _ = aduc.task_generate_storyboard(prompt, num_keyframes, ref_paths, progress)
95
+
96
+ resolution = int(resolution_str.split('x')[0])
97
+
98
+ def cb_factory(scene_index, total_scenes):
99
+ start_time = time.time()
100
+ total_steps = 12
101
+ def callback(pipe_self, step, timestep, callback_kwargs):
102
+ elapsed = time.time() - start_time
103
+ current_step = step + 1
104
+ if current_step > 0:
105
+ it_per_sec = current_step / elapsed
106
+ eta = (total_steps - current_step) / it_per_sec if it_per_sec > 0 else 0
107
+ desc = f"Keyframe {scene_index}/{total_scenes}: {int((current_step/total_steps)*100)}% | {current_step}/{total_steps} [{elapsed:.0f}s<{eta:.0f}s, {it_per_sec:.2f}it/s]"
108
+ base_progress = 0.2 + (scene_index - 1) * (0.8 / total_scenes)
109
+ step_progress = (current_step / total_steps) * (0.8 / total_scenes)
110
+ progress(base_progress + step_progress, desc=desc)
111
+ return {}
112
+ return callback
113
+
114
+ final_keyframes = aduc.task_generate_keyframes(storyboard, initial_ref_path, prompt, resolution, cb_factory)
115
+
116
+ return gr.update(value=storyboard), gr.update(value=final_keyframes), gr.update(visible=True, open=True)
117
+
118
+ def run_mode_b_wrapper(prompt, num_keyframes, ref_files, progress=gr.Progress()):
119
+ if not ref_files or len(ref_files) < 2:
120
+ raise gr.Error("Modo Fotógrafo requer pelo menos 2 imagens: uma base e uma para o banco de cenas.")
121
+
122
+ base_ref_paths = [aduc.process_image_for_story(ref_files[0].name, 480, "base_ref_processed_0.png")]
123
+ pool_ref_paths = [aduc.process_image_for_story(f.name, 480, f"pool_ref_{i+1}.png") for i, f in enumerate(ref_files[1:])]
124
+
125
+ progress(0.1, desc="Gerando roteiro...")
126
+ storyboard, _, _ = aduc.task_generate_storyboard(prompt, num_keyframes, base_ref_paths, progress)
127
+
128
+ progress(0.5, desc="IA (Fotógrafo) está selecionando as melhores cenas...")
129
+ selected_keyframes = aduc.task_select_keyframes(storyboard, base_ref_paths, pool_ref_paths)
130
+
131
+ return gr.update(value=storyboard), gr.update(value=selected_keyframes), gr.update(visible=True, open=True)
132
+
133
+ def run_video_production_wrapper(keyframes, prompt, duration,
134
+ trim_percent, handler_strength, destination_convergence_strength,
135
+ use_upscaler, use_refiner, use_hd, use_audio,
136
+ video_resolution,
137
+ progress=gr.Progress()):
138
+ yield {
139
+ final_video_output: gr.update(value=None, visible=True, label="🎬 Produzindo seu filme... Por favor, aguarde.")
140
+ }
141
+
142
+ resolution = int(video_resolution.split('x')[0])
143
+ final_movie_path = None
144
+
145
+ for update in aduc.task_produce_final_movie_with_feedback(
146
+ keyframes, prompt, duration,
147
+ int(trim_percent), handler_strength, destination_convergence_strength,
148
+ use_upscaler, use_refiner, use_hd, use_audio,
149
+ resolution, use_continuity_director=True, progress=progress
150
+ ):
151
+ if "final_path" in update and update["final_path"]:
152
+ final_movie_path = update["final_path"]
153
+ break
154
+
155
+ yield {
156
+ final_video_output: gr.update(value=final_movie_path, label="🎉 FILME COMPLETO 🎉")
157
+ }
158
+
159
+ def get_log_content():
160
+ try:
161
+ with open(LOG_FILE_PATH, "r", encoding="utf-8") as f:
162
+ return f.read()
163
+ except FileNotFoundError:
164
+ return "Arquivo de log ainda não criado. Inicie uma geração."
165
+
166
+ def update_ui_language(lang_code):
167
+ lang_map = i18n.get(lang_code, i18n.get('en', {}))
168
+ return {
169
+ title_md: gr.update(value=f"# {lang_map.get('app_title')}"),
170
+ subtitle_md: gr.update(value=lang_map.get('app_subtitle')),
171
+ lang_selector: gr.update(label=lang_map.get('lang_selector_label')),
172
+ step1_accordion: gr.update(label=lang_map.get('step1_accordion')),
173
+ prompt_input: gr.update(label=lang_map.get('prompt_label')),
174
+ ref_image_input: gr.update(label=lang_map.get('ref_images_label')),
175
+ num_keyframes_slider: gr.update(label=lang_map.get('keyframes_label')),
176
+ duration_per_fragment_slider: gr.update(label=lang_map.get('duration_label'), info=lang_map.get('duration_info')),
177
+ storyboard_and_keyframes_button: gr.update(value=lang_map.get('storyboard_and_keyframes_button')),
178
+ storyboard_from_photos_button: gr.update(value=lang_map.get('storyboard_from_photos_button')),
179
+ step1_mode_b_info_md: gr.update(value=f"*{lang_map.get('step1_mode_b_info')}*"),
180
+ storyboard_output: gr.update(label=lang_map.get('storyboard_output_label')),
181
+ keyframe_gallery: gr.update(label=lang_map.get('keyframes_gallery_label')),
182
+ step2_accordion: gr.update(label=lang_map.get('step3_accordion')),
183
+ step2_description_md: gr.update(value=lang_map.get('step3_description')),
184
+ produce_button: gr.update(value=lang_map.get('produce_button')),
185
+ final_video_output: gr.update(label=lang_map.get('final_movie_with_audio_label')),
186
+ log_accordion: gr.update(label=lang_map.get('log_accordion_label')),
187
+ log_display: gr.update(label=lang_map.get('log_display_label')),
188
+ update_log_button: gr.update(value=lang_map.get('update_log_button')),
189
+ advanced_options_accordion: gr.update(label=lang_map.get('advanced_options_accordion')),
190
+ causality_controls_title_md: gr.update(value=f"**{lang_map.get('causality_controls_title')}**"),
191
+ trim_percent_slider: gr.update(label=lang_map.get('trim_percent_label'), info=lang_map.get('trim_percent_info')),
192
+ forca_guia_slider: gr.update(label=lang_map.get('forca_guia_label'), info=lang_map.get('forca_guia_info')),
193
+ convergencia_destino_slider: gr.update(label=lang_map.get('convergencia_final_label'), info=lang_map.get('convergencia_final_info')),
194
+ post_production_controls_title_md: gr.update(value=f"**{lang_map.get('post_production_controls_title')}**"),
195
+ use_upscaler_checkbox: gr.update(label=lang_map.get('use_upscaler_label')),
196
+ use_refiner_checkbox: gr.update(label=lang_map.get('use_refiner_label')),
197
+ use_hd_checkbox: gr.update(label=lang_map.get('use_hd_label')),
198
+ use_audio_checkbox: gr.update(label=lang_map.get('use_audio_label')),
199
+ }
200
+
201
+ # --- 3. DEFINIÇÃO DA UI ---
202
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
203
+ default_lang = i18n.get('pt', {})
204
+
205
+ title_md = gr.Markdown(f"# {default_lang.get('app_title')}")
206
+ subtitle_md = gr.Markdown(default_lang.get('app_subtitle'))
207
+
208
+ with gr.Row():
209
+ lang_selector = gr.Radio(["pt", "en", "zh"], value="pt", label=default_lang.get('lang_selector_label'))
210
+ resolution_selector = gr.Radio(["480x480"], value="480x480", label="Resolução Base")
211
+
212
+ with gr.Accordion(default_lang.get('step1_accordion'), open=True) as step1_accordion:
213
+ prompt_input = gr.Textbox(label=default_lang.get('prompt_label'), value="A majestic lion walks across the savanna, sits down, and then roars at the setting sun.")
214
+ ref_image_input = gr.File(label=default_lang.get('ref_images_label'), file_count="multiple", file_types=["image"])
215
+ with gr.Row():
216
+ num_keyframes_slider = gr.Slider(minimum=3, maximum=42, value=5, step=1, label=default_lang.get('keyframes_label'))
217
+ duration_per_fragment_slider = gr.Slider(label=default_lang.get('duration_label'), info=default_lang.get('duration_info'), minimum=2.0, maximum=10.0, value=4.0, step=0.1)
218
+ with gr.Row():
219
+ storyboard_and_keyframes_button = gr.Button(default_lang.get('storyboard_and_keyframes_button'), variant="primary")
220
+ storyboard_from_photos_button = gr.Button(default_lang.get('storyboard_from_photos_button'))
221
+ step1_mode_b_info_md = gr.Markdown(f"*{default_lang.get('step1_mode_b_info')}*")
222
+ storyboard_output = gr.JSON(label=default_lang.get('storyboard_output_label'))
223
+ keyframe_gallery = gr.Gallery(label=default_lang.get('keyframes_gallery_label'), visible=True, object_fit="contain", height="auto", type="filepath")
224
+
225
+ with gr.Accordion(default_lang.get('step3_accordion'), open=False, visible=False) as step2_accordion:
226
+ step2_description_md = gr.Markdown(default_lang.get('step3_description'))
227
+
228
+ with gr.Accordion(default_lang.get('advanced_options_accordion'), open=True) as advanced_options_accordion:
229
+ causality_controls_title_md = gr.Markdown(f"**{default_lang.get('causality_controls_title')}**")
230
+ trim_percent_slider = gr.Slider(minimum=10, maximum=90, value=50, step=5,
231
+ label=default_lang.get('trim_percent_label'),
232
+ info=default_lang.get('trim_percent_info'))
233
+ with gr.Row():
234
+ forca_guia_slider = gr.Slider(label=default_lang.get('forca_guia_label'), minimum=0.0, maximum=1.0, value=0.5, step=0.05, info=default_lang.get('forca_guia_info'))
235
+ convergencia_destino_slider = gr.Slider(label=default_lang.get('convergencia_final_label'), minimum=0.0, maximum=1.0, value=0.75, step=0.05, info=default_lang.get('convergencia_final_info'))
236
+
237
+ gr.Markdown("---")
238
+ post_production_controls_title_md = gr.Markdown(f"**{default_lang.get('post_production_controls_title')}**")
239
+ with gr.Row():
240
+ use_upscaler_checkbox = gr.Checkbox(label=default_lang.get('use_upscaler_label'), value=False)
241
+ use_refiner_checkbox = gr.Checkbox(label=default_lang.get('use_refiner_label'), value=False)
242
+ use_hd_checkbox = gr.Checkbox(label=default_lang.get('use_hd_label'), value=False)
243
+ use_audio_checkbox = gr.Checkbox(label=default_lang.get('use_audio_label'), value=False)
244
+
245
+ produce_button = gr.Button(default_lang.get('produce_button'), variant="primary")
246
+
247
+ final_video_output = gr.Video(label=default_lang.get('final_movie_with_audio_label'), visible=False)
248
+
249
+ with gr.Accordion(default_lang.get('log_accordion_label'), open=False) as log_accordion:
250
+ log_display = gr.Textbox(label=default_lang.get('log_display_label'), lines=20, interactive=False, autoscroll=True)
251
+ update_log_button = gr.Button(default_lang.get('update_log_button'))
252
+
253
+ # --- 4. CONEXÕES DA UI ---
254
+ all_ui_components = list(update_ui_language('pt').keys())
255
+ lang_selector.change(fn=update_ui_language, inputs=lang_selector, outputs=all_ui_components)
256
+
257
+ storyboard_and_keyframes_button.click(
258
+ fn=run_mode_a_wrapper,
259
+ inputs=[prompt_input, num_keyframes_slider, ref_image_input, resolution_selector, duration_per_fragment_slider],
260
+ outputs=[storyboard_output, keyframe_gallery, step2_accordion]
261
+ )
262
+
263
+ storyboard_from_photos_button.click(
264
+ fn=run_mode_b_wrapper,
265
+ inputs=[prompt_input, num_keyframes_slider, ref_image_input],
266
+ outputs=[storyboard_output, keyframe_gallery, step2_accordion]
267
+ )
268
+
269
+ produce_button.click(
270
+ fn=run_video_production_wrapper,
271
+ inputs=[
272
+ keyframe_gallery, prompt_input, duration_per_fragment_slider,
273
+ trim_percent_slider, forca_guia_slider, convergencia_destino_slider,
274
+ use_upscaler_checkbox, use_refiner_checkbox, use_hd_checkbox, use_audio_checkbox,
275
+ resolution_selector
276
+ ],
277
+ outputs=[final_video_output]
278
+ )
279
+
280
+ update_log_button.click(fn=get_log_content, inputs=[], outputs=[log_display])
281
+
282
+ # --- 5. INICIALIZAÇÃO DA APLICAÇÃO ---
283
+ if __name__ == "__main__":
284
+ if os.path.exists(WORKSPACE_DIR):
285
+ logger.info(f"Limpando o workspace anterior em: {WORKSPACE_DIR}")
286
+ shutil.rmtree(WORKSPACE_DIR)
287
+ os.makedirs(WORKSPACE_DIR)
288
+ logger.info(f"Aplicação iniciada. Lançando interface Gradio...")
289
+ demo.queue().launch()