import asyncio from sqlalchemy import select from ..core.config import BASE_DIR, PHOTOS_DIR from ..core.db import Base, SessionLocal, engine from ..models.photo_model import Category, Photo DIRECTORY = PHOTOS_DIR async def init_db(): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) async def update_media(): if not DIRECTORY.is_dir(): print (f"{DIRECTORY} not exists") return async with SessionLocal() as session: stmt = select(Photo.filename) result = await session.execute(stmt) existing_filenames = set(result.scalars().all()) cached_categories = {ct.title:ct for ct in (await session.execute(select(Category))).scalars()} new_photos = [] for file_path in DIRECTORY.rglob("*"): if file_path.is_file(): relative_path = file_path.relative_to(DIRECTORY) if file_path.suffix.lower() != ".jpg": continue if file_path.name in existing_filenames: continue category_name = relative_path.parts[0] if len(relative_path.parts) > 1 else None category = cached_categories.get(category_name) if category is None: category = Category(title=category_name) session.add(category) await session.flush() cached_categories[category_name] = category photo = Photo( filename = file_path.name, path = str(file_path.relative_to(BASE_DIR)), category = category, ) new_photos.append(photo) existing_filenames.add(file_path.name) if new_photos: session.add_all(new_photos) await session.commit() async def main(): await init_db() await update_media() if __name__ == "__main__": asyncio.run(main())