-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathAdvanced Voice-to-Text Transcription using Python and Whisper
More file actions
43 lines (38 loc) · 1.76 KB
/
Advanced Voice-to-Text Transcription using Python and Whisper
File metadata and controls
43 lines (38 loc) · 1.76 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
import os, queue, json, sounddevice as sd, soundfile as sf, numpy as np, whisper
SAMPLE_RATE=16000
CHANNELS=1
MODEL_NAME="small"
DEVICE="cpu"
class Recorder:
def __init__(self,sample_rate=SAMPLE_RATE,channels=CHANNELS):
self.sample_rate=sample_rate;self.channels=channels;self.q=queue.Queue()
def _callback(self,indata,frames,time,status):
if status:print(status);self.q.put(indata.copy())
def record(self,duration,out_path):
with sd.InputStream(samplerate=self.sample_rate,channels=self.channels,dtype="int16",callback=self._callback):
frames=[];import time;start=time.time()
while time.time()-start<duration:frames.append(self.q.get())
audio=np.concatenate(frames,axis=0);sf.write(out_path,audio,self.sample_rate)
print(f"Recorded {duration}s to {out_path}")
class Transcriber:
def __init__(self,model_name=MODEL_NAME,device=DEVICE):
print("Loading model...");self.model=whisper.load_model(model_name,device=device)
def transcribe(self,path):
result=self.model.transcribe(path);return result["text"]
def save_text(text,path):
os.makedirs(os.path.dirname(path),exist_ok=True)
with open(path,"w",encoding="utf-8")as f:f.write(text)
print(f"Saved transcript to {path}")
def main():
print("1. Record new audio\n2. Transcribe existing file")
choice=input("Choose (1/2): ")
if choice=="1":
dur=float(input("Enter duration in seconds: "))
rec_path="recorded.wav";Recorder().record(dur,rec_path);file_path=rec_path
else:
file_path=input("Enter audio file path: ")
transcriber=Transcriber()
text=transcriber.transcribe(file_path)
print("\n--- TRANSCRIPT ---\n",text)
save_text(text,"transcript.txt")
if __name__=="__main__":main()