Respire fundo e trabalhe passo a passe nesse problema:
Algumas palavras estão desalinhadas um pouco pra cima ou pra baixo, preciso que todas as palavras fiquem perfeitamente alinhadas.
Mande o código completo e corrigido.
python
Assistant
import re
from datetime import timedelta
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import subprocess
import os
import multiprocessing
font_size = 35
image_size = (1280, 720)
font_color = (255, 0, 0) # Red
highlight_color = (255, 255, 255) # White
upper_case = True
fps = 20
def parse_time(time_str):
match = re.match(r'(\d+):(\d+):(\d+)', time_str)
if match:
minutes, seconds, milliseconds = map(int, match.groups())
time = timedelta(minutes=minutes, seconds=seconds, milliseconds=milliseconds)
return time
return timedelta(0)
def read_subtitles(filename):
subtitles = []
with open(filename, 'r', encoding='utf-8') as file:
for line in file:
match = re.match(r'\[(\d+:\d+:\d+)\] (.+)', line.strip())
if match:
time_str, word = match.groups()
subtitles.append((parse_time(time_str), word))
return subtitles
def create_gradient_word(word, font, width, height, start_color, end_color, progress):
# Crie uma imagem com fundo transparente
word_image = Image.new('RGBA', (int(width), height), (0, 0, 0, 0))
draw = ImageDraw.Draw(word_image)
# Obtenha as dimensões exatas do texto
bbox = font.getbbox(word)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
# Calcule a posição para centralizar o texto verticalmente
x = 0
y = (height - text_height) // 2 - bbox[1]
# Desenhe a palavra em branco
draw.text((x, y), word, font=font, fill=end_color)
# Crie uma máscara baseada no texto
mask = Image.new('L', word_image.size, 0)
mask_draw = ImageDraw.Draw(mask)
mask_draw.text((x, y), word, font=font, fill=255)
# Aplique um leve desfoque à máscara para suavizar as bordas
mask = mask.filter(ImageFilter.GaussianBlur(radius=0.5))
# Crie o gradiente
gradient = Image.new('RGBA', word_image.size, (0, 0, 0, 0))
for x in range(word_image.width):
ratio = max(0, min(1, (x / width - progress) / 0.1))
r = int(start_color[0] + (end_color[0] - start_color[0]) * ratio)
g = int(start_color[1] + (end_color[1] - start_color[1]) * ratio)
b = int(start_color[2] + (end_color[2] - start_color[2]) * ratio)
color = (r, g, b, 255)
ImageDraw.Draw(gradient).line([(x, 0), (x, word_image.height)], fill=color)
# Aplique a máscara ao gradiente
gradient.putalpha(mask)
return gradient
def generate_frames_chunk(args):
start_frame, end_frame, subtitles, output_dir, font_path, image_size, highlight_color, font_color, fps, upper_case = args
font = ImageFont.truetype(font_path, font_size)
space_width = font.getlength(' ')
# Alterar o número máximo de palavras por linha e o número de linhas
max_words_per_line = 7
num_lines = 3
line_spacing = 10
# Precompute word widths and positions
if upper_case:
words = [word.upper() for t, word in subtitles]
else:
words = [word for t, word in subtitles]
word_widths = [font.getlength(word) for word in words]
total_width = sum(word_widths) + space_width * (len(word_widths) - 1)
start_x = (image_size[0] - total_width) // 2
x_positions = []
x = start_x
for width in word_widths:
x_positions.append(x)
x += width + space_width
# Load background image
background_image = Image.open("background.jpg").convert("RGB")
background_image = background_image.resize(image_size)
total_duration = (subtitles[-1][0] + timedelta(seconds=2)).total_seconds()
for frame_index in range(start_frame, end_frame):
current_time = timedelta(seconds=frame_index / fps)
image = background_image.copy()
draw = ImageDraw.Draw(image)
# Calcular a posição y inicial para centralizar verticalmente as 3 linhas
total_height = num_lines * (font_size + line_spacing) - line_spacing
y = (image_size[1] - total_height) // 2
# Encontrar o índice do grupo de 3 linhas atual
current_group_index = 0 # Inicializa com 0
last_word_time = subtitles[0][0] # Inicializa com o tempo da primeira legenda
for i, (word_time, _) in enumerate(subtitles):
if word_time > current_time:
if i > 0:
current_group_index = ((i - 1) // (max_words_per_line * num_lines)) * (max_words_per_line * num_lines)
last_word_time = subtitles[i - 1][0]
else:
current_group_index = 0
last_word_time = subtitles[0][0]
break
# Verificar se o gradiente da última palavra do grupo atual foi concluído
if current_time > last_word_time + timedelta(seconds=0.5): # Adiciona um pequeno atraso
current_group_index += max_words_per_line * num_lines
# Exibir 3 linhas de texto
for line in range(num_lines):
start_index = current_group_index + line * max_words_per_line
end_index = start_index + max_words_per_line
line_words = words[start_index:min(end_index, len(words))]
line_widths = word_widths[start_index:min(end_index, len(word_widths))]
total_width = sum(line_widths) + space_width * (len(line_words) - 1)
start_x = (image_size[0] - total_width) // 2
x = start_x
for i, word in enumerate(line_words):
word_time, _ = subtitles[start_index + i]
if start_index + i + 1 < len(subtitles):
next_word_time = subtitles[start_index + i + 1][0]
else:
next_word_time = word_time + timedelta(seconds=2)
# Calcule a posição y para centralizar verticalmente o texto
bbox = font.getbbox(word)
text_height = bbox[3] - bbox[1]
y_centered = y + (font_size - text_height) // 2 - bbox[1]
if current_time >= next_word_time:
draw.text((x, y_centered), word, font=font, fill=font_color)
elif current_time >= word_time:
word_duration = (next_word_time - word_time).total_seconds()
progress = (current_time - word_time).total_seconds() / word_duration
progress = min(max(progress, 0.0), 1.0)
gradient_image = create_gradient_word(word, font, line_widths[i], font_size, font_color, highlight_color, progress)
image.paste(gradient_image, (int(x), int(y)), gradient_image)
else:
draw.text((x, y_centered), word, font=font, fill=highlight_color)
x += line_widths[i] + space_width
y += font_size + line_spacing
frame_filename = os.path.join(output_dir, f"frame_{frame_index:04d}.jpg")
image.save(frame_filename)
def generate_frames_parallel(subtitles, output_dir):
font_path = os.path.join(os.path.dirname(__file__), "impact.ttf")
font = ImageFont.truetype(font_path, font_size)
space_width = font.getlength(' ')
# Calculate total duration
total_duration = (subtitles[-1][0] + timedelta(seconds=2)).total_seconds()
num_frames = int(total_duration * fps) + 1
num_processes = multiprocessing.cpu_count()
chunk_size = num_frames // num_processes + 1
args_list = [
(
i * chunk_size,
min((i + 1) * chunk_size, num_frames),
subtitles,
output_dir,
font_path,
image_size,
highlight_color,
font_color,
fps,
upper_case
)
for i in range(num_processes)
]
with multiprocessing.Pool() as pool:
pool.map(generate_frames_chunk, args_list)
def create_video(frame_folder, output_video, framerate, audio_file):
frame_pattern = os.path.join(frame_folder, 'frame_%04d.jpg')
command = [
'ffmpeg',
'-y',
'-framerate', str(framerate),
'-i', frame_pattern,
'-i', audio_file,
'-c:v', 'h264_nvenc',
'-preset', 'slow',
'-crf', '23',
'-c:a', 'aac',
'-strict', 'experimental',
'-shortest',
output_video
]
subprocess.run(command, check=True)
if __name__ == "__main__":
subtitles = read_subtitles('legenda.srt')
output_dir = 'frames'
os.makedirs(output_dir, exist_ok=True)
generate_frames_parallel(subtitles, output_dir)
create_video(output_dir, 'output_video.mp4', fps, 'audio.wav')
Aqui está o código completo corrigido para alinhar perfeitamente todas as palavras:
python
import re
from datetime import timedelta
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import subprocess
import os
import multiprocessing
font_size = 35
image_size = (1280, 720)
font_color = (255, 0, 0) # Vermelho
highlight_color = (255, 255, 255) # Branco
upper_case = True
fps = 20
def parse_time(time_str):
match = re.match(r'(\d+):(\d+):(\d+)', time_str)
if match:
minutes, seconds, milliseconds = map(int, match.groups())
time = timedelta(minutes=minutes, seconds=seconds, milliseconds=milliseconds)
return time
return timedelta(0)
def read_subtitles(filename):
subtitles = []
with open(filename, 'r', encoding='utf-8') as file:
for line in file:
match = re.match(r'\[(\d+:\d+:\d+)\] (.+)', line.strip())
if match:
time_str, word = match.groups()
subtitles.append((parse_time(time_str), word))
return subtitles
def create_gradient_word(word, font, width, height, start_color, end_color, progress):
# Cria uma imagem com fundo transparente
word_image = Image.new('RGBA', (int(width), int(height)), (0, 0, 0, 0))
draw = ImageDraw.Draw(word_image)
# Obtém as dimensões exatas do texto
bbox = font.getbbox(word)
# Calcula a posição y baseada na linha de base
ascent, descent = font.getmetrics()
y = ascent - bbox[1]
x = 0
# Desenha a palavra na cor final
draw.text((x, y), word, font=font, fill=end_color)
# Cria uma máscara baseada no texto
mask = Image.new('L', word_image.size, 0)
mask_draw = ImageDraw.Draw(mask)
mask_draw.text((x, y), word, font=font, fill=255)
# Aplica um leve desfoque à máscara para suavizar as bordas
mask = mask.filter(ImageFilter.GaussianBlur(radius=0.5))
# Cria o gradiente
gradient = Image.new('RGBA', word_image.size, (0, 0, 0, 0))
for x_pos in range(word_image.width):
ratio = max(0, min(1, (x_pos / width - progress) / 0.1))
r = int(start_color[0] + (end_color[0] - start_color[0]) * ratio)
g = int(start_color[1] + (end_color[1] - start_color[1]) * ratio)
b = int(start_color[2] + (end_color[2] - start_color[2]) * ratio)
color = (r, g, b, 255)
ImageDraw.Draw(gradient).line([(x_pos, 0), (x_pos, word_image.height)], fill=color)
# Aplica a máscara ao gradiente
gradient.putalpha(mask)
return gradient
def generate_frames_chunk(args):
start_frame, end_frame, subtitles, output_dir, font_path, image_size, highlight_color, font_color, fps, upper_case = args
font = ImageFont.truetype(font_path, font_size)
ascent, descent = font.getmetrics()
line_spacing = 10
line_height = ascent + descent + line_spacing
space_width = font.getlength(' ')
# Define o número máximo de palavras por linha e o número de linhas
max_words_per_line = 7
num_lines = 3
# Pré-processa as palavras e suas larguras
if upper_case:
words = [word.upper() for t, word in subtitles]
else:
words = [word for t, word in subtitles]
word_widths = [font.getlength(word) for word in words]
# Carrega a imagem de fundo
background_image = Image.open("background.jpg").convert("RGB")
background_image = background_image.resize(image_size)
total_duration = (subtitles[-1][0] + timedelta(seconds=2)).total_seconds()
for frame_index in range(start_frame, end_frame):
current_time = timedelta(seconds=frame_index / fps)
image = background_image.copy()
draw = ImageDraw.Draw(image)
# Calcula a altura total e a posição y inicial para centralizar verticalmente as linhas
total_height = num_lines * line_height - line_spacing
y = (image_size[1] - total_height) // 2
# Encontra o índice do grupo de linhas atual
current_group_index = 0
last_word_time = subtitles[0][0]
for i, (word_time, _) in enumerate(subtitles):
if word_time > current_time:
if i > 0:
current_group_index = ((i - 1) // (max_words_per_line * num_lines)) * (max_words_per_line * num_lines)
last_word_time = subtitles[i - 1][0]
else:
current_group_index = 0
last_word_time = subtitles[0][0]
break
# Verifica se o gradiente da última palavra do grupo atual foi concluído
if current_time > last_word_time + timedelta(seconds=0.5):
current_group_index += max_words_per_line * num_lines
# Exibe as linhas de texto
for line in range(num_lines):
y_line = y + line * line_height
start_index = current_group_index + line * max_words_per_line
end_index = start_index + max_words_per_line
line_words = words[start_index:min(end_index, len(words))]
line_widths = word_widths[start_index:min(end_index, len(word_widths))]
total_width = sum(line_widths) + space_width * (len(line_words) - 1)
start_x = (image_size[0] - total_width) // 2
x = start_x
for i, word in enumerate(line_words):
word_time, _ = subtitles[start_index + i]
if start_index + i + 1 < len(subtitles):
next_word_time = subtitles[start_index + i + 1][0]
else:
next_word_time = word_time + timedelta(seconds=2)
y_position = y_line
if current_time >= next_word_time:
draw.text((x, y_position), word, font=font, fill=font_color)
elif current_time >= word_time:
word_duration = (next_word_time - word_time).total_seconds()
progress = (current_time - word_time).total_seconds() / word_duration
progress = min(max(progress, 0.0), 1.0)
gradient_image = create_gradient_word(word, font, line_widths[i], ascent + descent, font_color, highlight_color, progress)
image.paste(gradient_image, (int(x), int(y_position)), gradient_image)
else:
draw.text((x, y_position), word, font=font, fill=highlight_color)
x += line_widths[i] + space_width
frame_filename = os.path.join(output_dir, f"frame_{frame_index:04d}.jpg")
image.save(frame_filename)
def generate_frames_parallel(subtitles, output_dir):
font_path = os.path.join(os.path.dirname(__file__), "impact.ttf")
font = ImageFont.truetype(font_path, font_size)
space_width = font.getlength(' ')
# Calcula a duração total
total_duration = (subtitles[-1][0] + timedelta(seconds=2)).total_seconds()
num_frames = int(total_duration * fps) + 1
num_processes = multiprocessing.cpu_count()
chunk_size = num_frames // num_processes + 1
args_list = [
(
i * chunk_size,
min((i + 1) * chunk_size, num_frames),
subtitles,
output_dir,
font_path,
image_size,
highlight_color,
font_color,
fps,
upper_case
)
for i in range(num_processes)
]
with multiprocessing.Pool() as pool:
pool.map(generate_frames_chunk, args_list)
def create_video(frame_folder, output_video, framerate, audio_file):
frame_pattern = os.path.join(frame_folder, 'frame_%04d.jpg')
command = [
'ffmpeg',
'-y',
'-framerate', str(framerate),
'-i', frame_pattern,
'-i', audio_file,
'-c:v', 'h264_nvenc',
'-preset', 'slow',
'-crf', '23',
'-c:a', 'aac',
'-strict', 'experimental',
'-shortest',
output_video
]
subprocess.run(command, check=True)
if __name__ == "__main__":
subtitles = read_subtitles('legenda.srt')
output_dir = 'frames'
os.makedirs(output_dir, exist_ok=True)
generate_frames_parallel(subtitles, output_dir)
create_video(output_dir, 'output_video.mp4', fps, 'audio.wav')
Notas das correções:
Alinhamento vertical corrigido: Modifiquei o cálculo da posição vertical (y_position) para garantir que todas as palavras sejam alinhadas perfeitamente. Isso foi feito usando as métricas de fonte ascent e descent obtidas com font.getmetrics(), e ajustando a posição y de cada palavra de forma consistente.
Remoção de ajustes baseados em bbox: As diferenças nas caixas delimitadoras (bbox) de cada palavra estavam causando desalinhamentos. Removi os ajustes baseados em bbox[1] ao calcular y_position, assegurando que todas as palavras compartilhem a mesma linha de base.
Ajuste na função create_gradient_word: Atualizei a função para usar as métricas da fonte ao calcular a posição vertical do texto dentro da imagem da palavra. Isso garante que o gradiente seja aplicado corretamente e que as palavras sejam renderizadas sem desalinhamento.
Agora, todas as palavras devem estar perfeitamente alinhadas na linha, sem variações verticais indesejadas.