Files
telegram-helper-bot/scripts/voice_cleanup.py
2026-02-01 22:49:25 +03:00

104 lines
4.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
Скрипт для диагностики и очистки проблем с голосовыми файлами
"""
import asyncio
import os
import sys
from pathlib import Path
# Добавляем корневую директорию проекта в путь
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from database.async_db import AsyncBotDB
from helper_bot.handlers.voice.cleanup_utils import VoiceFileCleanupUtils
from logs.custom_logger import logger
async def main():
"""Основная функция скрипта"""
try:
# Инициализация базы данных
db_path = "database/tg-bot-database.db"
if not os.path.exists(db_path):
logger.error(f"База данных не найдена: {db_path}")
return
bot_db = AsyncBotDB(db_path)
cleanup_utils = VoiceFileCleanupUtils(bot_db)
print("=== Диагностика голосовых файлов ===")
# Запускаем полную диагностику
diagnostic_result = await cleanup_utils.run_full_diagnostic()
print(f"\n📊 Статистика диска:")
if "error" in diagnostic_result["disk_stats"]:
print(f" ❌ Ошибка: {diagnostic_result['disk_stats']['error']}")
else:
stats = diagnostic_result["disk_stats"]
print(f" 📁 Директория: {stats['directory']}")
print(f" 📄 Всего файлов: {stats['total_files']}")
print(f" 💾 Размер: {stats['total_size_mb']} MB")
print(f"\n🗄️ База данных:")
print(f" 📝 Записей в БД: {diagnostic_result['db_records_count']}")
print(f" 🔍 Записей без файлов: {diagnostic_result['orphaned_db_records_count']}")
print(f" 📁 Файлов без записей: {diagnostic_result['orphaned_files_count']}")
print(f"\n📋 Статус: {diagnostic_result['status']}")
if diagnostic_result['status'] == 'issues_found':
print("\n⚠️ Найдены проблемы!")
if diagnostic_result['orphaned_db_records_count'] > 0:
print(f"\n🗑️ Записи в БД без файлов (первые 10):")
for file_name, user_id in diagnostic_result['orphaned_db_records']:
print(f" - {file_name} (user_id: {user_id})")
if diagnostic_result['orphaned_files_count'] > 0:
print(f"\n📁 Файлы без записей в БД (первые 10):")
for file_path in diagnostic_result['orphaned_files']:
print(f" - {file_path}")
# Предлагаем очистку
print("\n🧹 Хотите выполнить очистку?")
print("1. Удалить записи в БД без файлов")
print("2. Удалить файлы без записей в БД")
print("3. Выполнить полную очистку")
print("4. Выход")
choice = input("\nВыберите действие (1-4): ").strip()
if choice == "1":
print("\n🗑️ Удаление записей в БД без файлов...")
deleted = await cleanup_utils.cleanup_orphaned_db_records(dry_run=False)
print(f"✅ Удалено {deleted} записей")
elif choice == "2":
print("\n📁 Удаление файлов без записей в БД...")
deleted = await cleanup_utils.cleanup_orphaned_files(dry_run=False)
print(f"✅ Удалено {deleted} файлов")
elif choice == "3":
print("\n🧹 Полная очистка...")
db_deleted = await cleanup_utils.cleanup_orphaned_db_records(dry_run=False)
files_deleted = await cleanup_utils.cleanup_orphaned_files(dry_run=False)
print(f"✅ Удалено {db_deleted} записей в БД и {files_deleted} файлов")
elif choice == "4":
print("👋 Выход...")
else:
print("❌ Неверный выбор")
else:
print("\n✅ Проблем не найдено!")
except Exception as e:
logger.error(f"Ошибка в скрипте: {e}")
print(f"❌ Ошибка: {e}")
if __name__ == "__main__":
asyncio.run(main())