-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcompact.py
88 lines (70 loc) · 2.46 KB
/
compact.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""
Script for turning VTT transcripts, e.g. those created by Zoom when you
record a meeting, into a denser format with less redundant information.
Created by: Will Larson (GitHub: lethain)
Original Source: https://github.com/lethain/vtt_compactor (unmodified usage)
"""
import argparse
class Segment:
def __init__(self):
self.num = 0
self.speaker = None
self.start = ""
self.end = ""
self.text = ""
def time(self, txt):
self.start, self.end = txt.split(' --> ')
def is_complete(self):
return self.num and self.speaker and self.text
def __repr__(self):
return "Segment(%s, %s, %s, text: %s)" % (self.num, self.speaker, self.start, len(self.text))
def segments(fd):
segments = []
seg = Segment()
for line in fd:
try:
if seg.is_complete():
segments.append(seg)
seg = Segment()
line = line.strip()
if line and line != "WEBVTT":
if not seg.num:
seg.num = int(line)
elif not seg.start:
seg.time(line)
elif seg.speaker is None:
parts = line.split(':', 1)
if len(parts) == 2:
seg.speaker, seg.text = parts
elif len(parts) == 1:
# this happens sometimes for unclear reasons
seg.speaker = "OMITTED"
seg.text = parts[0]
seg.text = seg.text.strip()
except Exception as e:
print("couldn't parse: %s" % (line,))
raise(e)
return segments
def compact(segs):
chunks = []
if len(segs) == 0:
return chunks
chunk = segs[0]
for seg in segs[1:]:
if seg.speaker == chunk.speaker:
chunk.text += "\n" + seg.text
chunk.end = seg.end
else:
chunks.append(chunk)
chunk = seg
chunks.append(chunk)
return chunks
def main_compact(filepath):
new_dest = "b_cmt_transcripts/"
new_path = new_dest + (filepath.split(".vtt")[0]+"_CMT.vtt").split("/")[1]
with open(new_path, 'w') as dest:
with open(filepath, 'r') as fin:
segs = segments(fin)
chunks = compact(segs)
for chunk in chunks:
print("%s. %s. %s -> %s\n\n%s\n" % (chunk.num, chunk.speaker, chunk.start, chunk.end, chunk.text), file=dest)