__init__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. """
  2. Trixy Core - Professional Voice Assistant System
  3. This module provides the core components and systems for the Trixy voice assistant,
  4. including event handling, configuration management, networking, plugins, and more.
  5. The core system is designed with:
  6. - Event-driven architecture using the central EventHandler
  7. - Professional dependency injection via ApplicationContainer
  8. - Thread-safe, scalable components supporting multiple satellites
  9. - Robust configuration management with validation
  10. - Plugin system with hot-loading capabilities
  11. - Professional logging and error handling
  12. Main Components:
  13. - ApplicationContainer: Central dependency injection container
  14. - EventHandler: Event-driven communication system
  15. - ConfigManager: Configuration management with validation
  16. - Plugin System: Dynamic plugin loading and management
  17. - Satellite Manager: Multi-satellite connection management
  18. - Network Manager: Custom Trixy protocol implementation
  19. Usage:
  20. from trixy_core import ApplicationContainer, DeploymentMode
  21. # Create application container
  22. application = ApplicationContainer(
  23. mode=DeploymentMode.SERVER,
  24. config_path="config/server_config.json"
  25. )
  26. # Start the application
  27. application.start()
  28. # Access components
  29. event_handler = application.get_event_handler()
  30. plugin_system = application.get_plugin_system()
  31. satellite_manager = application.get_satellite_manager()
  32. # Graceful shutdown
  33. application.shutdown()
  34. """
  35. # Version information
  36. __version__ = "1.0.0"
  37. __author__ = "Trixy Development Team"
  38. __description__ = "Professional voice assistant core system"
  39. # Import core application container
  40. try:
  41. from .application import (
  42. ApplicationContainer,
  43. ApplicationContainerError,
  44. ComponentInitializationError,
  45. ComponentLifecycleError,
  46. ApplicationStatus,
  47. ComponentStatus,
  48. ComponentHealth,
  49. create_application_container,
  50. get_application_container,
  51. cleanup_application_containers,
  52. )
  53. _APPLICATION_AVAILABLE = True
  54. except ImportError as e:
  55. print(f"Warning: Application container not available: {e}")
  56. _APPLICATION_AVAILABLE = False
  57. # Import event system
  58. try:
  59. from .events import (
  60. EventHandler,
  61. TrixyEvent,
  62. EventType,
  63. TrixyEventData,
  64. EventDataFactory,
  65. EventStatus,
  66. EventHistoryEntry,
  67. SatelliteInfo,
  68. SpeakerInfo,
  69. # Event data classes
  70. SatelliteConnectedEventData,
  71. SatelliteDisconnectedEventData,
  72. SatelliteRegisteredEventData,
  73. WakewordReceivedEventData,
  74. RawAudioInputReceivedEventData,
  75. TextReceivedEventData,
  76. IntentReceivedEventData,
  77. TTSReceivedEventData,
  78. SystemStartupEventData,
  79. SystemShutdownEventData,
  80. PluginEventData,
  81. PluginLoadedEventData,
  82. PluginUnloadedEventData,
  83. TrainingStartedEventData,
  84. TrainingCompletedEventData,
  85. ScheduleTriggeredEventData,
  86. # Registry and utilities
  87. TrixyEventRegistry,
  88. register_event_handlers,
  89. unregister_event_handlers,
  90. get_event_registry,
  91. validate_event_handler,
  92. list_registered_events,
  93. get_handler_info,
  94. create_default_event_handler,
  95. setup_event_system,
  96. )
  97. _EVENTS_AVAILABLE = True
  98. except ImportError as e:
  99. print(f"Warning: Event system not available: {e}")
  100. _EVENTS_AVAILABLE = False
  101. # Import configuration system
  102. try:
  103. from .config import (
  104. ConfigManager,
  105. ConfigValidator,
  106. ValidationResult,
  107. # Configuration models
  108. ServerConfig,
  109. ClientConfig,
  110. StandaloneConfig,
  111. ConfigType,
  112. NetworkConfig,
  113. AudioConfig,
  114. MLConfig,
  115. PluginConfig,
  116. SatelliteConfig,
  117. SecurityConfig,
  118. LoggingConfig,
  119. # Enums and types
  120. DeploymentMode,
  121. LogLevel,
  122. ConfigDict,
  123. # Exceptions
  124. ConfigurationError,
  125. ConfigurationValidationError,
  126. ConfigurationLoadError,
  127. ConfigurationSaveError,
  128. # Utility functions
  129. get_config_class,
  130. create_default_config,
  131. merge_configs,
  132. create_default_config_for_mode,
  133. get_env_override,
  134. get_environment_overrides,
  135. apply_environment_overrides,
  136. get_system_defaults,
  137. get_config_template,
  138. validate_environment,
  139. validate_config_dict,
  140. quick_validate,
  141. get_env_var_documentation,
  142. create_config_manager,
  143. load_config_from_file,
  144. validate_config_file,
  145. create_default_config_file,
  146. # Constants
  147. CONFIG_CLASSES,
  148. ENV_PREFIX,
  149. DEFAULT_PATHS,
  150. DEFAULT_PORTS,
  151. )
  152. _CONFIG_AVAILABLE = True
  153. except ImportError as e:
  154. print(f"Warning: Configuration system not available: {e}")
  155. _CONFIG_AVAILABLE = False
  156. def pprint(message: str) -> None:
  157. """
  158. Core module logging function that adapts based on application mode.
  159. This is the standard pprint() function referenced throughout CLAUDE.md:
  160. - Debug mode: Uses print() statements
  161. - Production mode: Uses logging system with Textual TUI
  162. Args:
  163. message: Message to print/log
  164. """
  165. # This will be enhanced when the main logging system is integrated
  166. print(f"[TRIXY_CORE] {message}")
  167. # Public API - Core Classes
  168. __all__ = []
  169. # Application Container
  170. if _APPLICATION_AVAILABLE:
  171. __all__.extend([
  172. "ApplicationContainer",
  173. "ApplicationContainerError",
  174. "ComponentInitializationError",
  175. "ComponentLifecycleError",
  176. "ApplicationStatus",
  177. "ComponentStatus",
  178. "ComponentHealth",
  179. "create_application_container",
  180. "get_application_container",
  181. "cleanup_application_containers",
  182. ])
  183. # Event System
  184. if _EVENTS_AVAILABLE:
  185. __all__.extend([
  186. "EventHandler",
  187. "TrixyEvent",
  188. "EventType",
  189. "TrixyEventData",
  190. "EventDataFactory",
  191. "EventStatus",
  192. "EventHistoryEntry",
  193. "SatelliteInfo",
  194. "SpeakerInfo",
  195. # Event data classes
  196. "SatelliteConnectedEventData",
  197. "SatelliteDisconnectedEventData",
  198. "SatelliteRegisteredEventData",
  199. "WakewordReceivedEventData",
  200. "RawAudioInputReceivedEventData",
  201. "TextReceivedEventData",
  202. "IntentReceivedEventData",
  203. "TTSReceivedEventData",
  204. "SystemStartupEventData",
  205. "SystemShutdownEventData",
  206. "PluginEventData",
  207. "PluginLoadedEventData",
  208. "PluginUnloadedEventData",
  209. "TrainingStartedEventData",
  210. "TrainingCompletedEventData",
  211. "ScheduleTriggeredEventData",
  212. # Registry and utilities
  213. "TrixyEventRegistry",
  214. "register_event_handlers",
  215. "unregister_event_handlers",
  216. "get_event_registry",
  217. "validate_event_handler",
  218. "list_registered_events",
  219. "get_handler_info",
  220. "create_default_event_handler",
  221. "setup_event_system",
  222. ])
  223. # Configuration System
  224. if _CONFIG_AVAILABLE:
  225. __all__.extend([
  226. "ConfigManager",
  227. "ConfigValidator",
  228. "ValidationResult",
  229. # Configuration models
  230. "ServerConfig",
  231. "ClientConfig",
  232. "StandaloneConfig",
  233. "ConfigType",
  234. "NetworkConfig",
  235. "AudioConfig",
  236. "MLConfig",
  237. "PluginConfig",
  238. "SatelliteConfig",
  239. "SecurityConfig",
  240. "LoggingConfig",
  241. # Enums and types
  242. "DeploymentMode",
  243. "LogLevel",
  244. "ConfigDict",
  245. # Exceptions
  246. "ConfigurationError",
  247. "ConfigurationValidationError",
  248. "ConfigurationLoadError",
  249. "ConfigurationSaveError",
  250. # Utility functions
  251. "get_config_class",
  252. "create_default_config",
  253. "merge_configs",
  254. "create_default_config_for_mode",
  255. "get_env_override",
  256. "get_environment_overrides",
  257. "apply_environment_overrides",
  258. "get_system_defaults",
  259. "get_config_template",
  260. "validate_environment",
  261. "validate_config_dict",
  262. "quick_validate",
  263. "get_env_var_documentation",
  264. "create_config_manager",
  265. "load_config_from_file",
  266. "validate_config_file",
  267. "create_default_config_file",
  268. # Constants
  269. "CONFIG_CLASSES",
  270. "ENV_PREFIX",
  271. "DEFAULT_PATHS",
  272. "DEFAULT_PORTS",
  273. ])
  274. # Always available
  275. __all__.extend([
  276. "pprint",
  277. ])
  278. def get_version() -> str:
  279. """Get the trixy_core module version."""
  280. return __version__
  281. def get_available_components() -> dict:
  282. """
  283. Get information about which core components are available.
  284. Returns:
  285. Dictionary showing availability status of each component
  286. """
  287. return {
  288. "application_container": _APPLICATION_AVAILABLE,
  289. "event_system": _EVENTS_AVAILABLE,
  290. "configuration_system": _CONFIG_AVAILABLE,
  291. "version": __version__,
  292. }
  293. def create_application(
  294. mode: str = "server",
  295. config_path: str = None,
  296. debug_mode: bool = False,
  297. **kwargs
  298. ) -> 'ApplicationContainer':
  299. """
  300. Convenience function to create and start a Trixy application.
  301. This is the main entry point for creating a Trixy application instance
  302. as referenced in CLAUDE.md.
  303. Args:
  304. mode: Deployment mode ("server", "client", "standalone")
  305. config_path: Path to configuration file
  306. debug_mode: Enable debug mode
  307. **kwargs: Additional configuration options
  308. Returns:
  309. ApplicationContainer instance
  310. Raises:
  311. ImportError: If application container is not available
  312. ApplicationContainerError: If application creation fails
  313. Example:
  314. application = create_application(
  315. mode="server",
  316. config_path="config/server_config.json",
  317. debug_mode=False
  318. )
  319. application.start()
  320. # Access components as specified in CLAUDE.md
  321. event_handler = application.get_event_handler()
  322. plugin_system = application.get_plugin_system()
  323. satellite_manager = application.get_satellite_manager()
  324. config_manager = application.get_config_manager()
  325. """
  326. if not _APPLICATION_AVAILABLE:
  327. raise ImportError("ApplicationContainer is not available. Check if all dependencies are installed.")
  328. pprint(f"Creating Trixy application in {mode} mode")
  329. application = create_application_container(
  330. mode=mode,
  331. config_path=config_path,
  332. debug_mode=debug_mode,
  333. **kwargs
  334. )
  335. pprint(f"Trixy application created successfully")
  336. return application
  337. def setup_trixy_core(debug_mode: bool = False) -> dict:
  338. """
  339. Set up the trixy_core module with default configurations.
  340. Args:
  341. debug_mode: Enable debug mode for all components
  342. Returns:
  343. Dictionary with setup information and component status
  344. Example:
  345. setup_info = setup_trixy_core(debug_mode=True)
  346. pprint(f"Setup completed: {setup_info}")
  347. """
  348. setup_info = {
  349. "trixy_core_version": __version__,
  350. "debug_mode": debug_mode,
  351. "available_components": get_available_components(),
  352. "setup_timestamp": time.time(),
  353. }
  354. pprint(f"Trixy Core v{__version__} setup completed")
  355. pprint(f"Available components: {list(setup_info['available_components'].keys())}")
  356. if debug_mode:
  357. pprint("Debug mode enabled for all core components")
  358. return setup_info
  359. # Initialize the module
  360. def _init_trixy_core():
  361. """Initialize the trixy_core module."""
  362. pprint(f"Trixy Core v{__version__} loaded")
  363. components = get_available_components()
  364. available = [name for name, status in components.items() if status and name != "version"]
  365. if available:
  366. pprint(f"Available components: {', '.join(available)}")
  367. else:
  368. pprint("Warning: No core components are available")
  369. pprint("This may be expected during initial setup")
  370. # Import time for setup function
  371. import time
  372. # Initialize on import
  373. _init_trixy_core()
  374. # Compatibility functions for easy integration
  375. def quick_start_server(config_path: str = None, debug_mode: bool = False) -> 'ApplicationContainer':
  376. """Quickly start a Trixy server instance."""
  377. application = create_application("server", config_path, debug_mode)
  378. application.start()
  379. return application
  380. def quick_start_client(config_path: str = None, debug_mode: bool = False) -> 'ApplicationContainer':
  381. """Quickly start a Trixy client/satellite instance."""
  382. application = create_application("client", config_path, debug_mode)
  383. application.start()
  384. return application
  385. def quick_start_standalone(config_path: str = None, debug_mode: bool = False) -> 'ApplicationContainer':
  386. """Quickly start a Trixy standalone instance."""
  387. application = create_application("standalone", config_path, debug_mode)
  388. application.start()
  389. return application
  390. # Add convenience functions to exports
  391. __all__.extend([
  392. "get_version",
  393. "get_available_components",
  394. "create_application",
  395. "setup_trixy_core",
  396. "quick_start_server",
  397. "quick_start_client",
  398. "quick_start_standalone",
  399. ])
  400. # Module documentation
  401. def get_module_info() -> dict:
  402. """
  403. Get comprehensive information about the trixy_core module.
  404. Returns:
  405. Dictionary with module information, component status, and usage examples
  406. """
  407. return {
  408. "module": "trixy_core",
  409. "version": __version__,
  410. "description": __description__,
  411. "author": __author__,
  412. "components": get_available_components(),
  413. "exported_symbols": len(__all__),
  414. "usage_example": """
  415. from trixy_core import create_application
  416. # Create and start Trixy application
  417. application = create_application(
  418. mode="server",
  419. config_path="config/server_config.json"
  420. )
  421. application.start()
  422. # Access core components as specified in CLAUDE.md
  423. event_handler = application.get_event_handler()
  424. plugin_system = application.get_plugin_system()
  425. satellite_manager = application.get_satellite_manager()
  426. config_manager = application.get_config_manager()
  427. # Graceful shutdown
  428. application.shutdown()
  429. """.strip()
  430. }
  431. __all__.append("get_module_info")