Skip to content

Commit

Permalink
Merge pull request #391 from DoubleStarK/feature/cli
Browse files Browse the repository at this point in the history
Feature/cli
  • Loading branch information
jianchang512 committed May 11, 2024
2 parents a267cbb + 01ea551 commit ff20b51
Show file tree
Hide file tree
Showing 8 changed files with 129 additions and 42 deletions.
18 changes: 11 additions & 7 deletions cli.ini
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,22 @@ proxy=
;输出结果文件到目录
target_dir=
;视频发音语言,从这里选择 zh-cn zh-tw en fr de ja ko ru es th it pt vi ar tr
source_language=zh-cn
source_language=en
;语音识别语言 无需填写
detect_language=
;翻译到的语言 zh-cn zh-tw en fr de ja ko ru es th it pt vi ar tr
target_language=en
target_language=zh-cn
;软字幕嵌入时的语言,不填写
subtitle_language=
;true=启用CUDA
cuda=false
;角色名称,openaiTTS角色名称“alloy,echo,fable,onyx,nova,shimmer”,edgeTTS角色名称从 voice_list.json 中对应语言的角色中寻找。elevenlabsTTS 的角色名称从 elevenlabs.json 中寻找
voice_role=en-CA-ClaraNeural
; 配音加速值,必须以 + 号或 - 号开头,+代表加速,-代表减速,以%结尾
;角色名称(No代表用原音),openaiTTS角色名称“alloy,echo,fable,onyx,nova,shimmer”,edgeTTS角色名称从 voice_list.json 中对应语言的角色中寻找。elevenlabsTTS 的角色名称从 elevenlabs.json 中寻找
voice_role=No
;背景声音音量降低或升高幅度,大于1升高,小于1降低
volume=+0.5%
;背景声音变调,大于1升高,小于1降低
pitch=+0%
;配音加速值,必须以 + 号或 - 号开头,+代表加速,-代表减速,以%结尾
voice_rate=+0%
;可选 edgetTTS openaiTTS elevenlabsTTS
tts_type=edgeTTS
Expand All @@ -27,8 +31,8 @@ voice_silence=500
is_separate=false
;all=整体识别,split=预先分割声音片段后识别
whisper_type=all
;语音识别模型可选,base small medium large-v3
whisper_model=base
;语音识别模型可选,tiny base small medium large-v3
whisper_model=tiny
model_type=faster
;翻译渠道,可选 google baidu chatGPT Azure Gemini tencent DeepL DeepLX
translate_type=google
Expand Down
128 changes: 100 additions & 28 deletions cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,38 +11,37 @@
import os
import re
import sys
import traceback
from videotrans.box.worker import Worker
from videotrans.configure import config
import argparse
from videotrans.task.trans_create import TransCreate
from videotrans.translator import LANG_CODE, is_allow_translate, BAIDU_NAME, TENCENT_NAME, CHATGPT_NAME, AZUREGPT_NAME, \
GEMINI_NAME, DEEPLX_NAME, DEEPL_NAME
from videotrans.util.tools import set_proxy, get_edge_rolelist, get_elevenlabs_role
from videotrans.util import tools
from videotrans.util.tools import send_notification, set_process, set_proxy, get_edge_rolelist, get_elevenlabs_role
from tqdm import tqdm

parser = argparse.ArgumentParser(description='cli.ini and source mp4')
parser.add_argument('-c', type=str, help='cli.ini file absolute filepath', default=os.path.join(os.getcwd(), 'cli.ini'))
parser.add_argument('-m', type=str, help='mp4 absolute filepath', default="")
parser.add_argument('-cuda', action='store_true', help='Activates the cuda option')
def __init__():
if not os.path.exists(os.path.join(config.rootdir, 'voice_list.json')) or os.path.getsize(
os.path.join(config.rootdir, 'voice_list.json')) == 0:
print("正在获取 edge TTS 角色...")
get_edge_rolelist()
if not os.path.exists(os.path.join(config.rootdir, 'elevenlabs.json')) or os.path.getsize(
os.path.join(config.rootdir, 'elevenlabs.json')) == 0:
print("正在获取 elevenlabs TTS 角色...")
get_elevenlabs_role()


def set_process(text, type="logs"):
print(f'[{type}] {text}\n')


if not os.path.exists(os.path.join(config.rootdir, 'voice_list.json')) or os.path.getsize(
os.path.join(config.rootdir, 'voice_list.json')) == 0:
print("正在获取 edge TTS 角色...")
get_edge_rolelist()
if not os.path.exists(os.path.join(config.rootdir, 'elevenlabs.json')) or os.path.getsize(
os.path.join(config.rootdir, 'elevenlabs.json')) == 0:
print("正在获取 elevenlabs TTS 角色...")
get_elevenlabs_role()

if __name__ == '__main__':
config.exec_mode = 'cli'
config.settings['countdown_sec'] = 0
parser = argparse.ArgumentParser(description='cli.ini and source mp4')
parser.add_argument('-c', type=str, help='cli.ini file absolute filepath', default=os.path.join(os.getcwd(), 'cli.ini'))
parser.add_argument('-m', type=str, help='mp4 absolute filepath', default="")
parser.add_argument('-cuda', action='store_true', help='Activates the cuda option')

args = vars(parser.parse_args())

config.settings['countdown_sec'] = 0
cfg_file = args['c']
if not os.path.exists(cfg_file):
print('不存在配置文件 cli.ini' if config.defaulelang == 'zh' else "cli.ini file not exists")
Expand All @@ -67,10 +66,21 @@ def set_process(text, type="logs"):
config.params['source_language']='-'
if not config.params['target_language']:
config.params['target_language']='-'
if not config.params.get('back_audio'):
config.params['back_audio']='-'
if args['cuda']:
config.params['cuda'] = True
if args['m'] and os.path.exists(args['m']):
config.params['source_mp4'] = args['m']

# 传多个视频的话,考虑支持批量处理
if type(args['m']) == str:
config.params['is_batch'] = False
else:
config.params['is_batch'] = True
print("命令行批量处理暂未支持")
sys.exit()

if not config.params['source_mp4'] or not os.path.exists(config.params['source_mp4']):
print(
"必须在命令行或cli.ini文件设置 source_mp4(视频文件)的绝对路径" if config.defaulelang == 'zh' else "The absolute path of source_mp4 (video file) must be set on the command line or in the cli.ini file.")
Expand All @@ -88,7 +98,7 @@ def set_process(text, type="logs"):
print(config.transobj['anerror'], config.transobj['baikeymust'])
sys.exit()
elif config.params['translate_type'] == TENCENT_NAME:
# 腾讯翻译
# 腾讯翻译
if not config.params["tencent_SecretId"] or not config.params["tencent_SecretKey"]:
print(config.transobj['tencent_key'])
sys.exit()
Expand Down Expand Up @@ -135,11 +145,73 @@ def set_process(text, type="logs"):
config.proxy = config.params['proxy'].strip()
set_proxy(config.proxy)
config.current_status = 'ing'
config.params['app_mode'] = 'cli'
(base, ext) = os.path.splitext(config.params['source_mp4'].replace('\\', '/'))
config.params['target_dir'] = os.path.dirname(base)
obj_format = tools.format_video(config.params['source_mp4'].replace('\\', '/'), config.params['target_dir'])

process_bar_data = [
config.transobj['kaishichuli'],
config.transobj['kaishishibie'],
config.transobj['starttrans'],
config.transobj['kaishipeiyin'],
config.transobj['kaishihebing'],
]

process_bar = tqdm(process_bar_data)
try:
video_task = TransCreate(config.params, obj_format)
try:
process_bar.set_description(process_bar_data[0])
video_task.prepare()
process_bar.update(1)
except Exception as e:
err=f'{config.transobj["yuchulichucuo"]}:' + str(e)
print(err)
sys.exit()
try:
process_bar.set_description(process_bar_data[1])
video_task.recogn()
process_bar.update(1)
except Exception as e:
err=f'{config.transobj["shibiechucuo"]}:' + str(e)
print(err)
sys.exit()
try:
process_bar.set_description(process_bar_data[2])
video_task.trans()
process_bar.update(1)
except Exception as e:
err=f'{config.transobj["fanyichucuo"]}:' + str(e)
print(err)
sys.exit()
try:
process_bar.set_description(process_bar_data[3])
video_task.dubbing()
process_bar.update(1)
except Exception as e:
err=f'{config.transobj["peiyinchucuo"]}:' + str(e)
print(err)
sys.exit()
try:
process_bar.set_description(process_bar_data[4])
video_task.hebing()
process_bar.update(1)
except Exception as e:
err=f'{config.transobj["hebingchucuo"]}:' + str(e)
print(err)
sys.exit()
try:
video_task.move_at_end()
process_bar.update(1)
except Exception as e:
err=f'{config.transobj["hebingchucuo"]}:' + str(e)
print(err)
sys.exit()

# try:
# task = TransCreate({"source_mp4": config.params['source_mp4'], 'app_mode': "biaozhun","mode":"cli"})
# set_process(config.transobj['kaishichuli'])
# res = task.run()
# print(f'{"执行完成" if config.defaulelang == "zh" else "Succeed"} {task.targetdir_mp4}')
# except Exception as e:
# print(f'\nException:{str(e)}\n')
send_notification(config.transobj["zhixingwc"], f'"subtitles -> audio"')
print(f'{"执行完成" if config.defaulelang == "zh" else "Succeed"} {video_task.targetdir_mp4}')
except Exception as e:
send_notification(e, f'{video_task.obj["raw_basename"]}')
# 捕获异常并重新绑定回溯信息
traceback.print_exc()
4 changes: 2 additions & 2 deletions videotrans/configure/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,9 @@ def parse_init():
# 软件界面
uilanglist = obj["ui_lang"]
# 语言代码:语言显示名称
langlist = obj["language_code_list"]
langlist: dict = obj["language_code_list"]
# 语言显示名称:语言代码
rev_langlist = {val: key for key, val in langlist.items()}
rev_langlist = {code_alias: code for code, code_alias in langlist.items()}
# 语言显示名称 list
langnamelist = list(langlist.values())
# 工具箱语言
Expand Down
1 change: 1 addition & 0 deletions videotrans/language/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"shibiechucuo": "Error in speech recognition",
"fanyichucuo": "Error in subtitle translation",
"peiyinchucuo": "Error in dubbing",
"hebingchucuo": "Error in combine",

"freechatgpt_tips": "apiskey.top sponsored ChatGPT, free to use",

Expand Down
1 change: 1 addition & 0 deletions videotrans/language/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"shibiechucuo": "Error in speech recognition",
"fanyichucuo": "Error in subtitle translation",
"peiyinchucuo": "Error in dubbing",
"hebingchucuo": "Error in combine",

"freechatgpt_tips": "apiskey.top sponsored ChatGPT, free to use",

Expand Down
2 changes: 1 addition & 1 deletion videotrans/set.ini
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
;Interface language text #############################
;默认界面跟随系统,也可以在此手动指定,zh=中文界面,en=英文界面
;Default interface follows the system, you can also specify it manually here, zh=Chinese interface, en=English interface.
lang =
lang = en

;##################视频质量############################
;Video quality ############################
Expand Down
15 changes: 12 additions & 3 deletions videotrans/task/trans_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class TransCreate():
'''

def __init__(self, config_params=None, obj=None):
def __init__(self, config_params: dict = None, obj=None):
# 视频原始路径 名称等信息
self.obj = obj
# 配置信息
Expand Down Expand Up @@ -164,8 +164,14 @@ def __init__(self, config_params=None, obj=None):
self.init['target_language_code'] = self.config_params['target_language']
else:
# 仅作为文件名标识
self.init['source_language_code']=config.rev_langlist[self.config_params['source_language']] if self.config_params['source_language'] != '-' else '-'
self.init['target_language_code'] = config.rev_langlist[self.config_params['target_language']] if self.config_params['target_language'] != '-' else '-'
var_a = config.rev_langlist.get(self.config_params['source_language'])
var_b = config.langlist.get(self.config_params['source_language'])
var_c = var_a if var_a is not None else var_b
self.init['source_language_code'] = var_c if var_c != '-' else '-'
var_a = config.rev_langlist.get(self.config_params['target_language'])
var_b = config.langlist.get(self.config_params['target_language'])
var_c = var_a if var_a is not None else var_b
self.init['target_language_code'] = var_c if var_c != '-' else '-'

# 检测字幕原始语言
if self.config_params['source_language'] != '-':
Expand Down Expand Up @@ -248,6 +254,7 @@ def runing():

self._split_wav_novicemp4()
self.step_inst=Runstep(init=self.init,obj=self.obj,config_params=self.config_params,parent=self)
return True

def __getattr__(self, precent):
return self.step_inst.precent if self.step_inst else 0
Expand Down Expand Up @@ -421,9 +428,11 @@ def move_at_end(self):
btnkey=self.init['btnkey']
)
tools.send_notification("Succeed", f"{self.obj['raw_basename']}")

#删除临时文件
shutil.rmtree(self.init['cache_folder'], ignore_errors=True)
if linshi_deldir:
shutil.rmtree(linshi_deldir)
if wait_deldir:
shutil.rmtree(wait_deldir,ignore_errors=True)
return True
2 changes: 1 addition & 1 deletion videotrans/tts/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def text_to_speech(
config.logger.error(f'no filename={filename} {tts_type=} {text=},{role=}')


def run(*, queue_tts=None, language=None,set_p=True,inst=None):
def run(*, queue_tts=None, language=None, set_p=True, inst=None):
queue_tts_copy=copy.deepcopy(queue_tts)
# 需要并行的数量3
n_total = len(queue_tts)
Expand Down

0 comments on commit ff20b51

Please sign in to comment.