Skip to content

Commit

Permalink
feat: Add subtitle conversion functions
Browse files Browse the repository at this point in the history
- Added functions for converting SRT to BCC format
- Added functions for converting VTT to BCC format
- Added functions for converting ASS to BCC format
- Added functions for converting ASS to SRT format
- Added functions for converting SRT to ASS format
- Added functions for converting BCC to SRT format
- Added functions for converting BCC to ASS format

The functions are implemented in the `srt2bcc`, `vtt2bcc`, `ass2bcc`, `ass2srt`, `srt2ass`, `bcc2srt`, and `bcc2ass` modules. These functions provide the capability to convert between different subtitle formats.
  • Loading branch information
sudoskys committed Jan 18, 2024
1 parent 8f2d157 commit 0d65f43
Show file tree
Hide file tree
Showing 8 changed files with 337 additions and 138 deletions.
1 change: 0 additions & 1 deletion src/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,3 @@ pysrt
pyvtt
chardet
pyasstosrt
pydantic
7 changes: 7 additions & 0 deletions src/subtitle_utils/NOTICE.MD
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# NOTICE OF THIS PROJECT

## MIT License

The MIT license applies to the files in:

file: "subtitle_utils/convert/bcc.py" motify from https://github.com/FXTD-ODYSSEY/bilibili-subtile-uploader
115 changes: 115 additions & 0 deletions src/subtitle_utils/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# -*- coding: utf-8 -*-
# @Time : 12/29/22 10:06 PM
# @FileName: convert.py
# @Software: PyCharm
# @Github :sudoskys
import json
from typing import Union, IO, Callable, Any

from .convert.ass import AssConvert
from .convert.bcc import BccConvert

FOOTNOTE = None


def srt2bcc(content: Union[str, IO]
) -> str:
result = BccConvert().srt2bcc(content=content, about=FOOTNOTE)
result = json.dumps(result, ensure_ascii=False, indent=None)
return result


def vtt2bcc(content: Union[str, IO]
) -> str:
result = BccConvert().vtt2bcc(content=content, about=FOOTNOTE)
result = json.dumps(result, ensure_ascii=False, indent=None)
return result


def ass2bcc(content: Union[str, IO]
) -> str:
ass_result = AssConvert().ass2srt(content=content)
result = BccConvert().srt2bcc(content=ass_result, about=FOOTNOTE)
result = json.dumps(result, ensure_ascii=False, indent=None)
return result


def ass2srt(content: Union[str, IO]
) -> str:
"""
:param content:
:return: result
"""
result = AssConvert().ass2srt(content=content)
return result


def srt2ass(content: Union[str, IO],
*,
header: str = None
) -> str:
"""
:param content: srt str| IO
:param header: ass subtitle style
:return:
"""
result = AssConvert().srt2ass(content=content, header=header)
return result


def bcc2srt(content: Union[str, IO],
) -> str:
result = BccConvert().bcc2srt(content=content)
return result


def bcc2ass(content: Union[str, IO]
) -> str:
bcc_result = BccConvert().bcc2srt(content=content)
result = AssConvert().srt2ass(content=bcc_result)
return result


_to_table = {
"2srt": {
"ass": ass2srt,
"bcc": bcc2srt,
},
"2bcc": {
"vtt": vtt2bcc,
"srt": srt2bcc,
"ass": ass2bcc,
},
"2ass": {
"srt": srt2ass,
"bcc": bcc2ass,
},
}


def get_method(method: str) -> Callable[..., Any]:
available_method = show_available()
assert method in available_method, f"Not available in {available_method}"
sub_key, key = method.split("2", maxsplit=1)
top_key = f"2{key}"
child = _to_table.get(top_key, None)
assert child, f"{method} NotImplemented for top class"
method_func = child.get(sub_key, None)
assert method_func, f"{method} NotImplemented for sub class"
return method_func


def show_available() -> list:
"""
查询可用方法,返回功能列表
:return:
"""
_method = []
for it in _to_table.keys():
_child = _to_table[it]
if not isinstance(_child, dict):
continue
_from = _child.keys()
for ti in _from:
_method.append(f"{ti}{it}")
return _method
21 changes: 21 additions & 0 deletions src/subtitle_utils/convert/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 智伤帝

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Original file line number Diff line number Diff line change
@@ -1,38 +1,42 @@
# -*- coding: utf-8 -*-
# @Time : 12/30/22 2:54 PM
# @FileName: AssConverter.py
# @Time : 2024/1/18 下午6:05
# @Author : sudoskys
# @File : ass.py
# @Software: PyCharm
# @Github :sudoskys
import re
from pathlib import Path
from pyasstosrt import Subtitle
import tempfile
from typing import Union, IO

from .utils import SrtParse
from pyasstosrt import Subtitle

from ..parse import SrtParse
from ..schema import Convert

class AssUtils(object):
@staticmethod
def defultHeader() -> str:
return """[V4+ Styles]
ASS_HEADER = """[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,Arial,20,&H00FFFFFF,&HF0000000,&H00000000,&HF0000000,1,0,0,0,100,100,0,0.00,1,1,0,2,30,30,10,134
[Events]
Format: Layer, Start, End, Style, Actor, MarginL, MarginR, MarginV, Effect, Text
"""

def ass_content(self, content, header: str) -> str:

class AssConvert(Convert):
@staticmethod
def srt2ass(content: Union[str, IO],
*,
header: str = None) -> str:
"""
字幕转换
:param timestamps: 时间轴
:param subtitles: 字幕
:param header: 头
:return: 合成字幕
Subtitle Converter
:param content: subtitle path or content
:param header: ASS HEADER (Style)
:return: processed subtitle
"""
subs = SrtParse().parse(strs=content)
assert isinstance(content, (str, IO)), "content must be str or IO"
subs = SrtParse().parse(content=content)
timestamps = [[str(sub.start), str(sub.end)] for sub in subs]
subtitles = [sub.text for sub in subs]
header = header if header else AssUtils.defultHeader()
if header is None:
header = ASS_HEADER
content = header + '\n'
body = {
'dialogue': 'Dialogue: ',
Expand Down Expand Up @@ -63,21 +67,19 @@ def ass_content(self, content, header: str) -> str:
content += '\n'
return content


class AssConvert(object):

def ass2srt(self, files: str) -> str:
path = Path(files)
sub = Subtitle(path)
dialog = sub.export(output_dialogues=True)
_result = []
for dialogue in dialog:
_result.append(str(dialogue))
@staticmethod
def ass2srt(content: Union[str, IO]) -> str:
assert isinstance(content, (str, IO)), "content must be str or IO"
# write to temp file
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", delete=False) as f:
if isinstance(content, str):
f.write(content)
else:
f.write(content.read())
f.close()
sub = Subtitle(filepath=f.name)
dialog = sub.export(output_dialogues=True)
_result = []
for dialogue in dialog:
_result.append(str(dialogue))
return "".join(_result)

def srt2ass(self, strs: str, header: str = "") -> str:
content = AssUtils().ass_content(content=strs, header=header)
return content

# res = AssConvert().ass2srt(files="../test/sub.ass")
# print(res)
Loading

0 comments on commit 0d65f43

Please sign in to comment.