| """ | |
| Complete Notebook Runner with Cell-by-Cell Debugging | |
| Executes all CA4 VQA notebooks and debugs errors | |
| """ | |
| import nbformat | |
| from nbconvert.preprocessors import ExecutePreprocessor, CellExecutionError | |
| import sys | |
| from pathlib import Path | |
| import json | |
| import traceback | |
| from datetime import datetime | |
| import warnings | |
| warnings.filterwarnings("ignore") | |
| class NotebookDebugger: | |
| """Runs notebooks cell by cell with debugging""" | |
| def __init__(self, notebook_path: Path, output_dir: Path): | |
| self.notebook_path = notebook_path | |
| self.output_dir = output_dir | |
| self.output_dir.mkdir(parents=True, exist_ok=True) | |
| self.results = { | |
| "notebook": str(notebook_path.name), | |
| "timestamp": datetime.now().isoformat(), | |
| "total_cells": 0, | |
| "executed_cells": 0, | |
| "failed_cells": 0, | |
| "skipped_cells": 0, | |
| "errors": [], | |
| "cell_results": [], | |
| } | |
| def load_notebook(self): | |
| """Load notebook file""" | |
| print(f"\n{'='*80}") | |
| print(f"Loading: {self.notebook_path.name}") | |
| print(f"{'='*80}") | |
| with open(self.notebook_path, "r", encoding="utf-8") as f: | |
| self.nb = nbformat.read(f, as_version=4) | |
| self.results["total_cells"] = len(self.nb.cells) | |
| print(f"Total cells: {self.results['total_cells']}") | |
| def execute_cell(self, cell, cell_index): | |
| """Execute a single cell with error handling""" | |
| cell_result = { | |
| "index": cell_index, | |
| "type": cell["cell_type"], | |
| "status": "pending", | |
| "error": None, | |
| "execution_time": 0, | |
| } | |
| # Skip non-code cells | |
| if cell["cell_type"] != "code": | |
| cell_result["status"] = "skipped" | |
| self.results["skipped_cells"] += 1 | |
| return cell_result | |
| # Get cell source | |
| source = cell["source"] | |
| # Skip empty cells | |
| if not source or not source.strip(): | |
| cell_result["status"] = "skipped" | |
| self.results["skipped_cells"] += 1 | |
| return cell_result | |
| print(f"\n[Cell {cell_index+1}/{self.results['total_cells']}] Executing...") | |
| print(f"Source preview: {source[:100]}...") | |
| try: | |
| # Create executor with kernel startup | |
| ep = ExecutePreprocessor( | |
| timeout=600, kernel_name="python3", allow_errors=False | |
| ) | |
| # Ensure kernel is started | |
| if not hasattr(self, "_kernel_manager") or self._kernel_manager is None: | |
| self._kernel_manager = ep.km | |
| # Execute cell | |
| start_time = datetime.now() | |
| # Start kernel if not already started | |
| if ep.km is None or ep.kc is None: | |
| ep.km, ep.kc = ep.start_new_kernel(cwd=str(self.notebook_path.parent)) | |
| ep.preprocess_cell( | |
| cell, {"metadata": {"path": str(self.notebook_path.parent)}}, cell_index | |
| ) | |
| end_time = datetime.now() | |
| cell_result["execution_time"] = (end_time - start_time).total_seconds() | |
| cell_result["status"] = "success" | |
| self.results["executed_cells"] += 1 | |
| print(f"✓ Success ({cell_result['execution_time']:.2f}s)") | |
| except CellExecutionError as e: | |
| cell_result["status"] = "error" | |
| cell_result["error"] = { | |
| "type": "CellExecutionError", | |
| "message": str(e), | |
| "traceback": e.traceback, | |
| } | |
| self.results["failed_cells"] += 1 | |
| self.results["errors"].append(cell_result["error"]) | |
| print(f"✗ Error: {str(e)[:200]}") | |
| print(f"Traceback:\n{e.traceback}") | |
| except Exception as e: | |
| cell_result["status"] = "error" | |
| cell_result["error"] = { | |
| "type": type(e).__name__, | |
| "message": str(e), | |
| "traceback": traceback.format_exc(), | |
| } | |
| self.results["failed_cells"] += 1 | |
| self.results["errors"].append(cell_result["error"]) | |
| print(f"✗ Unexpected error: {str(e)}") | |
| print(f"Traceback:\n{traceback.format_exc()}") | |
| return cell_result | |
| def run(self, stop_on_error=False): | |
| """Run all cells in the notebook""" | |
| self.load_notebook() | |
| # Initialize kernel manager | |
| self._kernel_manager = None | |
| try: | |
| for i, cell in enumerate(self.nb.cells): | |
| cell_result = self.execute_cell(cell, i) | |
| self.results["cell_results"].append(cell_result) | |
| # Stop on error if requested | |
| if stop_on_error and cell_result["status"] == "error": | |
| print(f"\n⚠ Stopping execution due to error in cell {i+1}") | |
| break | |
| finally: | |
| # Cleanup kernel | |
| if hasattr(self, "_kernel_manager") and self._kernel_manager is not None: | |
| try: | |
| self._kernel_manager.shutdown_kernel() | |
| except: | |
| pass | |
| # Save results | |
| self.save_results() | |
| # Save executed notebook | |
| self.save_notebook() | |
| # Print summary | |
| self.print_summary() | |
| return self.results | |
| def save_results(self): | |
| """Save execution results to JSON""" | |
| results_file = self.output_dir / f"{self.notebook_path.stem}_results.json" | |
| with open(results_file, "w", encoding="utf-8") as f: | |
| json.dump(self.results, f, indent=2) | |
| print(f"\n→ Results saved to: {results_file}") | |
| def save_notebook(self): | |
| """Save executed notebook""" | |
| output_nb = self.output_dir / f"{self.notebook_path.stem}_executed.ipynb" | |
| with open(output_nb, "w", encoding="utf-8") as f: | |
| nbformat.write(self.nb, f) | |
| print(f"→ Executed notebook saved to: {output_nb}") | |
| def print_summary(self): | |
| """Print execution summary""" | |
| print(f"\n{'='*80}") | |
| print(f"EXECUTION SUMMARY: {self.notebook_path.name}") | |
| print(f"{'='*80}") | |
| print(f"Total cells: {self.results['total_cells']}") | |
| print(f"Executed: {self.results['executed_cells']}") | |
| print(f"Failed: {self.results['failed_cells']}") | |
| print(f"Skipped: {self.results['skipped_cells']}") | |
| if self.results["failed_cells"] > 0: | |
| print(f"\n⚠ {self.results['failed_cells']} cells failed:") | |
| for i, error in enumerate(self.results["errors"], 1): | |
| print(f" {i}. {error['type']}: {error['message'][:100]}") | |
| else: | |
| print(f"\n✓ All cells executed successfully!") | |
| def main(): | |
| """Main execution function""" | |
| print("╔" + "=" * 78 + "╗") | |
| print("║" + " " * 78 + "║") | |
| print( | |
| "║" + "CA4 VQA Notebooks - Complete Execution & Debug System".center(78) + "║" | |
| ) | |
| print("║" + " " * 78 + "║") | |
| print("╚" + "=" * 78 + "╝") | |
| # Project paths | |
| project_root = Path(__file__).parent | |
| notebooks_dir = project_root / "notebooks" | |
| output_dir = project_root / "data" / "notebook_results" | |
| # Find all notebooks | |
| notebooks = list(notebooks_dir.glob("*.ipynb")) | |
| if not notebooks: | |
| print("⚠ No notebooks found!") | |
| return | |
| print(f"\nFound {len(notebooks)} notebook(s):") | |
| for nb in notebooks: | |
| print(f" • {nb.name}") | |
| # Results summary | |
| all_results = [] | |
| # Execute each notebook | |
| for notebook in notebooks: | |
| try: | |
| debugger = NotebookDebugger(notebook, output_dir) | |
| results = debugger.run(stop_on_error=False) | |
| all_results.append(results) | |
| except Exception as e: | |
| print(f"\n✗ Failed to process {notebook.name}: {str(e)}") | |
| print(traceback.format_exc()) | |
| # Overall summary | |
| print(f"\n{'='*80}") | |
| print(f"OVERALL SUMMARY") | |
| print(f"{'='*80}") | |
| print(f"Notebooks processed: {len(all_results)}/{len(notebooks)}") | |
| total_cells = sum(r["total_cells"] for r in all_results) | |
| total_executed = sum(r["executed_cells"] for r in all_results) | |
| total_failed = sum(r["failed_cells"] for r in all_results) | |
| print(f"Total cells: {total_cells}") | |
| print(f"Executed: {total_executed}") | |
| print(f"Failed: {total_failed}") | |
| print( | |
| f"Success rate: {(total_executed/(total_executed+total_failed)*100):.1f}%" | |
| if (total_executed + total_failed) > 0 | |
| else "N/A" | |
| ) | |
| # Save overall summary | |
| summary_file = ( | |
| output_dir | |
| / f"execution_summary_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json" | |
| ) | |
| with open(summary_file, "w", encoding="utf-8") as f: | |
| json.dump( | |
| { | |
| "timestamp": datetime.now().isoformat(), | |
| "notebooks": all_results, | |
| "summary": { | |
| "total_notebooks": len(notebooks), | |
| "processed_notebooks": len(all_results), | |
| "total_cells": total_cells, | |
| "total_executed": total_executed, | |
| "total_failed": total_failed, | |
| }, | |
| }, | |
| f, | |
| indent=2, | |
| ) | |
| print(f"\n→ Overall summary saved to: {summary_file}") | |
| print(f"\n{'='*80}") | |
| print("Execution complete!") | |
| print(f"{'='*80}") | |
| if __name__ == "__main__": | |
| main() | |
Xet Storage Details
- Size:
- 9.43 kB
- Xet hash:
- fc51961ab7cc356087b972041730ce9381fcb237641c6ba9b8b1ecbd101006a9
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.