videocr/video.py (view raw)
1from __future__ import annotations
2from concurrent import futures
3import datetime
4import pytesseract
5import cv2
6
7from . import constants
8from .models import PredictedFrame, PredictedSubtitle
9
10
11class Video:
12 path: str
13 lang: str
14 use_fullframe: bool
15 num_frames: int
16 fps: float
17 pred_frames: List[PredictedFrame]
18 pred_subs: List[PredictedSubtitle]
19
20 def __init__(self, path: str):
21 self.path = path
22 v = cv2.VideoCapture(path)
23 self.num_frames = int(v.get(cv2.CAP_PROP_FRAME_COUNT))
24 self.fps = v.get(cv2.CAP_PROP_FPS)
25 v.release()
26
27 def run_ocr(self, lang: str, time_start: str, time_end: str,
28 use_fullframe: bool) -> None:
29 self.lang = lang
30 self.use_fullframe = use_fullframe
31
32 ocr_start = self._frame_index(time_start) if time_start else 0
33 ocr_end = self._frame_index(time_end) if time_end else self.num_frames
34
35 if ocr_end < ocr_start:
36 raise ValueError('time_start is later than time_end')
37 num_ocr_frames = ocr_end - ocr_start
38
39 # get frames from ocr_start to ocr_end
40 v = cv2.VideoCapture(self.path)
41 v.set(cv2.CAP_PROP_POS_FRAMES, ocr_start)
42 frames = (v.read()[1] for _ in range(num_ocr_frames))
43
44 # perform ocr to frames in parallel
45 with futures.ProcessPoolExecutor() as pool:
46 ocr_map = pool.map(self._single_frame_ocr, frames, chunksize=10)
47 self.pred_frames = [PredictedFrame(i + ocr_start, data)
48 for i, data in enumerate(ocr_map)]
49
50 v.release()
51
52 # convert time str to frame index
53 def _frame_index(self, time: str) -> int:
54 t = time.split(':')
55 t = list(map(float, t))
56 if len(t) == 3:
57 td = datetime.timedelta(hours=t[0], minutes=t[1], seconds=t[2])
58 elif len(t) == 2:
59 td = datetime.timedelta(minutes=t[0], seconds=t[1])
60 else:
61 raise ValueError(
62 'time data "{}" does not match format "%H:%M:%S"'.format(time))
63
64 index = int(td.total_seconds() * self.fps)
65 if index > self.num_frames or index < 0:
66 raise ValueError(
67 'time data "{}" exceeds video duration'.format(time))
68
69 return index
70
71 def _single_frame_ocr(self, img) -> str:
72 if not self.use_fullframe:
73 # only use bottom half of the frame by default
74 img = img[self.height // 2:, :]
75 config = '--tessdata-dir "{}"'.format(constants.TESSDATA_DIR)
76 return pytesseract.image_to_data(img, lang=self.lang, config=config)
77
78 def get_subtitles(self) -> str:
79 self._generate_subtitles()
80 return ''.join(
81 '{}\n{} --> {}\n{}\n\n'.format(
82 i,
83 self._srt_timestamp(sub.index_start),
84 self._srt_timestamp(sub.index_end),
85 sub.text)
86 for i, sub in enumerate(self.pred_subs))
87
88 def _generate_subtitles(self) -> None:
89 self.pred_subs = []
90
91 if self.pred_frames is None:
92 raise AttributeError(
93 'Please call self.run_ocr() first to perform ocr on frames')
94
95 # divide ocr of frames into subtitle paragraphs using sliding window
96 WIN_BOUND = int(self.fps // 2) # 1/2 sec sliding window boundary
97 bound = WIN_BOUND
98 i = 0
99 j = 1
100 while j < len(self.pred_frames):
101 fi, fj = self.pred_frames[i], self.pred_frames[j]
102
103 if fi.is_similar_to(fj):
104 bound = WIN_BOUND
105 elif bound > 0:
106 bound -= 1
107 else:
108 # divide subtitle paragraphs
109 para_new = j - WIN_BOUND
110 self._append_sub(
111 PredictedSubtitle(self.pred_frames[i:para_new]))
112 i = para_new
113 j = i
114 bound = WIN_BOUND
115
116 j += 1
117
118 # also handle the last remaining frames
119 if i < len(self.pred_frames) - 1:
120 self._append_sub(PredictedSubtitle(self.pred_frames[i:]))
121
122 def _append_sub(self, sub: PredictedSubtitle) -> None:
123 if len(sub.text) == 0:
124 return
125
126 # merge new sub to the last subs if they are similar
127 while self.pred_subs and sub.is_similar_to(self.pred_subs[-1]):
128 ls = self.pred_subs[-1]
129 del self.pred_subs[-1]
130 sub = PredictedSubtitle(ls.frames + sub.frames)
131
132 self.pred_subs.append(sub)
133
134 def _srt_timestamp(self, frame_index: int) -> str:
135 td = datetime.timedelta(seconds=frame_index / self.fps)
136 ms = td.microseconds // 1000
137 m, s = divmod(td.seconds, 60)
138 h, m = divmod(m, 60)
139 return '{:02d}:{:02d}:{:02d},{:03d}'.format(h, m, s, ms)