Skip to content

Commit

Permalink
fix: bugs and update
Browse files Browse the repository at this point in the history
  • Loading branch information
jianchang512 committed May 27, 2024
1 parent 9c04192 commit eb54aaa
Show file tree
Hide file tree
Showing 7 changed files with 90 additions and 71 deletions.
4 changes: 2 additions & 2 deletions videotrans/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# -*- coding: utf-8 -*-

VERSION="v1.79"
VERSION_NUM=110709
VERSION="v1.80"
VERSION_NUM=110780
16 changes: 15 additions & 1 deletion videotrans/task/main_worker.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
import copy
import os
import shutil
import time
from PySide6.QtCore import QThread
Expand Down Expand Up @@ -186,7 +187,17 @@ def run(self) -> None:
self.tasklist = {}
config.queue_mp4 = []
set_process("", 'end')

self._unlink_tmp()


def _unlink_tmp(self):
if not os.path.isdir(config.TEMP_DIR):
return
for it in os.listdir(config.TEMP_DIR):
if os.path.isfile(config.TEMP_DIR+f"/{it}"):
Path(config.TEMP_DIR+f"/{it}").unlink(missing_ok=True)
else:
shutil.rmtree(config.TEMP_DIR+f"/{it}", ignore_errors=True)

def wait_end(self):
#开始等待任务执行完毕
Expand Down Expand Up @@ -215,9 +226,12 @@ def wait_end(self):
self.tasklist = {}
config.queue_mp4 = []
set_process("", 'end')

self._unlink_tmp()

def stop(self):
set_process("", 'stop')
self.tasklist = {}
config.queue_mp4=[]
self._unlink_tmp()

110 changes: 58 additions & 52 deletions videotrans/task/step.py
Original file line number Diff line number Diff line change
Expand Up @@ -841,31 +841,10 @@ def _separate(self):
def _compos_video(self):
if self.config_params['app_mode'] in ['tiqu', 'peiyin']:
return True

# 判断novoice_mp4是否完成
if not tools.is_novoice_mp4(self.init['novoice_mp4'], self.init['noextname']):
raise Exception(config.transobj['fenlinoviceerror'])

# 需要字幕
if self.config_params['subtitle_type'] > 0 and not tools.vail_file(self.init['target_sub']):
raise Exception(f"{config.transobj['No subtitles file']}: {self.init['target_sub']}")

if self.precent < 90:
self.precent = 90
# 存放目标字幕
target_sub_list = []
# 存放原始字幕
source_sub_list = []
if self.config_params['subtitle_type'] > 0:
try:
target_sub_list = tools.get_subtitle_from_srt(self.init['target_sub'])
except Exception as e:
raise Exception(f'{config.transobj["Subtitles error"]}-1 :{str(e)}')
if self.config_params['subtitle_type'] in [3, 4] and tools.vail_file(self.init['source_sub']):
try:
source_sub_list = tools.get_subtitle_from_srt(self.init['source_sub'])
except Exception as e:
raise Exception(f'{config.transobj["Subtitles error"]}-1 :{str(e)}')

# 无声音视频 或 合并模式时原视频
novoice_mp4_path = Path(self.init['novoice_mp4'])
novoice_mp4 = Path(self.init['novoice_mp4']).as_posix()
Expand All @@ -879,40 +858,69 @@ def _compos_video(self):
hard_srt = "tmp.srt"
hard_srt_path = Path(mp4_dirpath / hard_srt)

vh = ""
try:
remain_h = 20
if config.settings['subtitle_bottom'] and config.settings['subtitle_bottom'] > (
self.init['video_info']['height'] - remain_h):
vh = f",MarginV={self.init['video_info']['height'] - remain_h}"
elif config.settings['subtitle_bottom'] and config.settings['subtitle_bottom'] > 0:
vh = f",MarginV={vh}"
except Exception:
pass
maxlen = config.settings['cjk_len'] if self.init['target_language_code'][:2] in ["zh", "ja", "jp",
"ko"] else \
config.settings['other_len']
maxlen_source = config.settings['cjk_len'] if self.init['source_language_code'][:2] in ["zh", "ja", "jp",
"ko"] else \
config.settings['other_len']
# 需要字幕
if self.config_params['subtitle_type'] > 0:
# 存放目标字幕
target_sub_list = []
# 存放原始字幕
source_sub_list = []
vh = ""
try:
remain_h = 20
if config.settings['subtitle_bottom'] and config.settings['subtitle_bottom'] > (
self.init['video_info']['height'] - remain_h):
vh = f",MarginV={self.init['video_info']['height'] - remain_h}"
elif config.settings['subtitle_bottom'] and config.settings['subtitle_bottom'] > 0:
vh = f",MarginV={vh}"
except Exception:
pass
maxlen_source = config.settings['cjk_len'] if self.init['source_language_code'][:2] in ["zh", "ja", "jp","ko"] else config.settings['other_len']
if tools.vail_file(self.init['source_sub']):
try:
source_sub_list = tools.get_subtitle_from_srt(self.init['source_sub'])
except Exception as e:
raise Exception(f'{config.transobj["Subtitles error"]}-1 :{str(e)}')
#如果未设置目标语言,仅存在原始语言
if not self.init['target_language_code']:
if self.config_params['subtitle_type']==3:
self.config_params['subtitle_type']=1
elif self.config_params['subtitle_type']==4:
self.config_params['subtitle_type']=2
# 软字幕使用原始语言字幕
soft_srt = Path(self.init['source_sub']).as_posix()
# 硬字幕均为原始字幕
if self.config_params['subtitle_type'] ==1:
text = ""
for i, it in enumerate(source_sub_list):
it['text'] = textwrap.fill(it['text'], maxlen_source,replace_whitespace=False).replace('\n', '\\N')
text += f"{it['line']}\n{it['time']}\n{it['text'].strip()}\n\n"
hard_srt_path.write_text(text, encoding='utf-8', errors="ignore")
os.chdir(mp4_dirpath)
hard_srt = tools.set_ass_font(hard_srt_path.as_posix())
else:
#存在目标语言
maxlen = config.settings['cjk_len'] if self.init['target_language_code'][:2] in ["zh", "ja", "jp","ko"] else config.settings['other_len']
try:
target_sub_list = tools.get_subtitle_from_srt(self.init['target_sub'])
# 提前处理单硬字幕
if self.config_params['subtitle_type'] in [1, 3]:
text = ""
for i, it in enumerate(target_sub_list):
it['text'] = textwrap.fill(it['text'], maxlen, replace_whitespace=False).replace('\n', '\\N')
text += f"{it['line']}\n{it['time']}\n{it['text'].strip()}\n\n"
hard_srt_path.write_text(text, encoding='utf-8', errors="ignore")
os.chdir(mp4_dirpath)
hard_srt = tools.set_ass_font(hard_srt_path.as_posix())
except Exception as e:
raise Exception(f'{config.transobj["Subtitles error"]}-1 :{str(e)}')


if self.precent < 90:
self.precent = 90

# 提前处理单硬字幕
if self.config_params['subtitle_type'] in [1, 3]:
text = ""
for i, it in enumerate(target_sub_list):
it['text'] = textwrap.fill(it['text'], maxlen, replace_whitespace=False).replace('\n', '\\N')
text += f"{it['line']}\n{it['time']}\n{it['text'].strip()}\n\n"
hard_srt_path.write_text(text, encoding='utf-8', errors="ignore")
os.chdir(mp4_dirpath)
hard_srt = tools.set_ass_font(hard_srt_path.as_posix())

# 如果是合并字幕模式 双字幕强制为单
if self.config_params['app_mode'] == 'hebing':
if self.config_params['subtitle_type'] in [1, 3]:

tools.runffmpeg([
"-y",
"-i",
Expand Down Expand Up @@ -956,7 +964,7 @@ def _compos_video(self):
raise Exception(f"{config.transobj['Dubbing']}{config.transobj['anerror']}:{self.init['target_wav']}")

# 需要双字幕
if self.init['source_language_code'] != self.init['target_language_code'] and len(source_sub_list) > 0:
if len(target_sub_list)>0 and len(source_sub_list) > 0:
# 处理双硬字幕
if self.config_params['subtitle_type'] == 3:
text = ""
Expand All @@ -973,8 +981,6 @@ def _compos_video(self):
shutil.copy2(hard_srt_path.as_posix(), f"{self.obj['output']}/shuang.srt")
hard_srt = tools.set_ass_font(hard_srt_path.as_posix())



# 双字幕 软字幕
elif self.config_params['subtitle_type'] == 4:
text = ""
Expand Down
20 changes: 11 additions & 9 deletions videotrans/task/trans_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,8 @@ def __init__(self, config_params: dict = None, obj=None):
var_c = var_a if var_a is not None else var_b
self.init['target_language_code'] = var_c if var_c != '-' else '-'
else:
self.init['target_language_code'] = self.init['source_language_code'] = '-'
self.init['target_language_code']=None
self.init['source_language_code'] = '-'

# 检测字幕原始语言
if self.config_params['source_language'] != '-':
Expand Down Expand Up @@ -202,8 +203,9 @@ def __init__(self, config_params: dict = None, obj=None):
# 如果存在字幕,则视为目标字幕,直接生成,不再识别和翻译
if "subtitles" in self.config_params and self.config_params['subtitles'].strip():
sub_file = self.init['target_sub']
if self.config_params['source_language'] != self.config_params['target_language'] and self.config_params[
'source_language'] != '-' and self.config_params['target_language'] != '-':
if self.config_params['app_mode']=='hebing':
sub_file=self.init['source_sub']
elif self.init['source_language_code'] and self.init['target_language_code'] and self.init['source_language_code'] != self.init['target_language_code']:
# 原始和目标语言都存在,并且不相等,需要翻译,作为待翻译字幕
sub_file = self.init['source_sub']
with open(sub_file, 'w', encoding="utf-8", errors="ignore") as f:
Expand Down Expand Up @@ -433,7 +435,7 @@ def move_at_end(self):
if int(self.config_params['subtitle_type']) not in [2, 4]:
try:
self.obj['output'] = outputpath.parent.resolve().as_posix()
wait_deldir = outputpath.resolve().as_posix()
#wait_deldir = outputpath.resolve().as_posix()
except Exception:
pass

Expand All @@ -449,9 +451,9 @@ def move_at_end(self):
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)
#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
7 changes: 2 additions & 5 deletions videotrans/translator/freegoogle.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@

urls=[
"https://g0.pyvideotrans.com",
"https://g1.pyvideotrans.com",
"https://g2.pyvideotrans.com",
"https://g3.pyvideotrans.com",
"https://g4.pyvideotrans.com"
"https://g1.pyvideotrans.com"
]

shound_del=False
Expand Down Expand Up @@ -58,7 +55,7 @@ def trans(text_list, target_language="en", *, set_p=True,inst=None,stop=0,source
if config.exit_soft or (config.current_status!='ing' and config.box_trans!='ing'):
return
if iter_num >= config.settings['retries']:
err=f'{iter_num}{"次重试后依然出错" if config.defaulelang == "zh" else " retries after error persists "}:{err}'
err=f'{iter_num}{"次重试后依然出错,请尝试填写网络代理或更换其他翻译渠道" if config.defaulelang == "zh" else " retries after error persists "}:{err}'
break

iter_num += 1
Expand Down
2 changes: 1 addition & 1 deletion videotrans/ui/transapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def retranslateUi(self, transapiform):
}
Usage: github.com/jianchang512/translate-api
"""
transapiform.setWindowTitle("自定义翻译API" if config.defaulelang=='zh' else "Customizing the Translate API")
transapiform.setWindowTitle("自定义翻译API/无编码能力勿使用该功能" if config.defaulelang=='zh' else "Customizing the Translate API")
self.label_3.setText("密钥" if config.defaulelang=='zh' else "Secret")
self.miyue.setPlaceholderText("填写密钥")

Expand Down
2 changes: 1 addition & 1 deletion videotrans/ui/ttsapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def retranslateUi(self, ttsapiform):
data:On successful synthesis, return the full url of the mp3 file for downloading within the software. When it fails, the url will be empty.
}
"""
ttsapiform.setWindowTitle("自定义TTS-API" if config.defaulelang=='zh' else "Customizing the TTS-API")
ttsapiform.setWindowTitle("自定义TTS-API/无编码能力勿使用该功能" if config.defaulelang=='zh' else "Customizing the TTS-API")
self.label_3.setText("额外参数" if config.defaulelang=='zh' else "additional parameter")
self.tips.setPlainText(tips)
self.tips.setPlaceholderText("")
Expand Down

0 comments on commit eb54aaa

Please sign in to comment.