svg_cache_manager.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """SVG Cache Manager for pre-generating and managing SVG previews."""
  2. import os
  3. import json
  4. import asyncio
  5. import logging
  6. from pathlib import Path
  7. from modules.core.pattern_manager import list_theta_rho_files, THETA_RHO_DIR
  8. logger = logging.getLogger(__name__)
  9. # Constants
  10. CACHE_DIR = os.path.join(THETA_RHO_DIR, "cached_svg")
  11. def ensure_cache_dir():
  12. """Ensure the cache directory exists."""
  13. Path(CACHE_DIR).mkdir(parents=True, exist_ok=True)
  14. def get_cache_path(pattern_file):
  15. """Get the cache path for a pattern file."""
  16. # Convert the pattern file path to a safe filename
  17. safe_name = pattern_file.replace('/', '_').replace('\\', '_')
  18. return os.path.join(CACHE_DIR, f"{safe_name}.svg")
  19. def needs_cache(pattern_file):
  20. """Check if a pattern file needs its cache generated."""
  21. cache_path = get_cache_path(pattern_file)
  22. return not os.path.exists(cache_path)
  23. async def generate_svg_preview(pattern_file):
  24. """Generate SVG preview for a single pattern file."""
  25. from modules.core.preview import generate_preview_svg
  26. try:
  27. # Generate the SVG
  28. svg_content = await generate_preview_svg(pattern_file)
  29. # Save to cache
  30. cache_path = get_cache_path(pattern_file)
  31. with open(cache_path, 'w', encoding='utf-8') as f:
  32. f.write(svg_content)
  33. return True
  34. except Exception as e:
  35. # Only log the error message, not the full SVG content
  36. logger.error(f"Failed to generate SVG for {pattern_file}")
  37. return False
  38. async def generate_all_svg_previews():
  39. """Generate SVG previews for all pattern files."""
  40. ensure_cache_dir()
  41. # Get all pattern files and filter for .thr files only
  42. pattern_files = [f for f in list_theta_rho_files() if f.endswith('.thr')]
  43. # Filter out patterns that already have cache
  44. patterns_to_cache = [f for f in pattern_files if needs_cache(f)]
  45. total_files = len(patterns_to_cache)
  46. if total_files == 0:
  47. logger.info("All patterns are already cached")
  48. return
  49. logger.info(f"Generating SVG cache for {total_files} uncached .thr patterns...")
  50. # Process files concurrently in batches to avoid overwhelming the system
  51. batch_size = 5
  52. successful = 0
  53. for i in range(0, total_files, batch_size):
  54. batch = patterns_to_cache[i:i + batch_size]
  55. tasks = [generate_svg_preview(file) for file in batch]
  56. results = await asyncio.gather(*tasks)
  57. successful += sum(1 for r in results if r)
  58. logger.info(f"SVG cache generation completed: {successful}/{total_files} patterns cached")