Download scripts/cli.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 11.2 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/scripts/cli.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/scripts/cli.py
-
curl -L -o cli.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/scripts/cli.py
11.2 kB
| #!/usr/bin/env python3 | |
| """ | |
| YAZ Care Platform CLI | |
| Command-line interface for healthcare analytics | |
| """ | |
| import argparse | |
| import asyncio | |
| import json | |
| import sys | |
| from pathlib import Path | |
| from typing import Dict, List, Optional | |
| # Add src to path for imports | |
| sys.path.insert(0, str(Path(__file__).parent / "src")) | |
| try: | |
| # Try to import the required modules | |
| from core.api_client import APIClient | |
| API_AVAILABLE = True | |
| except ImportError: | |
| # Fallback mode without API client | |
| API_AVAILABLE = False | |
| print("⚠️ API client not available. Running in demo mode.") | |
| class YazCareCLI: | |
| """Command-line interface for YAZ Care Platform""" | |
| def __init__(self): | |
| if API_AVAILABLE: | |
| self.client = APIClient() | |
| else: | |
| self.client = None | |
| def print_banner(self): | |
| """Print YAZ Care banner""" | |
| banner = """ | |
| ╔══════════════════════════════════════════════════════════════╗ | |
| ║ YAZ Care Platform ║ | |
| ║ Healthcare Analytics & Management ║ | |
| ╚══════════════════════════════════════════════════════════════╝ | |
| """ | |
| print(banner) | |
| def print_table(self, data: List[Dict], headers: Optional[List[str]] = None): | |
| """Print data as a formatted table""" | |
| if not data: | |
| print("No data available") | |
| return | |
| if not headers: | |
| headers = list(data[0].keys()) if data else [] | |
| # Calculate column widths | |
| widths = {} | |
| for header in headers: | |
| widths[header] = max(len(str(header)), | |
| max(len(str(row.get(header, ""))) for row in data)) | |
| # Print header | |
| header_row = " | ".join(f"{header:<{widths[header]}}" for header in headers) | |
| print(header_row) | |
| print("-" * len(header_row)) | |
| # Print data rows | |
| for row in data: | |
| data_row = " | ".join(f"{str(row.get(header, '')):<{widths[header]}}" for header in headers) | |
| print(data_row) | |
| def list_studies(self): | |
| """List all studies""" | |
| print("\n📊 Studies:") | |
| print("-" * 50) | |
| try: | |
| # Mock data for CLI demo | |
| studies = [ | |
| {"ID": "1", "Name": "Oujda_2025_Gastric_ADK_CI", "Status": "Active", "Patients": 127}, | |
| {"ID": "2", "Name": "Casablanca_D2_Validation", "Status": "Completed", "Patients": 89}, | |
| {"ID": "3", "Name": "FLOT_Dosing_Analysis", "Status": "In Progress", "Patients": 156} | |
| ] | |
| self.print_table(studies) | |
| except Exception as e: | |
| print(f"Error fetching studies: {e}") | |
| def import_study(self, file_path: str, study_name: str): | |
| """Import study data from file""" | |
| print(f"\n📁 Importing study: {study_name}") | |
| print(f"File: {file_path}") | |
| print("-" * 50) | |
| try: | |
| if not Path(file_path).exists(): | |
| print(f"❌ File not found: {file_path}") | |
| return | |
| # Mock import process | |
| print("🔄 Processing file...") | |
| print("✅ Validating data format...") | |
| print("✅ Importing patient records...") | |
| print("✅ Running quality checks...") | |
| print(f"✅ Study '{study_name}' imported successfully!") | |
| print(f" - Records processed: 127") | |
| print(f" - Validation errors: 0") | |
| print(f" - Warnings: 3") | |
| except Exception as e: | |
| print(f"❌ Import failed: {e}") | |
| def run_analysis(self, study_id: str, analysis_type: str = "survival"): | |
| """Run analysis on study data""" | |
| print(f"\n📈 Running {analysis_type} analysis") | |
| print(f"Study ID: {study_id}") | |
| print("-" * 50) | |
| try: | |
| print("🔄 Loading study data...") | |
| print("🔄 Running statistical analysis...") | |
| print("🔄 Generating results...") | |
| # Mock analysis results | |
| results = { | |
| "study_id": study_id, | |
| "analysis_type": analysis_type, | |
| "total_patients": 127, | |
| "survival_rate": "94.2%", | |
| "median_follow_up": "18.3 months", | |
| "complications_rate": "5.8%" | |
| } | |
| print("✅ Analysis completed!") | |
| print("\n📋 Results:") | |
| for key, value in results.items(): | |
| print(f" {key.replace('_', ' ').title()}: {value}") | |
| except Exception as e: | |
| print(f"❌ Analysis failed: {e}") | |
| def validate_cohort(self, study_id: str): | |
| """Validate study cohort""" | |
| print(f"\n🔍 Validating cohort for study: {study_id}") | |
| print("-" * 50) | |
| try: | |
| print("🔄 Checking data completeness...") | |
| print("🔄 Validating D2 compliance...") | |
| print("🔄 Analyzing FLOT dosing intensity...") | |
| # Mock validation results | |
| validation = { | |
| "total_patients": 127, | |
| "complete_records": 124, | |
| "d2_compliant": 119, | |
| "missing_data": 3, | |
| "quality_score": "94.5%" | |
| } | |
| print("✅ Validation completed!") | |
| print("\n📋 Validation Summary:") | |
| for key, value in validation.items(): | |
| print(f" {key.replace('_', ' ').title()}: {value}") | |
| # Print warnings if any | |
| if validation["missing_data"] > 0: | |
| print(f"\n⚠️ {validation['missing_data']} patients have missing data fields") | |
| except Exception as e: | |
| print(f"❌ Validation failed: {e}") | |
| def show_status(self): | |
| """Show platform status""" | |
| print("\n📊 Platform Status:") | |
| print("-" * 50) | |
| try: | |
| status = { | |
| "🟢 System": "Operational", | |
| "📚 Active Studies": "3", | |
| "👥 Total Patients": "372", | |
| "⚡ Processing Queue": "Empty", | |
| "💾 Storage Used": "1.2 GB", | |
| "🔄 Last Backup": "2 hours ago" | |
| } | |
| for key, value in status.items(): | |
| print(f"{key}: {value}") | |
| except Exception as e: | |
| print(f"❌ Status check failed: {e}") | |
| def run_interactive(self): | |
| """Run interactive CLI mode""" | |
| self.print_banner() | |
| print("🚀 Welcome to YAZ Care Platform CLI") | |
| print("Type 'help' for available commands or 'quit' to exit\n") | |
| commands = { | |
| "studies": "List all studies", | |
| "status": "Show platform status", | |
| "import": "Import study data (usage: import <file> <study_name>)", | |
| "analyze": "Run analysis (usage: analyze <study_id> [analysis_type])", | |
| "validate": "Validate cohort (usage: validate <study_id>)", | |
| "help": "Show this help message", | |
| "quit": "Exit the CLI" | |
| } | |
| while True: | |
| try: | |
| cmd = input("yaz-care> ").strip().split() | |
| if not cmd: | |
| continue | |
| command = cmd[0].lower() | |
| if command == "quit": | |
| print("👋 Goodbye!") | |
| break | |
| elif command == "help": | |
| print("\n📖 Available Commands:") | |
| for cmd_name, desc in commands.items(): | |
| print(f" {cmd_name:<10} - {desc}") | |
| print() | |
| elif command == "studies": | |
| self.list_studies() | |
| elif command == "status": | |
| self.show_status() | |
| elif command == "import" and len(cmd) >= 3: | |
| file_path = cmd[1] | |
| study_name = " ".join(cmd[2:]) | |
| self.import_study(file_path, study_name) | |
| elif command == "analyze" and len(cmd) >= 2: | |
| study_id = cmd[1] | |
| analysis_type = cmd[2] if len(cmd) > 2 else "survival" | |
| self.run_analysis(study_id, analysis_type) | |
| elif command == "validate" and len(cmd) >= 2: | |
| study_id = cmd[1] | |
| self.validate_cohort(study_id) | |
| else: | |
| print(f"❌ Unknown command: {command}") | |
| print("Type 'help' for available commands") | |
| except KeyboardInterrupt: | |
| print("\n👋 Goodbye!") | |
| break | |
| except Exception as e: | |
| print(f"❌ Error: {e}") | |
| def main(): | |
| """Main CLI entry point""" | |
| parser = argparse.ArgumentParser( | |
| description="YAZ Care Platform CLI", | |
| formatter_class=argparse.RawDescriptionHelpFormatter, | |
| epilog=""" | |
| Examples: | |
| %(prog)s # Interactive mode | |
| %(prog)s studies # List studies | |
| %(prog)s import data.csv "Study Name" # Import study | |
| %(prog)s analyze study_1 survival # Run analysis | |
| %(prog)s validate study_1 # Validate cohort | |
| %(prog)s status # Show status | |
| """ | |
| ) | |
| parser.add_argument("command", nargs="?", help="Command to execute") | |
| parser.add_argument("args", nargs="*", help="Command arguments") | |
| parser.add_argument("--version", action="version", version="YAZ Care Platform CLI v1.0.0") | |
| args = parser.parse_args() | |
| cli = YazCareCLI() | |
| if not args.command: | |
| # Interactive mode | |
| cli.run_interactive() | |
| else: | |
| # Single command mode | |
| command = args.command.lower() | |
| if command == "studies": | |
| self.list_studies() | |
| elif command == "status": | |
| self.show_status() | |
| elif command == "import" and len(args.args) >= 2: | |
| file_path = args.args[0] | |
| study_name = " ".join(args.args[1:]) | |
| self.import_study(file_path, study_name) | |
| elif command == "analyze" and len(args.args) >= 1: | |
| study_id = args.args[0] | |
| analysis_type = args.args[1] if len(args.args) > 1 else "survival" | |
| self.run_analysis(study_id, analysis_type) | |
| elif command == "validate" and len(args.args) >= 1: | |
| study_id = args.args[0] | |
| self.validate_cohort(study_id) | |
| else: | |
| cli.print_banner() | |
| print(f"❌ Unknown command: {command}") | |
| print("Use --help for usage information") | |
| if __name__ == "__main__": | |
| main() | |