Download worker_mfa.py from montreal-forced-align-polygot/MFA-RUST: direct link, hf CLI and curl.
- Browser
- Download file 3.61 kB
-
https://huggingface.co/spaces/montreal-forced-align-polygot/MFA-RUST/resolve/main/worker_mfa.py
- Command line
-
hf download hf://spaces/montreal-forced-align-polygot/MFA-RUST/worker_mfa.py
-
curl -L -o worker_mfa.py https://huggingface.co/spaces/montreal-forced-align-polygot/MFA-RUST/resolve/main/worker_mfa.py
3.61 kB
| #!/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() |