Ejemplo n.º 1
0
	def suffixStyleNaming(input_file: Path, style_suffix: str):
		print(F"adding suffix '{style_suffix}' to styles in: {input_file.name}")
		output_tmp = input_file.append_stem("_tmp")
		new_file = []

		with input_file.open('r', encoding='utf-8-sig') as f:
			for line in f:
				line = line.strip()
				m = DIALOGUE_RE.search(line)
				if ASS_STYLE_RE.match(line):
					styleDict = mkvstuff.style_to_dict(line)
					styleDict["name"] = styleDict["name"] + "_" + style_suffix
					new_file.append(mkvstuff.dict_to_style(styleDict))
				elif m:
					gd = m.groupdict()
					newLine = gd["part1"] + gd["style_name"] + "_" + style_suffix + gd["part2"]
					new_file.append(newLine)
				elif "Dialogue:" in line or "Comment:" in line:
					print("Failed to rx parse: \n " + line)
					print("The subfile is probably f****d, lack of proper QA in fansubs..")
					exit(1)
				else:
					new_file.append(line)

		with output_tmp.open('w', encoding='utf-8-sig') as nf:
			nf.write("\n".join(new_file))
		input_file.unlink()
		output_tmp.move(input_file)
		return input_file
Ejemplo n.º 2
0
	def replaceAssStylesWithList(input_file: Path, style_list: dict):
		print(F"replacing styles in: {input_file.name}")
		output_tmp = input_file.append_stem("_tmp")
		new_file = []
		with input_file.open('r', encoding='utf-8-sig') as f:
			for line in f:
				line = line.strip()
				if re.match(r'^Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding$', line):
					new_file.append(line)
					for styleName, styleDict in style_list.items():
						new_file.append(mkvstuff.dict_to_style(styleDict))
				elif not ASS_STYLE_RE.match(line):
					new_file.append(line)

		with output_tmp.open('w', encoding='utf-8-sig') as nf:
			nf.write("\n".join(new_file))
		input_file.unlink()
		output_tmp.move(input_file)
		return input_file
Ejemplo n.º 3
0
    def buildMkvFromSegments(self,
                             segmentList,
                             output_file: Path,
                             tmpDir: Path,
                             chapter=None):
        concat_file = Path("concat.txt")
        font_dir = tmpDir.joinpath("fonts")
        font_dir.mkdir(exist_ok=True)
        style_list = {}
        for i in sorted(segmentList.keys()):
            seg = segmentList[i]
            if 'file_path' not in seg:
                continue

            mkvstuff.ext_all_fonts_to_dir(seg['file_path'], font_dir)
            sub_file = mkvstuff.extract_first_subtitle(seg['file_path'],
                                                       tmpDir)

            sub_file = mkvstuff.suffixStyleNaming(
                sub_file, F"partid_{i}")  # silly double up

            for styleStr in mkvstuff.getStylesFromAssFile(sub_file):
                styleDict = mkvstuff.style_to_dict(styleStr)
                style_list[styleDict["name"]] = styleDict

            sub_file.unlink()

        for i in sorted(segmentList.keys()):
            seg = segmentList[i]
            if 'file_path' not in seg:
                continue
            _fixed_sub = mkvstuff.extract_first_subtitle(
                seg["file_path"], tmpDir)
            _fixed_sub = mkvstuff.suffixStyleNaming(
                _fixed_sub, F"partid_{i}"
            )  # silly double up, but too lazy to save in memory
            _fixed_sub = mkvstuff.replaceAssStylesWithList(
                _fixed_sub, style_list)
            _fixed_sub_mkv = mkvstuff.replaceSubFileWith(
                seg["file_path"], _fixed_sub, tmpDir)
            segmentList[i]["file_path"] = _fixed_sub_mkv

        with concat_file.open("w", encoding="utf-8") as f:
            for i in sorted(segmentList.keys()):
                seg = segmentList[i]
                if 'file_path' not in seg:
                    continue
                f.write(F"file '{seg['file_path']}'\n")

        _fixed_sub.unlink()

        output_file_tmp = output_file.append_stem('_tmp')

        cmd = [
            'ffmpeg',
            '-y',
            '-f',
            'concat',
            '-safe',
            '0',
            '-i',
            F'{concat_file}',
        ]

        if self.args.re_encode:
            cmd.append('-map')
            cmd.append('0')
            cmd.append('-g')
            cmd.append('1')
            cmd.append('-pix_fmt')
            cmd.append('yuv420p')
            cmd.append('-c:v')
            cmd.append('h264_nvenc')
            cmd.append('-c:a')
            cmd.append('pcm_s16le')
            cmd.append('-b:v')
            cmd.append('2M')
            cmd.append('-s')
            cmd.append('1280x720')
        else:
            cmd.append('-c')
            cmd.append('copy')
        cmd.append(F'{output_file_tmp}')

        fonts_list = mkvstuff.build_font_list(font_dir)

        print(
            F"Merging into{' (with re-encode)' if self.args.re_encode else ''}: {output_file_tmp}"
        )
        common.run_process(cmd, silent=True)
        concat_file.unlink()

        output_file = output_file.parent.joinpath(
            common.strip_crc(output_file.stem) + output_file.suffix)

        print(F"Merging (with chapter & fonts) into: {output_file}")
        cmd = [
            "mkvmerge",
            "--ui-language",
            "en",
            "--output",
            F"{output_file}",
            "(",
            F"{output_file_tmp}",
            ")",
        ]
        if chapter:
            cmd.extend([
                "--chapter-language",
                "eng",
                "--chapters",
                F"{chapter}",
            ])
        for font in fonts_list:
            cmd.extend([
                "--attachment-name", F"{font.name}", "--attachment-mime-type",
                F"{font.mime}", "--attach-file", F"{font.resolve()}"
            ])
        common.run_process(cmd, silent=True)
        output_file_tmp.unlink()
        print("\rCalculating and appending CRC-Sum...", end='')
        csum = common.crc32f(output_file)
        output_file.move(output_file.append_stem(F' [{csum}]'))
        print(F"\rCalculating and appending CRC-Sum, OK: {csum}")