Spaces:
Sleeping
Sleeping
| 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 = {} | |
| def send_welcome(message): | |
| bot.reply_to(message, | |
| "Привет! Отправь мне видео, и я интерполирую кадры до нужного FPS.\n" | |
| "Инструкция:\n" | |
| "1. Отправь видео файл\n" | |
| "2. Укажи желаемый FPS (целое число)\n" | |
| "3. Жди результат обработки" | |
| ) | |
| 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) |