-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphoneme-cmd.py
More file actions
112 lines (95 loc) · 3.05 KB
/
phoneme-cmd.py
File metadata and controls
112 lines (95 loc) · 3.05 KB
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
import os
import sys
import json
import torch
import torchaudio
from transformers.models.wav2vec2 import Wav2Vec2ForCTC, Wav2Vec2Processor
from huggingface_hub import snapshot_download
def load_model(model_dir):
model_file = os.path.join(model_dir, "model.safetensors")
if not os.path.exists(model_file):
print(
json.dumps(
{"status": "downloading", "message": "Starting model download..."}
),
)
try:
# Download the model files
snapshot_download(
repo_id="vitouphy/wav2vec2-xls-r-300m-timit-phoneme",
local_dir=model_dir,
ignore_patterns=["*.bin"],
)
print(
json.dumps(
{"status": "downloading", "message": "Model download complete."}
),
)
except Exception as e:
print(
json.dumps(
{"status": "error", "message": f"Download failed: {str(e)}"}
),
)
sys.exit(1)
else:
print(
json.dumps(
{"status": "found", "message": "Model loaded from local directory."}
),
)
processor = Wav2Vec2Processor.from_pretrained(model_dir)
model = Wav2Vec2ForCTC.from_pretrained(model_dir)
return processor, model
def process_audio(audio_path):
waveform, sample_rate = torchaudio.load(audio_path)
# Resample to 16kHz
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(
orig_freq=sample_rate, new_freq=16000
)
waveform = resampler(waveform)
# Convert to mono
waveform = waveform.mean(dim=0, keepdim=True)
return waveform
def main():
if len(sys.argv) < 3:
print(
json.dumps(
{
"status": "error",
"message": "Usage: script.py <model_dir> <audio_path>",
}
)
)
sys.exit(1)
model_dir = sys.argv[1]
audio_path = sys.argv[2]
try:
processor, model = load_model(model_dir)
waveform = process_audio(audio_path)
input_values = processor(
waveform.squeeze().numpy(), sampling_rate=16000, return_tensors="pt"
).input_values
with torch.no_grad():
logits = model(input_values).logits
predicted_ids = torch.argmax(logits, dim=-1)
transcription = processor.batch_decode(predicted_ids)
result = transcription[0].strip()
if result == "":
print(
json.dumps(
{
"status": "success",
"phonemes": None,
"message": "No phonemes detected.",
}
)
)
else:
print(json.dumps({"status": "success", "phonemes": result}))
except Exception as e:
print(json.dumps({"status": "error", "message": str(e)}))
sys.exit(1)
if __name__ == "__main__":
main()