Сервис для хранения файлов аудио, индексации файлов, записи и выдачи результатов распознавания
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

106 lines
4.3 KiB

from autoLoader.config import FILESAPTH
from autoLoader.loader import ConnectorSFTP
import datetime, os
from autoLoader.database import Audio, get_db_session
from sqlalchemy import inspect
local_path = os.path.join(os.getcwd(), FILESAPTH)
class Loader():
def __init__(self):
self.call_types = ['in']
pass
def filter_call(self, filename: str):
if filename.split("-")[0] in self.call_types:
return True
return False
def check_database(self):
"""Проверяет существование таблиц в БД"""
from autoLoader.database import engine
inspector = inspect(engine)
existing_tables = inspector.get_table_names()
if 'audio' not in existing_tables:
print("❌ Таблица 'audio' не существует в базе данных!")
print("💡 Запустите 'python init_db.py' для создания таблиц")
return False
return True
def load(self):
# Проверяем БД перед началом работы
if not self.check_database():
exit(1)
date_now = datetime.datetime.now()# - datetime.timedelta(days=1)
remote_path = f"/{date_now.strftime('%Y/%m/%d')}"
connector = ConnectorSFTP()
connector.connect(remote_path=remote_path)
sftp_client = connector.sftp
ssh_client = connector.ssh
if sftp_client is None or ssh_client is None:
print("Не удалось подключиться к SFTP. Завершение работы.")
exit(1)
try:
listdir = sftp_client.listdir()
os.makedirs(local_path, exist_ok = True)
for file in listdir:
if self.filter_call(filename=file):
remote_file = f"{file}".lstrip('/')
filepath = os.path.join(local_path, file)
# Проверяем, существует ли файл локально
if os.path.exists(filepath):
print(f"Файл уже существует локально: {file}")
continue
try:
# Скачиваем файл
sftp_client.get(remote_file, filepath)
print(f"📥 Скачан файл: {remote_file}")
# Получаем размер файла
file_size = os.path.getsize(filepath)
# Сохраняем в БД через контекстный менеджер
with get_db_session() as db:
# Проверяем, есть ли уже такой файл в БД
existing_audio = db.query(Audio).filter(Audio.filename == file).first()
if existing_audio:
print(f" Файл {file} уже есть в БД, пропускаем")
continue
# Создаём новую запись
audio = Audio()
audio.index_date = datetime.datetime.now()
audio.filename = file
audio.file_size = file_size
db.add(audio)
# commit произойдёт автоматически при выходе из контекста
print(f"✅ Файл {file} сохранён в БД")
except Exception as e:
print(f"❌ Ошибка при обработке файла {remote_file}: {e}")
# Если файл скачался, но ошибка в БД - удаляем файл
if os.path.exists(filepath):
try:
os.remove(filepath)
print(f"🗑 Файл {file} удалён из-за ошибки")
except:
pass
finally:
# Закрываем соединения
sftp_client.close()
ssh_client.close()