Guest User

Untitled

a guest
Aug 3rd, 2024
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.09 KB | Source Code | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. # prerequisites: as described in https://alphacephei.com/vosk/install and also python module `sounddevice` (simply run command `pip install sounddevice`)
  4. # Example usage using Dutch (nl) recognition model: `python test_microphone.py -m nl`
  5. # For more help run: `python test_microphone.py -h`
  6.  
  7. import argparse
  8. import queue
  9. import sys
  10. import sounddevice as sd
  11. import json
  12. from pywinauto.keyboard import send_keys
  13.  
  14. from vosk import Model, KaldiRecognizer
  15.  
  16. q = queue.Queue()
  17.  
  18. def int_or_str(text):
  19.     """Helper function for argument parsing."""
  20.     try:
  21.         return int(text)
  22.     except ValueError:
  23.         return text
  24.  
  25. def callback(indata, frames, time, status):
  26.     """This is called (from a separate thread) for each audio block."""
  27.     if status:
  28.         print(status, file=sys.stderr)
  29.     q.put(bytes(indata))
  30.  
  31. parser = argparse.ArgumentParser(add_help=False)
  32. parser.add_argument(
  33.     "-l", "--list-devices", action="store_true",
  34.     help="show list of audio devices and exit")
  35. args, remaining = parser.parse_known_args()
  36. if args.list_devices:
  37.     print(sd.query_devices())
  38.     parser.exit(0)
  39. parser = argparse.ArgumentParser(
  40.     description=__doc__,
  41.     formatter_class=argparse.RawDescriptionHelpFormatter,
  42.     parents=[parser])
  43. parser.add_argument(
  44.     "-f", "--filename", type=str, metavar="FILENAME",
  45.     help="audio file to store recording to")
  46. parser.add_argument(
  47.     "-d", "--device", type=int_or_str,
  48.     help="input device (numeric ID or substring)")
  49. parser.add_argument(
  50.     "-r", "--samplerate", type=int, help="sampling rate")
  51. parser.add_argument(
  52.     "-m", "--model", type=str, help="language model; e.g. en-us, fr, nl; default is en-us")
  53. args = parser.parse_args(remaining)
  54.  
  55. try:
  56.     if args.samplerate is None:
  57.         device_info = sd.query_devices(args.device, "input")
  58.         # soundfile expects an int, sounddevice provides a float:
  59.         args.samplerate = int(device_info["default_samplerate"])
  60.        
  61.     if args.model is None:
  62.         model = Model(lang="pl")
  63.     else:
  64.         model = Model(lang=args.model)
  65.  
  66.     if args.filename:
  67.         dump_fn = open(args.filename, "wb")
  68.     else:
  69.         dump_fn = None
  70.  
  71.     with sd.RawInputStream(samplerate=args.samplerate, blocksize = 8000, device=args.device,
  72.             dtype="int16", channels=1, callback=callback):
  73.         print("#" * 80)
  74.         print("Press Ctrl+C to stop the recording")
  75.         print("#" * 80)
  76.  
  77.         rec = KaldiRecognizer(model, args.samplerate)
  78.         while True:
  79.             data = q.get()
  80.             if rec.AcceptWaveform(data):
  81.                
  82.                 result = rec.Result()
  83.                 parsed = json.loads(result)
  84.                 send_keys(parsed["text"], with_spaces = True)
  85.                
  86.                 print(parsed["text"])
  87.                
  88.             else:
  89.                 print(rec.PartialResult())
  90.             if dump_fn is not None:
  91.                 dump_fn.write(data)
  92.  
  93.  
  94. except KeyboardInterrupt:
  95.     print("\nDone")
  96.     parser.exit(0)
  97. except Exception as e:
  98.     parser.exit(type(e).__name__ + ": " + str(e))
  99.  
Advertisement
Add Comment
Please, Sign In to add comment