CoolFace
Apppublic

sandy45/ChestViT-Explainable-XRay-AI

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
demo_launch.py85 linesDownload Raw Back to root
1"""2demo_launch.py3--------------4One-command launcher for the ChestViT Gradio demo.5Handles Windows encoding, DEMO_MODE, and opens browser automatically.6 7Usage:8  python demo_launch.py              # Auto-detect: use trained model if exists9  python demo_launch.py --demo       # Force DEMO_MODE (random weights, works instantly)10  python demo_launch.py --port 7861  # Custom port11"""12 13import os14import sys15import argparse16from pathlib import Path17 18# MUST be first — fix Windows console encoding before any other imports19if sys.platform == "win32":20    sys.stdout.reconfigure(encoding="utf-8", errors="replace")21    sys.stderr.reconfigure(encoding="utf-8", errors="replace")22    os.environ.setdefault("PYTHONIOENCODING", "utf-8")23 24# Add project root to path25sys.path.insert(0, str(Path(__file__).parent))26 27def main():28    parser = argparse.ArgumentParser(description="Launch ChestViT Gradio Demo")29    parser.add_argument("--demo", action="store_true",30                        help="Force DEMO_MODE (random weights, no checkpoint needed)")31    parser.add_argument("--port", type=int, default=7860,32                        help="Port for Gradio server (default: 7860)")33    parser.add_argument("--share", action="store_true",34                        help="Create a public Gradio share link")35    args = parser.parse_args()36 37    # Check for trained checkpoint38    ckpt = Path("checkpoints/best_model.pt")39    if not ckpt.exists() and not args.demo:40        print("\n  No trained checkpoint found at checkpoints/best_model.pt")41        print("  Automatically switching to DEMO_MODE (random weights).")42        print("  UI and attention rollout will be fully functional.")43        print("  To get real predictions: run python training/train.py first.\n")44        args.demo = True45 46    if args.demo:47        os.environ["DEMO_MODE"] = "1"48        print("\n  [DEMO MODE] Starting with random weights.")49        print("  Attention rollout maps will still show real spatial patterns.\n")50    else:51        print(f"\n  Loading trained model from: {ckpt}")52 53    # Override config port if specified54    if args.port != 7860:55        # Temporarily patch config56        import yaml57        cfg_path = Path("config/config.yaml")58        with open(cfg_path) as f:59            cfg = yaml.safe_load(f)60        cfg["inference"]["gradio_port"] = args.port61        cfg["inference"]["gradio_share"] = args.share62        with open(cfg_path, "w") as f:63            yaml.dump(cfg, f, default_flow_style=False, allow_unicode=True)64 65    print("  Starting Gradio server...")66    print(f"  URL: http://localhost:{args.port}")67    print("  Press Ctrl+C to stop.\n")68 69    # Import and run70    from app.gradio_app import build_interface71    from config_loader import load_config72 73    cfg = load_config()74    demo = build_interface()75    demo.launch(76        server_port=args.port,77        share=args.share,78        show_error=True,79        inbrowser=True,80    )81 82 83if __name__ == "__main__":84    main()85