subtitles.py (2481B)
1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\eve\client\script\ui\shared\subtitles.py 2 import blue 3 import logging 4 import urllib2 5 logger = logging.getLogger(__name__) 6 7 def GetSubtitlePathForVideo(videoPath, languageID): 8 basePath = _rchop(videoPath, '.webm') 9 subtitlePath = '%s_%s.srt' % (basePath, languageID) 10 return subtitlePath 11 12 13 def _rchop(s, suffix): 14 if suffix and s.endswith(suffix): 15 return s[:-len(suffix)] 16 return s 17 18 19 def _ParseTime(timeStr): 20 import re 21 22 def matchToMilliseconds(offset): 23 return int(match.group(3 + offset)) + int(match.group(2 + offset)) * 1000 + int(match.group(1 + offset)) * 1000 * 60 + int(match.group(0 + offset)) * 1000 * 60 * 60 24 25 match = re.match('(\\d{1,2}):(\\d{1,2}):(\\d{1,2}),(\\d{1,3})\\s+-->\\s+(\\d{1,2}):(\\d{1,2}):(\\d{1,2}),(\\d{1,3}).*', timeStr) 26 if match is None: 27 raise ValueError 28 return (matchToMilliseconds(1), matchToMilliseconds(5)) 29 30 31 class Subtitles(object): 32 33 def __init__(self): 34 self._subtitles = [] 35 36 def LoadSubtitleFile(self, path): 37 if path.lower().startswith('res:/') or path.find(':') < 2: 38 try: 39 text = blue.paths.GetFileContentsWithYield(path).read() 40 except (IOError, RuntimeError): 41 logger.warn("Video Player: Can't load subtitles in path: %s" % path) 42 return 43 44 else: 45 try: 46 text = urllib2.urlopen(path).read() 47 except IOError: 48 return 49 50 return text 51 52 def PrepareSubtitles(self, text): 53 text = text.decode('utf-8') 54 state = 'number' 55 time = '' 56 subText = [] 57 for line in text.split('\n'): 58 if state == 'number': 59 state = 'time' 60 elif state == 'time': 61 time = line.strip() 62 state = 'text' 63 else: 64 line = line.strip() 65 if line == '': 66 try: 67 self._subtitles.append((_ParseTime(time), '\n'.join(subText))) 68 except ValueError: 69 pass 70 71 state = 'number' 72 subText = [] 73 else: 74 subText.append(line) 75 76 def GetSubtitle(self, milliseconds): 77 for time, text in self._subtitles: 78 if time[0] <= milliseconds <= time[1]: 79 return text 80 81 return ''