quality_monitor.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 软著申请材料质量监控和检测工具
  5. 功能:全方位监控生成过程的质量,提供实时反馈和智能建议
  6. 监控维度:
  7. 1. 生成进度跟踪
  8. 2. 代码质量检测
  9. 3. 文档完整性验证
  10. 4. 申请成功率预测
  11. 5. 性能指标分析
  12. """
  13. import sys
  14. import json
  15. import re
  16. from pathlib import Path
  17. from datetime import datetime
  18. from typing import Dict, List, Optional
  19. # 颜色输出类
  20. class Colors:
  21. RED = '\033[0;31m'
  22. GREEN = '\033[0;32m'
  23. YELLOW = '\033[1;33m'
  24. BLUE = '\033[0;34m'
  25. PURPLE = '\033[0;35m'
  26. CYAN = '\033[0;36m'
  27. NC = '\033[0m' # No Color
  28. def print_success(message: str):
  29. print(f"{Colors.GREEN}✓ {message}{Colors.NC}")
  30. def print_info(message: str):
  31. print(f"{Colors.BLUE}ℹ {message}{Colors.NC}")
  32. def print_warning(message: str):
  33. print(f"{Colors.YELLOW}⚠ {message}{Colors.NC}")
  34. def print_error(message: str):
  35. print(f"{Colors.RED}✗ {message}{Colors.NC}")
  36. def print_header(message: str):
  37. print(f"{Colors.PURPLE}{'=' * 80}{Colors.NC}")
  38. print(f"{Colors.PURPLE}{message.center(80)}{Colors.NC}")
  39. print(f"{Colors.PURPLE}{'=' * 80}{Colors.NC}")
  40. class QualityMonitor:
  41. """质量监控器"""
  42. def __init__(self):
  43. self.project_root = Path.cwd()
  44. self.config_path = self.project_root / "ai-copyright-config.json"
  45. self.monitoring_results = {}
  46. def load_config(self) -> Optional[dict]:
  47. """加载项目配置"""
  48. if not self.config_path.exists():
  49. return None
  50. try:
  51. with open(self.config_path, 'r', encoding='utf-8') as f:
  52. return json.load(f)
  53. except:
  54. return None
  55. def check_generation_progress(self) -> Dict[str, any]:
  56. """检查生成进度"""
  57. progress = {
  58. 'requirements_doc': False,
  59. 'framework_design': False,
  60. 'page_list': False,
  61. 'frontend_code': False,
  62. 'backend_code': False,
  63. 'database_code': False,
  64. 'user_manual': False,
  65. 'registration_form': False,
  66. 'merged_frontend': False,
  67. 'merged_backend': False,
  68. 'merged_database': False
  69. }
  70. file_mappings = {
  71. 'requirements_doc': 'requires_docs/需求文档.md',
  72. 'framework_design': 'process_docs/*框架设计文档.md',
  73. 'page_list': 'process_docs/页面清单.md',
  74. 'frontend_code': 'output_sourcecode/front/*.html',
  75. 'backend_code': 'output_sourcecode/backend/*',
  76. 'database_code': 'output_sourcecode/db/*.sql',
  77. 'user_manual': 'output_docs/*用户手册.md',
  78. 'registration_form': 'output_docs/*软件著作权登记信息表.md',
  79. 'merged_frontend': 'output_docs/前端源代码.txt',
  80. 'merged_backend': 'output_docs/后端源代码.txt',
  81. 'merged_database': 'output_docs/数据库源代码.txt'
  82. }
  83. for key, pattern in file_mappings.items():
  84. if '*' in pattern:
  85. # 使用glob匹配
  86. matches = list(self.project_root.glob(pattern))
  87. progress[key] = len(matches) > 0
  88. else:
  89. # 直接检查文件
  90. file_path = self.project_root / pattern
  91. progress[key] = file_path.exists()
  92. # 计算完成度
  93. completed_stages = sum(progress.values())
  94. total_stages = len(progress)
  95. completion_rate = (completed_stages / total_stages) * 100
  96. return {
  97. 'progress': progress,
  98. 'completed_stages': completed_stages,
  99. 'total_stages': total_stages,
  100. 'completion_rate': completion_rate
  101. }
  102. def analyze_code_quality(self) -> Dict[str, any]:
  103. """分析代码质量"""
  104. quality_metrics = {
  105. 'frontend': self.analyze_frontend_quality(),
  106. 'backend': self.analyze_backend_quality(),
  107. 'database': self.analyze_database_quality()
  108. }
  109. # 计算总体质量分数
  110. quality_scores = [metrics['quality_score'] for metrics in quality_metrics.values() if metrics['quality_score'] > 0]
  111. overall_score = sum(quality_scores) / len(quality_scores) if quality_scores else 0
  112. return {
  113. 'components': quality_metrics,
  114. 'overall_score': overall_score,
  115. 'quality_level': self.get_quality_level(overall_score)
  116. }
  117. def analyze_frontend_quality(self) -> Dict[str, any]:
  118. """分析前端代码质量"""
  119. frontend_dir = self.project_root / "output_sourcecode" / "front"
  120. if not frontend_dir.exists():
  121. return {'exists': False, 'quality_score': 0}
  122. html_files = list(frontend_dir.glob("*.html"))
  123. if not html_files:
  124. return {'exists': False, 'quality_score': 0}
  125. metrics = {
  126. 'file_count': len(html_files),
  127. 'total_size': 0,
  128. 'avg_size': 0,
  129. 'has_css': 0,
  130. 'has_js': 0,
  131. 'has_responsive': 0,
  132. 'has_navigation': 0,
  133. 'html5_compliant': 0,
  134. 'quality_score': 0
  135. }
  136. for html_file in html_files:
  137. try:
  138. with open(html_file, 'r', encoding='utf-8') as f:
  139. content = f.read()
  140. file_size = len(content)
  141. metrics['total_size'] += file_size
  142. # 检查各种质量指标
  143. if '<style>' in content or 'class=' in content:
  144. metrics['has_css'] += 1
  145. if '<script>' in content or 'function' in content:
  146. metrics['has_js'] += 1
  147. if 'responsive' in content.lower() or '@media' in content:
  148. metrics['has_responsive'] += 1
  149. if '<nav>' in content or 'navigation' in content.lower():
  150. metrics['has_navigation'] += 1
  151. if '<!DOCTYPE html>' in content:
  152. metrics['html5_compliant'] += 1
  153. except:
  154. continue
  155. if metrics['file_count'] > 0:
  156. metrics['avg_size'] = metrics['total_size'] / metrics['file_count']
  157. # 计算质量分数
  158. score = 0
  159. score += min(metrics['file_count'] * 10, 50) # 文件数量 (最多50分)
  160. score += (metrics['has_css'] / metrics['file_count']) * 15 # CSS使用率 (15分)
  161. score += (metrics['has_js'] / metrics['file_count']) * 15 # JS使用率 (15分)
  162. score += (metrics['has_responsive'] / metrics['file_count']) * 10 # 响应式 (10分)
  163. score += (metrics['has_navigation'] / metrics['file_count']) * 5 # 导航 (5分)
  164. score += (metrics['html5_compliant'] / metrics['file_count']) * 5 # HTML5 (5分)
  165. metrics['quality_score'] = min(score, 100)
  166. metrics['exists'] = True
  167. return metrics
  168. def analyze_backend_quality(self) -> Dict[str, any]:
  169. """分析后端代码质量"""
  170. backend_dir = self.project_root / "output_sourcecode" / "backend"
  171. if not backend_dir.exists():
  172. return {'exists': False, 'quality_score': 0}
  173. # 收集源代码文件
  174. source_extensions = ['.java', '.py', '.js', '.php', '.cs', '.go', '.rb']
  175. source_files = []
  176. for ext in source_extensions:
  177. source_files.extend(backend_dir.rglob(f"*{ext}"))
  178. if not source_files:
  179. return {'exists': False, 'quality_score': 0}
  180. metrics = {
  181. 'file_count': len(source_files),
  182. 'total_size': 0,
  183. 'avg_size': 0,
  184. 'has_functions': 0,
  185. 'has_classes': 0,
  186. 'has_comments': 0,
  187. 'has_error_handling': 0,
  188. 'complexity_score': 0,
  189. 'quality_score': 0
  190. }
  191. for source_file in source_files:
  192. try:
  193. with open(source_file, 'r', encoding='utf-8') as f:
  194. content = f.read()
  195. file_size = len(content)
  196. metrics['total_size'] += file_size
  197. # 检查代码特征
  198. if re.search(r'function\s+\w+|def\s+\w+|public\s+\w+\s+\w+\s*\(', content):
  199. metrics['has_functions'] += 1
  200. if re.search(r'class\s+\w+|public\s+class\s+\w+', content):
  201. metrics['has_classes'] += 1
  202. if '//' in content or '/*' in content or '#' in content or '"""' in content:
  203. metrics['has_comments'] += 1
  204. if re.search(r'try\s*{|except:|catch\s*\(|error|exception', content, re.IGNORECASE):
  205. metrics['has_error_handling'] += 1
  206. # 计算复杂度分数(基于关键词密度)
  207. complexity_keywords = ['if', 'for', 'while', 'switch', 'case', 'else', 'elif']
  208. complexity_count = sum(content.lower().count(keyword) for keyword in complexity_keywords)
  209. metrics['complexity_score'] += complexity_count
  210. except:
  211. continue
  212. if metrics['file_count'] > 0:
  213. metrics['avg_size'] = metrics['total_size'] / metrics['file_count']
  214. # 计算质量分数
  215. score = 0
  216. score += min(metrics['file_count'] * 8, 40) # 文件数量 (最多40分)
  217. score += (metrics['has_functions'] / metrics['file_count']) * 20 # 函数定义 (20分)
  218. score += (metrics['has_classes'] / metrics['file_count']) * 15 # 类定义 (15分)
  219. score += (metrics['has_comments'] / metrics['file_count']) * 10 # 注释 (10分)
  220. score += (metrics['has_error_handling'] / metrics['file_count']) * 10 # 错误处理 (10分)
  221. score += min(metrics['complexity_score'] / metrics['file_count'], 5) # 复杂度 (5分)
  222. metrics['quality_score'] = min(score, 100)
  223. metrics['exists'] = True
  224. return metrics
  225. def analyze_database_quality(self) -> Dict[str, any]:
  226. """分析数据库质量"""
  227. db_dir = self.project_root / "output_sourcecode" / "db"
  228. if not db_dir.exists():
  229. return {'exists': False, 'quality_score': 0}
  230. sql_files = list(db_dir.glob("*.sql"))
  231. if not sql_files:
  232. return {'exists': False, 'quality_score': 0}
  233. metrics = {
  234. 'file_count': len(sql_files),
  235. 'total_size': 0,
  236. 'create_table_count': 0,
  237. 'index_count': 0,
  238. 'constraint_count': 0,
  239. 'procedure_count': 0,
  240. 'view_count': 0,
  241. 'quality_score': 0
  242. }
  243. for sql_file in sql_files:
  244. try:
  245. with open(sql_file, 'r', encoding='utf-8') as f:
  246. content = f.read().upper()
  247. metrics['total_size'] += len(content)
  248. metrics['create_table_count'] += content.count('CREATE TABLE')
  249. metrics['index_count'] += content.count('CREATE INDEX')
  250. metrics['constraint_count'] += content.count('CONSTRAINT') + content.count('PRIMARY KEY') + content.count('FOREIGN KEY')
  251. metrics['procedure_count'] += content.count('CREATE PROCEDURE') + content.count('CREATE FUNCTION')
  252. metrics['view_count'] += content.count('CREATE VIEW')
  253. except:
  254. continue
  255. # 计算质量分数
  256. score = 0
  257. score += min(metrics['create_table_count'] * 10, 40) # 表数量 (最多40分)
  258. score += min(metrics['index_count'] * 5, 15) # 索引 (最多15分)
  259. score += min(metrics['constraint_count'] * 3, 15) # 约束 (最多15分)
  260. score += min(metrics['procedure_count'] * 10, 20) # 存储过程 (最多20分)
  261. score += min(metrics['view_count'] * 5, 10) # 视图 (最多10分)
  262. metrics['quality_score'] = min(score, 100)
  263. metrics['exists'] = True
  264. return metrics
  265. def get_quality_level(self, score: float) -> str:
  266. """根据分数获取质量等级"""
  267. if score >= 90:
  268. return "优秀"
  269. elif score >= 75:
  270. return "良好"
  271. elif score >= 60:
  272. return "及格"
  273. elif score >= 40:
  274. return "较差"
  275. else:
  276. return "很差"
  277. def predict_approval_probability(self, progress_data: Dict, quality_data: Dict) -> Dict[str, any]:
  278. """预测申请成功率"""
  279. # 基于进度和质量数据预测成功率
  280. progress_weight = 0.4
  281. quality_weight = 0.6
  282. progress_score = progress_data['completion_rate']
  283. quality_score = quality_data['overall_score']
  284. # 计算加权分数
  285. weighted_score = (progress_score * progress_weight + quality_score * quality_weight)
  286. # 转换为成功率
  287. if weighted_score >= 90:
  288. probability = 0.95
  289. level = "很高"
  290. elif weighted_score >= 80:
  291. probability = 0.85
  292. level = "高"
  293. elif weighted_score >= 70:
  294. probability = 0.70
  295. level = "中等"
  296. elif weighted_score >= 60:
  297. probability = 0.55
  298. level = "较低"
  299. else:
  300. probability = 0.30
  301. level = "低"
  302. return {
  303. 'probability': probability,
  304. 'percentage': probability * 100,
  305. 'level': level,
  306. 'weighted_score': weighted_score,
  307. 'factors': {
  308. 'progress_contribution': progress_score * progress_weight,
  309. 'quality_contribution': quality_score * quality_weight
  310. }
  311. }
  312. def generate_recommendations(self, progress_data: Dict, quality_data: Dict, prediction: Dict) -> List[str]:
  313. """生成改进建议"""
  314. recommendations = []
  315. # 基于进度的建议
  316. progress = progress_data['progress']
  317. if not progress['requirements_doc']:
  318. recommendations.append("🔴 紧急:创建需求文档是所有后续工作的基础")
  319. elif not progress['framework_design']:
  320. recommendations.append("🔴 重要:生成框架设计文档以指导后续开发")
  321. elif not progress['frontend_code'] and not progress['backend_code']:
  322. recommendations.append("🔴 关键:开始生成前端和后端代码")
  323. elif not progress['merged_frontend'] or not progress['merged_backend']:
  324. recommendations.append("🟡 建议:执行代码合并以生成申请材料")
  325. # 基于质量的建议
  326. quality_components = quality_data['components']
  327. if quality_components['frontend']['exists'] and quality_components['frontend']['quality_score'] < 60:
  328. recommendations.append("🔧 前端代码质量有待提升:增加CSS样式、JavaScript交互和响应式设计")
  329. if quality_components['backend']['exists'] and quality_components['backend']['quality_score'] < 60:
  330. recommendations.append("🔧 后端代码质量有待提升:增加函数模块化、类设计和错误处理")
  331. if quality_components['database']['exists'] and quality_components['database']['quality_score'] < 60:
  332. recommendations.append("🔧 数据库设计有待完善:增加表结构、索引和约束设计")
  333. # 基于成功率预测的建议
  334. if prediction['probability'] < 0.7:
  335. recommendations.append("⚠️ 当前申请成功率偏低,建议全面提升文档质量后再提交")
  336. elif prediction['probability'] < 0.85:
  337. recommendations.append("💡 申请成功率中等,可考虑优化部分薄弱环节")
  338. return recommendations
  339. def run_monitoring(self) -> Dict[str, any]:
  340. """执行完整监控"""
  341. print_header("软著申请材料质量监控")
  342. config = self.load_config()
  343. project_name = config.get('title', '未知项目') if config else '未知项目'
  344. print_info(f"项目: {project_name}")
  345. print_info(f"监控时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  346. print()
  347. # 检查生成进度
  348. print_info("检查生成进度...")
  349. progress_data = self.check_generation_progress()
  350. # 分析代码质量
  351. print_info("分析代码质量...")
  352. quality_data = self.analyze_code_quality()
  353. # 预测申请成功率
  354. print_info("评估申请成功率...")
  355. prediction = self.predict_approval_probability(progress_data, quality_data)
  356. # 生成改进建议
  357. recommendations = self.generate_recommendations(progress_data, quality_data, prediction)
  358. return {
  359. 'project_name': project_name,
  360. 'timestamp': datetime.now().isoformat(),
  361. 'progress': progress_data,
  362. 'quality': quality_data,
  363. 'prediction': prediction,
  364. 'recommendations': recommendations
  365. }
  366. def generate_monitoring_report(monitoring_result: Dict) -> str:
  367. """生成监控报告"""
  368. current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  369. project_name = monitoring_result['project_name']
  370. progress = monitoring_result['progress']
  371. quality = monitoring_result['quality']
  372. prediction = monitoring_result['prediction']
  373. recommendations = monitoring_result['recommendations']
  374. report = f"""
  375. {'-' * 80}
  376. 软著申请材料质量监控报告
  377. {'-' * 80}
  378. 项目名称: {project_name}
  379. 监控时间: {current_time}
  380. {'-' * 80}
  381. 生成进度概览
  382. {'-' * 80}
  383. 总体完成度: {progress['completion_rate']:.1f}% ({progress['completed_stages']}/{progress['total_stages']})
  384. 进度详情:
  385. """
  386. stage_names = {
  387. 'requirements_doc': '需求文档',
  388. 'framework_design': '框架设计',
  389. 'page_list': '页面清单',
  390. 'frontend_code': '前端代码',
  391. 'backend_code': '后端代码',
  392. 'database_code': '数据库代码',
  393. 'user_manual': '用户手册',
  394. 'registration_form': '登记信息表',
  395. 'merged_frontend': '前端合并文档',
  396. 'merged_backend': '后端合并文档',
  397. 'merged_database': '数据库合并文档'
  398. }
  399. for key, completed in progress['progress'].items():
  400. status = "✓" if completed else "✗"
  401. name = stage_names.get(key, key)
  402. report += f" {status} {name}\n"
  403. report += f"""
  404. {'-' * 80}
  405. 代码质量分析
  406. {'-' * 80}
  407. 总体质量分数: {quality['overall_score']:.1f}/100 ({quality['quality_level']})
  408. 组件质量详情:
  409. """
  410. # 前端质量
  411. frontend = quality['components']['frontend']
  412. if frontend['exists']:
  413. report += f" ✓ 前端代码: {frontend['quality_score']:.1f}/100\n"
  414. report += f" - 页面文件数: {frontend['file_count']}\n"
  415. report += f" - 平均文件大小: {frontend['avg_size']:.0f} 字符\n"
  416. report += f" - CSS使用率: {frontend['has_css']}/{frontend['file_count']}\n"
  417. report += f" - JavaScript使用率: {frontend['has_js']}/{frontend['file_count']}\n"
  418. else:
  419. report += " ✗ 前端代码: 未生成\n"
  420. # 后端质量
  421. backend = quality['components']['backend']
  422. if backend['exists']:
  423. report += f" ✓ 后端代码: {backend['quality_score']:.1f}/100\n"
  424. report += f" - 源文件数: {backend['file_count']}\n"
  425. report += f" - 函数定义: {backend['has_functions']}/{backend['file_count']}\n"
  426. report += f" - 类定义: {backend['has_classes']}/{backend['file_count']}\n"
  427. report += f" - 错误处理: {backend['has_error_handling']}/{backend['file_count']}\n"
  428. else:
  429. report += " ✗ 后端代码: 未生成\n"
  430. # 数据库质量
  431. database = quality['components']['database']
  432. if database['exists']:
  433. report += f" ✓ 数据库设计: {database['quality_score']:.1f}/100\n"
  434. report += f" - 数据表数: {database['create_table_count']}\n"
  435. report += f" - 索引数: {database['index_count']}\n"
  436. report += f" - 约束数: {database['constraint_count']}\n"
  437. report += f" - 存储过程数: {database['procedure_count']}\n"
  438. else:
  439. report += " ✗ 数据库设计: 未生成\n"
  440. report += f"""
  441. {'-' * 80}
  442. 申请成功率预测
  443. {'-' * 80}
  444. 预测成功率: {prediction['percentage']:.1f}% ({prediction['level']})
  445. 加权评分: {prediction['weighted_score']:.1f}/100
  446. 评分构成:
  447. - 进度贡献: {prediction['factors']['progress_contribution']:.1f}分 (权重40%)
  448. - 质量贡献: {prediction['factors']['quality_contribution']:.1f}分 (权重60%)
  449. """
  450. # 添加改进建议
  451. if recommendations:
  452. report += f"{'-' * 80}\n改进建议\n{'-' * 80}\n\n"
  453. for i, recommendation in enumerate(recommendations, 1):
  454. report += f"{i}. {recommendation}\n"
  455. # 添加行动计划
  456. report += f"""
  457. {'-' * 80}
  458. 下一步行动计划
  459. {'-' * 80}
  460. """
  461. if progress['completion_rate'] < 50:
  462. report += "🔴 当前处于初期阶段,重点任务:\n"
  463. report += " 1. 完善需求文档内容\n"
  464. report += " 2. 生成框架设计文档\n"
  465. report += " 3. 开始代码生成工作\n"
  466. elif progress['completion_rate'] < 80:
  467. report += "🟡 当前处于开发阶段,重点任务:\n"
  468. report += " 1. 完成所有代码生成\n"
  469. report += " 2. 提升代码质量和复杂度\n"
  470. report += " 3. 准备申请材料合并\n"
  471. else:
  472. report += "🟢 当前处于收尾阶段,重点任务:\n"
  473. report += " 1. 执行代码合并脚本\n"
  474. report += " 2. 生成用户手册和登记表\n"
  475. report += " 3. 最终质量检查和提交\n"
  476. if quality['overall_score'] < 60:
  477. report += "\n🔧 质量提升重点:\n"
  478. report += " 1. 增加代码的功能复杂度\n"
  479. report += " 2. 完善错误处理和异常管理\n"
  480. report += " 3. 增强用户界面和交互设计\n"
  481. report += " 4. 优化数据库设计和约束\n"
  482. report += f"\n{'-' * 80}\n报告生成时间: {current_time}\n{'-' * 80}\n"
  483. return report
  484. def main():
  485. """主函数"""
  486. if len(sys.argv) > 1 and sys.argv[1] in ['-h', '--help']:
  487. print("软著申请材料质量监控工具")
  488. print("\n用法:")
  489. print(" python3 quality_monitor.py")
  490. print("\n功能:")
  491. print(" - 监控生成进度和质量")
  492. print(" - 分析代码复杂度和专业性")
  493. print(" - 预测申请成功率")
  494. print(" - 提供改进建议和行动计划")
  495. print("\n输出:")
  496. print(" - 终端显示监控结果")
  497. print(" - 生成详细的质量监控报告")
  498. return
  499. # 执行监控
  500. monitor = QualityMonitor()
  501. result = monitor.run_monitoring()
  502. # 显示关键结果
  503. print_header("监控结果概览")
  504. progress = result['progress']
  505. quality = result['quality']
  506. prediction = result['prediction']
  507. print_info(f"生成进度: {progress['completion_rate']:.1f}% ({progress['completed_stages']}/{progress['total_stages']})")
  508. print_info(f"代码质量: {quality['overall_score']:.1f}/100 ({quality['quality_level']})")
  509. if prediction['probability'] >= 0.8:
  510. print_success(f"申请成功率: {prediction['percentage']:.1f}% ({prediction['level']})")
  511. elif prediction['probability'] >= 0.6:
  512. print_warning(f"申请成功率: {prediction['percentage']:.1f}% ({prediction['level']})")
  513. else:
  514. print_error(f"申请成功率: {prediction['percentage']:.1f}% ({prediction['level']})")
  515. # 显示关键建议
  516. if result['recommendations']:
  517. print()
  518. print_header("关键建议")
  519. for i, recommendation in enumerate(result['recommendations'][:5], 1): # 显示前5条
  520. print_info(f"{i}. {recommendation}")
  521. # 生成并保存报告
  522. print()
  523. print_info("生成详细监控报告...")
  524. report = generate_monitoring_report(result)
  525. # 保存报告
  526. report_file = Path("质量监控报告.txt")
  527. try:
  528. with open(report_file, 'w', encoding='utf-8') as f:
  529. f.write(report)
  530. print_success(f"监控报告已保存: {report_file}")
  531. except Exception as e:
  532. print_error(f"保存报告失败: {e}")
  533. # 返回状态码
  534. if prediction['probability'] >= 0.7:
  535. sys.exit(0) # 成功
  536. else:
  537. sys.exit(1) # 需要改进
  538. if __name__ == "__main__":
  539. main()