File size: 5,131 Bytes
2ab2b76 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | """Generate the four modular Colab-ready notebooks matching the repository architecture."""
import nbformat as nbf
from src.config import NOTEBOOKS_DIR
COMMON_SETUP = (
"import json, sys\n"
"from pathlib import Path\n"
"import pandas as pd\n"
"ROOT = Path('.').resolve()\n"
"if not (ROOT / 'src').exists() and (ROOT.parent / 'src').exists():\n"
" ROOT = ROOT.parent\n"
"if str(ROOT) not in sys.path:\n"
" sys.path.insert(0, str(ROOT))\n"
"print('Workspace root:', ROOT)"
)
def _save_nb(nb, filename: str) -> None:
nb["metadata"] = {
"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},
"language_info": {"name": "python", "version": "3.11"},
}
out = NOTEBOOKS_DIR / filename
with out.open("w", encoding="utf-8") as f:
nbf.write(nb, f)
print(f"Wrote {out}")
def build_all_notebooks() -> None:
NOTEBOOKS_DIR.mkdir(parents=True, exist_ok=True)
# 01_dataset_preparation.ipynb
nb1 = nbf.v4.new_notebook()
nb1["cells"] = [
nbf.v4.new_markdown_cell("# 01 — Corpus, Source Manifest & Bilingual Intent Dataset Preparation"),
nbf.v4.new_code_cell(COMMON_SETUP),
nbf.v4.new_code_cell(
"from scripts.verify_dataset import verify_all\n"
"summary = verify_all()\n"
"manifest = pd.read_csv(ROOT / 'data' / 'manifests' / 'source_manifest.csv')\n"
"display(manifest[['document_id', 'format', 'date', 'version', 'amends_doc_id', 'title']])"
),
nbf.v4.new_code_cell(
"intents_df = pd.read_csv(ROOT / 'data' / 'intent_dataset.csv')\n"
"display(pd.crosstab(intents_df['intent'], [intents_df['split'], intents_df['language']]))"
),
]
_save_nb(nb1, "01_dataset_preparation.ipynb")
# 02_baseline_training.ipynb
nb2 = nbf.v4.new_notebook()
nb2["cells"] = [
nbf.v4.new_markdown_cell("# 02 — TF-IDF + Logistic Regression Baseline Training & Validation Tuning"),
nbf.v4.new_code_cell(COMMON_SETUP),
nbf.v4.new_code_cell(
"from scripts.train_classifiers import train_tfidf_baseline\n"
"df = pd.read_csv(ROOT / 'data' / 'intent_dataset.csv')\n"
"baseline_res = train_tfidf_baseline(df)\n"
"print('Selected baseline settings:', baseline_res['selected_settings'])\n"
"print('Val Macro-F1:', baseline_res['val_macro_f1'], '| Test Macro-F1:', baseline_res['test_macro_f1'])\n"
"display(pd.DataFrame(baseline_res['validation_trials']))"
),
]
_save_nb(nb2, "02_baseline_training.ipynb")
# 03_encoder_finetuning.ipynb
nb3 = nbf.v4.new_notebook()
nb3["cells"] = [
nbf.v4.new_markdown_cell("# 03 — Fine-Tuning Small Multilingual Afro-XLMR Intent Encoder"),
nbf.v4.new_code_cell(COMMON_SETUP),
nbf.v4.new_code_cell(
"from scripts.train_classifiers import train_finetuned_encoder\n"
"from src.classification.classifier import EncoderIntentClassifier\n"
"comp_path = ROOT / 'artifacts' / 'classifier_comparison.json'\n"
"if comp_path.exists():\n"
" enc_res = json.loads(comp_path.read_text(encoding='utf-8'))['fine_tuned_encoder']\n"
"else:\n"
" df = pd.read_csv(ROOT / 'data' / 'intent_dataset.csv')\n"
" enc_res = train_finetuned_encoder(df)\n"
"print('Test Macro-F1:', enc_res['test_macro_f1'], '| Settings:', enc_res['selected_settings'])\n"
"clf = EncoderIntentClassifier()\n"
"print('Checkpoint reload check:', clf.predict('I fit still apply on 12 June?'))"
),
]
_save_nb(nb3, "03_encoder_finetuning.ipynb")
# 04_model_evaluation.ipynb
nb4 = nbf.v4.new_notebook()
nb4["cells"] = [
nbf.v4.new_markdown_cell("# 04 — Classifier Comparison, Confusion Matrix & End-to-End Rubric Evaluation"),
nbf.v4.new_code_cell(COMMON_SETUP),
nbf.v4.new_code_cell(
"comp = json.loads((ROOT / 'artifacts' / 'classifier_comparison.json').read_text(encoding='utf-8'))\n"
"print('Baseline Test Macro-F1:', comp['baseline']['test_macro_f1'])\n"
"print('Encoder Test Macro-F1 :', comp['fine_tuned_encoder']['test_macro_f1'])\n"
"labels = comp['fine_tuned_encoder']['confusion_matrix_labels']\n"
"display(pd.DataFrame(comp['fine_tuned_encoder']['confusion_matrix'], index=labels, columns=labels))"
),
nbf.v4.new_code_cell(
"from src.evaluation.metrics import compute_aggregates\n"
"e2e_path = ROOT / 'evaluation' / 'actual_outputs' / 'e2e_results.jsonl'\n"
"if e2e_path.exists():\n"
" records = [json.loads(line) for line in e2e_path.read_text(encoding='utf-8').splitlines() if line.strip()]\n"
" agg = compute_aggregates(records)\n"
" print(json.dumps(agg['metrics'], indent=2))"
),
]
_save_nb(nb4, "04_model_evaluation.ipynb")
if __name__ == "__main__":
build_all_notebooks()
|