InsightCompanion / ui_run.py
Sheerio's picture
Update ui_run.py
fd54f1d verified
Raw History Blame Contribute Delete
4.99 kB
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()