1
0
mirror of https://github.com/spaam/svtplay-dl.git synced 2024-11-28 06:04:17 +01:00
svtplay-dl/lib/svtplay_dl/subtitle/__init__.py

301 lines
10 KiB
Python
Raw Normal View History

2014-04-21 19:52:09 +02:00
import xml.etree.ElementTree as ET
import json
import re
2018-01-30 22:09:31 +01:00
from io import StringIO
2014-04-21 19:52:09 +02:00
from svtplay_dl.log import log
from svtplay_dl.utils.text import decode_html_entities
from svtplay_dl.utils.http import HTTP
2018-05-13 13:06:45 +02:00
from svtplay_dl.utils.output import output
from requests import __build__ as requests_version
import platform
2014-04-21 19:52:09 +02:00
2015-01-25 14:41:29 +01:00
2014-07-28 15:53:23 +02:00
class subtitle(object):
2018-05-08 22:46:11 +02:00
def __init__(self, config, subtype, url, subfix=None, **kwargs):
2014-04-21 19:52:09 +02:00
self.url = url
self.subtitle = None
2018-05-08 22:46:11 +02:00
self.config = config
self.subtype = subtype
2018-05-08 22:46:11 +02:00
self.http = HTTP(config)
self.subfix = subfix
self.bom = False
2018-05-13 13:06:45 +02:00
self.output = kwargs.pop("output", None)
2014-04-21 19:52:09 +02:00
2018-05-12 15:12:37 +02:00
def __repr__(self):
return "<Subtitle(type={}, url={}>".format(self.subtype, self.url)
def download(self):
subdata = self.http.request("get", self.url)
if subdata.status_code != 200:
log.warning("Can't download subtitle file")
return
data = None
if "mtgx" in self.url and subdata.content[:3] == b"\xef\xbb\xbf":
subdata.encoding = "utf-8"
self.bom = True
if self.subtype == "tt":
data = self.tt(subdata)
if self.subtype == "json":
data = self.json(subdata)
if self.subtype == "sami":
data = self.sami(subdata)
if self.subtype == "smi":
data = self.smi(subdata)
if self.subtype == "wrst":
2017-09-17 11:21:04 +02:00
if "tv4play" in self.url and subdata.content[:3] == b"\xef\xbb\xbf":
subdata.encoding = "utf-8"
self.bom = True
if "dplay" in self.url:
subdata.encoding = "utf-8"
data = self.wrst(subdata)
2015-10-30 00:51:35 +01:00
if self.subtype == "raw":
data = self.raw(subdata)
2018-01-30 20:11:37 +01:00
2016-04-27 19:41:23 +02:00
if self.subfix:
if self.config.get("get_all_subtitles"):
if self.output["episodename"]:
self.output["episodename"] = "{}-{}".format(self.output["episodename"], self.subfix)
else:
self.output["episodename"] = self.subfix
2018-01-30 20:11:37 +01:00
if self.config.get("get_raw_subtitles"):
subdata = self.raw(subdata)
self.save_file(subdata, self.subtype)
2018-01-30 20:11:37 +01:00
self.save_file(data, "srt")
2018-01-30 20:11:37 +01:00
def save_file(self, data, subtype):
2018-01-13 20:27:40 +01:00
if platform.system() == "Windows":
file_d = output(self.output, self.config, subtype, mode="wt", encoding="utf-8")
else:
file_d = output(self.output, self.config, subtype, mode="wt")
if hasattr(file_d, "read") is False:
return
file_d.write(data)
file_d.close()
2018-01-30 20:11:37 +01:00
def raw(self, subdata):
2018-01-13 20:27:40 +01:00
return subdata.text
2018-01-30 20:11:37 +01:00
def tt(self, subdata):
2014-04-21 19:52:09 +02:00
i = 1
data = ""
2018-01-13 20:27:40 +01:00
subs = subdata.text
2016-01-27 19:49:38 +01:00
2015-10-10 16:31:42 +02:00
subdata = re.sub(' xmlns="[^"]+"', '', subs, count=1)
tree = ET.XML(subdata)
xml = tree.find("body").find("div")
plist = list(xml.findall("p"))
for node in plist:
2014-04-21 19:52:09 +02:00
tag = norm(node.tag)
if tag == "p" or tag == "span":
2014-04-21 19:52:09 +02:00
begin = node.attrib["begin"]
if not ("dur" in node.attrib):
duration = node.attrib["duration"]
else:
duration = node.attrib["dur"]
if not ("end" in node.attrib):
begin2 = begin.split(":")
duration2 = duration.split(":")
try:
sec = float(begin2[2]) + float(duration2[2])
except ValueError:
sec = 0.000
end = "%02d:%02d:%06.3f" % (int(begin2[0]), int(begin2[1]), sec)
2014-04-21 19:52:09 +02:00
else:
end = node.attrib["end"]
2014-12-26 02:04:29 +01:00
data += '%s\n%s --> %s\n' % (i, begin.replace(".", ","), end.replace(".", ","))
data = tt_text(node, data)
data += "\n"
2014-04-21 19:52:09 +02:00
i += 1
2018-01-13 20:27:40 +01:00
return data
2014-04-21 19:52:09 +02:00
def json(self, subdata):
data = json.loads(subdata.text)
2014-04-21 19:52:09 +02:00
number = 1
subs = ""
for i in data:
subs += "%s\n%s --> %s\n" % (number, timestr(int(i["startMillis"])), timestr(int(i["endMillis"])))
2018-01-13 20:27:40 +01:00
subs += "%s\n\n" % i["text"]
2014-04-21 19:52:09 +02:00
number += 1
return subs
2014-04-21 19:52:09 +02:00
def sami(self, subdata):
2016-06-01 22:43:39 +02:00
text = subdata.text
text = re.sub(r'&', '&amp;', text)
tree = ET.fromstring(text)
2014-04-21 19:52:09 +02:00
subt = tree.find("Font")
subs = ""
n = 0
for i in subt.getiterator():
if i.tag == "Subtitle":
n = i.attrib["SpotNumber"]
2014-04-21 19:52:09 +02:00
if i.attrib["SpotNumber"] == "1":
subs += "%s\n%s --> %s\n" % (i.attrib["SpotNumber"], timecolon(i.attrib["TimeIn"]), timecolon(i.attrib["TimeOut"]))
2014-04-21 19:52:09 +02:00
else:
subs += "\n%s\n%s --> %s\n" % (i.attrib["SpotNumber"], timecolon(i.attrib["TimeIn"]), timecolon(i.attrib["TimeOut"]))
2014-04-21 19:52:09 +02:00
else:
if int(n) > 0 and i.text:
subs += "%s\n" % decode_html_entities(i.text)
2014-04-21 19:52:09 +02:00
2016-06-01 22:43:39 +02:00
subs = re.sub('&amp;', r'&', subs)
return subs
2014-04-21 19:52:09 +02:00
def smi(self, subdata):
if requests_version < 0x20300:
2018-01-13 20:27:40 +01:00
subdata = subdata.content.decode("latin")
else:
subdata.encoding = "ISO-8859-1"
subdata = subdata.text
ssubdata = StringIO(subdata)
timea = 0
2014-04-21 19:52:09 +02:00
number = 1
data = None
2014-04-21 19:52:09 +02:00
subs = ""
TAG_RE = re.compile(r'<(?!\/?i).*?>')
bad_char = re.compile(r'\x96')
for i in ssubdata.readlines():
2015-05-01 22:34:02 +02:00
i = i.rstrip()
2015-04-28 23:16:44 +02:00
sync = re.search(r"<SYNC Start=(\d+)>", i)
if sync:
if int(sync.group(1)) != int(timea):
2015-05-01 22:34:02 +02:00
if data and data != "&nbsp;":
subs += "%s\n%s --> %s\n" % (number, timestr(timea), timestr(sync.group(1)))
text = "%s\n" % TAG_RE.sub('', data.replace("<br>", "\n"))
text = decode_html_entities(text)
2018-01-30 20:11:37 +01:00
if text[len(text) - 2] != "\n":
2015-05-01 22:34:02 +02:00
text += "\n"
subs += text
number += 1
timea = sync.group(1)
text = re.search("<P Class=SVCC>(.*)", i)
if text:
data = text.group(1)
recomp = re.compile(r'\r')
text = bad_char.sub('-', recomp.sub('', subs))
return text
2014-04-21 19:52:09 +02:00
def wrst(self, subdata):
ssubdata = StringIO(subdata.text)
2014-04-21 19:52:09 +02:00
srt = ""
subtract = False
2015-03-01 21:44:55 +01:00
number_b = 1
number = 0
block = 0
subnr = False
if self.bom:
ssubdata.read(1)
2015-03-01 21:44:55 +01:00
for i in ssubdata.readlines():
2015-04-28 23:16:44 +02:00
match = re.search(r"^[\r\n]+", i)
match2 = re.search(r"([\d:\.]+ --> [\d:\.]+)", i)
match3 = re.search(r"^(\d+)\s", i)
2015-03-01 21:44:55 +01:00
if i[:6] == "WEBVTT":
continue
elif "X-TIMESTAMP" in i:
continue
elif match and number_b == 1 and self.bom:
continue
2015-03-01 21:44:55 +01:00
elif match and number_b > 1:
block = 0
srt += "\n"
elif match2:
if not subnr:
srt += "%s\n" % number_b
matchx = re.search(r'(?P<h1>\d+):(?P<m1>\d+):(?P<s1>[\d\.]+) --> (?P<h2>\d+):(?P<m2>\d+):(?P<s2>[\d\.]+)', i)
if matchx:
hour1 = int(matchx.group("h1"))
hour2 = int(matchx.group("h2"))
if int(number) == 1:
if hour1 > 9:
subtract = True
if subtract:
hour1 -= 10
hour2 -= 10
else:
matchx = re.search(r'(?P<m1>\d+):(?P<s1>[\d\.]+) --> (?P<m2>\d+):(?P<s2>[\d\.]+)', i)
hour1 = 0
hour2 = 0
2018-01-30 20:11:37 +01:00
time = "{0:02d}:{1}:{2} --> {3:02d}:{4}:{5}\n".format(hour1, matchx.group("m1"), matchx.group("s1").replace(".", ","),
hour2, matchx.group("m2"), matchx.group("s2").replace(".", ","))
2015-03-01 21:44:55 +01:00
srt += time
block = 1
subnr = False
number_b += 1
elif match3 and block == 0:
number = match3.group(1)
srt += "%s\n" % number
subnr = True
else:
if self.config.get("convert_subtitle_colors"):
2018-01-30 20:11:37 +01:00
colors = {'30': '#000000', '31': '#ff0000', '32': '#00ff00', '33': '#ffff00',
'34': '#0000ff', '35': '#ff00ff', '36': '#00ffff', '37': '#ffffff'}
sub = i
for tag, color in colors.items():
regex1 = '<' + tag + '>'
replace = '<font color="' + color + '">'
sub = re.sub(regex1, replace, sub)
2018-01-30 20:11:37 +01:00
sub = re.sub('</.+>', '</font>', sub)
else:
sub = re.sub('<[^>]*>', '', i)
2016-04-20 18:42:46 +02:00
srt += sub.strip()
2018-01-30 20:11:37 +01:00
srt += "\n"
srt = decode_html_entities(srt)
return srt
2015-09-15 20:10:32 +02:00
2014-04-21 19:52:09 +02:00
def timestr(msec):
"""
Convert a millisecond value to a string of the following
format:
HH:MM:SS,SS
with 10 millisecond precision. Note the , seperator in
the seconds.
"""
sec = float(msec) / 1000
hours = int(sec / 3600)
sec -= hours * 3600
minutes = int(sec / 60)
sec -= minutes * 60
2016-06-03 00:09:11 +02:00
output = "%02d:%02d:%06.3f" % (hours, minutes, sec)
2014-04-21 19:52:09 +02:00
return output.replace(".", ",")
2015-09-15 20:10:32 +02:00
def timecolon(data):
2014-12-22 10:20:37 +01:00
match = re.search(r"(\d+:\d+:\d+):(\d+)", data)
return "%s,%s" % (match.group(1), match.group(2))
2015-09-15 20:10:32 +02:00
2014-04-21 19:52:09 +02:00
def norm(name):
if name[0] == "{":
_, tag = name[1:].split("}")
return tag
else:
return name
2015-09-15 20:10:32 +02:00
def tt_text(node, data):
if node.text:
data += "%s\n" % node.text.strip(' \t\n\r')
for i in node:
if i.text:
data += "%s\n" % i.text.strip(' \t\n\r')
if i.tail:
text = i.tail.strip(' \t\n\r')
if text:
data += "%s\n" % text
2015-01-05 21:52:34 +01:00
return data