File size: 2,309 Bytes
531b9c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
'Cross-score a shared set of transcripts with differently tokenized CTC encoders.'

import numpy as np

from multiview_decode import candidate_paths
from multiview_decode import score_paths

from train import normalize

def cross_scores(model, tokenizer, views, paths, texts, blank, normalize_text=normalize):
    alternatives = {}
    for path, prediction in paths.items():
        text = normalize_text(prediction)
        if text in texts:
            alternatives[path] = text
    original_count = len(alternatives)
    represented = set(alternatives.values())
    for text in texts:
        if text in represented:
            continue
        path = tuple(tokenizer.encode(text))
        if normalize_text(model.render_tokens(path)) == text and path not in alternatives:
            alternatives[path] = text

    scores = score_paths(model, views, alternatives, blank)
    indices = np.array([texts[text] for text in alternatives.values()], dtype=np.int64)
    result = np.full(len(texts), -np.inf)
    np.maximum.at(result, indices, scores)
    native = None
    choices = scores[:original_count]
    if np.isfinite(choices).any():
        native = indices[choices.argmax()]
    return result, native

def candidates(models, views, extra=(), normalize_text=normalize):
    native = [candidate_paths(model, sample) for (model, _, _), sample in zip(models, views)]
    transcripts = dict.fromkeys(normalize_text(text) for row in native for text in row.values())
    transcripts.update(dict.fromkeys(normalize_text(text) for text in extra))
    texts = {text: index for index, text in enumerate(transcripts)}
    results = [cross_scores(model, tokens, audio, paths, texts, blank, normalize_text)
               for (model, tokens, blank), audio, paths in zip(models, views, native)]
    return list(texts), np.stack([row[0] for row in results]), [row[1] for row in results]

def fusion_indices(scores, weights, native):
    defaults = [index if index is not None else 0 for index in native]
    best = [row.argmax() if np.isfinite(row).any() else i for row, i in zip(scores, defaults)]
    finite = np.flatnonzero(np.isfinite(scores).all(axis=0))
    fused = [finite[(weight @ scores[:, finite]).argmax()] if len(finite) else defaults[0] for weight in weights]
    return defaults + best + fused, finite