исправь ошибки
import tensorflow as tf
import json
import numpy as np
import re
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.preprocessing.text import Tokenizer
from sklearn.preprocessing import LabelBinarizer
from nltk.corpus import stopwords
from nltk.stem.snowball import RussianStemmer
import nltk

# Загрузка необходимых данных NLTK
nltk.download('stopwords')


def load_data():
    try:
        with open('bd.json', 'r', encoding='utf-8') as file:
            data = json.load(file)
        return data
    except Exception as error:
        print('Ошибка при загрузке данных:', error)
        raise


def preprocess_text(text):
    stemmer = RussianStemmer()
    text = text.lower()
    tokens = re.findall(r'[а-яё]+', text)
    tokens = [word for word in tokens if word not in stopwords.words('russian')]
    stemmed_tokens = [stemmer.stem(token) for token in tokens]
    return stemmed_tokens


def create_word_index(all_tokens):
    tokenizer = Tokenizer()
    tokenizer.fit_on_texts(all_tokens)
    return tokenizer


def vectorize_questions(questions_tokens, tokenizer, max_length):
    # Преобразуем списки токенов в строку для работы токенайзера
    text_data = [' '.join(tokens) for tokens in questions_tokens]
    sequences = tokenizer.texts_to_sequences(text_data)
    return pad_sequences(sequences, maxlen=max_length, padding='post')


def train_model(data):
    # Предобрабатываем вопросы в токены
    questions_tokens = [preprocess_text(item['question']) for item in data]
    all_tokens = [tokens for tokens in questions_tokens]  # Используем все токены для настройки токенайзера
    tokenizer = create_word_index(all_tokens)

    # Устанавливаем максимальную длину для паддинга
    max_length = max(len(tokens) for tokens in questions_tokens)

    X_data = vectorize_questions(questions_tokens, tokenizer, max_length)
    X = np.array(X_data)

    # Бинаризуем ответы
    lb = LabelBinarizer()
    Y_data = lb.fit_transform([item['answer'] for item in data])
    Y = np.array(Y_data)

    # Создаем и компилируем модель
    model = tf.keras.Sequential([
        tf.keras.layers.Embedding(input_dim=len(tokenizer.word_index) + 1, output_dim=128, input_length=max_length),
        tf.keras.layers.LSTM(units=64, return_sequences=False),
        tf.keras.layers.Dropout(rate=0.5),
        tf.keras.layers.Dense(units=Y.shape[1], activation='softmax')
    ])

    model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

    model.fit(X, Y, epochs=500, batch_size=8, validation_split=0.2, verbose=2)

    return model, tokenizer, max_length, lb


def predict_answer(model, tokenizer, input_question, max_length, lb):
    tokens = preprocess_text(input_question)
    input_vector = vectorize_questions([tokens], tokenizer, max_length)
    prediction = model.predict(input_vector)

    predicted_index = np.argmax(prediction, axis=1)
    return lb.inverse_transform(predicted_index)[0]


def main():
    try:
        data = load_data()
        model, tokenizer, max_length, lb = train_model(data)

        while True:
            input_question = input('Введите вопрос (или "exit" для выхода): ')
            if input_question.lower() == 'exit':
                break
            answer = predict_answer(model, tokenizer, input_question, max_length, lb)
            print('Ответ:', answer)
    except Exception as error:
        print('Ошибка в главной функции:', error)


if __name__ == "__main__":
    main()