File size: 3,614 Bytes
3570431
 
 
 
 
 
 
 
 
 
 
 
 
be3de18
3570431
be3de18
 
3570431
 
 
be3de18
3570431
be3de18
3570431
 
be3de18
3570431
 
 
 
 
 
be3de18
3570431
be3de18
3570431
 
 
be3de18
3570431
 
 
 
 
 
be3de18
 
3570431
 
be3de18
3570431
 
 
be3de18
 
3570431
 
 
 
 
 
 
 
 
 
 
 
 
be3de18
3570431
be3de18
 
 
3570431
 
be3de18
 
 
 
 
3570431
be3de18
 
 
 
 
 
 
 
 
3570431
 
 
 
 
be3de18
 
 
3570431
 
 
 
 
 
be3de18
3570431
 
be3de18
3570431
 
 
 
be3de18
3570431
 
be3de18
3570431
 
be3de18
3570431
 
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
#!/usr/bin/env python3
"""
MFA worker process for Rust MFA aligner
"""
import sys
import json
import os
import shutil
from pathlib import Path

from montreal_forced_aligner.alignment import PretrainedAligner
from praatio import textgrid

MFA_ACOUSTIC   = "english_mfa"
MFA_DICTIONARY = "english_mfa"
MFA_ROOT       = "/mfa"


def parse_textgrid(tg_path):
    """Parse TextGrid and extract word timestamps"""
    tg    = textgrid.openTextgrid(tg_path, includeEmptyIntervals=False)
    names = tg.tierNames
    tier  = next((n for n in names if "word" in n.lower()), names[0] if names else None)
    if not tier:
        return []

    words = []
    for interval in tg.getTier(tier).entries:
        label = interval.label.strip()
        if not label or label.lower() in {"sp", "sil", "<eps>", "spn"}:
            continue
        words.append({
            "word":  label,
            "start": round(float(interval.start), 3),
            "end":   round(float(interval.end),   3),
        })
    return words


def main():
    if len(sys.argv) != 4:
        print(json.dumps({"error": "Invalid arguments"}), file=sys.stderr)
        sys.exit(1)

    wav_path = sys.argv[1]
    text     = sys.argv[2]
    language = sys.argv[3]  # kept for API compatibility

    # Create temporary directory structure
    work_root  = Path("/dev/shm/mfa_work")
    corpus_dir = work_root / "corpus"
    speaker_dir = corpus_dir / "speaker1"
    output_dir = work_root / "output"
    temp_dir   = work_root / "tmp"

    for d in [speaker_dir, output_dir, temp_dir]:
        d.mkdir(parents=True, exist_ok=True)

    # Copy WAV file to corpus
    wav_dest = speaker_dir / "utt.wav"
    shutil.copy2(wav_path, wav_dest)

    # Write text file
    lab_file = speaker_dir / "utt.lab"
    lab_file.write_text(text, encoding="utf-8")

    # Clean output and temp directories
    shutil.rmtree(output_dir, ignore_errors=True)
    shutil.rmtree(temp_dir,   ignore_errors=True)
    output_dir.mkdir(parents=True, exist_ok=True)
    temp_dir.mkdir(parents=True,   exist_ok=True)

    original_stdout = sys.stdout

    try:
        # Redirect stdout → stderr during MFA alignment.
        # MFA prints progress integers (1, 2, …) to stdout which would
        # corrupt the JSON array that Rust reads from this process's stdout.
        sys.stdout = sys.stderr

        aligner = PretrainedAligner(
            corpus_directory    = str(corpus_dir),
            dictionary_path     = MFA_DICTIONARY,
            acoustic_model_path = MFA_ACOUSTIC,
            output_directory    = str(output_dir),
            temporary_directory = str(temp_dir),
            mfa_root_dir        = MFA_ROOT,
            fine_tune           = False,
            jobs                = 1,
            overwrite           = True,
        )
        aligner.setup()
        aligner.align()
        aligner.export_files(str(output_dir))

        # Restore stdout BEFORE printing the result
        sys.stdout = original_stdout

        tg_files = list(output_dir.rglob("*.TextGrid"))
        if not tg_files:
            raise RuntimeError("MFA produced no TextGrid output")

        word_timestamps = parse_textgrid(tg_files[0])
        print(json.dumps(word_timestamps))
        sys.stdout.flush()

    except Exception as e:
        sys.stdout = original_stdout  # always restore
        print(json.dumps({"error": str(e)}), file=sys.stderr)
        sys.exit(1)

    finally:
        # Clean up the temp WAV file passed in by Rust
        try:
            os.unlink(wav_path)
        except Exception:
            pass


if __name__ == "__main__":
    main()