You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
2.1 KiB
64 lines
2.1 KiB
3 years ago
|
import dataclasses
|
||
6 years ago
|
import json
|
||
6 months ago
|
from typing import Any, Optional, TextIO
|
||
|
|
||
|
from ..common import Color
|
||
|
from ..ssaevent import SSAEvent
|
||
|
from ..ssastyle import SSAStyle
|
||
|
from .base import FormatBase
|
||
|
from ..ssafile import SSAFile
|
||
6 years ago
|
|
||
|
|
||
3 years ago
|
# We're using Color dataclass
|
||
|
# https://stackoverflow.com/questions/51286748/make-the-python-json-encoder-support-pythons-new-dataclasses
|
||
|
class EnhancedJSONEncoder(json.JSONEncoder):
|
||
6 months ago
|
def default(self, o: Any) -> Any:
|
||
3 years ago
|
if dataclasses.is_dataclass(o):
|
||
|
return dataclasses.asdict(o)
|
||
|
return super().default(o)
|
||
|
|
||
|
|
||
6 years ago
|
class JSONFormat(FormatBase):
|
||
3 years ago
|
"""
|
||
|
Implementation of JSON subtitle pseudo-format (serialized pysubs2 internal representation)
|
||
|
|
||
|
This is essentially SubStation Alpha as JSON.
|
||
|
"""
|
||
6 years ago
|
@classmethod
|
||
6 months ago
|
def guess_format(cls, text: str) -> Optional[str]:
|
||
3 years ago
|
"""See :meth:`pysubs2.formats.FormatBase.guess_format()`"""
|
||
6 months ago
|
if text.startswith("{\"") and "\"info\":" in text:
|
||
6 years ago
|
return "json"
|
||
6 months ago
|
else:
|
||
|
return None
|
||
6 years ago
|
|
||
|
@classmethod
|
||
6 months ago
|
def from_file(cls, subs: "SSAFile", fp: TextIO, format_: str, **kwargs: Any) -> None:
|
||
3 years ago
|
"""See :meth:`pysubs2.formats.FormatBase.from_file()`"""
|
||
6 years ago
|
data = json.load(fp)
|
||
|
|
||
|
subs.info.clear()
|
||
|
subs.info.update(data["info"])
|
||
|
|
||
|
subs.styles.clear()
|
||
|
for name, fields in data["styles"].items():
|
||
|
subs.styles[name] = sty = SSAStyle()
|
||
|
for k, v in fields.items():
|
||
|
if "color" in k:
|
||
3 years ago
|
setattr(sty, k, Color(**v))
|
||
6 years ago
|
else:
|
||
|
setattr(sty, k, v)
|
||
|
|
||
|
subs.events = [SSAEvent(**fields) for fields in data["events"]]
|
||
|
|
||
|
@classmethod
|
||
6 months ago
|
def to_file(cls, subs: "SSAFile", fp: TextIO, format_: str, **kwargs: Any) -> None:
|
||
3 years ago
|
"""See :meth:`pysubs2.formats.FormatBase.to_file()`"""
|
||
6 years ago
|
data = {
|
||
|
"info": dict(**subs.info),
|
||
|
"styles": {name: sty.as_dict() for name, sty in subs.styles.items()},
|
||
|
"events": [ev.as_dict() for ev in subs.events]
|
||
|
}
|
||
|
|
||
3 years ago
|
json.dump(data, fp, cls=EnhancedJSONEncoder)
|