File size: 4,094 Bytes
301c4bf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | """
Migration script: Move existing thumbnails from flat structure to subdirectories.
Old structure:
data/thumbnails/12345.jpg
New structure (10k files per dir):
data/thumbnails/0/12345.jpg (media_id 0-9999)
data/thumbnails/1/12345.jpg (media_id 10000-19999)
data/thumbnails/N/... (media_id N*10000 to (N+1)*10000-1)
Run this once after updating to the new thumbnail structure.
"""
from __future__ import annotations
import sys
import shutil
from pathlib import Path
# Add project root to path
BASE_DIR = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(BASE_DIR))
from app.core.config import THUMBNAILS_DIR
from app.services.hf_sync import HF_FILES_PER_DIR, get_thumb_local_path
def migrate_thumbnails(dry_run: bool = False) -> None:
"""Move thumbnails from flat structure to subdirectories."""
if not THUMBNAILS_DIR.exists():
print("No thumbnails directory found. Nothing to migrate.")
return
# Find thumbnails in the root directory (old structure)
root_thumbs = list(THUMBNAILS_DIR.glob("*.jpg"))
if not root_thumbs:
print("No thumbnails in root directory. Migration not needed.")
return
print(f"Found {len(root_thumbs)} thumbnails to migrate.")
moved = 0
skipped = 0
errors = 0
for thumb_path in root_thumbs:
# Parse media_id from filename
try:
media_id = int(thumb_path.stem)
except ValueError:
print(f" Skipping non-numeric file: {thumb_path.name}")
skipped += 1
continue
# Get new path in subdirectory
new_path = get_thumb_local_path(media_id)
# Skip if already exists
if new_path.exists():
print(f" Skipping {thumb_path.name} (already exists in subdirectory)")
skipped += 1
continue
if dry_run:
print(f" Would move: {thumb_path.name} -> {new_path.relative_to(THUMBNAILS_DIR)}")
moved += 1
continue
try:
new_path.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(thumb_path), str(new_path))
moved += 1
except Exception as e:
print(f" Error moving {thumb_path.name}: {e}")
errors += 1
print(f"\nMigration complete: {moved} moved, {skipped} skipped, {errors} errors.")
if not dry_run and moved > 0:
# Remove empty __pycache__ if created
pycache = THUMBNAILS_DIR / "__pycache__"
if pycache.exists():
shutil.rmtree(pycache, ignore_errors=True)
def verify_migration() -> None:
"""Verify that no thumbnails remain in the root directory."""
if not THUMBNAILS_DIR.exists():
print("No thumbnails directory found.")
return
root_thumbs = list(THUMBNAILS_DIR.glob("*.jpg"))
if root_thumbs:
print(f"WARNING: {len(root_thumbs)} thumbnails still in root directory:")
for t in root_thumbs[:10]:
print(f" - {t.name}")
if len(root_thumbs) > 10:
print(f" ... and {len(root_thumbs) - 10} more")
else:
print("OK: No thumbnails in root directory.")
# Count thumbnails in subdirectories
subdirs = [d for d in THUMBNAILS_DIR.iterdir() if d.is_dir() and d.name.isdigit()]
total = sum(len(list(d.glob("*.jpg"))) for d in subdirs)
print(f"Subdirectories: {len(subdirs)}, Total thumbnails: {total}")
for d in sorted(subdirs, key=lambda x: int(x.name)):
count = len(list(d.glob("*.jpg")))
print(f" thumbnails/{d.name}/: {count} files")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Migrate thumbnails to subdirectory structure")
parser.add_argument("--dry-run", action="store_true", help="Show what would be moved without actually moving")
parser.add_argument("--verify", action="store_true", help="Verify migration status")
args = parser.parse_args()
if args.verify:
verify_migration()
else:
migrate_thumbnails(dry_run=args.dry_run)
|