#!/usr/bin/env python3 """Revert book cover URLs from full URLs back to relative paths""" import asyncio import sqlite3 from app.database import async_session from app.models import Book, User from sqlalchemy import select async def revert_cover_urls(): """Convert full URLs back to relative paths""" async with async_session() as db: # Get all users to find the ABS URL patterns result = await db.execute(select(User)) users = result.scalars().all() if not users: print("No users found") return # Get unique ABS URLs abs_urls = set(u.abs_url.rstrip('/') for u in users) print(f"Found ABS URLs: {abs_urls}") # Get all books with cover URLs result = await db.execute( select(Book).where( Book.cover_url.isnot(None), Book.cover_url != '' ) ) books = result.scalars().all() reverted_count = 0 for book in books: if book.cover_url: # Check if it's a full URL for abs_url in abs_urls: if book.cover_url.startswith(abs_url): # Strip the ABS URL to get relative path old_url = book.cover_url book.cover_url = book.cover_url[len(abs_url):] print(f"Reverted: {book.title[:50]}") print(f" Old: {old_url}") print(f" New: {book.cover_url}") print() reverted_count += 1 break await db.commit() print(f"\nReverted {reverted_count} cover URLs to relative paths") if __name__ == "__main__": print("Reverting book cover URLs to relative paths...") print("-" * 60) asyncio.run(revert_cover_urls())