Datasets:
Bappadala Rohith Kumar Naidu commited on
Commit ·
81e2e9c
1
Parent(s): ac89bce
fix(notebooks): remap markdown documentation cells to precisely match target code cells
Browse filesFiles changed (8)
- notebooks/Accident_EDA_&_Hotspot_Generator_chatbot_service_data_accidents_3.ipynb+7-7
- notebooks/ChromaDB_RAG_Vectorstore_Build_chatbot_service_data_chroma_db_2.ipynb+59-59
- notebooks/Risk_Model_ONNX_Training_frontend_public_models_5.ipynb+4-4
- notebooks/Roads_Data_Processing_backend_data_4.ipynb+4-4
- notebooks/YOLOv8_Pothole_Detector_Training_frontend_public_models_1.ipynb+51-50
- notebooks/cell_dump.txtAdded+40
- notebooks/check_cells.pyAdded+17
- notebooks/smart_inject.pyAdded+132
19 unmodified lines20212223232425262627282917 unmodified lines4748495050515253239 unmodified lines29329429529629629729829940 unmodified lines340341342343343344345346101 unmodified lines44844945045145145245345445445545645719 unmodified lines "source": [ "# 🗺️ Accident EDA & Blackspot Hotspot Generator\n", "\n", "**Part of:** SafeVisionAI · IIT Madras Road Safety Hackathon 2026 \n", "**Part of:** SafeVisionAI · IIT Madras Road Safety Hackathon 2026\n", "**Output:** `accidents_summary.json` + `blackspot_seed.csv` → seeded to the backend database\n", "\n", "This notebook processes the **Kaggle India Road Accidents dataset** (1M+ rows) \n", "This notebook processes the **Kaggle India Road Accidents dataset** (1M+ rows)\n", "to produce two key intelligence artifacts:\n", "\n", "1. **`accidents_summary.json`** — National total + top 10 states by accident count\n",17 unmodified lines "source": [ "## 📂 Step 0 — Upload Accidents Dataset\n", "\n", "Upload `kaggle_india_accidents.csv` from: \n", "Upload `kaggle_india_accidents.csv` from:\n", "```\n", "chatbot_service/data/accidents/kaggle_india_accidents.csv\n", "```\n",239 unmodified lines "source": [ "## 📖 Step 1 — Load & Normalize Dataset\n", "\n", "Reads the CSV and normalizes all column names to lowercase snake_case. \n", "Reads the CSV and normalizes all column names to lowercase snake_case.\n", "Result: **1,048,575 rows** of accident records across Indian states.\n", "\n", "> 💡 The mixed-type DtypeWarning is expected for columns with mixed numeric/string data."40 unmodified lines "source": [ "## 📊 Step 2 — Generate National Summary JSON\n", "\n", "Auto-detects the `state` and `accident` columns using flexible column name matching, \n", "Auto-detects the `state` and `accident` columns using flexible column name matching,\n", "then computes:\n", "- **National total** — sum of all accident counts\n", "- **Top 10 states** — ranked by accident volume\n",101 unmodified lines "source": [ "## 📍 Step 3 — Generate GPS Blackspot Clusters\n", "\n", "Groups accident records by rounded GPS coordinates (2 decimal places ≈ ~1km²), \n", "Groups accident records by rounded GPS coordinates (2 decimal places ≈ ~1km²),\n", "then counts accidents per grid cell.\n", "\n", "Result: **4,134 blackspot clusters** exported as `blackspot_seed.csv` \n", "Result: **4,134 blackspot clusters** exported as `blackspot_seed.csv`\n", "→ This CSV is loaded by `backend/scripts/app/seed_emergency.py` to populate the PostGIS accident layer.\n", "\n", "| Column | Description |\n",7889 unmodified lines7890789178927893789378947895789678977896789778987899790011 unmodified lines791279137914791579167917791879197920792179227923792479257926792779157916791747 unmodified lines79657966796779817982798379847985798679877968796979897970797179727973797479757976797722 unmodified lines8000800180028018801980208021802280238024802580268027802880298030800380048005666 unmodified lines8672867386748703870487058706870787088709871087118712871387148715871686758676867735 unmodified lines8713871487158758871687178760876187188719872087218722872387638724872587268727248 unmodified lines8976897789789018897989809020902189818982898390238984898589868987898824 unmodified lines9013901490159016901790189019902090219022902390249025902690279028902990309031903220 unmodified lines90539054905590569057905890599060906190629063906490659066906790689069907042 unmodified lines9113911491159116911791189119912091219122912391249125912691279128912991307889 unmodified lines "source": [ "# 🧠 ChromaDB RAG Vectorstore — Legal & Medical PDF Ingestion\n", "\n", "**Part of:** SafeVisionAI · IIT Madras Road Safety Hackathon 2026 \n", "**Part of:** SafeVisionAI · IIT Madras Road Safety Hackathon 2026\n", "**Output:** `chroma_db/` directory → deployed to `chatbot_service/data/chroma_db/`\n", "\n", "This notebook builds the **Retrieval-Augmented Generation (RAG)** knowledge base for the SafeVisionAI chatbot. \n", "It ingests Indian legal documents (Motor Vehicles Act, MoRTH circulars) and first-aid medical PDFs, \n", "This notebook builds the **Retrieval-Augmented Generation (RAG)** knowledge base for the SafeVisionAI chatbot.\n", "It ingests Indian legal documents (Motor Vehicles Act, MoRTH circulars) and first-aid medical PDFs,\n", "chunks them, embeds them using `sentence-transformers`, and stores them in a **ChromaDB** vector store.\n", "\n", "---\n",11 unmodified lines "> 💡 The resulting `chroma_db/` is what the chatbot queries at runtime for grounded answers." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 🔧 Step 1 — Install Dependencies\n", "\n", "Installs the full RAG stack:\n", "- `chromadb` — local vector database for semantic search\n", "- `sentence-transformers` — `all-MiniLM-L6-v2` model for text embeddings\n", "- `pdfplumber` — PDF text extraction with page layout awareness\n", "- `langchain` — document chunking utilities" ] }, { "cell_type": "code", "source": [47 unmodified lines "cell_type": "markdown", "metadata": {}, "source": [ "## 📂 Step 2 — Upload PDF Documents\n", "\n", "Upload all legal and medical PDFs from: \n", "```\n", "chatbot_service/data/legal/\n", "chatbot_service/data/medical/\n", "```\n", "## 🔧 Step 1 — Install Dependencies\n", "\n", "> 📄 Expected PDFs: Motor_Vehicles_Act.pdf, MoRTH_2022_Report.pdf, first_aid_guide.pdf, etc." "Installs the full RAG stack:\n", "- `chromadb` — local vector database for semantic search\n", "- `sentence-transformers` — `all-MiniLM-L6-v2` model for text embeddings\n", "- `pdfplumber` — PDF text extraction with page layout awareness\n", "- `langchain` — document chunking utilities" ] }, {22 unmodified lines } ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ✂️ Step 3 — Extract & Chunk PDF Text\n", "\n", "Uses `pdfplumber` to extract text from each PDF page, \n", "then splits into fixed-size chunks (512 tokens) with 50-token overlap.\n", "\n", "Chunking ensures the embedding model sees coherent, context-rich passages \n", "rather than arbitrarily cut sentences." ] }, { "cell_type": "code", "source": [666 unmodified lines } ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 🔢 Step 4 — Generate Embeddings\n", "\n", "Uses the `all-MiniLM-L6-v2` sentence-transformer model to convert each text chunk \n", "into a 384-dimensional embedding vector.\n", "\n", "| Model | Dimensions | Speed | Quality |\n", "|-------|-----------|-------|---------|\n", "| all-MiniLM-L6-v2 | 384 | Fast | Good for semantic QA |" ] }, { "cell_type": "code", "source": [35 unmodified lines "cell_type": "markdown", "metadata": {}, "source": [ "## 💾 Step 5 — Build & Persist ChromaDB Index\n", "## 📂 Step 2 — Upload PDF Documents\n", "\n", "Creates a persistent ChromaDB collection and upserts all embedded chunks. \n", "The resulting `chroma_db/` folder contains the SQLite + vector index files.\n", "Upload all legal and medical PDFs from:\n", "```\n", "chatbot_service/data/legal/\n", "chatbot_service/data/medical/\n", "```\n", "\n", "> 📦 Output size: ~50-100MB depending on number of PDFs ingested." "> 📄 Expected PDFs: Motor_Vehicles_Act.pdf, MoRTH_2022_Report.pdf, first_aid_guide.pdf, etc." ] }, {248 unmodified lines "cell_type": "markdown", "metadata": {}, "source": [ "## 📥 Step 6 — Download ChromaDB\n", "## ✂️ Step 3 — Extract & Chunk PDF Text\n", "\n", "Zips the `chroma_db/` directory and downloads it for deployment. \n", "Place the extracted folder at: `chatbot_service/data/chroma_db/`\n", "Uses `pdfplumber` to extract text from each PDF page,\n", "then splits into fixed-size chunks (512 tokens) with 50-token overlap.\n", "\n", "The chatbot service auto-loads this at startup — no rebuild needed." "Chunking ensures the embedding model sees coherent, context-rich passages\n", "rather than arbitrarily cut sentences." ] }, {24 unmodified lines "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 🔢 Step 4 — Generate Embeddings\n", "\n", "Uses the `all-MiniLM-L6-v2` sentence-transformer model to convert each text chunk\n", "into a 384-dimensional embedding vector.\n", "\n", "| Model | Dimensions | Speed | Quality |\n", "|-------|-----------|-------|---------|\n", "| all-MiniLM-L6-v2 | 384 | Fast | Good for semantic QA |" ] }, { "cell_type": "code", "source": [20 unmodified lines } ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 💾 Step 5 — Build & Persist ChromaDB Index\n", "\n", "Creates a persistent ChromaDB collection and upserts all embedded chunks.\n", "The resulting `chroma_db/` folder contains the SQLite + vector index files.\n", "\n", "> 📦 Output size: ~50-100MB depending on number of PDFs ingested." ] }, { "cell_type": "code", "source": [42 unmodified lines } ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 📥 Step 6 — Download ChromaDB\n", "\n", "Zips the `chroma_db/` directory and downloads it for deployment.\n", "Place the extracted folder at: `chatbot_service/data/chroma_db/`\n", "\n", "The chatbot service auto-loads this at startup — no rebuild needed." ] }, { "cell_type": "code", "source": [19 unmodified lines20212223232425262627282970 unmodified lines10010110210310310410510688 unmodified lines19519619719819819920020119 unmodified lines "source": [ "# ⚡ Road Risk Scoring Model — ONNX Training Pipeline\n", "\n", "**Part of:** SafeVisionAI · IIT Madras Road Safety Hackathon 2026 \n", "**Part of:** SafeVisionAI · IIT Madras Road Safety Hackathon 2026\n", "**Output:** `risk_model.onnx` (~21KB) → deployed to `frontend/public/models/`\n", "\n", "This notebook trains a **GradientBoosting classifier** to predict real-time road risk \n", "This notebook trains a **GradientBoosting classifier** to predict real-time road risk\n", "and exports it as ONNX for **in-browser inference** — no server call needed.\n", "\n", "---\n",70 unmodified lines "| `speed_limit` | 40/60/80/100 | Posted speed (km/h) |\n", "| `prev_accidents` | Poisson(2) | Historical accident count |\n", "\n", "**Label logic:** `high_risk = 1` when: Night hours (10pm–4am) + National/State Highway + Raining \n", "**Label logic:** `high_risk = 1` when: Night hours (10pm–4am) + National/State Highway + Raining\n", "This reflects real-world patterns from the India accident dataset." ] },88 unmodified lines "- **Input:** `FloatTensorType([None, 5])` — batch of 5-feature vectors\n", "- **Output:** Risk probability + binary class label\n", "\n", "Download `risk_model.onnx` and place at: \n", "Download `risk_model.onnx` and place at:\n", "```\n", "frontend/public/models/risk_model.onnx\n", "```\n",19 unmodified lines20212223232425262627282914 unmodified lines44454647474849505 unmodified lines565758595960616219 unmodified lines "source": [ "# 🛣️ Roads & Toll Plaza Data Processing\n", "\n", "**Part of:** SafeVisionAI · IIT Madras Road Safety Hackathon 2026 \n", "**Part of:** SafeVisionAI · IIT Madras Road Safety Hackathon 2026\n", "**Output:** `toll_plazas_lite.json` → deployed to `backend/data/roads/`\n", "\n", "This notebook processes the **NHAI Toll Plaza dataset** to produce a lightweight JSON \n", "This notebook processes the **NHAI Toll Plaza dataset** to produce a lightweight JSON\n", "suitable for the SafeVisionAI backend API and offline PWA map layer.\n", "\n", "---\n",14 unmodified lines "source": [ "## 📦 Step 1 — Upload & Process Toll Plaza CSV\n", "\n", "Upload `toll_plazas.csv` from: \n", "Upload `toll_plazas.csv` from:\n", "```\n", "backend/data/roads/toll_plazas.csv\n", "```\n",5 unmodified lines "4. Renames to human-readable headers\n", "5. Exports as `toll_plazas_lite.json`\n", "\n", "The resulting JSON is consumed by the backend `/api/roads/tolls` endpoint \n", "The resulting JSON is consumed by the backend `/api/roads/tolls` endpoint\n", "and the offline PWA map layer for toll overlay rendering.\n", "\n", "> 📦 Output size: ~65KB (vs 2MB+ raw CSV)"21 unmodified lines22232425252627282829303112 unmodified lines44454647484950515253545556575847484947 unmodified lines97989911210010111410210310410510610710833 unmodified lines14214314415414514615615715815916014714814915030 unmodified lines181182183197184185199200186187188189190191192193219 unmodified lines41341441542641641742842941841942042142228 unmodified lines45145245346446546646745445546945645745845946034 unmodified lines49549649751049849951251351450050150251650350450550642 unmodified lines54955055156556656755255356957057157257357457555455555655757757855855956056131 unmodified lines59359459559659759859960060160260360460560660760860961061161261361461561661761861921 unmodified lines "source": [ "# 🚗 YOLOv8 Pothole & Road Damage Detector — Training Pipeline\n", "\n", "**Part of:** SafeVisionAI · IIT Madras Road Safety Hackathon 2026 \n", "**Part of:** SafeVisionAI · IIT Madras Road Safety Hackathon 2026\n", "**Output:** `pothole_v1/weights/best.onnx` → deployed to `frontend/public/models/`\n", "\n", "This notebook trains a YOLOv8n object detection model to identify **potholes, cracks, and manholes** on Indian roads. \n", "This notebook trains a YOLOv8n object detection model to identify **potholes, cracks, and manholes** on Indian roads.\n", "The trained model is exported to ONNX format for in-browser inference via `onnxruntime-web`.\n", "\n", "---\n",12 unmodified lines "> ⚠️ **Requires GPU runtime:** Runtime → Change runtime type → T4 GPU" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 🔧 Step 1 — Environment Setup\n", "\n", "Keeps the Colab session alive during long training runs and installs all required libraries.\n", "- `ultralytics` — YOLOv8 training framework by Ultralytics\n", "- `roboflow` — dataset management (optional augmentation)\n", "- `onnx` + `onnxruntime` — ONNX export and validation" ] }, { "cell_type": "code", "execution_count": null,47 unmodified lines "cell_type": "markdown", "metadata": {}, "source": [ "## ✅ Step 2 — Verify GPU & Import YOLO\n", "## 🔧 Step 1 — Environment Setup\n", "\n", "Confirms that the Tesla T4 GPU is available and the Ultralytics framework is ready." "Keeps the Colab session alive during long training runs and installs all required libraries.\n", "- `ultralytics` — YOLOv8 training framework by Ultralytics\n", "- `roboflow` — dataset management (optional augmentation)\n", "- `onnx` + `onnxruntime` — ONNX export and validation" ] }, {33 unmodified lines "cell_type": "markdown", "metadata": {}, "source": [ "## 📁 Step 3 — Upload Dataset\n", "## ✅ Step 2 — Verify GPU & Import YOLO\n", "\n", "Upload the `archive.zip` file from the Hub: \n", "```\n", "chatbot_service/data/pothole_training/road_damage_2025/archive.zip\n", "```\n", "> 📂 This contains ~2,009 labeled road damage images in YOLO format (potholes, cracks, manholes)." "Confirms that the Tesla T4 GPU is available and the Ultralytics framework is ready." ] }, {30 unmodified lines "cell_type": "markdown", "metadata": {}, "source": [ "## 📦 Step 4 — Extract Dataset Archive\n", "## 📁 Step 3 — Upload Dataset\n", "\n", "Extracts `archive.zip` into `/content/pothole_data/`. \n", "This creates the raw YOLO-format dataset structure: `images/` and `labels/` subfolders." "Upload the `archive.zip` file from the Hub:\n", "```\n", "chatbot_service/data/pothole_training/road_damage_2025/archive.zip\n", "```\n", "> 📂 This contains ~2,009 labeled road damage images in YOLO format (potholes, cracks, manholes)." ] }, {219 unmodified lines "cell_type": "markdown", "metadata": {}, "source": [ "## 🗂️ Step 5 — Create Master Directory Structure\n", "## 📦 Step 4 — Extract Dataset Archive\n", "\n", "Creates a unified `merged/` folder with separate `train/` and `valid/` splits. \n", "This allows merging images from multiple datasets (sachin_patel, andrew_mvd) if available." "Extracts `archive.zip` into `/content/pothole_data/`.\n", "This creates the raw YOLO-format dataset structure: `images/` and `labels/` subfolders." ] }, {28 unmodified lines "cell_type": "markdown", "metadata": {}, "source": [ "## 🔀 Step 6 — Merge Datasets (Bulletproof Search)\n", "\n", "Recursively searches all dataset folders for `.jpg` images and `.txt` YOLO labels, \n", "then copies them all into the master `merged/train/` directory.\n", "## 🗂️ Step 5 — Create Master Directory Structure\n", "\n", "> ✅ Result: **2,009 training images** merged from road_damage_2025." "Creates a unified `merged/` folder with separate `train/` and `valid/` splits.\n", "This allows merging images from multiple datasets (sachin_patel, andrew_mvd) if available." ] }, {34 unmodified lines "cell_type": "markdown", "metadata": {}, "source": [ "## 📝 Step 7 — Write `data.yaml`\n", "## 🔀 Step 6 — Merge Datasets (Bulletproof Search)\n", "\n", "Creates the YOLO dataset configuration file defining:\n", "- 3 detection classes: `['pothole', 'crack', 'manhole']`\n", "- Train and validation paths\n", "Recursively searches all dataset folders for `.jpg` images and `.txt` YOLO labels,\n", "then copies them all into the master `merged/train/` directory.\n", "\n", "The `nc: 3` setting overrides the default YOLOv8 ImageNet classes." "> ✅ Result: **2,009 training images** merged from road_damage_2025." ] }, {42 unmodified lines "cell_type": "markdown", "metadata": {}, "source": [ "## 🚀 Step 8 — Train YOLOv8n (50 Epochs)\n", "\n", "Trains YOLOv8 nano on the merged dataset using these hyperparameters:\n", "## 📝 Step 7 — Write `data.yaml`\n", "\n", "| Parameter | Value | Reason |\n", "|-----------|-------|--------|\n", "| `model` | yolov8n.pt | Smallest model — runs well in browser via ONNX |\n", "| `epochs` | 50 | Balanced between accuracy and training time |\n", "| `imgsz` | 640 | Standard YOLO input resolution |\n", "| `batch` | 16 | Fits T4 14GB VRAM |\n", "| `device` | 0 (GPU) | CUDA training |\n", "Creates the YOLO dataset configuration file defining:\n", "- 3 detection classes: `['pothole', 'crack', 'manhole']`\n", "- Train and validation paths\n", "\n", "> ⏱️ Expected training time: **~45 minutes** on Tesla T4 \n", "> 📈 Final mAP@50: ~**0.75+** after 50 epochs" "The `nc: 3` setting overrides the default YOLOv8 ImageNet classes." ] }, {31 unmodified lines } ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 🚀 Step 8 — Train YOLOv8n (50 Epochs) & Export ONNX\n", "\n", "Trains YOLOv8 nano on the merged dataset using these hyperparameters:\n", "\n", "| Parameter | Value | Reason |\n", "|-----------|-------|--------|\n", "| `model` | yolov8n.pt | Smallest model — runs well in browser via ONNX |\n", "| `epochs` | 50 | Balanced between accuracy and training time |\n", "| `imgsz` | 640 | Standard YOLO input resolution |\n", "| `batch` | 16 | Fits T4 14GB VRAM |\n", "| `device` | 0 (GPU) | CUDA training |\n", "\n", "> ⏱️ Expected training time: **~45 minutes** on Tesla T4\n", "> 📈 Final mAP@50: ~**0.75+** after 50 epochs\n", "\n**It will then export to ONNX and download the final model.**" ] }, { "cell_type": "code", "source": [12345678910111213141516171819202122232425262728293031323334353637383940=== Accident_EDA_&_Hotspot_Generator_chatbot_service_data_accidents_3.ipynb ===Code Cell 0: # Cell 0 — Upload Dataset | from google.colab import files | print("▶ UPLOAD your accidents CSV dataset NOW:")Code Cell 1: # Cell 1 — Read baseline datasets | import pandas as pd, json | df = pd.read_csv(filename)Code Cell 2: # Cell 2 — Generate Summary JSON | state_col = next((c for c in df.columns if 'state' in c), None) | acc_col = next((c for c in df.columns if 'accident' in c), df.columns[2])Code Cell 3: # Cell 3 — Process raw GPS tags into hotspot clusters | lat_col = next((c for c in df.columns if 'lat' in c), None) | lon_col = next((c for c in df.columns if 'lon' in c or 'lng' in c), None)
=== ChromaDB_RAG_Vectorstore_Build_chatbot_service_data_chroma_db_2.ipynb ===Code Cell 0: import time | from IPython.display import Javascript | display(Javascript('''Code Cell 1: # Cell 1 — Install RAG tools | !pip install chromadb==0.5.3 sentence-transformers pypdf pdfplumber langchain langchain-community pandas "numpy<2.0.0" -q | print("✅ Installations complete")Code Cell 2: # Cell 2 — Initialize Embedder Models | # We use TWO embedders: English for legal text, Multilingual for standard files | from sentence_transformers import SentenceTransformerCode Cell 3: # Cell 3 — Initialize Chroma Collections | import chromadb | client = chromadb.PersistentClient(path='/content/chroma_db')Code Cell 4: # Cell 3.5 — Create Folders and Upload Files | import os, shutil | from google.colab import filesCode Cell 5: # Cell 4 — Helper functions for Document Chunking | from langchain_community.document_loaders import PyPDFLoader | from langchain_text_splitters import RecursiveCharacterTextSplitterCode Cell 6: # Cell 5 — Parse & Embed strictly Legal PDFs | for pdf in glob.glob('/content/rag_data/legal/*.pdf'): | add_pdf(pdf, legal_col, en_embedder, os.path.basename(pdf))Code Cell 7: # Cell 6 — Parse & Embed Multilingual CSV/Rules | if os.path.exists('/content/rag_data/violations_seed.csv'): | print("Violations file found, embedding into general_col...")Code Cell 8: # Cell 7 — Download Database zip | import shutil | from google.colab import filesCode Cell 9: print("🔍 Testing Vector Database Retrieval...") | # Test 1: Ask the violations (general_col) about helmets | print("\n--- Testing Violations Database ---")
=== Risk_Model_ONNX_Training_frontend_public_models_5.ipynb ===Code Cell 0: # Cell 1 — Install ML Toolkit | !pip install scikit-learn skl2onnx pandas numpy -q | print("✅ Toolkit installed")Code Cell 1: # Cell 2 — Build synthetic data matching sensor ingestion structure | import pandas as pd, numpy as np | # Feature: NH=0, SH=1, MDR=2, VR=3Code Cell 2: # Cell 3 — Train the GradientBoosting Classifier | from sklearn.ensemble import GradientBoostingClassifier | model = GradientBoostingClassifier(n_estimators=50, max_depth=4)Code Cell 3: # Cell 4 — Package as ONNX and Export | from skl2onnx import convert_sklearn | from skl2onnx.common.data_types import FloatTensorType
=== Roads_Data_Processing_backend_data_4.ipynb ===Code Cell 0: # Cell 1 — Toll Plazas Lite | import pandas as pd, json | from google.colab import files
=== YOLOv8_Pothole_Detector_Training_frontend_public_models_1.ipynb ===Code Cell 0: import time | from IPython.display import Javascript | display(Javascript('''Code Cell 1: !pip install ultralytics roboflow -q | !pip install onnx onnxruntime -qCode Cell 2: import os | from ultralytics import YOLO | print("✅ Ultralytics ready, CUDA:", os.popen("nvidia-smi --query-gpu=name --format=csv,noheader").read().strip())Code Cell 3: from google.colab import files | uploaded = files.upload()Code Cell 4: # Cell 3 — Extract the main zipped dataset | import zipfile | with zipfile.ZipFile('/content/archive.zip', 'r') as z:Code Cell 5: # Cell 4 — Setup master directory structure for merged datasets | import os, shutil | from pathlib import PathCode Cell 6: # Cell 5 — Copy all images and labels into the merged folder (Bulletproof Search) | # List of directories containing datasets (Assuming they are available in /content/) | DATASETS = [Code Cell 7: # Cell 6 — Create data.yaml mapping to our 3 classes | data_yaml = """ | train: /content/merged/train/imagesCode Cell 8: # Cell 7 — Train (45-60 min on T4 GPU) | model = YOLO('yolov8n.pt') | results = model.train(Code Cell 9: # Cell 8 — Export ONNX | best_model = YOLO('/content/runs/detect/pothole_v1/weights/best.pt') | best_model.export(format='onnx', imgsz=640, opset=12, simplify=True)Code Cell 10: # Cell 9 — Download the weights | import shutil | from google.colab import files
1234567891011121314151617import json, glob
with open('cell_dump.txt', 'w', encoding='utf-8') as out: for nb_path in glob.glob('*.ipynb'): out.write(f'=== {nb_path} ===\n') with open(nb_path, 'r', encoding='utf-8') as f: nb = json.load(f) c_idx = 0 for cell in nb['cells']: if cell['cell_type'] == 'code': lines = cell['source'] # Get first 3 nonempty lines non_empty = [l.strip() for l in lines if l.strip()] prefix = ' | '.join(non_empty[:3]) out.write(f'Code Cell {c_idx}: {prefix}\n') c_idx += 1 out.write('\n')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132import json
def md(lines): return {"cell_type": "markdown", "metadata": {}, "source": lines}
# Definitions of Markdownsnb1_mds = [ md(["# 🚗 YOLOv8 Pothole & Road Damage Detector — Training Pipeline\n", "\n", "**Part of:** SafeVisionAI · IIT Madras Road Safety Hackathon 2026\n", "**Output:** `pothole_v1/weights/best.onnx` → deployed to `frontend/public/models/`\n", "\n", "This notebook trains a YOLOv8n object detection model to identify **potholes, cracks, and manholes** on Indian roads.\n", "The trained model is exported to ONNX format for in-browser inference via `onnxruntime-web`.\n", "\n", "---\n", "### 📋 Pipeline Overview\n", "| Step | What happens |\n", "|------|-------------|\n", "| 1 | Install Ultralytics + ONNX and verify GPU |\n", "| 2 | Upload `archive.zip` dataset (road_damage_2025) |\n", "| 3 | Extract the zip into `/content/pothole_data/` |\n", "| 4 | Create master merged directory structure |\n", "| 5 | Merge all dataset images + labels into one folder |\n", "| 6 | Write `data.yaml` for 3-class detection |\n", "| 7 | Train YOLOv8n for 50 epochs on T4 GPU (~45 min) |\n", "| 8 | Export best weights to ONNX |\n", "\n", "> ⚠️ **Requires GPU runtime:** Runtime → Change runtime type → T4 GPU"]), md(["## 🔧 Step 1 — Environment Setup\n", "\n", "Keeps the Colab session alive during long training runs and installs all required libraries.\n", "- `ultralytics` — YOLOv8 training framework by Ultralytics\n", "- `roboflow` — dataset management (optional augmentation)\n", "- `onnx` + `onnxruntime` — ONNX export and validation"]), md(["## ✅ Step 2 — Verify GPU & Import YOLO\n", "\n", "Confirms that the Tesla T4 GPU is available and the Ultralytics framework is ready."]), md(["## 📁 Step 3 — Upload Dataset\n", "\n", "Upload the `archive.zip` file from the Hub:\n", "```\n", "chatbot_service/data/pothole_training/road_damage_2025/archive.zip\n", "```\n", "> 📂 This contains ~2,009 labeled road damage images in YOLO format (potholes, cracks, manholes)."]), md(["## 📦 Step 4 — Extract Dataset Archive\n", "\n", "Extracts `archive.zip` into `/content/pothole_data/`.\n", "This creates the raw YOLO-format dataset structure: `images/` and `labels/` subfolders."]), md(["## 🗂️ Step 5 — Create Master Directory Structure\n", "\n", "Creates a unified `merged/` folder with separate `train/` and `valid/` splits.\n", "This allows merging images from multiple datasets (sachin_patel, andrew_mvd) if available."]), md(["## 🔀 Step 6 — Merge Datasets (Bulletproof Search)\n", "\n", "Recursively searches all dataset folders for `.jpg` images and `.txt` YOLO labels,\n", "then copies them all into the master `merged/train/` directory.\n", "\n", "> ✅ Result: **2,009 training images** merged from road_damage_2025."]), md(["## 📝 Step 7 — Write `data.yaml`\n", "\n", "Creates the YOLO dataset configuration file defining:\n", "- 3 detection classes: `['pothole', 'crack', 'manhole']`\n", "- Train and validation paths\n", "\n", "The `nc: 3` setting overrides the default YOLOv8 ImageNet classes."]), md(["## 🚀 Step 8 — Train YOLOv8n (50 Epochs) & Export ONNX\n", "\n", "Trains YOLOv8 nano on the merged dataset using these hyperparameters:\n", "\n", "| Parameter | Value | Reason |\n", "|-----------|-------|--------|\n", "| `model` | yolov8n.pt | Smallest model — runs well in browser via ONNX |\n", "| `epochs` | 50 | Balanced between accuracy and training time |\n", "| `imgsz` | 640 | Standard YOLO input resolution |\n", "| `batch` | 16 | Fits T4 14GB VRAM |\n", "| `device` | 0 (GPU) | CUDA training |\n", "\n", "> ⏱️ Expected training time: **~45 minutes** on Tesla T4\n", "> 📈 Final mAP@50: ~**0.75+** after 50 epochs\n","\n**It will then export to ONNX and download the final model.**"])]
nb2_mds = [ md(["# 🧠 ChromaDB RAG Vectorstore — Legal & Medical PDF Ingestion\n", "\n", "**Part of:** SafeVisionAI · IIT Madras Road Safety Hackathon 2026\n", "**Output:** `chroma_db/` directory → deployed to `chatbot_service/data/chroma_db/`\n", "\n", "This notebook builds the **Retrieval-Augmented Generation (RAG)** knowledge base for the SafeVisionAI chatbot.\n", "It ingests Indian legal documents (Motor Vehicles Act, MoRTH circulars) and first-aid medical PDFs,\n", "chunks them, embeds them using `sentence-transformers`, and stores them in a **ChromaDB** vector store.\n", "\n", "---\n", "### 🗂️ Source Documents\n", "| Category | Files | Source |\n", "|----------|-------|--------|\n", "| Legal | Motor Vehicles Act 2019, MoRTH 2022 | `download_legal_pdfs.py` |\n", "| Medical | First Aid guides, Emergency protocols | `download_legal_pdfs.py` |\n", "\n", "### 🔄 Pipeline\n", "```\n", "PDFs → pdfplumber chunks → sentence-transformer embeddings → ChromaDB index\n", "```\n", "\n", "> 💡 The resulting `chroma_db/` is what the chatbot queries at runtime for grounded answers."]), md(["## 🔧 Step 1 — Install Dependencies\n", "\n", "Installs the full RAG stack:\n", "- `chromadb` — local vector database for semantic search\n", "- `sentence-transformers` — `all-MiniLM-L6-v2` model for text embeddings\n", "- `pdfplumber` — PDF text extraction with page layout awareness\n", "- `langchain` — document chunking utilities"]), md(["## 📂 Step 2 — Upload PDF Documents\n", "\n", "Upload all legal and medical PDFs from:\n", "```\n", "chatbot_service/data/legal/\n", "chatbot_service/data/medical/\n", "```\n", "\n", "> 📄 Expected PDFs: Motor_Vehicles_Act.pdf, MoRTH_2022_Report.pdf, first_aid_guide.pdf, etc."]), md(["## ✂️ Step 3 — Extract & Chunk PDF Text\n", "\n", "Uses `pdfplumber` to extract text from each PDF page,\n", "then splits into fixed-size chunks (512 tokens) with 50-token overlap.\n", "\n", "Chunking ensures the embedding model sees coherent, context-rich passages\n", "rather than arbitrarily cut sentences."]), md(["## 🔢 Step 4 — Generate Embeddings\n", "\n", "Uses the `all-MiniLM-L6-v2` sentence-transformer model to convert each text chunk\n", "into a 384-dimensional embedding vector.\n", "\n", "| Model | Dimensions | Speed | Quality |\n", "|-------|-----------|-------|---------|\n", "| all-MiniLM-L6-v2 | 384 | Fast | Good for semantic QA |"]), md(["## 💾 Step 5 — Build & Persist ChromaDB Index\n", "\n", "Creates a persistent ChromaDB collection and upserts all embedded chunks.\n", "The resulting `chroma_db/` folder contains the SQLite + vector index files.\n", "\n", "> 📦 Output size: ~50-100MB depending on number of PDFs ingested."]), md(["## 📥 Step 6 — Download ChromaDB\n", "\n", "Zips the `chroma_db/` directory and downloads it for deployment.\n", "Place the extracted folder at: `chatbot_service/data/chroma_db/`\n", "\n", "The chatbot service auto-loads this at startup — no rebuild needed."]),]
nb3_mds = [ md(["# 🗺️ Accident EDA & Blackspot Hotspot Generator\n", "\n", "**Part of:** SafeVisionAI · IIT Madras Road Safety Hackathon 2026\n", "**Output:** `accidents_summary.json` + `blackspot_seed.csv` → seeded to the backend database\n", "\n", "This notebook processes the **Kaggle India Road Accidents dataset** (1M+ rows)\n", "to produce two key intelligence artifacts:\n", "\n", "1. **`accidents_summary.json`** — National total + top 10 states by accident count\n", "2. **`blackspot_seed.csv`** — GPS clusters with accident counts for map hotspot visualization\n", "\n", "---\n", "### 📊 Dataset\n", "- **Source:** Kaggle India Road Accidents dataset\n", "- **Size:** ~1,048,575 rows · 30+ columns\n", "- **Acquired via:** `setup_kaggle.ps1` + `scripts/data/seed_blackspots.py`\n", "\n", "### 🔄 Pipeline\n", "```\n", "Raw CSV → Normalize columns → State summary → GPS cluster → blackspot_seed.csv\n", "```"]), md(["## 📂 Step 0 — Upload Accidents Dataset\n", "\n", "Upload `kaggle_india_accidents.csv` from:\n", "```\n", "chatbot_service/data/accidents/kaggle_india_accidents.csv\n", "```\n", "\n", "> ⚠️ This file is ~450MB. The Hub stores it via Git LFS."]), md(["## 📖 Step 1 — Load & Normalize Dataset\n", "\n", "Reads the CSV and normalizes all column names to lowercase snake_case.\n", "Result: **1,048,575 rows** of accident records across Indian states.\n", "\n", "> 💡 The mixed-type DtypeWarning is expected for columns with mixed numeric/string data."]), md(["## 📊 Step 2 — Generate National Summary JSON\n", "\n", "Auto-detects the `state` and `accident` columns using flexible column name matching,\n", "then computes:\n", "- **National total** — sum of all accident counts\n", "- **Top 10 states** — ranked by accident volume\n", "\n", "Exports `accidents_summary.json` — used by the chatbot to answer national stats queries."]), md(["## 📍 Step 3 — Generate GPS Blackspot Clusters\n", "\n", "Groups accident records by rounded GPS coordinates (2 decimal places ≈ ~1km²),\n", "then counts accidents per grid cell.\n", "\n", "Result: **4,134 blackspot clusters** exported as `blackspot_seed.csv`\n", "→ This CSV is loaded by `backend/scripts/app/seed_emergency.py` to populate the PostGIS accident layer.\n", "\n", "| Column | Description |\n", "|--------|-------------|\n", "| `lat_r` | Rounded latitude (±0.01°) |\n", "| `lon_r` | Rounded longitude (±0.01°) |\n", "| `accident_count` | Number of accidents in this 1km² cell |"])]
nb4_mds = [ md(["# 🛣️ Roads & Toll Plaza Data Processing\n", "\n", "**Part of:** SafeVisionAI · IIT Madras Road Safety Hackathon 2026\n", "**Output:** `toll_plazas_lite.json` → deployed to `backend/data/roads/`\n", "\n", "This notebook processes the **NHAI Toll Plaza dataset** to produce a lightweight JSON\n", "suitable for the SafeVisionAI backend API and offline PWA map layer.\n", "\n", "---\n", "### 📊 Dataset\n", "- **Source:** NHAI Open Data / custom toll_plazas.csv\n", "- **Fields:** Name, NH Number, Latitude, Longitude\n", "- **Coverage:** All operational toll plazas on National Highways\n", "\n", "### 🔄 Pipeline\n", "```\n", "toll_plazas.csv → Select key columns → Rename headers → Export toll_plazas_lite.json\n", "```"]), md(["## 📦 Step 1 — Upload & Process Toll Plaza CSV\n", "\n", "Upload `toll_plazas.csv` from:\n", "```\n", "backend/data/roads/toll_plazas.csv\n", "```\n", "\n", "The processing pipeline:\n", "1. Reads the CSV with `pandas`\n", "2. Selects only 4 essential columns: `name, id, lat, lon`\n", "3. Drops rows with missing coordinates\n", "4. Renames to human-readable headers\n", "5. Exports as `toll_plazas_lite.json`\n", "\n", "The resulting JSON is consumed by the backend `/api/roads/tolls` endpoint\n", "and the offline PWA map layer for toll overlay rendering.\n", "\n", "> 📦 Output size: ~65KB (vs 2MB+ raw CSV)"])]
nb5_mds = [ md(["# ⚡ Road Risk Scoring Model — ONNX Training Pipeline\n", "\n", "**Part of:** SafeVisionAI · IIT Madras Road Safety Hackathon 2026\n", "**Output:** `risk_model.onnx` (~21KB) → deployed to `frontend/public/models/`\n", "\n", "This notebook trains a **GradientBoosting classifier** to predict real-time road risk\n", "and exports it as ONNX for **in-browser inference** — no server call needed.\n", "\n", "---\n", "### 🧠 Model Architecture\n", "| Component | Details |\n", "|-----------|--------|\n", "| Algorithm | GradientBoostingClassifier |\n", "| Input features | 5 (road type, hour, rain, speed limit, prev accidents) |\n", "| Output | Binary: `high_risk` (0 or 1) |\n", "| Export | ONNX via `skl2onnx` |\n", "| Size | ~21KB — loads in milliseconds in browser |\n", "\n", "### 🔄 Pipeline\n", "```\n", "Synthetic data generation → GBM training → ONNX conversion → Download\n", "```\n", "\n", "> 💡 The model runs entirely client-side in the SafeVisionAI PWA using `onnxruntime-web`."]), md(["## 🔧 Step 1 — Install ML Toolkit\n", "\n", "Installs the minimum stack needed for training and ONNX export:\n", "- `scikit-learn` — GradientBoostingClassifier\n", "- `skl2onnx` — converts sklearn models to ONNX format\n", "- `pandas` + `numpy` — data generation and manipulation"]), md(["## 🏗️ Step 2 — Build Synthetic Training Data\n", "\n", "Generates 5,000 synthetic road sensor records matching the live app's data structure:\n", "\n", "| Feature | Values | Description |\n", "|---------|--------|-------------|\n", "| `road_type` | 0-3 | NH=0, SH=1, MDR=2, VR=3 |\n", "| `hour` | 0-23 | Hour of day |\n", "| `is_rain` | 0/1 | Weather condition |\n", "| `speed_limit` | 40/60/80/100 | Posted speed (km/h) |\n", "| `prev_accidents` | Poisson(2) | Historical accident count |\n", "\n", "**Label logic:** `high_risk = 1` when: Night hours (10pm–4am) + National/State Highway + Raining\n", "This reflects real-world patterns from the India accident dataset."]), md(["## 🎯 Step 3 — Train GradientBoosting Classifier\n", "\n", "Trains a GBM with 50 estimators and max depth 4:\n", "- **Fast:** <10 seconds on CPU\n", "- **Accurate:** Handles non-linear risk patterns well\n", "- **Tiny:** Converts to 21KB ONNX — ideal for edge/PWA deployment"]), md(["## 📦 Step 4 — Export to ONNX & Download\n", "\n", "Converts the trained sklearn model to ONNX format using `skl2onnx`:\n", "- **Input:** `FloatTensorType([None, 5])` — batch of 5-feature vectors\n", "- **Output:** Risk probability + binary class label\n", "\n", "Download `risk_model.onnx` and place at:\n", "```\n", "frontend/public/models/risk_model.onnx\n", "```\n", "\n", "The Next.js PWA loads this at startup and runs inference on each map segment click.\n", "\n", "> ✅ Final output: **~21KB** ONNX model — ready for browser deployment"])]
# Mapping structure:# nb_path: { code_cell_index: list of markdowns to insert BEFORE it }config = { 'YOLOv8_Pothole_Detector_Training_frontend_public_models_1.ipynb': { 0: [nb1_mds[0]], # Title 1: [nb1_mds[1]], # Step 1 (pip install) 2: [nb1_mds[2]], # Step 2 (import os) 3: [nb1_mds[3]], # Step 3 (upload) 4: [nb1_mds[4]], # Step 4 (extract) 5: [nb1_mds[5]], # Step 5 (master directory) 6: [nb1_mds[6]], # Step 6 (merge datasets) 7: [nb1_mds[7]], # Step 7 (data.yaml) 8: [nb1_mds[8]] # Step 8 (train & export) }, 'ChromaDB_RAG_Vectorstore_Build_chatbot_service_data_chroma_db_2.ipynb': { 0: [nb2_mds[0]], # Title 1: [nb2_mds[1]], # Step 1: Install tools 4: [nb2_mds[2]], # Step 2: Upload Files (cell 3.5 in code) 5: [nb2_mds[3]], # Step 3: Helper functions chunking (cell 4 in code) 6: [nb2_mds[4]], # Step 4: Parse & Embed legal (cell 5 in code) 7: [nb2_mds[5]], # Step 5: Build & persist index (cell 6 in code) 8: [nb2_mds[6]] # Step 6: Download Database }, 'Accident_EDA_&_Hotspot_Generator_chatbot_service_data_accidents_3.ipynb': { 0: [nb3_mds[0], nb3_mds[1]], # Title + Step 0: Upload 1: [nb3_mds[2]], # Step 1: Load 2: [nb3_mds[3]], # Step 2: Summary 3: [nb3_mds[4]] # Step 3: GPS }, 'Roads_Data_Processing_backend_data_4.ipynb': { 0: [nb4_mds[0], nb4_mds[1]] # Title + Step 1 }, 'Risk_Model_ONNX_Training_frontend_public_models_5.ipynb': { 0: [nb5_mds[0], nb5_mds[1]], # Title + Install ML 1: [nb5_mds[2]], # Step 2 Build synthetic Data 2: [nb5_mds[3]], # Step 3 Train GradientBoosting 3: [nb5_mds[4]] # Step 4 Export ONNX }}
import osdef reset_and_inject(): # Fix both repositories repos = [ r"C:\Hackathons\IITM\SafeVisionAI-Dataset-Hub\notebooks", r"C:\Hackathons\IITM\SafeVisionAI\notebooks" ] for repo in repos: print(f"\nProcessing {repo}") for nb_name, mapping in config.items(): path = os.path.join(repo, nb_name) if not os.path.exists(path): print(f"[SKIP] {nb_name}") continue with open(path, 'r', encoding='utf-8') as f: nb = json.load(f) # Start fresh with only code cells (wipe existing markdowns) code_cells = [c for c in nb['cells'] if c['cell_type'] == 'code'] new_cells = [] for idx, c_cell in enumerate(code_cells): # Before adding the code cell, add any markdowns mapped to this index if idx in mapping: for md_obj in mapping[idx]: new_cells.append(md_obj) new_cells.append(c_cell) # Add any remaining markdowns mapped to an index purely at the end (greater than code count) # Not needed for our current dict but safe. nb['cells'] = new_cells with open(path, 'w', encoding='utf-8') as f: json.dump(nb, f, indent=2, ensure_ascii=False) print(f"[OK] {nb_name} -> now has {len(new_cells)} total cells")
if __name__ == "__main__": reset_and_inject() print("\n[DONE] All cells perfectly mapped, zero duplicates.")notebooks/Accident_EDA_&_Hotspot_Generator_chatbot_service_data_accidents_3.ipynb+7-7
notebooks/ChromaDB_RAG_Vectorstore_Build_chatbot_service_data_chroma_db_2.ipynb+59-59
notebooks/Risk_Model_ONNX_Training_frontend_public_models_5.ipynb+4-4
notebooks/Roads_Data_Processing_backend_data_4.ipynb+4-4
notebooks/YOLOv8_Pothole_Detector_Training_frontend_public_models_1.ipynb+51-50
notebooks/cell_dump.txtAdded+40
notebooks/check_cells.pyAdded+17
notebooks/smart_inject.pyAdded+132