Spaces:
Configuration error
Configuration error
Delete app.py
Browse files
app.py
DELETED
@@ -1,207 +0,0 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
import pytesseract
|
3 |
-
import cv2
|
4 |
-
import multiprocessing
|
5 |
-
from fuzzywuzzy import fuzz
|
6 |
-
from dataclasses import dataclass
|
7 |
-
from urllib.request import urlopen
|
8 |
-
import shutil
|
9 |
-
import pathlib
|
10 |
-
import datetime
|
11 |
-
import sys
|
12 |
-
|
13 |
-
# Constants
|
14 |
-
TESSDATA_DIR = pathlib.Path.home() / 'tessdata'
|
15 |
-
TESSDATA_URL = 'https://github.com/tesseract-ocr/tessdata_fast/raw/master/{}.traineddata'
|
16 |
-
TESSDATA_SCRIPT_URL = 'https://github.com/tesseract-ocr/tessdata_best/raw/master/script/{}.traineddata'
|
17 |
-
|
18 |
-
|
19 |
-
# Download language data files if necessary
|
20 |
-
def download_lang_data(lang: str):
|
21 |
-
TESSDATA_DIR.mkdir(parents=True, exist_ok=True)
|
22 |
-
for lang_name in lang.split('+'):
|
23 |
-
filepath = TESSDATA_DIR / f'{lang_name}.traineddata'
|
24 |
-
if not filepath.is_file():
|
25 |
-
url = TESSDATA_SCRIPT_URL.format(lang_name) if lang_name[0].isupper() else TESSDATA_URL.format(lang_name)
|
26 |
-
with urlopen(url) as res, open(filepath, 'w+b') as f:
|
27 |
-
shutil.copyfileobj(res, f)
|
28 |
-
|
29 |
-
|
30 |
-
# Helper functions for time and frame conversion
|
31 |
-
def get_frame_index(time_str: str, fps: float):
|
32 |
-
t = list(map(float, time_str.split(':')))
|
33 |
-
if len(t) == 3:
|
34 |
-
td = datetime.timedelta(hours=t[0], minutes=t[1], seconds=t[2])
|
35 |
-
elif len(t) == 2:
|
36 |
-
td = datetime.timedelta(minutes=t[0], seconds=t[1])
|
37 |
-
else:
|
38 |
-
raise ValueError(f'Time data "{time_str}" does not match format "%H:%M:%S"')
|
39 |
-
return int(td.total_seconds() * fps)
|
40 |
-
|
41 |
-
|
42 |
-
def get_srt_timestamp(frame_index: int, fps: float):
|
43 |
-
td = datetime.timedelta(seconds=frame_index / fps)
|
44 |
-
ms = td.microseconds // 1000
|
45 |
-
m, s = divmod(td.seconds, 60)
|
46 |
-
h, m = divmod(m, 60)
|
47 |
-
return f'{h:02d}:{m:02d}:{s:02d},{ms:03d}'
|
48 |
-
|
49 |
-
|
50 |
-
# Video capture class using OpenCV
|
51 |
-
class Capture:
|
52 |
-
def __init__(self, video_path):
|
53 |
-
self.path = video_path
|
54 |
-
|
55 |
-
def __enter__(self):
|
56 |
-
self.cap = cv2.VideoCapture(self.path)
|
57 |
-
if not self.cap.isOpened():
|
58 |
-
raise IOError(f'Cannot open video {self.path}.')
|
59 |
-
return self.cap
|
60 |
-
|
61 |
-
def __exit__(self, exc_type, exc_value, traceback):
|
62 |
-
self.cap.release()
|
63 |
-
|
64 |
-
|
65 |
-
@dataclass
|
66 |
-
class PredictedWord:
|
67 |
-
confidence: int
|
68 |
-
text: str
|
69 |
-
|
70 |
-
|
71 |
-
class PredictedFrame:
|
72 |
-
def __init__(self, index: int, pred_data: str, conf_threshold: int):
|
73 |
-
self.index = index
|
74 |
-
self.words = []
|
75 |
-
block = 0
|
76 |
-
for l in pred_data.splitlines()[1:]:
|
77 |
-
word_data = l.split()
|
78 |
-
if len(word_data) < 12:
|
79 |
-
continue
|
80 |
-
_, _, block_num, *_, conf, text = word_data
|
81 |
-
block_num, conf = int(block_num), int(conf)
|
82 |
-
if block < block_num:
|
83 |
-
block = block_num
|
84 |
-
if self.words and self.words[-1].text != '\n':
|
85 |
-
self.words.append(PredictedWord(0, '\n'))
|
86 |
-
if conf >= conf_threshold:
|
87 |
-
self.words.append(PredictedWord(conf, text))
|
88 |
-
self.confidence = sum(word.confidence for word in self.words)
|
89 |
-
self.text = ' '.join(word.text for word in self.words).translate(str.maketrans('|', 'I', '<>{}[];`@#$%^*_=~\\')).replace(' \n ', '\n').strip()
|
90 |
-
|
91 |
-
def is_similar_to(self, other, threshold=70):
|
92 |
-
return fuzz.ratio(self.text, other.text) >= threshold
|
93 |
-
|
94 |
-
|
95 |
-
class PredictedSubtitle:
|
96 |
-
def __init__(self, frames, sim_threshold):
|
97 |
-
self.frames = [f for f in frames if f.confidence > 0]
|
98 |
-
self.sim_threshold = sim_threshold
|
99 |
-
self.text = max(self.frames, key=lambda f: f.confidence).text if self.frames else ''
|
100 |
-
|
101 |
-
@property
|
102 |
-
def index_start(self):
|
103 |
-
return self.frames[0].index if self.frames else 0
|
104 |
-
|
105 |
-
@property
|
106 |
-
def index_end(self):
|
107 |
-
return self.frames[-1].index if self.frames else 0
|
108 |
-
|
109 |
-
def is_similar_to(self, other):
|
110 |
-
return fuzz.partial_ratio(self.text, other.text) >= self.sim_threshold
|
111 |
-
|
112 |
-
|
113 |
-
class Video:
|
114 |
-
def __init__(self, path):
|
115 |
-
self.path = path
|
116 |
-
with Capture(path) as v:
|
117 |
-
self.num_frames = int(v.get(cv2.CAP_PROP_FRAME_COUNT))
|
118 |
-
self.fps = v.get(cv2.CAP_PROP_FPS)
|
119 |
-
self.height = int(v.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
120 |
-
|
121 |
-
def run_ocr(self, lang, time_start, time_end, conf_threshold, use_fullframe):
|
122 |
-
self.lang = lang
|
123 |
-
self.use_fullframe = use_fullframe
|
124 |
-
ocr_start = get_frame_index(time_start, self.fps) if time_start else 0
|
125 |
-
ocr_end = get_frame_index(time_end, self.fps) if time_end else self.num_frames
|
126 |
-
if ocr_end < ocr_start:
|
127 |
-
raise ValueError('time_start is later than time_end')
|
128 |
-
|
129 |
-
num_ocr_frames = ocr_end - ocr_start
|
130 |
-
with Capture(self.path) as v, multiprocessing.Pool() as pool:
|
131 |
-
v.set(cv2.CAP_PROP_POS_FRAMES, ocr_start)
|
132 |
-
frames = (v.read()[1] for _ in range(num_ocr_frames))
|
133 |
-
it_ocr = pool.imap(self._image_to_data, frames, chunksize=10)
|
134 |
-
self.pred_frames = [PredictedFrame(i + ocr_start, data, conf_threshold) for i, data in enumerate(it_ocr)]
|
135 |
-
|
136 |
-
def _image_to_data(self, img):
|
137 |
-
if not self.use_fullframe:
|
138 |
-
img = img[self.height // 2:, :]
|
139 |
-
config = f'--tessdata-dir "{TESSDATA_DIR}"'
|
140 |
-
try:
|
141 |
-
return pytesseract.image_to_data(img, lang=self.lang, config=config)
|
142 |
-
except Exception as e:
|
143 |
-
sys.exit(f'{e.__class__.__name__}: {e}')
|
144 |
-
|
145 |
-
def get_subtitles(self, sim_threshold):
|
146 |
-
self._generate_subtitles(sim_threshold)
|
147 |
-
return ''.join(f'{i}\n{get_srt_timestamp(sub.index_start, self.fps)} --> {get_srt_timestamp(sub.index_end, self.fps)}\n{sub.text}\n\n' for i, sub in enumerate(self.pred_subs))
|
148 |
-
|
149 |
-
def _generate_subtitles(self, sim_threshold):
|
150 |
-
self.pred_subs = []
|
151 |
-
if self.pred_frames is None:
|
152 |
-
raise AttributeError('Please call self.run_ocr() first to perform OCR on frames')
|
153 |
-
|
154 |
-
WIN_BOUND = int(self.fps // 2)
|
155 |
-
bound = WIN_BOUND
|
156 |
-
i = 0
|
157 |
-
j = 1
|
158 |
-
while j < len(self.pred_frames):
|
159 |
-
fi, fj = self.pred_frames[i], self.pred_frames[j]
|
160 |
-
if fi.is_similar_to(fj):
|
161 |
-
bound = WIN_BOUND
|
162 |
-
elif bound > 0:
|
163 |
-
bound -= 1
|
164 |
-
else:
|
165 |
-
para_new = j - WIN_BOUND
|
166 |
-
self._append_sub(PredictedSubtitle(self.pred_frames[i:para_new], sim_threshold))
|
167 |
-
i = para_new
|
168 |
-
j = i
|
169 |
-
bound = WIN_BOUND
|
170 |
-
j += 1
|
171 |
-
if i < len(self.pred_frames) - 1:
|
172 |
-
self._append_sub(PredictedSubtitle(self.pred_frames[i:], sim_threshold))
|
173 |
-
|
174 |
-
def _append_sub(self, sub):
|
175 |
-
if not sub.text:
|
176 |
-
return
|
177 |
-
while self.pred_subs and sub.is_similar_to(self.pred_subs[-1]):
|
178 |
-
ls = self.pred_subs.pop()
|
179 |
-
sub = PredictedSubtitle(ls.frames + sub.frames, sub.sim_threshold)
|
180 |
-
self.pred_subs.append(sub)
|
181 |
-
|
182 |
-
|
183 |
-
# Gradio app
|
184 |
-
def extract_subtitles(video_file, lang, time_start, time_end, conf_threshold, use_fullframe, sim_threshold):
|
185 |
-
video = Video(video_file.name)
|
186 |
-
video.run_ocr(lang, time_start, time_end, conf_threshold, use_fullframe)
|
187 |
-
subtitles = video.get_subtitles(sim_threshold)
|
188 |
-
return subtitles
|
189 |
-
|
190 |
-
|
191 |
-
iface = gr.Interface(
|
192 |
-
fn=extract_subtitles,
|
193 |
-
inputs=[
|
194 |
-
gr.Video(label="Video File"),
|
195 |
-
gr.Textbox(value='eng', label="OCR Language"),
|
196 |
-
gr.Textbox(value='00:00:00', label="Start Time (HH:MM:SS)"),
|
197 |
-
gr.Textbox(value='', label="End Time (HH:MM:SS, leave empty for full video)"),
|
198 |
-
gr.Slider(0, 100, value=60, step=1, label="Confidence Threshold"),
|
199 |
-
gr.Checkbox(label="Use Full Frame for OCR", default=False),
|
200 |
-
gr.Slider(0, 100, value=70, step=1, label="Similarity Threshold")
|
201 |
-
],
|
202 |
-
outputs=gr.Textbox(label="Extracted Subtitles"),
|
203 |
-
title="Video Subtitle Extractor",
|
204 |
-
description="Extract hardcoded subtitles from videos using machine learning.",
|
205 |
-
)
|
206 |
-
|
207 |
-
iface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|