Skip to content

Commit

Permalink
Fix: #660
Browse files Browse the repository at this point in the history
  • Loading branch information
jianchang512 committed Dec 11, 2024
1 parent 4ec46d8 commit 2be1e34
Show file tree
Hide file tree
Showing 7 changed files with 170 additions and 10 deletions.
156 changes: 156 additions & 0 deletions hook-sptest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
"""
pyVideoTrans: Translate the video from one language to another and add dubbing
Home-page: https://github.com/jianchang512/pyvideotrans
Author: jianchang512@gmail.com
Documents: https://pyvideotrans.com
License: GPL-V3
# 代码是一坨屎,但又不是不能跑O(∩_∩)O~
# 代码越写越是坨屎,好烦
"""
try:
import pyi_splash

# Update the text on the splash screen
pyi_splash.update_text("pyVideoTrans!")

except:
pass
# Close the splash screen. It does not matter when the call
# to this function is made, the splash screen remains open until
# this function is called or the Python program is terminated.


import multiprocessing
import sys, os
import time

from PySide6 import QtWidgets
from PySide6.QtCore import Qt, QTimer, QPoint, QSettings, QSize
from PySide6.QtGui import QPixmap, QIcon, QGuiApplication

from videotrans import VERSION

os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"

'''
class StartWindow(QtWidgets.QWidget):
def __init__(self):
super(StartWindow, self).__init__()
self.width = 1200
self.height = 700
self.resize(560, 350)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
self.label = QtWidgets.QLabel(self)
self.pixmap = QPixmap("./videotrans/styles/logo.png")
self.label.setPixmap(self.pixmap)
self.label.setScaledContents(True)
self.label.setAlignment(Qt.AlignCenter)
self.label.setGeometry(self.rect()) #直接设置几何形状覆盖
self.setWindowIcon(QIcon("./videotrans/styles/icon.ico"))
v1 = QtWidgets.QVBoxLayout()
v1.addStretch(1)
h1 = QtWidgets.QHBoxLayout()
v1.addLayout(h1)
v1.addStretch(0)
h1.addStretch(1)
self.lab = QtWidgets.QLabel()
self.lab.setStyleSheet("""font-size:16px;color:#fff;text-align:center;background-color:transparent""")
self.lab.setText(f"pyVideoTrans {VERSION} Loading...")
h1.addWidget(self.lab)
h1.addStretch(0)
self.setLayout(v1)
self.show()
self.center()
QTimer.singleShot(100, self.run)
def run(self):
# 创建并显示窗口B
print(time.time())
import videotrans.ui.dark.darkstyle_rc
with open('./videotrans/styles/style.qss', 'r', encoding='utf-8') as f:
app.setStyleSheet(f.read())
from videotrans.configure import config
try:
from videotrans.mainwin._main_win import MainWindow
sets=QSettings("pyvideotrans", "settings")
w,h=int(self.width*0.85), int(self.height*0.85)
size = sets.value("windowSize", QSize(w,h))
try:
w=size.width()
h=size.height()
except:
pass
config.MAINWIN=MainWindow(width=w, height=h)
config.MAINWIN.move(QPoint(int((self.width - w) / 2), int((self.height - h) / 2)))
except Exception as e:
import traceback
from PySide6.QtWidgets import QMessageBox
msg=traceback.format_exc()
if msg.find('torch._C')>0:
QtWidgets.QMessageBox.critical(startwin,"Error",'因底层torch升级,请重新下载完整包' if config.defaulelang=='zh' else 'Please download the full package again')
else:
QtWidgets.QMessageBox.critical(startwin,"Error",msg)
finally:
try:
import pyi_splash
pyi_splash.close()
except:
pass
print(time.time())
QTimer.singleShot(500, lambda :self.close())
def center(self):
screen = QGuiApplication.primaryScreen()
screen_resolution = screen.geometry()
self.width, self.height = screen_resolution.width(), screen_resolution.height()
self.move(QPoint(int((self.width - 560) / 2), int((self.height - 350) / 2)))
'''
if __name__ == "__main__":
multiprocessing.freeze_support() # Windows 上需要这个来避免子进程的递归执行问题
try:
QtWidgets.QApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
except:
pass

app = QtWidgets.QApplication(sys.argv)
startwin = None
try:
#startwin = StartWindow()

from videotrans.mainwin._main_win import MainWindow
sets=QSettings("pyvideotrans", "settings")
screen = QGuiApplication.primaryScreen()
screen_resolution = screen.geometry()
width, height = screen_resolution.width(), screen_resolution.height()
w,h=int(width*0.85), int(height*0.85)
size = sets.value("windowSize", QSize(w,h))
try:
w=size.width()
h=size.height()
except:
pass
from videotrans.configure import config
config.MAINWIN=MainWindow(width=w, height=h)
config.MAINWIN.move(QPoint(int((width - w) / 2), int((height - h) / 2)))
try:
import pyi_splash
pyi_splash.close()
except:
pass
except Exception as e:
import traceback
msg=traceback.format_exc()
QtWidgets.QMessageBox.critical(None,"Error",msg)
sys.exit(app.exec())
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 = "v3.33"
VERSION_NUM = 120333
VERSION = "v3.34"
VERSION_NUM = 120334
2 changes: 1 addition & 1 deletion videotrans/configure/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ def parse_init():
"cuda_qp": False,
"cuda_decode":False,

"videoslow_hard":False,
"videoslow_hard":True,

"preset": "fast",
"ffmpeg_cmd": "",
Expand Down
1 change: 1 addition & 0 deletions videotrans/mainwin/_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,7 @@ def check_start(self):
return

if self.cfg['target_language'] == '-' and self.cfg['subtitle_type'] > 0:
self.main.startbtn.setDisabled(False)
return QMessageBox.critical(self.main, config.transobj['anerror'],
'必须选择目标语言才可嵌入字幕' if config.defaulelang == 'zh' else 'Target language must be selected to embed subtitles')
# 核对是否存在名字相同后缀不同的文件,以及若存在音频则强制为tiqu模式
Expand Down
5 changes: 3 additions & 2 deletions videotrans/recognition/_funasr.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def _exec(self)->Union[List[Dict], None]:
if self.inst and self.inst.status_text:
self.inst.status_text=msg
res = model.generate(input=self.audio_file, return_raw_text=True, is_final=True,
sentence_timestamp=True, batch_size_s=100)
sentence_timestamp=True, batch_size_s=100,disable_pbar=True)
raw_subtitles = []

for it in res[0]['sentence_info']:
Expand Down Expand Up @@ -138,7 +138,8 @@ def _exec1(self) -> Union[List[Dict], None]:
res = model.generate(
input=filename,
language=self.detect_language[:2], # "zh", "en", "yue", "ja", "ko", "nospeech"
use_itn=True
use_itn=True,
disable_pbar=True
)
text = self.remove_unwanted_characters(rich_transcription_postprocess(res[0]["text"]))
srt={
Expand Down
4 changes: 2 additions & 2 deletions videotrans/task/_rate.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ def _ajust_audio(self):
if total_files<1:
return
results = []
with concurrent.futures.ProcessPoolExecutor(max_workers=min(os.cpu_count(),total_files) ) as executor:
with concurrent.futures.ProcessPoolExecutor(max_workers=min(2,total_files) ) as executor:
futures = [executor.submit(process_audio, item.copy()) for item in should_speed]
for i, future in enumerate(concurrent.futures.as_completed(futures)):
filename, success, error_message = future.result()
Expand Down Expand Up @@ -477,7 +477,7 @@ def _ajust_video(self):


config.logger.info(should_speed)
worker_nums=max(min(int(os.cpu_count()/2),total_files),1)
worker_nums=1#min(1,total_files)
with concurrent.futures.ProcessPoolExecutor(max_workers=worker_nums ) as executor:
futures = [executor.submit(process_video, item.copy(),config.settings.get('video_codec',264),config.settings.get('crf',1),config.settings.get('preset','slow'),config.settings.get('videoslow_hard',False)) for item in should_speed]
for i, future in enumerate(concurrent.futures.as_completed(futures)):
Expand Down
8 changes: 5 additions & 3 deletions videotrans/util/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1645,17 +1645,19 @@ def set_ass_font(srtfile=None):
return os.path.basename(srtfile)
runffmpeg(['-y', '-i', srtfile, f'{srtfile}.ass'])
assfile = f'{srtfile}.ass'
#import shutil
#shutil.copy2(assfile,assfile+"-test2.ass")
with open(assfile, 'r', encoding='utf-8') as f:
ass_str = f.readlines()

for i, it in enumerate(ass_str):
if it.find('Style: ') == 0:
ass_str[
i] = 'Style: Default,{fontname},{fontsize},{fontcolor},&HFFFFFF,{fontbordercolor},&H0,0,0,0,0,100,100,0,0,1,1,0,2,10,10,{subtitle_bottom},1'.format(
ass_str[i] = 'Style: Default,{fontname},{fontsize},{fontcolor},&HFFFFFF,{fontbordercolor},&H0,0,0,0,0,100,100,0,0,1,1,0,2,10,10,{subtitle_bottom},1'.format(
fontname=config.settings['fontname'], fontsize=config.settings['fontsize'],
fontcolor=config.settings['fontcolor'], fontbordercolor=config.settings['fontbordercolor'],
subtitle_bottom=config.settings['subtitle_bottom'])
break
elif it.find('Dialogue: ')==0:
ass_str[i]=it.replace(' ','\\N')

with open(assfile, 'w', encoding='utf-8') as f:
f.write("".join(ass_str))
Expand Down

0 comments on commit 2be1e34

Please sign in to comment.