FaceDeer

Simple script for transcribing using Whisper

Sep 20th, 2024 (edited)
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.51 KB | Source Code | 0 0
  1. import os
  2. import json
  3. from transformers import pipeline
  4. import datetime
  5. import signal
  6. from moviepy.editor import AudioFileClip
  7.  
  8. chunk_length = 30
  9. stride_length = (5, 5)
  10.  
  11. kwargs = {"language": "english"}
  12.  
  13. model = "whisper-large-v3-turbo"
  14.  
  15. print("Initializing pipeline...")
  16. pipe = pipeline("automatic-speech-recognition", model="C:\\Git\\" + model, chunk_length_s=chunk_length, stride_length_s=stride_length, return_timestamps=True, generate_kwargs=kwargs)
  17. #  The original full text can roughly be recovered by doing "".join(chunk["text"] for chunk in output["chunks"]).
  18. print("Pipeline initialized.")
  19.  
  20. file_extensions = tuple([".wav", ".mp3", ".wma", ".mp4"])
  21.  
  22. def get_json_file_path(audio_file_path):
  23.   file_extension = os.path.splitext(audio_file_path)[1]
  24.   if file_extension in file_extensions:
  25.     return audio_file_path.replace(file_extension, ".json")
  26.  
  27. def signal_handler(sig, frame):
  28.     global running
  29.     if (running):
  30.         print("Interrupt registered. Finishing current task.")
  31.         running = False
  32.     else:
  33.         print("Interrupt interrupted, will continue processing.")
  34.         running = True
  35.  
  36. def seconds_to_hms(seconds):
  37.     hours = (seconds // 3600)
  38.     minutes = (seconds // 60) % 60
  39.     seconds = seconds % 60
  40.     return f"{hours}:{minutes}:{seconds}"
  41.  
  42. def process_audio_file(audio_file_path):
  43.     """Processes an audio file and saves the result as a JSON file."""
  44.     try:
  45.         # Check if the JSON file already exists
  46.         json_file_path = get_json_file_path(audio_file_path)
  47.         if (json_file_path is None) or os.path.exists(json_file_path):
  48.             return
  49.  
  50.         audio_clip = AudioFileClip(audio_file_path)
  51.         duration_seconds = int(audio_clip.duration)
  52.        
  53.         print(f"Processing {audio_file_path}. Duration: "+seconds_to_hms(duration_seconds))
  54.         start_time = datetime.datetime.now()
  55.         print("Started at time: " + start_time.strftime("%I:%M:%S %p"))
  56.         # Process the audio file
  57.         result = pipe(audio_file_path)
  58.         end_time = datetime.datetime.now()
  59.         time_taken = end_time-start_time
  60.         print("Elapsed time: " + seconds_to_hms(time_taken.seconds))
  61.         result["model"] = model
  62.         result["parameters"] = "chunk_length_s=30, stride_length_s=(5, 5)"
  63.         result["source_path"] = audio_file_path
  64.  
  65.         directory_path = os.path.dirname(audio_file_path)
  66.         last_directory = os.path.basename(directory_path)
  67.         try:
  68.             date = datetime.datetime.fromisoformat(last_directory)
  69.             result["date"] = last_directory
  70.         except ValueError:
  71.             pass
  72.  
  73.         # Save the result as a JSON file
  74.         with open(json_file_path, "w") as f:
  75.             json.dump(result, f, indent=4)
  76.  
  77.         print(f"Saved result to {json_file_path}")
  78.     except Exception as e:
  79.         print(f"Error processing {audio_file_path}: {e}")
  80.  
  81. def process_directory(directory_path):
  82.     """Processes all audio files in a directory and its subdirectories."""
  83.  
  84.     global running
  85.     if not running:
  86.         return
  87.  
  88.     for root, dirs, files in os.walk(directory_path):
  89.         for file in files:
  90.             file = file.lower()
  91.             if file.endswith(file_extensions):
  92.                 audio_file_path = os.path.join(root, file)
  93.                 process_audio_file(audio_file_path)
  94.                 if not running:
  95.                     print("Interrupted.")
  96.                     return
  97.  
  98. running = True
  99. signal.signal(signal.SIGINT, signal_handler)
  100.  
  101. process_directory("D:\\Recordings")
  102.  
Advertisement
Add Comment
Please, Sign In to add comment