summaryrefslogtreecommitdiffstats
path: root/roles/caption/templates/process-captions.py
blob: a42439b9d3db5f1422e9ecc97d99eabfab5ccad2 (plain) (blame)
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#!/usr/bin/python3
"""Use OpenAI Whisper to automatically generate captions for the video files in the specified directory."""

# {{ ansible_managed }}

# The MIT License (MIT)
# Copyright © 2022 Sacha Chua <sacha@sachachua.com>

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the “Software”), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:

# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from collections import defaultdict
import subprocess
import datetime
import sys
import webvtt
import xml.etree.ElementTree as ET
from lhotse import RecordingSet, Recording, AudioSource, SupervisionSegment, SupervisionSet, create_cut_set_eager, align_with_torchaudio, CutSet, annotate_with_whisper
import whisper
import re
import os
import json
import torch

THREADS = {{ cpus }}
VIDEO_REGEXP = '\\.(webm|mov|mp4|mkv)$'
AUDIO_REGEXP = '\\.(ogg|opus)$'
ALWAYS = False
TRIM_AUDIO = False
MODEL = os.environ.get('MODEL', 'large')  # Set to tiny for testing
WORK_DIR = "{{ emacsconf_caption_dir }}"
JSON_FILE = os.path.join(WORK_DIR, 'talks.json')
DO_SRV2 = False

# ----------------------------------------------------------------

def get_slug_from_filename(filename):
    m = re.search('emacsconf-[0-9]+-([a-z]+)--', filename)
    if m:
        return m.group(1)
    else:
        return os.path.basename(os.path.dirname(filename))

def get_files_to_work_on(directory):
    """Return the list of audio files to work on.
    The specified directory is checked recursively.
    Skip any videos that already have caption files.

    Convert any videos that don't already have audio files, and return the audio files instead.
    When there are multiple videos and audio files for a talk, pick one.
    """
    info = defaultdict(lambda: {}, {})
    directory = os.path.expanduser(directory)
    for folder, subs, files in os.walk(directory):
        for filename in files:
            f = os.path.join(folder, filename)
            slug = get_slug_from_filename(f)
            info[slug]['slug'] = slug
            if re.search(AUDIO_REGEXP, filename):
                info[slug]['audio'] = f
            elif re.search(VIDEO_REGEXP, filename):
                info[slug]['video'] = f
            elif re.search('vtt$', filename):
                info[slug]['vtt'] = f
            elif re.search('srv2$', filename):
                info[slug]['srv2'] = f
            elif re.search('txt$', filename):
                info[slug]['txt'] = f
    needs_work = []
    if JSON_FILE:
        with open(JSON_FILE) as f:
            talks = json.load(f)['talks']
    for key, val in info.items():
        if not 'video' in val and not 'audio' in val: continue
        if talks:
            talk = next(filter(lambda talk: talk['slug'] == val['slug'], talks), None)
        if talk:
            val['base'] = os.path.join(os.path.dirname(val['video'] or val['audio']),
                                       base_name(talk['file-prefix']))
        else:
            val['base'] = os.path.join(os.path.dirname(val['video'] or val['audio']),
                                       base_name(val['video'] or val['audio']))
        if ALWAYS or (not 'vtt' in val or (DO_SRV2 and not 'srv2' in val) or (not 'txt' in val)):
            if not 'audio' in val and 'video' in val:
                # No audio, need to convert it
                val = extract_audio(val)
            needs_work.append(val)
    return needs_work

def extract_audio(work):
    output = subprocess.check_output(['ffprobe', work['video']], stderr=subprocess.STDOUT)
    extension = 'opus'
    if 'Audio: vorbis' in output.decode():
        extension = 'ogg'
    new_file = work['base'] + '.' + extension
    acodec = 'copy' if re.search('\\.webm$', work['video']) else 'libopus'
    log("Extracting audio from %s acodec %s" % (work['video'], acodec))
    output = subprocess.check_output(['ffmpeg', '-y', '-i', work['video'], '-acodec', acodec, '-vn', new_file], stderr=subprocess.STDOUT)
    work['audio'] = new_file
    if os.path.isfile("/data/emacsconf/{{ emacsconf_year }}/scripts/upload.sh"):
        subprocess.call(["/data/emacsconf/{{ emacsconf_year }}/scripts/upload.sh", work['audio']])
    return work

def to_sec(time_str):
    "Convert a WebVTT time into seconds."
    h, m, s, ms = re.split('[\\.:]', time_str)
    return int(h) * 3600 + int(m) * 60 + int(s) + (int(ms) / 1000)

def log(s):
    print(datetime.datetime.now(), s)

def clean_up_timestamps(result):
    segs = list(result['segments'])
    seg_len = len(segs)
    for i, seg in enumerate(segs[:-1]):
        seg['end'] = min(segs[i + 1]['start'] - 0.001, seg['end'])
    result['segments'] = segs
    return result

def generate_captions(work):
    """Generate a VTT file based on the audio file."""
    log("Generating captions")
    new_file = work['base'] + '.vtt'
    model = whisper.load_model(MODEL, device="cuda" if torch.cuda.is_available() else "cpu")
    audio = whisper.load_audio(work['audio'])
    if TRIM_AUDIO:
        audio = whisper.pad_or_trim(audio)
    result = model.transcribe(audio, verbose=True, language="en")
    result = clean_up_timestamps(result)
    vtt_writer = whisper.utils.get_writer('vtt', os.path.dirname(new_file))
    txt_writer = whisper.utils.get_writer('txt', os.path.dirname(new_file))
    vtt_writer(result, work['audio'], {'max_line_width': 60, 'max_line_count': None, 'highlight_words': None})
    txt_writer(result, work['audio'], {'max_line_width': 60, 'max_line_count': None, 'highlight_words': None})
    work['vtt'] = new_file
    work['txt'] = work['base'] + '.txt'
    if os.path.isfile("/data/emacsconf/{{ emacsconf_year }}/scripts/upload.sh"):
        subprocess.call(["/data/emacsconf/{{ emacsconf_year }}/scripts/upload.sh", work['vtt'], work['txt']])
    if 'srv2' in work: del work['srv2']
    return work

def generate_text(work):
    with open(work['base'] + '.txt', 'w') as txt:
        for i, caption in enumerate(webvtt.read(work['vtt'])):
            txt.write(caption.text + "\n")
    work['txt'] = work['base'] + '.txt'
    return work

def generate_srv2(work):
    """Generate a SRV2 file."""
    log("Generating SRV2")
    recs = RecordingSet.from_recordings([Recording.from_file(work['audio'])])
    rec_id = recs[0].id
    captions = []
    for i, caption in enumerate(webvtt.read(work['vtt'])):
        if TRIM_AUDIO and i > 2: break
        captions.append(SupervisionSegment(id=rec_id + '-sup' + '%05d' % i, channel=recs[0].channel_ids[0], recording_id=rec_id, start=to_sec(caption.start), duration=to_sec(caption.end) - to_sec(caption.start), text=caption.text, language='English'))
    sups = SupervisionSet.from_segments(captions)
    main = CutSet.from_manifests(recordings=recs, supervisions=sups)
    work['cuts'] = main.trim_to_supervisions(keep_overlapping=False, keep_all_channels=True) 
    cuts_aligned = align_with_torchaudio(work['cuts'])
    root = ET.Element("timedtext")
    doc = ET.SubElement(root, "window")
    for line, aligned in enumerate(cuts_aligned):
        if len(aligned.supervisions) > 0:
            aligned_words = aligned.supervisions[0].alignment['word']
            for w, word in enumerate(aligned_words):
                el = ET.SubElement(doc, 'text',
                                  t=str(float(word.start)*1000),
                                  d=str(float(word.duration)*1000),
                                  w="1",
                                  append="1")
                el.text = word.symbol
                el.tail = "\n"
        else:
            print("No supervisions", aligned)
    tree = ET.ElementTree(root)
    work['srv2'] = work['base'] + '.srv2'
    with open(work['srv2'], "w") as f:
        tree.write(f.buffer)
    return work

def base_name(s):
    """
    Return the base name of file so that we can add extensions to it.
    Remove tokens like --normalized, --recoded, etc.
    Make sure the filename has either --main or --questions.
    """
    s = os.path.basename(s)
    type = 'questions' if '--questions.' in s else 'main'
    if TRIM_AUDIO:
        type = 'test'
    match = re.match('^(emacsconf-[0-9]+-[a-z]+--.*?--.*?)(--|\.)', s)
    if (match):
        return match.group(1) + '--' + type
    else:
        return os.path.splitext(s)[0] + '--' + type
# assert(base_name('/home/sachac/current/sqlite/emacsconf-2022-sqlite--using-sqlite-as-a-data-source-a-framework-and-an-example--andrew-hyatt--normalized.webm.vtt') == 'emacsconf-2022-sqlite--using-sqlite-as-a-data-source-a-framework-and-an-example--andrew-hyatt--main')

log(f"MODEL {MODEL} ALWAYS {ALWAYS} TRIM_AUDIO {TRIM_AUDIO}")
directory = sys.argv[1] if len(sys.argv) > 1 else WORK_DIR

needs_work = get_files_to_work_on(directory)
if len(needs_work) > 0:
    while len(needs_work) > 0:
        if THREADS > 0:
            torch.set_num_threads(THREADS)
            for work in needs_work:
                log("Started processing %s" % work['base'])
                if work['audio']:
                    if ALWAYS or not 'vtt' in work:
                        work = generate_captions(work)
                    if DO_SRV2 and (ALWAYS or not 'srv2' in work):
                        work = generate_srv2(work)
                        #     print("Aligning words", audio_file, datetime.datetime.now())
                        #     word_cuts = align_words(cuts)
                        #     convert_cuts_to_word_timing(audio_file, word_cuts)
                    log("Done %s" % str(work['base']))
                if not 'txt' in work:
                    work = generate_text(work)
            needs_work = get_files_to_work_on(directory)
else:
    log("No work needed.")