Исправь ощибку в коде UnboundLocalError: local variable 'end_frame' referenced before assignment

import pyaudio
import wave
import speech_recognition as sr
import numpy as np
import re
import contextlib

# Установка параметров записи
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 1024
WAVE_OUTPUT_FILENAME = "output.wav"
BEEP_FILENAME = "beep.wav"


def record_audio():
    audio = pyaudio.PyAudio()
    stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)

    print("Запись аудио... Нажмите Ctrl+C для остановки.")
    frames = []

    try:
        while True:
            data = stream.read(CHUNK)
            frames.append(data)
    except KeyboardInterrupt:
        print("Запись остановлена.")

    stream.stop_stream()
    stream.close()
    audio.terminate()

    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(audio.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()


def create_beep():
    beep_duration = 0.5  # продолжительность звука "пик" (в секундах)
    beep_frequency = 1000  # частота "пика"

    t = np.linspace(0, beep_duration, int(RATE * beep_duration), False)
    beep = 0.5 * np.sin(2 * np.pi * beep_frequency * t)
    beep = (beep * np.iinfo(np.int16).max).astype(np.int16)

    # Сохранение звука "пик" в файл
    with wave.open(BEEP_FILENAME, 'wb') as wf:
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(2)  # 16 бит
        wf.setframerate(RATE)
        wf.writeframes(beep.tobytes())


def remove_profanity(audio_file):
    # Определите ненормативную лексику
    profanities = ["мат1", "мат2", "мат3"]  # Замените на реальные слова
    recognizer = sr.Recognizer()

    # Распознавание аудиодорожки
    with sr.AudioFile(audio_file) as source:
        audio_data = recognizer.record(source)

    try:
        # Преобразование аудио в текст
        recognized_text = recognizer.recognize_google(audio_data, language='ru-RU')
        print("Распознанный текст:", recognized_text)

        modified_audio = bytearray()
        start_time = 0
        audio_segments = []

        with wave.open(audio_file, 'rb') as wf:
            frame_rate = wf.getframerate()
            n_channels = wf.getnchannels()
            frame_width = wf.getsampwidth()
            n_frames = wf.getnframes()
            original_audio = wf.readframes(n_frames)

        for profanity in profanities:
            profanity_regex = re.compile(r'\b' + re.escape(profanity) + r'\b', re.IGNORECASE)
            matches = list(profanity_regex.finditer(recognized_text))

            for match in matches:
                start_index = match.start()
                end_index = match.end()

                # Расчет времени начала и конца ненормативной лексики
                start_time_audio = (
                            recognized_text[:start_index].count(' ') * 1000 * 0.1)  # Предполагаем 100 мс на слово
                end_time_audio = (recognized_text[:end_index].count(' ') * 1000 * 0.1)

                start_frame = int(start_time_audio / 1000 * frame_rate)
                end_frame = int(end_time_audio / 1000 * frame_rate)

                # Добавляем аудиосегмент до мата
                modified_audio.extend(
                    original_audio[start_frame * frame_width * n_channels:end_frame * frame_width * n_channels])

                # Добавляем звук "пик"
                with wave.open(BEEP_FILENAME, 'rb') as beep_wf:
                    beep_data = beep_wf.readframes(beep_wf.getnframes())
                    modified_audio.extend(beep_data)

                # Обновляем позицию для следующего сегмента
                start_time = end_index

            # Добавляем оставшиеся аудиофреймы
        modified_audio.extend(original_audio[end_frame * frame_width * n_channels:])

        # Сохранение итогового аудиофайла
        with wave.open("cleaned_output.wav", 'wb') as wf:
            wf.setnchannels(n_channels)
            wf.setsampwidth(frame_width)
            wf.setframerate(frame_rate)
            wf.writeframes(modified_audio)

    except sr.UnknownValueError:
        print("Google Speech Recognition не смог распознать аудио")
    except sr.RequestError as e:
        print(f"Ошибка запроса к Google Speech Recognition service; {e}")


if __name__ == "__main__":
    create_beep()
    record_audio()
    remove_profanity(WAVE_OUTPUT_FILENAME)