File size: 5,060 Bytes
05aeae1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import argparse
import re
import tempfile

FRAME_RATE = 30

def natural_sort_key(s):
    """Key function for natural sorting (handles numbers in strings correctly)."""
    return [int(text) if text.isdigit() else text.lower()
            for text in re.split(r'(\d+)', s)]


def add_audio_to_face_renders(input_path, wav_path, output_path):
    is_meta_render_dir = all(os.path.isdir(os.path.join(input_path, f)) for f in os.listdir(input_path))
    if is_meta_render_dir:
        input_dirs = [os.path.join(input_path, f) for f in sorted(os.listdir(input_path))]
    else:
        input_dirs = [input_path]

    for dir_path in input_dirs:
        audio_file_path = os.path.join(wav_path, os.path.basename(dir_path) + '.wav')
        output_file_path = os.path.join(output_path, os.path.basename(dir_path) + '.mp4')

        # Find and sort PNG files
        png_files = [f for f in os.listdir(dir_path) if f.lower().endswith('.png')]
        if not png_files:
            print(f"No PNG files found in {dir_path}. Skipping.")
            continue
        png_files.sort(key=natural_sort_key)

        # Create temporary file list for ffmpeg concat demuxer
        list_file_content = ""
        for png_file in png_files:
            abs_path = os.path.abspath(os.path.join(dir_path, png_file)).replace('\\', '/')
            list_file_content += f"file '{abs_path}'\n"
            list_file_content += f"duration {1/FRAME_RATE}\n"

        with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False, encoding='utf-8') as tf:
            tf.write(list_file_content)
            temp_list_file = tf.name

        temp_list_file_escaped = temp_list_file.replace('\\', '/')

        print(f"Processing: {dir_path}")
        os.system(f'ffmpeg -f concat -safe 0 -i "{temp_list_file_escaped}" '
                  f'-i "{audio_file_path}" '
                  f'-c:v libx264 -pix_fmt yuv420p -r {FRAME_RATE} '
                  f'-c:a aac -shortest '
                  f'-y "{output_file_path}"')

        os.remove(temp_list_file)


def find_audio_files(wav_path, date, scenario):
    audio_files = []
    for file in os.listdir(os.path.join(wav_path)):
        if not file.endswith('.wav'):
            continue
        parts = file.split('_')
        if parts[0] == date and parts[2].split('.')[0] == scenario:
            audio_files.append(os.path.join(wav_path, file))
    assert len(audio_files) == 2
    return audio_files


def add_audio_to_body_renders(input_path, wav_path, output_path):
    input_files = []
    if os.path.isdir(input_path):
        input_files = [os.path.join(input_path, f) for f in sorted(os.listdir(input_path)) if f.endswith('.mkv')]
    else:
        input_files = [input_path]
    
    for file_path in input_files:
        filename = os.path.basename(file_path)
        date, scenario = filename.split('.')[0].split('_')
        audio_file_paths = find_audio_files(wav_path, date, scenario)
        output_file_path = os.path.join(output_path, filename.replace('.mkv', '.mp4'))
        
        print('Processing:', file_path)
        os.system(f"ffmpeg -i {file_path} \

            -i {audio_file_paths[0]} \

            -i {audio_file_paths[1]} \

            -filter_complex \"[1:a][2:a]amix=inputs=2:duration=longest[aout]\" \

            -map 0:v \

            -map \"[aout]\" \

            -c:v copy \

            -c:a aac \

            {output_file_path}")


if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('--input_type', '-it', type=str, default='face', help='Type of input to process: face or body')
    parser.add_argument('--input_face', '-if', type=str, default=os.path.join('..', 'face_renders_noaudio'), help='Path to single-instance face render folder or multi-instance folder without audio')
    parser.add_argument('--output_face', '-of', type=str, default=os.path.join('..', 'face_renders_withaudio'), help='Folder path to store output face render folder with audio')
    parser.add_argument('--input_body', '-ib', type=str, default=os.path.join('..', 'body_renders_noaudio'), help='Path to single-instance body render folder or multi-instance folder without audio')
    parser.add_argument('--output_body', '-ob', type=str, default=os.path.join('..', 'body_renders_withaudio'), help='Folder path to store output body render folder with audio')
    parser.add_argument('--wav_path', '-w', type=str, default=os.path.join('..', 'wav'), help='Path to folder containing wav files')
    args = parser.parse_args()

    if args.input_type == 'face':
        os.makedirs(args.output_face, exist_ok=True)
        add_audio_to_face_renders(args.input_face, args.wav_path, args.output_face)
    elif args.input_type == 'body':
        os.makedirs(args.output_body, exist_ok=True)
        add_audio_to_body_renders(args.input_body, args.wav_path, args.output_body)
    else:
        raise ValueError("Invalid input type. Choose 'face' or 'body'.")