import asyncio from uuid import UUID from sqlalchemy import select from core.database import async_session_factory from core.deps import get_arq_pool from models.kb_article import KBArticle from core.logging import get_logger logger = get_logger(__name__) async def backfill_summaries(): """ Identifies KB articles missing AI summaries and enqueues them for re-indexing. """ async with async_session_factory() as db: # 1. Find articles with NULL summary stmt = select(KBArticle.id).where( KBArticle.summary.is_(None), KBArticle.deleted_at.is_(None) ) result = await db.execute(stmt) article_ids = result.scalars().all() if not article_ids: print("✅ All Knowledge Base articles already have summaries.") return print(f"🔍 Found {len(article_ids)} articles missing summaries. Enqueueing for AI processing...") # 2. Get ARQ pool # Mimic get_arq_pool dependency logic import redis.asyncio as redis from core.config import get_settings settings = get_settings() redis_pool = redis.from_url(settings.REDIS_URL, decode_responses=False) # We'll use a local mock or a real one if available. # But wait, I can just use the arq_pool if I can get it. # For a script, I'll connect to Redis directly. from arq import create_pool from arq.connections import RedisSettings # Extract host/port from REDIS_URL # redis://localhost:6379/0 redis_settings = RedisSettings.from_dsn(settings.REDIS_URL) arq_pool = await create_pool(redis_settings) # 3. Enqueue Jobs for a_id in article_ids: await arq_pool.enqueue_job("index_kb_article", a_id) print(f" -> Enqueued: {a_id}") await arq_pool.close() print(f"🚀 Successfully enqueued {len(article_ids)} background tasks.") if __name__ == "__main__": asyncio.run(backfill_summaries())