| import gradio as gr |
| from PIL import Image, ImageDraw, ImageFont |
| from moviepy.editor import ImageClip, concatenate_videoclips |
| import os |
|
|
| def create_video(word_list): |
| |
| font_size = 60 |
| try: |
| |
| font_path = "ARIAL.TTF" |
| font = ImageFont.truetype(font_path, font_size) |
| except OSError: |
| |
| print("Không tìm thấy tệp font, đang sử dụng font mặc định.") |
| font = ImageFont.load_default() |
|
|
| |
| width, height = 800, 600 |
| background_color = (255, 255, 255) |
| text_color = (0, 0, 0) |
|
|
| |
| slide_images = [] |
| words = word_list |
| for word, phonetic in words: |
| |
| img = Image.new("RGB", (width, height), background_color) |
| draw = ImageDraw.Draw(img) |
|
|
| |
| |
|
|
| |
| word_text_bbox = draw.textbbox((0, 0), word, font=font) |
| phonetic_text_bbox = draw.textbbox((0, 0), phonetic, font=font) |
|
|
| |
| word_position = ((width - (word_text_bbox[2] - word_text_bbox[0])) // 2, |
| (height - (word_text_bbox[3] - word_text_bbox[1])) // 2 - 50) |
| phonetic_position = ((width - (phonetic_text_bbox[2] - phonetic_text_bbox[0])) // 2, |
| word_position[1] + (word_text_bbox[3] - word_text_bbox[1]) + 20) |
|
|
| |
| draw.text(word_position, word, font=font, fill=text_color) |
| draw.text(phonetic_position, phonetic, font=font, fill=text_color) |
|
|
| |
| slide_images.append(img) |
|
|
| |
| clips = [] |
| for i, img in enumerate(slide_images): |
| img_path = f"slide_{i}.png" |
| img.save(img_path) |
| |
| clip = ImageClip(img_path).set_duration(3) |
| clips.append(clip) |
|
|
| |
| video = concatenate_videoclips(clips, method="compose") |
| video_path = "output_video.mp4" |
| video.write_videofile(video_path, fps=24) |
|
|
| |
| return video_path |
|
|
| |
| def process_input(input_text): |
| |
| word_list = [] |
| lines = input_text.strip().split("\n") |
| for line in lines: |
| if line.strip(): |
| word, phonetic = line.split(",") |
| word_list.append((word.strip(), phonetic.strip())) |
|
|
| |
| return create_video(word_list) |
|
|
| |
| description = "Nhập danh sách từ và phiên âm, mỗi dòng gồm từ và phiên âm cách nhau bằng dấu phẩy. Ví dụ: Atmosphere, [ˈætməsfɪə]" |
| with gr.Blocks() as demo: |
| gr.Markdown("# Tạo Video từ Danh Sách Từ") |
| gr.Markdown(description) |
| input_text = gr.Textbox(label="Danh sách từ", placeholder="Ví dụ:\nAtmosphere, [ˈætməsfɪə]\nBoard, [bɔːd]...") |
| video_output = gr.Video(label="Video đầu ra") |
| generate_button = gr.Button("Tạo video") |
| |
| generate_button.click(fn=process_input, inputs=input_text, outputs=video_output) |
|
|
| |
| demo.launch() |