File size: 4,994 Bytes
79fcc3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
529f7b8
 
79fcc3e
918b324
79fcc3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd54f1d
79fcc3e
 
 
 
 
 
 
 
529f7b8
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
from argparse import ArgumentParser
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.generation import GenerationConfig
import os
import asyncio
import edge_tts
import sys
import configparser
import subprocess

# 获取当前脚本所在的目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 获取当前目录的上一级目录
parent_dir = os.path.dirname(current_dir)
# 定义默认的检查点路径
DEFAULT_CKPT_PATH = os.path.join(parent_dir, 'InsightCompanion/INFJ')

# 创建wav_output文件夹路径
wav_output_dir = os.path.join(parent_dir, 'InsightCompanion/wav_output')
if not os.path.exists(wav_output_dir):
    os.makedirs(wav_output_dir)

# TTS参数
VOICE = "zh-CN-YunyangNeural"
RATE = "-1%"  # 降低语速
VOLUME = "-10%"  # 降低音量10%
OUTPUT_FILE = os.path.join(wav_output_dir, "input_audio.wav")  # 音频文件名

def _get_args():
    parser = ArgumentParser()
    parser.add_argument("-c", "--checkpoint-path", type=str, default=DEFAULT_CKPT_PATH,
                        help="检查点名称或路径,默认为 %(default)r")
    parser.add_argument("--cpu-only", action="store_true", help="仅使用 CPU 运行演示")
    args = parser.parse_args()
    return args

def _load_model_tokenizer(args):
    tokenizer = AutoTokenizer.from_pretrained(
        args.checkpoint_path, trust_remote_code=True, resume_download=False,
    )

    device_map = "cpu" if args.cpu_only else "auto"

    model = AutoModelForCausalLM.from_pretrained(
        args.checkpoint_path,
        device_map=device_map,
        trust_remote_code=True,
        resume_download=False,
    ).eval()

    config = GenerationConfig.from_pretrained(
        args.checkpoint_path, trust_remote_code=True, resume_download=False,
    )

    return model, tokenizer, config

async def _generate_audio(text, output_path):
    communicate = edge_tts.Communicate(
        text=text,
        voice=VOICE,
        rate=RATE,
        volume=VOLUME
    )
    await communicate.save(output_path)
    return output_path

def _chat(model, tokenizer, config):
    history = []
    while True:
        query = input("你: ")
        if query.lower() in ["exit", "quit", "q"]:
            print("结束对话。")
            break
        
        # 生成完整的回复内容
        response = ""
        for part in model.chat_stream(tokenizer, query, history=history, generation_config=config):
            response = part  # 仅保留最终结果

        print(f"模型: {response}")
        history.append((query, response))

        # 生成音频文件
        asyncio.run(_generate_audio(response, OUTPUT_FILE))
        print(f"生成的音频文件已保存至: {OUTPUT_FILE}")
        
        # 调用视频生成部分
        generate_video(OUTPUT_FILE)

def generate_video(audio_path):
    # 清空temp
    os.system("rm -rf ../Easy-Wav2Lip/temp")
    os.makedirs("../Easy-Wav2Lip/temp")

    video_file = "../InsightCompanion/video_data/input_video.mp4"

    quality = "fast"
    output_height = "full resolution"
    use_previous_tracking_data = True

    wav2lip_version = "Wav2Lip"
    nosmooth = False

    U = 0
    D = 20
    L = 0
    R = 0

    size = 1.5
    feathering = 1
    mouth_tracking = False
    debug_mask = False

    batch_process = False
    output_suffix = "_Easy-Wav2Lip"
    include_settings_in_suffix = False
    preview_input = False
    preview_settings = False
    frame_to_preview = 100

    # 创建 ConfigParser 对象
    config = configparser.ConfigParser()

    # 将所有变量存储在字典中
    options = {
        'video_file': video_file,
        'vocal_file': audio_path,  # 使用生成的音频文件路径
        'quality': quality,
        'output_height': output_height,
        'wav2lip_version': wav2lip_version,
        'use_previous_tracking_data': use_previous_tracking_data,
        'nosmooth': nosmooth
    }
    padding = {
        'U': U,
        'D': D,
        'L': L,
        'R': R
    }
    mask = {
        'size': size,
        'feathering': feathering,
        'mouth_tracking': mouth_tracking,
        'debug_mask': debug_mask
    }
    other = {
        'batch_process': batch_process,
        'output_suffix': output_suffix,
        'include_settings_in_suffix': include_settings_in_suffix,
        'preview_input': preview_input,
        'preview_settings': preview_settings,
        'frame_to_preview': frame_to_preview
    }

    # 将字典添加到 ConfigParser 对象中
    config['OPTIONS'] = options
    config['PADDING'] = padding
    config['MASK'] = mask
    config['OTHER'] = other

    # 将数据写入 INI 配置文件
    with open('config.ini', 'w') as f:
        config.write(f)

    # 运行 Wav2Lip 生成视频
    subprocess.run([sys.executable, 'run.py'], check=True)


def main():
    args = _get_args()
    model, tokenizer, config = _load_model_tokenizer(args)
    _chat(model, tokenizer, config)

if __name__ == '__main__':
    main()