-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_lofi_project.py
More file actions
395 lines (339 loc) · 17 KB
/
Copy pathgenerate_lofi_project.py
File metadata and controls
395 lines (339 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
#!/usr/bin/env python3
"""
Gerador de projeto MLT para Shotcut - Otimizado para YouTube
SOLUÇÃO CORRIGIDA: Texto como filtro aplicado no vídeo, não como producer separado
"""
import os
import math
import xml.etree.ElementTree as ET
from xml.dom import minidom
# Configurações otimizadas para YouTube
VIDEOS_DIR = "Videos"
AUDIO_DIR = "FASSounds"
ARTIST_NAME = "FASSounds"
FPS = 30 # 30fps é ideal para YouTube
# RESOLUÇÃO: 720p nativo (mesma dos vídeos = SEM upscaling = MELHOR qualidade)
WIDTH = 1280 # 720p HD - resolução nativa dos vídeos
HEIGHT = 720 # Sem upscaling = sem perda de qualidade
GAP_SECONDS = 0.5
GAP_FRAMES = int(GAP_SECONDS * FPS)
# Configurações de texto animado
TEXT_ANIMATION_CYCLE = 2 # segundos para um ciclo de flutuação (sobe e desce)
TEXT_SIZE = 96 # Texto bem maior
FONT_NAME = "Sans"
TEXT_MARGIN_RIGHT = 50 # pixels da borda direita
TEXT_MARGIN_BOTTOM = 50 # pixels da borda inferior
TEXT_FLOAT_AMPLITUDE = 30 # amplitude da flutuação em pixels (sobe/desce do ponto base)
# Informações dos vídeos (todos 1280x720, 8 segundos a 24fps = 192 frames)
# Convertendo para 30fps: 8 segundos * 30fps = 240 frames
videos = [
{"file": "1.mp4", "frames": 240},
{"file": "2.mp4", "frames": 240},
{"file": "3.mp4", "frames": 240},
{"file": "4.mp4", "frames": 240},
{"file": "5.mp4", "frames": 240},
{"file": "6.mp4", "frames": 240},
]
# Informações dos áudios (nome e duração em segundos)
audios = [
("Blizzard.mp3", 131.265281),
("Chill Night.mp3", 120.868563),
("Coding Night.mp3", 88.920813),
("Cooking Beats.mp3", 138.527344),
("Fireplace.mp3", 136.071813),
("Focus.mp3", 127.791000),
("Good Night - Lofi Cozy Chill Music.mp3", 147.121625),
("Hot Coffee - Lofi Vlog Chill Hop.mp3", 136.202438),
("Jazz Cafe.mp3", 122.644875),
("Lazy Time - Summer Relax Lofi.mp3", 134.321625),
("Lofi Chill - Commercial Fashion Vlog.mp3", 124.969781),
("Lofi Mood.mp3", 153.129781),
("Lofi Study - Calm Peaceful Chill Hop.mp3", 147.226094),
("Lofi Vintage.mp3", 138.031000),
("Luxury - Summer Fall Travel Vlog Lofi Hip-Hop.mp3", 120.032625),
("Midnight Works (Chill Cozy Lofi).mp3", 124.577938),
("November - Chill Fall Autumn Lofi Hip-Hop.mp3", 122.697125),
("Passionate - Mediation Ambient Yoga Lofi.mp3", 166.791813),
("Rainy Day - Slow Chill Lofi.mp3", 118.308563),
("Romantic Dinner - Lofi Relax Beat.mp3", 139.546094),
("Satisfying - Lofi for Focus Study & Working.mp3", 130.089781),
("Spring Bloom - Autumn Lofi Chill Beat.mp3", 127.033469),
("Starry Night - Aesthetic Dreamy Lofi.mp3", 207.124875),
("Sunset.mp3", 88.111000),
("Take A Break - Cozy Ambient Lofi.mp3", 159.242438),
("Tasty - Chill Lofi Vibe.mp3", 139.337125),
("Winter - Holiday Chill Hop.mp3", 129.906938),
]
def get_song_name(filename):
"""Remove extensão .mp3 do nome do arquivo"""
return filename.replace(".mp3", "")
def calculate_timeline():
"""Calcula posições no timeline para cada música"""
timeline = []
current_frame = 0
for filename, duration_sec in audios:
duration_frames = int(duration_sec * FPS)
timeline.append({
"file": filename,
"name": get_song_name(filename),
"start_frame": current_frame,
"end_frame": current_frame + duration_frames - 1,
"duration_frames": duration_frames
})
current_frame += duration_frames + GAP_FRAMES
total_frames = current_frame - GAP_FRAMES
return timeline, total_frames
def create_mlt_project():
"""Cria o arquivo MLT XML"""
timeline, total_frames = calculate_timeline()
# Criar elemento raiz
mlt = ET.Element("mlt", {
"LC_NUMERIC": "C",
"version": "7.22.0",
"title": "LoFi Music Mix - YouTube Optimized",
"producer": "main_bin"
})
# Profile Full HD 1080p 30fps (otimizado para YouTube)
profile = ET.SubElement(mlt, "profile", {
"description": "Full HD 1080p 30fps",
"width": str(WIDTH),
"height": str(HEIGHT),
"progressive": "1",
"sample_aspect_num": "1",
"sample_aspect_den": "1",
"display_aspect_num": "16",
"display_aspect_den": "9",
"frame_rate_num": str(FPS),
"frame_rate_den": "1",
"colorspace": "709"
})
# Chains de vídeo (upscaled para 1080p)
for i, video in enumerate(videos):
chain = ET.SubElement(mlt, "chain", {
"id": f"video_{i}",
"out": str(video["frames"] - 1)
})
ET.SubElement(chain, "property", {"name": "resource"}).text = f"{VIDEOS_DIR}/{video['file']}"
ET.SubElement(chain, "property", {"name": "mlt_service"}).text = "avformat-novalidate"
ET.SubElement(chain, "property", {"name": "audio_index"}).text = "-1"
ET.SubElement(chain, "property", {"name": "shotcut:caption"}).text = video["file"]
# Chains de áudio
for i, (filename, duration) in enumerate(audios):
duration_frames = int(duration * FPS)
chain = ET.SubElement(mlt, "chain", {
"id": f"audio_{i}",
"out": str(duration_frames - 1)
})
ET.SubElement(chain, "property", {"name": "resource"}).text = f"{AUDIO_DIR}/{filename}"
ET.SubElement(chain, "property", {"name": "mlt_service"}).text = "avformat-novalidate"
ET.SubElement(chain, "property", {"name": "video_index"}).text = "-1"
ET.SubElement(chain, "property", {"name": "shotcut:caption"}).text = filename
# Producer preto (background)
black = ET.SubElement(mlt, "producer", {
"id": "black",
"out": str(total_frames + 1000)
})
ET.SubElement(black, "property", {"name": "mlt_service"}).text = "colour"
ET.SubElement(black, "property", {"name": "resource"}).text = "black"
# Playlist main_bin
main_bin = ET.SubElement(mlt, "playlist", {"id": "main_bin"})
ET.SubElement(main_bin, "property", {"name": "shotcut:name"}).text = "main bin"
# Playlist de vídeo (loop) COM FILTRO DE TEXTO APLICADO DIRETAMENTE
video_playlist = ET.SubElement(mlt, "playlist", {"id": "video_playlist"})
ET.SubElement(video_playlist, "property", {"name": "shotcut:video"}).text = "1"
ET.SubElement(video_playlist, "property", {"name": "shotcut:name"}).text = "V1"
# Adicionar vídeos em loop até cobrir todo o áudio
current_frame = 0
video_index = 0
song_index = 0
frames_in_current_song = 0
while current_frame < total_frames:
video = videos[video_index % len(videos)]
# Determinar qual música está tocando neste momento
while song_index < len(timeline) and current_frame > timeline[song_index]["end_frame"]:
song_index += 1
frames_in_current_song = 0
if song_index >= len(timeline):
break
song_info = timeline[song_index]
# Criar entry do vídeo
entry = ET.SubElement(video_playlist, "entry", {
"producer": f"video_{video_index % len(videos)}",
"in": "0",
"out": str(video["frames"] - 1)
})
# APLICAR FILTRO DE TEXTO DIRETAMENTE NO ENTRY COM ANIMAÇÃO DE FLUTUAÇÃO
# Adicionar filtro qtext com animação flutuante
text_filter = ET.SubElement(entry, "filter")
ET.SubElement(text_filter, "property", {"name": "mlt_service"}).text = "qtext"
text_content = f"FASSounds - {song_info['name']}"
ET.SubElement(text_filter, "property", {"name": "argument"}).text = text_content
ET.SubElement(text_filter, "property", {"name": "family"}).text = FONT_NAME
ET.SubElement(text_filter, "property", {"name": "size"}).text = str(TEXT_SIZE)
ET.SubElement(text_filter, "property", {"name": "weight"}).text = "700"
ET.SubElement(text_filter, "property", {"name": "fgcolour"}).text = "0xffffffff"
ET.SubElement(text_filter, "property", {"name": "bgcolour"}).text = "0xcc000000"
ET.SubElement(text_filter, "property", {"name": "olcolour"}).text = "0x000000ff"
ET.SubElement(text_filter, "property", {"name": "outline"}).text = "3"
ET.SubElement(text_filter, "property", {"name": "pad"}).text = "30"
ET.SubElement(text_filter, "property", {"name": "halign"}).text = "right"
ET.SubElement(text_filter, "property", {"name": "valign"}).text = "bottom"
# Calcular animação de flutuação vertical
cycle_frames = int(TEXT_ANIMATION_CYCLE * FPS) # Frames para um ciclo completo
# CORREÇÃO: Usar geometria que cobre toda a largura da tela
# O texto vai alinhar à direita dentro dessa caixa graças ao halign="right"
# A caixa vai de X=0 até WIDTH-TEXT_MARGIN_RIGHT
x_pos = 0
box_width = WIDTH - TEXT_MARGIN_RIGHT # 1920 - 50 = 1870px
box_height = 120
# Posição Y base (canto inferior)
y_base = HEIGHT - TEXT_MARGIN_BOTTOM - box_height # 1080 - 50 - 120 = 910
# Calcular posição inicial e final deste clipe dentro da música
frame_start_in_song = frames_in_current_song
frame_end_in_song = frames_in_current_song + video["frames"] - 1
# Função para calcular Y baseado na posição no ciclo (movimento senoidal)
def get_y_position(frame_in_song):
# Normalizar para 0-1 dentro do ciclo
cycle_position = (frame_in_song % cycle_frames) / cycle_frames
# Usar seno para movimento suave (0 -> 1 -> 0)
sine_value = math.sin(cycle_position * 2 * math.pi)
# Aplicar amplitude (negativo porque Y cresce para baixo)
y_offset = sine_value * TEXT_FLOAT_AMPLITUDE
return y_base - y_offset # Subtrair porque queremos subir quando positivo
# Criar keyframes a cada segundo (ou a cada ciclo completo)
keyframes = []
# Sempre adicionar keyframe no início
y_start = get_y_position(frame_start_in_song)
keyframes.append(f"0~={int(x_pos)}/{int(y_start)}:{int(box_width)}x{int(box_height)}")
# Adicionar keyframes intermediários se o clipe for longo o suficiente
# Um keyframe a cada quarto de ciclo (0.5s) para capturar bem a curva
quarter_cycle = cycle_frames // 4
current_check = frame_start_in_song + quarter_cycle
while current_check < frame_end_in_song:
frame_in_clip = current_check - frame_start_in_song
y_mid = get_y_position(current_check)
keyframes.append(f"{frame_in_clip}~={int(x_pos)}/{int(y_mid)}:{int(box_width)}x{int(box_height)}")
current_check += quarter_cycle
# Sempre adicionar keyframe no fim
y_end = get_y_position(frame_end_in_song)
keyframes.append(f"{video['frames'] - 1}~={int(x_pos)}/{int(y_end)}:{int(box_width)}x{int(box_height)}")
# Juntar todos os keyframes
geometry_value = ";".join(keyframes)
ET.SubElement(text_filter, "property", {"name": "geometry"}).text = geometry_value
current_frame += video["frames"]
frames_in_current_song += video["frames"]
video_index += 1
# Playlist de áudio
audio_playlist = ET.SubElement(mlt, "playlist", {"id": "audio_playlist"})
ET.SubElement(audio_playlist, "property", {"name": "shotcut:audio"}).text = "1"
ET.SubElement(audio_playlist, "property", {"name": "shotcut:name"}).text = "A1"
for i, song_info in enumerate(timeline):
ET.SubElement(audio_playlist, "entry", {
"producer": f"audio_{i}",
"in": "0",
"out": str(song_info["duration_frames"] - 1)
})
# Gap entre músicas (exceto depois da última)
if i < len(timeline) - 1:
ET.SubElement(audio_playlist, "blank", {"length": str(GAP_FRAMES)})
# Background playlist
background = ET.SubElement(mlt, "playlist", {"id": "background"})
ET.SubElement(background, "entry", {
"producer": "black",
"in": "0",
"out": str(total_frames - 1)
})
# Tractor principal
tractor = ET.SubElement(mlt, "tractor", {
"id": "tractor0",
"in": "0",
"out": str(total_frames - 1)
})
ET.SubElement(tractor, "property", {"name": "shotcut"}).text = "1"
ET.SubElement(tractor, "property", {"name": "shotcut:projectAudioChannels"}).text = "2"
# Multitrack - APENAS 3 TRACKS!
multitrack = ET.SubElement(tractor, "multitrack")
ET.SubElement(multitrack, "track", {"producer": "background"}) # Track 0: fundo preto
ET.SubElement(multitrack, "track", {"producer": "audio_playlist", "hide": "video"}) # Track 1: áudio only
ET.SubElement(multitrack, "track", {"producer": "video_playlist"}) # Track 2: vídeo com texto embutido
# Transitions - SIMPLIFICADAS!
# Mix de áudio (track 0 com track 1)
trans_audio = ET.SubElement(tractor, "transition")
ET.SubElement(trans_audio, "property", {"name": "a_track"}).text = "0"
ET.SubElement(trans_audio, "property", {"name": "b_track"}).text = "1"
ET.SubElement(trans_audio, "property", {"name": "mlt_service"}).text = "mix"
ET.SubElement(trans_audio, "property", {"name": "sum"}).text = "1"
# Composição do vídeo sobre o background (track 0 + track 2)
trans_video_base = ET.SubElement(tractor, "transition")
ET.SubElement(trans_video_base, "property", {"name": "a_track"}).text = "0"
ET.SubElement(trans_video_base, "property", {"name": "b_track"}).text = "2"
ET.SubElement(trans_video_base, "property", {"name": "mlt_service"}).text = "frei0r.cairoblend"
# Mix de áudio do vídeo (track 0 + track 2 áudio)
trans_video_audio = ET.SubElement(tractor, "transition")
ET.SubElement(trans_video_audio, "property", {"name": "a_track"}).text = "0"
ET.SubElement(trans_video_audio, "property", {"name": "b_track"}).text = "2"
ET.SubElement(trans_video_audio, "property", {"name": "mlt_service"}).text = "mix"
ET.SubElement(trans_video_audio, "property", {"name": "sum"}).text = "1"
return mlt, timeline, total_frames
def prettify_xml(elem):
"""Formata XML de forma legível"""
rough_string = ET.tostring(elem, encoding='utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ", encoding='utf-8').decode('utf-8')
def main():
print("🎵 Gerando projeto MLT para Shotcut - OTIMIZADO PARA YOUTUBE")
print("✨ SOLUÇÃO CORRIGIDA: Texto aplicado como filtro no vídeo")
print()
print(f"📹 Resolução: {WIDTH}x{HEIGHT} (Full HD 1080p)")
print(f"🎞️ Frame Rate: {FPS}fps (otimizado para YouTube)")
print(f"📺 Vídeos: {len(videos)} arquivos (upscaled de 720p para 1080p)")
print(f"🎼 Músicas: {len(audios)} arquivos")
print(f"⏱️ Gap entre músicas: {GAP_SECONDS}s ({GAP_FRAMES} frames)")
print(f"💬 Texto: Tamanho {TEXT_SIZE}px, posição fixa no canto inferior direito")
print(f"🔄 Animação: Flutuação vertical suave ({TEXT_ANIMATION_CYCLE}s por ciclo, amplitude {TEXT_FLOAT_AMPLITUDE}px)")
print(f"📍 Margens: {TEXT_MARGIN_RIGHT}px da direita, {TEXT_MARGIN_BOTTOM}px de baixo")
print()
mlt, timeline, total_frames = create_mlt_project()
total_seconds = total_frames / FPS
print(f"📊 Duração total do projeto: {total_frames} frames ({total_seconds:.2f}s / {total_seconds/60:.2f}min)")
print()
print("🎬 Timeline:")
for i, song in enumerate(timeline, 1):
start_sec = song["start_frame"] / FPS
end_sec = song["end_frame"] / FPS
print(f" {i:2d}. {song['name'][:50]:<50} | {start_sec:7.2f}s - {end_sec:7.2f}s")
# Salvar arquivo
output_file = "lofi_mix.mlt"
xml_string = prettify_xml(mlt)
with open(output_file, 'w', encoding='utf-8') as f:
f.write(xml_string)
print()
print(f"✅ Arquivo criado: {output_file}")
print(f"🎯 Abra o arquivo no Shotcut para visualizar o projeto!")
print()
print("📝 Estrutura do projeto (SOLUÇÃO DEFINITIVA):")
print(f" - Track 0 (Background): Fundo preto")
print(f" - Track 1 (A1): {len(audios)} músicas em sequência")
print(f" - Track 2 (V1): Vídeos em loop COM TEXTO EMBUTIDO")
print()
print("🎥 Configurações de export recomendadas no Shotcut:")
print(" - Format: MP4")
print(" - Video codec: libx264")
print(" - Rate control: Quality-based VBR")
print(" - Quality: 55-60%")
print(" - Bitrate: 8000k-12000k (para 1080p 30fps)")
print(" - Audio codec: AAC")
print(" - Audio bitrate: 192k-256k")
print()
print("✨ Correções aplicadas (baseadas em pesquisa extensiva):")
print(" ✅ SEM producers de texto separados (causavam INVALIDE)")
print(" ✅ Filtro qtext aplicado DIRETAMENTE nos entries de vídeo")
print(" ✅ Apenas 3 tracks (background, áudio, vídeo)")
print(" ✅ Animação calculada frame-by-frame para cada clipe")
print(" ✅ Sem emoji (pode causar problemas de encoding)")
print(" ✅ Texto flutuando no canto inferior direito (50px margens)")
print(" ✅ Animação senoidal suave (sobe e desce 20px)")
print(" ✅ Texto MAIOR (96px) para melhor legibilidade")
print(" ✅ Texto muda automaticamente a cada mudança de música")
if __name__ == "__main__":
main()