/
nevers
/
hackINTERPOL
Обзор
Документация
Войти
/
nevers
/
hackINTERPOL
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/studypulse/cli.py
123 строки
4 KB
nevers
upload files
13 янв 2026, 17:20
13 янв 2026, 17:20
9f6acdd
Код
Авторство
О чём код?
"""CLI interface for StudyPulse.""" import json from pathlib import Path import sys from typing import Any import typer from studypulse.io import load_and_validate from studypulse.metrics import ( compute_descriptive_stats, compute_risk_flags, compute_risk_score, get_top_risks, ) from studypulse.report import generate_html_report app = typer.Typer( name="studypulse", help="StudyPulse: Learning Analytics CLI + HTML Report Generator", add_completion=False, ) @app.command() def validate( input: str = typer.Option(..., "--input", "-i", help="Path to input CSV file"), ) -> None: """Validate CSV file schema and data ranges. Exits with code 0 on success, 1 on validation failure. """ try: df = load_and_validate(input) print(f"✓ Validation passed: {len(df)} records found") print(f" Columns: {', '.join(df.columns)}") except SystemExit: raise except Exception as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) @app.command() def analyze( input: str = typer.Option(..., "--input", "-i", help="Path to input CSV file"), out: str = typer.Option( ..., "--out", "-o", help="Path to output JSON summary file" ), ) -> None: """Compute analytics and write JSON summary. Prints concise console summary and writes detailed JSON to output file. """ try: df = load_and_validate(input) df_with_risk = compute_risk_score(compute_risk_flags(df)) stats = compute_descriptive_stats(df) top_risks = get_top_risks(df_with_risk, top_n=10) # Print console summary print("=" * 60) print("StudyPulse Analytics Summary") print("=" * 60) print(f"Total Students: {stats['total_students']}") print(f"Mean Assignment Score: {stats['mean_assignment_score']:.2f}") print(f"Mean Attendance Rate: {stats['mean_attendance_rate']:.2%}") print(f"Students at Risk: {stats['low_score_count'] + stats['low_attendance_count'] + stats['inactive_count']}") print("\nTop 3 Risk Students:") for _idx, row in top_risks.head(3).iterrows(): print( f" {row['student_name']} (ID: {row['student_id']}) - " f"Risk Score: {row['risk_score']:.1f}" ) print("=" * 60) # Build JSON summary summary: dict[str, Any] = { "summary_stats": stats, "top_risks": top_risks.to_dict(orient="records"), "total_records": len(df), } # Write JSON out_path = Path(out) out_path.parent.mkdir(parents=True, exist_ok=True) with open(out_path, "w", encoding="utf-8") as f: json.dump(summary, f, indent=2, default=str) print(f"\n✓ JSON summary written to: {out}") except SystemExit: raise except Exception as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) @app.command() def report( input: str = typer.Option(..., "--input", "-i", help="Path to input CSV file"), out: str = typer.Option(..., "--out", "-o", help="Path to output HTML report"), ) -> None: """Generate HTML report with analytics and visualizations. Creates a self-contained HTML file with tables and embedded plots. """ try: df = load_and_validate(input) generate_html_report(df, out) print(f"✓ HTML report generated: {out}") print(f" Open in browser to view: file://{Path(out).absolute()}") except SystemExit: raise except Exception as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) if __name__ == "__main__": app()