Technical Guide

Video Transcription with Google Colab

A free and straightforward guide to transcribe your video audio into .SRT subtitle files using Google Colab and Python.

Python Google Colab Speech Recognition SRT
Video Transcription Guide

Introduction

This guide will walk you through the process of transcribing audio from video files into .SRT format subtitle files using Google Colab. This method is completely free and requires no specialized software installation on your computer.

With this solution, you can:

  • Extract audio from video files
  • Transcribe spoken content into text
  • Generate properly formatted .SRT subtitle files
  • Work with different languages (configurable)

Step-by-Step Procedure

1 Open Google Colab

Navigate to Google Colab and create a new notebook.

2 Paste the Code

Copy the following code and paste it into the Colab notebook cell:

!pip install SpeechRecognition
from google.colab import files
import subprocess
import os
import speech_recognition as sr
import datetime

def extract_audio():
    print("Upload a video file...")
    uploaded = files.upload()
    video_filename = list(uploaded.keys())[0]
    audio_filename = os.path.splitext(video_filename)[0] + ".wav"
    subprocess.run(["ffmpeg", "-i", video_filename, "-ac", "1", "-ar", "16000", audio_filename], check=True)
    print("Extraction completed! Download the audio:")
    files.download(audio_filename)

def transcribe_audio():
    print("Upload an audio file for transcription...")
    uploaded = files.upload()
    audio_filename = list(uploaded.keys())[0]
    subtitle_filename = os.path.splitext(audio_filename)[0] + ".srt"
    recognizer = sr.Recognizer()
    with sr.AudioFile(audio_filename) as source:
        duration = int(source.DURATION) # Total duration of the audio in seconds
        chunk_size = 5 # Seconds for each segment
        subtitles = []
        for i in range(0, duration, chunk_size):
            source_audio = recognizer.record(source, duration=chunk_size)
            try:
                text = recognizer.recognize_google(source_audio, language="it-IT")

                start_time = str(datetime.timedelta(seconds=i)) + ",000"
                end_time = str(datetime.timedelta(seconds=i + chunk_size)) + ",000"
                subtitles.append(f"{len(subtitles) + 1}\n{start_time} --> {end_time}\n{text}\n\n")
            except sr.UnknownValueError:
                continue
            except sr.RequestError:
                print("Error in transcription request.")
                return
    with open(subtitle_filename, "w") as f:
        f.writelines(subtitles)
    print("Transcription completed! Download the subtitle file:")
    files.download(subtitle_filename)

print("Choose an operation:")
print("1: Extract audio from a video")
print("2: Transcribe an audio file into subtitles")
choice = input("Enter 1 or 2: ")

if choice == "1":
    extract_audio()
elif choice == "2":
    transcribe_audio()
else:
    print("Invalid choice. Try again.")
3 Run the Code

Click on the play button (run cell) or press Shift+Enter to execute the code.

4 Choose a Function

When prompted, enter the number of the function you want to run:

  • Option 1: Extract audio from a video file
  • Option 2: Transcribe an audio file into subtitles
5 Upload and Process Files

Follow the prompts to upload your video or audio file. The script will:

  • For Option 1: Extract audio and provide a download link for the .wav file
  • For Option 2: Create a .srt subtitle file and provide a download link

Customization Options

Changing Language

To change the recognition language, modify the language parameter in the line:

text = recognizer.recognize_google(source_audio, language="it-IT")

For example, use:

  • language="en-US" for US English
  • language="es-ES" for Spanish
  • language="fr-FR" for French
  • language="de-DE" for German
Adjusting Chunk Size

To adjust the length of each subtitle segment, change the chunk_size variable:

chunk_size = 5 # Seconds for each segment

A smaller value will create more, shorter subtitles; a larger value will create fewer, longer subtitles.

Benefits of This Approach

Free to Use

No subscription or paid software required

Cloud-Based

No need to install anything on your computer

Multi-Language

Works with various languages by changing a single parameter

Automatic Formatting

Creates perfectly formatted .SRT files ready to use

Conclusion

This method provides a quick, free, and effective solution for generating subtitle files from video content. It utilizes Google's powerful speech recognition capabilities without requiring technical expertise or expensive software.

Happy transcribing!

Home