validate_system.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. #!/usr/bin/env python3
  2. """
  3. Voice Recognition System Validation Script
  4. This script validates the completeness and correctness of the voice recognition
  5. system implementation without requiring PyTorch to be installed.
  6. """
  7. import os
  8. import sys
  9. import importlib.util
  10. from pathlib import Path
  11. from typing import List, Dict, Any
  12. def check_file_exists(file_path: str) -> bool:
  13. """Check if a file exists."""
  14. return Path(file_path).exists()
  15. def validate_module_structure() -> Dict[str, Any]:
  16. """Validate the module structure and file completeness."""
  17. base_path = Path(__file__).parent
  18. required_files = [
  19. '__init__.py',
  20. 'config.py',
  21. 'detector.py',
  22. 'audio_features.py',
  23. 'vad.py',
  24. 'model_architectures.py',
  25. 'model_loader.py',
  26. 'speaker_embeddings.py',
  27. 'speaker_manager.py',
  28. 'recognition_engine.py',
  29. 'optimization.py',
  30. 'integration.py',
  31. 'examples.py',
  32. 'README.md'
  33. ]
  34. results = {
  35. 'total_files': len(required_files),
  36. 'found_files': 0,
  37. 'missing_files': [],
  38. 'found_files_list': [],
  39. 'file_sizes': {}
  40. }
  41. for file_name in required_files:
  42. file_path = base_path / file_name
  43. if file_path.exists():
  44. results['found_files'] += 1
  45. results['found_files_list'].append(file_name)
  46. results['file_sizes'][file_name] = file_path.stat().st_size
  47. else:
  48. results['missing_files'].append(file_name)
  49. return results
  50. def validate_python_syntax() -> Dict[str, Any]:
  51. """Validate Python syntax of all modules."""
  52. base_path = Path(__file__).parent
  53. python_files = list(base_path.glob('*.py'))
  54. results = {
  55. 'total_files': len(python_files),
  56. 'valid_files': 0,
  57. 'invalid_files': [],
  58. 'syntax_errors': {}
  59. }
  60. for py_file in python_files:
  61. try:
  62. with open(py_file, 'r', encoding='utf-8') as f:
  63. content = f.read()
  64. # Compile to check syntax
  65. compile(content, str(py_file), 'exec')
  66. results['valid_files'] += 1
  67. except SyntaxError as e:
  68. results['invalid_files'].append(py_file.name)
  69. results['syntax_errors'][py_file.name] = str(e)
  70. except Exception as e:
  71. results['invalid_files'].append(py_file.name)
  72. results['syntax_errors'][py_file.name] = f"Error reading file: {e}"
  73. return results
  74. def validate_imports_structure() -> Dict[str, Any]:
  75. """Validate import structure without actually importing (to avoid PyTorch dependency)."""
  76. base_path = Path(__file__).parent
  77. results = {
  78. 'modules_checked': 0,
  79. 'import_structures': {},
  80. 'potential_issues': []
  81. }
  82. # Check __init__.py for proper exports
  83. init_file = base_path / '__init__.py'
  84. if init_file.exists():
  85. try:
  86. with open(init_file, 'r', encoding='utf-8') as f:
  87. content = f.read()
  88. # Count imports and exports
  89. import_lines = [line for line in content.split('\n') if line.strip().startswith('from .')]
  90. export_lines = [line for line in content.split('\n') if '__all__' in line or line.strip().startswith('"')]
  91. results['import_structures']['__init__.py'] = {
  92. 'import_count': len(import_lines),
  93. 'has_all_exports': '__all__' in content,
  94. 'content_length': len(content)
  95. }
  96. except Exception as e:
  97. results['potential_issues'].append(f"Error reading __init__.py: {e}")
  98. # Check other key modules
  99. key_modules = ['detector.py', 'config.py', 'integration.py']
  100. for module_name in key_modules:
  101. module_file = base_path / module_name
  102. if module_file.exists():
  103. try:
  104. with open(module_file, 'r', encoding='utf-8') as f:
  105. content = f.read()
  106. # Basic structure analysis
  107. class_count = content.count('class ')
  108. function_count = content.count('def ')
  109. docstring_count = content.count('"""')
  110. results['import_structures'][module_name] = {
  111. 'class_count': class_count,
  112. 'function_count': function_count,
  113. 'docstring_count': docstring_count,
  114. 'content_length': len(content)
  115. }
  116. results['modules_checked'] += 1
  117. except Exception as e:
  118. results['potential_issues'].append(f"Error reading {module_name}: {e}")
  119. return results
  120. def validate_documentation() -> Dict[str, Any]:
  121. """Validate documentation completeness."""
  122. base_path = Path(__file__).parent
  123. results = {
  124. 'readme_exists': False,
  125. 'readme_size': 0,
  126. 'module_docstrings': {},
  127. 'documentation_coverage': 0.0
  128. }
  129. # Check README
  130. readme_file = base_path / 'README.md'
  131. if readme_file.exists():
  132. results['readme_exists'] = True
  133. results['readme_size'] = readme_file.stat().st_size
  134. # Check module docstrings
  135. python_files = [f for f in base_path.glob('*.py') if f.name != '__pycache__']
  136. documented_modules = 0
  137. for py_file in python_files:
  138. try:
  139. with open(py_file, 'r', encoding='utf-8') as f:
  140. content = f.read()
  141. # Check for module docstring
  142. has_module_docstring = content.strip().startswith('"""') or content.strip().startswith("'''")
  143. # Count docstrings
  144. docstring_count = content.count('"""') + content.count("'''")
  145. results['module_docstrings'][py_file.name] = {
  146. 'has_module_docstring': has_module_docstring,
  147. 'docstring_count': docstring_count
  148. }
  149. if has_module_docstring:
  150. documented_modules += 1
  151. except Exception as e:
  152. results['module_docstrings'][py_file.name] = {'error': str(e)}
  153. if python_files:
  154. results['documentation_coverage'] = documented_modules / len(python_files)
  155. return results
  156. def generate_system_report() -> Dict[str, Any]:
  157. """Generate comprehensive system validation report."""
  158. print("🔍 Validating Trixy Voice Recognition System...")
  159. print("=" * 60)
  160. # Run all validations
  161. structure_results = validate_module_structure()
  162. syntax_results = validate_python_syntax()
  163. import_results = validate_imports_structure()
  164. doc_results = validate_documentation()
  165. # Compile overall results
  166. overall_results = {
  167. 'structure': structure_results,
  168. 'syntax': syntax_results,
  169. 'imports': import_results,
  170. 'documentation': doc_results,
  171. 'overall_score': 0.0,
  172. 'recommendations': []
  173. }
  174. # Calculate overall score
  175. structure_score = structure_results['found_files'] / structure_results['total_files']
  176. syntax_score = syntax_results['valid_files'] / syntax_results['total_files'] if syntax_results['total_files'] > 0 else 0
  177. doc_score = doc_results['documentation_coverage']
  178. overall_results['overall_score'] = (structure_score + syntax_score + doc_score) / 3
  179. # Generate recommendations
  180. if structure_results['missing_files']:
  181. overall_results['recommendations'].append(f"Missing files: {', '.join(structure_results['missing_files'])}")
  182. if syntax_results['invalid_files']:
  183. overall_results['recommendations'].append(f"Syntax errors in: {', '.join(syntax_results['invalid_files'])}")
  184. if doc_score < 0.8:
  185. overall_results['recommendations'].append("Improve documentation coverage")
  186. if not doc_results['readme_exists']:
  187. overall_results['recommendations'].append("Add README.md file")
  188. return overall_results
  189. def print_validation_report(results: Dict[str, Any]):
  190. """Print a formatted validation report."""
  191. print(f"📋 VALIDATION REPORT")
  192. print("=" * 60)
  193. # Structure validation
  194. structure = results['structure']
  195. print(f"📁 MODULE STRUCTURE:")
  196. print(f" Files found: {structure['found_files']}/{structure['total_files']}")
  197. if structure['missing_files']:
  198. print(f" Missing: {', '.join(structure['missing_files'])}")
  199. print()
  200. # Syntax validation
  201. syntax = results['syntax']
  202. print(f"🐍 PYTHON SYNTAX:")
  203. print(f" Valid files: {syntax['valid_files']}/{syntax['total_files']}")
  204. if syntax['invalid_files']:
  205. print(f" Syntax errors: {', '.join(syntax['invalid_files'])}")
  206. for file, error in syntax['syntax_errors'].items():
  207. print(f" {file}: {error}")
  208. print()
  209. # Import structure
  210. imports = results['imports']
  211. print(f"📦 IMPORT STRUCTURE:")
  212. print(f" Modules checked: {imports['modules_checked']}")
  213. if imports.get('potential_issues'):
  214. print(f" Issues: {len(imports['potential_issues'])}")
  215. for issue in imports['potential_issues']:
  216. print(f" - {issue}")
  217. print()
  218. # Documentation
  219. docs = results['documentation']
  220. print(f"📚 DOCUMENTATION:")
  221. print(f" README exists: {'✅' if docs['readme_exists'] else '❌'}")
  222. print(f" Documentation coverage: {docs['documentation_coverage']:.1%}")
  223. print()
  224. # Overall score
  225. score = results['overall_score']
  226. print(f"🎯 OVERALL SCORE: {score:.1%}")
  227. if score >= 0.9:
  228. print(" Status: ✅ EXCELLENT")
  229. elif score >= 0.8:
  230. print(" Status: ✅ GOOD")
  231. elif score >= 0.7:
  232. print(" Status: ⚠️ FAIR")
  233. else:
  234. print(" Status: ❌ NEEDS IMPROVEMENT")
  235. print()
  236. # Recommendations
  237. if results['recommendations']:
  238. print("💡 RECOMMENDATIONS:")
  239. for i, rec in enumerate(results['recommendations'], 1):
  240. print(f" {i}. {rec}")
  241. else:
  242. print("💡 No issues found - system looks good!")
  243. print("=" * 60)
  244. def main():
  245. """Main validation function."""
  246. try:
  247. results = generate_system_report()
  248. print_validation_report(results)
  249. # Return exit code based on overall score
  250. if results['overall_score'] >= 0.8:
  251. print("✅ Validation completed successfully!")
  252. return 0
  253. else:
  254. print("⚠️ Validation completed with issues.")
  255. return 1
  256. except Exception as e:
  257. print(f"❌ Validation failed with error: {e}")
  258. import traceback
  259. traceback.print_exc()
  260. return 2
  261. if __name__ == "__main__":
  262. sys.exit(main())