2021-07-15 07:13:28 +08:00
|
|
|
import dataclasses
|
2018-11-01 00:08:29 +08:00
|
|
|
import json
|
2021-07-15 07:13:28 +08:00
|
|
|
from .common import Color
|
2018-11-01 00:08:29 +08:00
|
|
|
from .ssaevent import SSAEvent
|
|
|
|
from .ssastyle import SSAStyle
|
|
|
|
from .formatbase import FormatBase
|
|
|
|
|
|
|
|
|
2021-07-15 07:13:28 +08:00
|
|
|
# We're using Color dataclass
|
|
|
|
# https://stackoverflow.com/questions/51286748/make-the-python-json-encoder-support-pythons-new-dataclasses
|
|
|
|
class EnhancedJSONEncoder(json.JSONEncoder):
|
|
|
|
def default(self, o):
|
|
|
|
if dataclasses.is_dataclass(o):
|
|
|
|
return dataclasses.asdict(o)
|
|
|
|
return super().default(o)
|
|
|
|
|
|
|
|
|
2018-11-01 00:08:29 +08:00
|
|
|
class JSONFormat(FormatBase):
|
2021-07-15 07:13:28 +08:00
|
|
|
"""
|
|
|
|
Implementation of JSON subtitle pseudo-format (serialized pysubs2 internal representation)
|
|
|
|
|
|
|
|
This is essentially SubStation Alpha as JSON.
|
|
|
|
"""
|
2018-11-01 00:08:29 +08:00
|
|
|
@classmethod
|
|
|
|
def guess_format(cls, text):
|
2021-07-15 07:13:28 +08:00
|
|
|
"""See :meth:`pysubs2.formats.FormatBase.guess_format()`"""
|
2018-11-01 00:08:29 +08:00
|
|
|
if text.startswith("{\""):
|
|
|
|
return "json"
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_file(cls, subs, fp, format_, **kwargs):
|
2021-07-15 07:13:28 +08:00
|
|
|
"""See :meth:`pysubs2.formats.FormatBase.from_file()`"""
|
2018-11-01 00:08:29 +08:00
|
|
|
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:
|
2021-07-15 07:13:28 +08:00
|
|
|
setattr(sty, k, Color(**v))
|
2018-11-01 00:08:29 +08:00
|
|
|
else:
|
|
|
|
setattr(sty, k, v)
|
|
|
|
|
|
|
|
subs.events = [SSAEvent(**fields) for fields in data["events"]]
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def to_file(cls, subs, fp, format_, **kwargs):
|
2021-07-15 07:13:28 +08:00
|
|
|
"""See :meth:`pysubs2.formats.FormatBase.to_file()`"""
|
2018-11-01 00:08:29 +08:00
|
|
|
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]
|
|
|
|
}
|
|
|
|
|
2021-07-15 07:13:28 +08:00
|
|
|
json.dump(data, fp, cls=EnhancedJSONEncoder)
|