File size: 4,232 Bytes
ba96aa5
 
600bbe2
 
ba96aa5
 
 
 
 
600bbe2
ba96aa5
600bbe2
 
ba96aa5
600bbe2
 
 
 
 
 
ba96aa5
600bbe2
ba96aa5
 
600bbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba96aa5
600bbe2
 
ba96aa5
600bbe2
ba96aa5
600bbe2
 
 
ba96aa5
600bbe2
 
 
 
 
ba96aa5
600bbe2
 
ba96aa5
 
 
 
 
 
 
600bbe2
ba96aa5
 
600bbe2
ba96aa5
 
 
 
 
 
 
 
 
 
 
 
 
 
600bbe2
 
ba96aa5
600bbe2
 
ba96aa5
600bbe2
ba96aa5
600bbe2
ba96aa5
600bbe2
 
 
 
 
 
ba96aa5
 
600bbe2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import os
import subprocess
import telebot
from telebot import types

TOKEN = "7709328099:AAHvvz2Dqkzb2c0lNh9OViTBnUoW6ZcpreA"
ALLOWED_EXTENSIONS = {'mp4', 'avi', 'mov', 'mkv'}
TEMP_DIR = "temp_files"

bot = telebot.TeleBot(TOKEN)

# Хранилище данных пользователя
user_data = {}

@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
    bot.reply_to(message, 
        "Привет! Отправь мне видео, и я интерполирую кадры до нужного FPS.\n"
        "Инструкция:\n"
        "1. Отправь видео файл\n"
        "2. Укажи желаемый FPS (целое число)\n"
        "3. Жди результат обработки"
    )

@bot.message_handler(content_types=['video'])
def handle_video(message):
    try:
        # Скачивание файла
        file_info = bot.get_file(message.video.file_id)
        downloaded_file = bot.download_file(file_info.file_path)
        
        # Создание временной директории
        os.makedirs(TEMP_DIR, exist_ok=True)
        
        # Сохранение файла
        ext = file_info.file_path.split('.')[-1] if file_info.file_path else 'mp4'
        input_path = os.path.join(TEMP_DIR, f"input_{message.chat.id}.{ext}")
        
        with open(input_path, 'wb') as new_file:
            new_file.write(downloaded_file)
        
        user_data[message.chat.id] = {'input_path': input_path}
        
        # Запрос FPS
        msg = bot.send_message(message.chat.id, "Видео получено. Введите желаемый FPS:")
        bot.register_next_step_handler(msg, process_fps)

    except Exception as e:
        bot.reply_to(message, f"Ошибка: {str(e)}")

def process_fps(message):
    try:
        chat_id = message.chat.id
        target_fps = int(message.text)
        
        if target_fps <= 0:
            raise ValueError("FPS должен быть положительным числом")
        
        if chat_id not in user_data or not os.path.exists(user_data[chat_id]['input_path']):
            bot.send_message(chat_id, "Ошибка: видео не найдено")
            return

        input_path = user_data[chat_id]['input_path']
        output_path = os.path.join(TEMP_DIR, f"output_{chat_id}.mp4")

        # Получаем исходный FPS
        cmd = f"ffprobe -v error -select_streams v:0 -show_entries stream=r_frame_rate -of default=noprint_wrappers=1:nokey=1 {input_path}"
        original_fps = subprocess.check_output(cmd, shell=True).decode().strip().split('/')
        original_fps = float(original_fps[0])/float(original_fps[1])
        
        if target_fps <= original_fps:
            bot.send_message(chat_id, f"Целевой FPS должен быть больше исходного ({original_fps:.2f})")
            return

        # Обработка видео
        cmd = [
            'ffmpeg',
            '-i', input_path,
            '-vf', f'minterpolate=fps={target_fps}',
            '-c:v', 'libx264',
            '-preset', 'medium',
            '-crf', '23',
            '-y',
            output_path
        ]
        
        subprocess.run(cmd, check=True, timeout=300)
        
        # Отправка результата
        with open(output_path, 'rb') as video_file:
            bot.send_video(chat_id, video_file)
        
    except ValueError:
        bot.send_message(chat_id, "Пожалуйста, введите корректное целое число FPS")
    except subprocess.TimeoutExpired:
        bot.send_message(chat_id, "Обработка заняла слишком много времени")
    except Exception as e:
        bot.send_message(chat_id, f"Ошибка при обработке: {str(e)}")
    finally:
        # Очистка временных файлов
        if chat_id in user_data:
            for path in [user_data[chat_id].get('input_path'), output_path]:
                if path and os.path.exists(path):
                    os.remove(path)
            del user_data[chat_id]

if __name__ == '__main__':
    bot.polling(none_stop=True)