__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. """
  2. Trixy Asset Management System
  3. This module provides comprehensive asset management for the Trixy voice assistant
  4. application, including profile-based asset loading, caching, validation, and
  5. integrity checking as specified in CLAUDE.md.
  6. The asset management system is designed to handle various types of assets used
  7. throughout the Trixy application:
  8. - Audio assets: Success sounds, error notifications, wakeword confirmations
  9. - Image assets: Icons, status indicators, UI elements
  10. - Text assets: Templates, messages, response texts
  11. - Configuration assets: Settings templates, profile configurations
  12. - Model assets: ML models, training data references
  13. - Binary assets: Compressed files, executables
  14. Key Features:
  15. - Profile-based asset resolution with fallback to default profile
  16. - High-performance caching with configurable policies
  17. - Comprehensive validation and integrity checking
  18. - Hot-reload capabilities for development
  19. - Thread-safe operations for multi-satellite support
  20. - Integration with application container and event system
  21. Asset Resolution Path:
  22. 1. Primary: ./assets/{profile}/path/to/asset
  23. 2. Fallback: ./assets/default/path/to/asset
  24. 3. Returns False if not found in either location
  25. Usage Examples:
  26. Basic Usage:
  27. from trixy_core.assets import AssetManager, create_asset_manager
  28. # Create asset manager
  29. asset_manager = create_asset_manager(
  30. assets_directory="./assets",
  31. profile="production",
  32. cache_enabled=True
  33. )
  34. # Get asset path (main API as per CLAUDE.md)
  35. audio_path = asset_manager.get_path("audio/success.wav")
  36. if audio_path:
  37. print(f"Found asset at: {audio_path}")
  38. else:
  39. print("Asset not found")
  40. Advanced Configuration:
  41. from trixy_core.assets import AssetManager, AssetManagerConfig
  42. config = AssetManagerConfig(
  43. assets_directory="./assets",
  44. current_profile="development",
  45. cache_enabled=True,
  46. validation_enabled=True,
  47. hot_reload_enabled=True,
  48. preload_patterns=["audio/*.wav", "images/*.png"]
  49. )
  50. asset_manager = AssetManager(config=config)
  51. Integration with Application Container:
  52. # The asset manager is automatically available through the application container
  53. application = get_application_container()
  54. asset_manager = application.get_asset_manager()
  55. # Use in plugins or components
  56. success_sound = asset_manager.get_path("audio/success.wav")
  57. Public API:
  58. AssetManager: Main asset management class
  59. AssetManagerConfig: Configuration for asset manager
  60. AssetType: Enumeration of supported asset types
  61. AssetCache: High-performance caching system
  62. AssetValidator: Comprehensive validation system
  63. create_asset_manager(): Convenience factory function
  64. """
  65. # Import core asset management classes
  66. from .asset_manager import (
  67. # Main classes
  68. AssetManager,
  69. AssetManagerConfig,
  70. AssetInfo,
  71. # Enums and types
  72. AssetStatus,
  73. ProfileMode,
  74. # Exceptions
  75. AssetLoadError,
  76. AssetValidationError,
  77. AssetNotFoundError,
  78. AssetManagerError,
  79. # Factory function
  80. create_asset_manager,
  81. )
  82. # Import asset type system
  83. from .asset_types import (
  84. # Core types
  85. AssetType,
  86. AssetConstraints,
  87. AssetMetadata,
  88. # Functions
  89. get_asset_type_from_path,
  90. get_asset_constraints,
  91. validate_asset_type,
  92. extract_asset_metadata,
  93. get_asset_category,
  94. is_asset_type_supported,
  95. get_supported_extensions,
  96. get_extensions_for_type,
  97. # Constants
  98. ASSET_TYPE_CONSTRAINTS,
  99. EXTENSION_TO_TYPE,
  100. ASSET_TYPE_CATEGORIES,
  101. )
  102. # Import caching system
  103. from .asset_cache import (
  104. # Core classes
  105. AssetCache,
  106. CachePolicy,
  107. CacheEntry,
  108. CacheStats,
  109. # Enums
  110. CacheEntryStatus,
  111. CacheEvictionStrategy,
  112. # Factory functions
  113. create_memory_cache,
  114. create_persistent_cache,
  115. )
  116. # Import validation system
  117. from .asset_validator import (
  118. # Core classes
  119. AssetValidator,
  120. AssetIntegrityChecker,
  121. AssetValidationResult,
  122. ValidationIssue,
  123. # Enums
  124. ValidationSeverity,
  125. ValidationCategory,
  126. # Functions
  127. quick_validate,
  128. batch_validate,
  129. )
  130. # Module version and metadata
  131. __version__ = "1.0.0"
  132. __author__ = "Trixy Development Team"
  133. __description__ = "Professional asset management system for Trixy voice assistant"
  134. # Public API - explicitly define what gets imported with "from trixy_core.assets import *"
  135. __all__ = [
  136. # Main asset manager
  137. "AssetManager",
  138. "AssetManagerConfig",
  139. "AssetInfo",
  140. "AssetStatus",
  141. "ProfileMode",
  142. "create_asset_manager",
  143. # Asset types
  144. "AssetType",
  145. "AssetConstraints",
  146. "AssetMetadata",
  147. "get_asset_type_from_path",
  148. "get_asset_constraints",
  149. "validate_asset_type",
  150. "extract_asset_metadata",
  151. "get_asset_category",
  152. "is_asset_type_supported",
  153. "get_supported_extensions",
  154. "get_extensions_for_type",
  155. # Caching
  156. "AssetCache",
  157. "CachePolicy",
  158. "CacheEntry",
  159. "CacheStats",
  160. "CacheEntryStatus",
  161. "CacheEvictionStrategy",
  162. "create_memory_cache",
  163. "create_persistent_cache",
  164. # Validation
  165. "AssetValidator",
  166. "AssetIntegrityChecker",
  167. "AssetValidationResult",
  168. "ValidationIssue",
  169. "ValidationSeverity",
  170. "ValidationCategory",
  171. "quick_validate",
  172. "batch_validate",
  173. # Exceptions
  174. "AssetLoadError",
  175. "AssetValidationError",
  176. "AssetNotFoundError",
  177. "AssetManagerError",
  178. # Constants
  179. "ASSET_TYPE_CONSTRAINTS",
  180. "EXTENSION_TO_TYPE",
  181. "ASSET_TYPE_CATEGORIES",
  182. ]
  183. # Logging function for the assets module
  184. def pprint(message: str) -> None:
  185. """
  186. Asset management logging function that adapts based on mode.
  187. Uses the same pattern as specified in CLAUDE.md.
  188. """
  189. print(f"[ASSETS] {message}")
  190. # Module initialization
  191. def _init_assets_module():
  192. """Initialize the assets module."""
  193. pprint(f"Asset management system loaded (version {__version__})")
  194. # Log available asset types
  195. try:
  196. supported_extensions = get_supported_extensions()
  197. pprint(f"Supporting {len(supported_extensions)} file extensions")
  198. # Log asset type categories
  199. categories = list(ASSET_TYPE_CATEGORIES.keys())
  200. pprint(f"Asset categories: {', '.join(categories)}")
  201. except Exception as e:
  202. pprint(f"Warning: Could not initialize asset type information: {e}")
  203. # Initialize the module
  204. _init_assets_module()
  205. # Convenience functions for common operations
  206. def get_default_asset_manager() -> AssetManager:
  207. """
  208. Get a default asset manager instance with reasonable settings.
  209. Returns:
  210. AssetManager instance configured with defaults
  211. """
  212. return create_asset_manager(
  213. assets_directory="./assets",
  214. cache_enabled=True,
  215. validation_enabled=True,
  216. hot_reload_enabled=False
  217. )
  218. def validate_asset_file(file_path: str, asset_type: str = None) -> AssetValidationResult:
  219. """
  220. Convenience function to quickly validate an asset file.
  221. Args:
  222. file_path: Path to the asset file
  223. asset_type: Expected asset type (optional)
  224. Returns:
  225. AssetValidationResult with validation details
  226. """
  227. return quick_validate(file_path, asset_type)
  228. def create_development_asset_manager(assets_dir: str = "./assets") -> AssetManager:
  229. """
  230. Create an asset manager optimized for development.
  231. Features enabled:
  232. - Hot-reload for file changes
  233. - Detailed validation
  234. - Debug logging
  235. - Reduced caching for faster iteration
  236. Args:
  237. assets_dir: Assets directory path
  238. Returns:
  239. AssetManager configured for development
  240. """
  241. config = AssetManagerConfig(
  242. assets_directory=assets_dir,
  243. cache_enabled=True,
  244. cache_max_size=50, # Smaller cache for development
  245. validation_enabled=True,
  246. hot_reload_enabled=True,
  247. hot_reload_debounce=0.2, # Quick response to changes
  248. enable_integrity_checks=True,
  249. auto_create_directories=True
  250. )
  251. return AssetManager(config=config)
  252. def create_production_asset_manager(
  253. assets_dir: str = "./assets",
  254. profile: str = "default",
  255. cache_size_mb: int = 100
  256. ) -> AssetManager:
  257. """
  258. Create an asset manager optimized for production.
  259. Features enabled:
  260. - Aggressive caching for performance
  261. - Validation with integrity checks
  262. - No hot-reload for stability
  263. - Preloading of common assets
  264. Args:
  265. assets_dir: Assets directory path
  266. profile: Asset profile to use
  267. cache_size_mb: Cache size in megabytes
  268. Returns:
  269. AssetManager configured for production
  270. """
  271. config = AssetManagerConfig(
  272. assets_directory=assets_dir,
  273. current_profile=profile,
  274. cache_enabled=True,
  275. cache_max_size=500,
  276. cache_max_memory=cache_size_mb * 1024 * 1024,
  277. validation_enabled=True,
  278. hot_reload_enabled=False,
  279. enable_integrity_checks=True,
  280. compress_cached_assets=True,
  281. preload_patterns=[
  282. "audio/success.wav",
  283. "audio/error.wav",
  284. "audio/notification.wav",
  285. "images/icons/*.png"
  286. ]
  287. )
  288. return AssetManager(config=config)
  289. def get_asset_info(file_path: str) -> dict:
  290. """
  291. Get comprehensive information about an asset file.
  292. Args:
  293. file_path: Path to the asset file
  294. Returns:
  295. Dictionary with asset information including type, metadata, validation results
  296. """
  297. try:
  298. # Detect asset type
  299. asset_type = get_asset_type_from_path(file_path)
  300. # Extract metadata
  301. metadata = extract_asset_metadata(file_path, asset_type)
  302. # Validate asset
  303. validation_result = quick_validate(file_path, asset_type.value if hasattr(asset_type, 'value') else str(asset_type))
  304. return {
  305. 'file_path': file_path,
  306. 'asset_type': asset_type.value if hasattr(asset_type, 'value') else str(asset_type),
  307. 'category': get_asset_category(asset_type),
  308. 'is_supported': is_asset_type_supported(asset_type),
  309. 'metadata': metadata.to_dict() if hasattr(metadata, 'to_dict') else metadata,
  310. 'validation': validation_result.to_dict() if hasattr(validation_result, 'to_dict') else validation_result,
  311. 'constraints': get_asset_constraints(asset_type)
  312. }
  313. except Exception as e:
  314. return {
  315. 'file_path': file_path,
  316. 'error': str(e),
  317. 'asset_type': 'unknown'
  318. }
  319. # Add convenience exports
  320. __all__.extend([
  321. 'pprint',
  322. 'get_default_asset_manager',
  323. 'validate_asset_file',
  324. 'create_development_asset_manager',
  325. 'create_production_asset_manager',
  326. 'get_asset_info',
  327. ])
  328. def get_version() -> str:
  329. """Get the asset management system version."""
  330. return __version__
  331. def get_supported_asset_types() -> list:
  332. """Get a list of all supported asset types."""
  333. try:
  334. return [asset_type.value for asset_type in AssetType]
  335. except Exception:
  336. return []
  337. def get_asset_statistics() -> dict:
  338. """Get statistics about the asset management system."""
  339. return {
  340. 'version': __version__,
  341. 'supported_extensions': len(get_supported_extensions()),
  342. 'asset_categories': len(ASSET_TYPE_CATEGORIES),
  343. 'total_asset_types': len(list(AssetType)),
  344. 'validation_available': True,
  345. 'caching_available': True,
  346. 'hot_reload_available': True
  347. }
  348. # Final exports
  349. __all__.extend([
  350. 'get_version',
  351. 'get_supported_asset_types',
  352. 'get_asset_statistics'
  353. ])