Untitled

 avatar
unknown
plain_text
4 months ago
2.9 kB
2
Indexable
import telebot
from PIL import Image
import io
import numpy as np
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from tensorflow.keras import utils

# Загрузка и подготовка данных MNIST
(x_train_org, y_train_org), (x_test_org, y_test_org) = mnist.load_data()
x_train = x_train_org.reshape(60000, 784).astype('float32') / 255
x_test = x_test_org.reshape(10000, 784).astype('float32') / 255
y_train = utils.to_categorical(y_train_org, 10)
y_test = utils.to_categorical(y_test_org, 10)

# Создание и обучение модели
model = Sequential([
    Dense(800, input_dim=784, activation="relu"),
    Dense(400, activation="relu"),
    Dense(10, activation="softmax")
])
model.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=128, epochs=15, verbose=1)
model.save_weights('model.weights.h5')
model.load_weights('model.weights.h5')

def send_message_bot():
    # Инициализация бота
    bot = telebot.TeleBot('7628175392:AAHXaKwbbEt5qaGAcY7usbMfEiRWLj-RFeI')

    # Обработка фотографий
    @bot.message_handler(content_types=['photo'])
    def get_user_pics(message):
        try:
            file_id = message.photo[-1].file_id
            file_info = bot.get_file(file_id)
            downloaded_file = bot.download_file(file_info.file_path)
            print("Загружено изображение:", file_info.file_path)

            # Открытие изображения из байтов и предобработка
            image_size = 28
            img = Image.open(io.BytesIO(downloaded_file)).convert('L')
            img = img.resize((image_size, image_size))

            img_arr = np.array(img).astype('float32') / 255
            img_arr = 1 - img_arr  # Инвертируем изображение, если фон белый, а цифра чёрная
            img_arr = img_arr.reshape((1, image_size * image_size))
            print("Размер изображения после обработки:", img_arr.shape)

            # Предсказание модели
            result = model.predict(img_arr)
            predicted_digit = np.argmax(result[0])
            print("Предсказано число:", predicted_digit)

            # Отправка результата пользователю
            bot.send_message(message.chat.id, f'Я думаю, что это цифра: {predicted_digit}')
        except Exception as e:
            print(f"Ошибка: {e}")
            bot.send_message(message.chat.id, f'Произошла ошибка: {e}')

    bot.infinity_polling(timeout=10, long_polling_timeout=5)

send_message_bot()
Editor is loading...
Leave a Comment