Datasets:
Bappadala Rohith Kumar Naidu commited on
Commit ·
198bb3d
1
Parent(s): ae454c7
fix: sync scripts/data with main repo, fix import patterns
Browse files- _overpass_utils.py: remove stale ROOT_DIR export, add **kwargs to
fetch_elements() and normalize_row() to match main repo signatures
- fetch_hospitals/ambulance/police/fire/blood_banks.py: stop importing
ROOT_DIR from _overpass_utils; define ROOT_DIR locally per-script
(mirrors the pattern used in the main SafeVisionAI repo)
- bootstrap_local_data.py: remove unused 'import tempfile'
- Add __init__.py to scripts/scripts/data/ and scripts/backend/data/
for Python package consistency
Files changed (15)
- README.md+18-8
- notebooks/Accident_EDA_&_Hotspot_Generator_chatbot_service_data_accidents_3.ipynb+66-445
- notebooks/ChromaDB_RAG_Vectorstore_Build_chatbot_service_data_chroma_db_2.ipynb
- notebooks/Risk_Model_ONNX_Training_frontend_public_models_5.ipynb+93-186
- notebooks/Roads_Data_Processing_backend_data_4.ipynb+25-306
- notebooks/YOLOv8_Pothole_Detector_Training_frontend_public_models_1.ipynb+191-877
- scripts/backend/data/__init__.pyAdded+1
- scripts/scripts/data/__init__.pyAdded+1
- scripts/scripts/data/_overpass_utils.py+2-3
- scripts/scripts/data/bootstrap_local_data.py-1
- scripts/scripts/data/fetch_ambulance.py+4-1
- scripts/scripts/data/fetch_blood_banks.py+4-1
- scripts/scripts/data/fetch_fire.py+4-1
- scripts/scripts/data/fetch_hospitals.py+4-1
- scripts/scripts/data/fetch_police.py+4-1
49 unmodified lines50515253545556575859606182 unmodified lines14414514614714814915015115249 unmodified lines│ ├── chatbot_service/data/ ← Legal PDFs, GIS CSVs, accident data, models│ └── backend/datasets/ ← Challan rules, road infrastructure│├── scripts/ ← Reproducible data acquisition pipeline│ ├── scripts/data/ ← Root-level data scripts (fetchers, extractors)│ ├── backend/data/ ← Backend data transforms (pure Python)│ └── chatbot_service/data/ ← Pro Overpass GIS fetchers│└── notebooks/ ← Research notebooks and analysis```---82 unmodified lines---## 📓 NotebooksSee `notebooks/README.md` for the full Colab quickstart guide.---49 unmodified lines5051525354555657585982 unmodified lines14214314414514614714814915015115215315415515615715815916016116249 unmodified lines│ ├── chatbot_service/data/ ← Legal PDFs, GIS CSVs, accident data, models│ └── backend/datasets/ ← Challan rules, road infrastructure│└── scripts/ ← Reproducible data acquisition pipeline├── scripts/data/ ← Root-level data scripts (fetchers, extractors)├── backend/data/ ← Backend data transforms (pure Python)└── chatbot_service/data/ ← Pro Overpass GIS fetchers```---82 unmodified lines---## 📓 Research Notebooks — Open in Colab> We advise running all notebooks through **Google Colab** for the easiest setup. Colab gives you a free T4 GPU with 16 GB of VRAM. All notebooks were built and tested on Colab, so it is the most stable platform. Any other cloud provider should work too.| # | Notebook | What It Produces | Open in Colab ||---|---|---|---|| 1 | **YOLOv8 Pothole Detector Training** | ONNX road damage model | [](https://colab.research.google.com/drive/1oe4Gk899lFB_vbRMUuOh4dqpsa3bbycI) || 2 | **ChromaDB RAG Vectorstore Build** | ChromaDB index for legal RAG | [](https://colab.research.google.com/drive/1AzPdN9xjcjW20ko0shTYn0mvbxTUw57Q) || 3 | **Accident EDA & Hotspot Generator** | Blackspot seed CSV + heatmap | [](https://colab.research.google.com/drive/1xh_lwv_B_jc0_83dvuNppWQRtVhqExTS) || 4 | **Roads Data Processing** | Sampled PMGSY GeoJSON | [](https://colab.research.google.com/drive/10_WfTlbbxW9A7ceQBZGaKF5UkydlUDin#scrollTo=z4XxGZmx0ymX) || 5 | **Risk Model ONNX Training** | Risk scoring ONNX model | [](https://colab.research.google.com/drive/16IH-rn3CedYtfIpJP4iLa_KUjvfy8hAY) |**Recommended run order:** `1 → 2 → 3 → 4 → 5`> Each notebook auto-clones this Hub at the start — no manual data setup needed.---
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869703 unmodified lines74757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013026 unmodified lines3093103113123133143153163173183193203213223233243253263273283293303316 unmodified lines3383393403413423433443453463473483493503513523533543559 unmodified lines36536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746812 unmodified lines481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569{"nbformat": 4,"nbformat_minor": 0,"metadata": {"colab": {"provenance": []},"kernelspec": {"name": "python3","display_name": "Python 3"},"language_info": {"name": "python"}},"cells": [{"cell_type": "markdown","metadata": {},"source": ["# 🗺️ 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","```"]},{"cell_type": "markdown","metadata": {},"source": ["## 📂 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."]},{"cell_type": "code","source": ["# Cell 0 — Upload Dataset\n","from google.colab import files\n","print(\"▶ UPLOAD your accidents CSV dataset NOW:\")\n","uploaded = files.upload()\n","filename = list(uploaded.keys())[0]\n","print(f\"✅ Uploaded {filename}\")\n"],"metadata": {"colab": {"base_uri": "https://localhost:8080/",3 unmodified lines"id": "wTQPiBKuOGj6","outputId": "567b68a9-fb9e-43b3-faae-75d66a415c7e"},"execution_count": null,"outputs": [{"output_type": "stream","name": "stdout","text": ["▶ UPLOAD your accidents CSV dataset NOW:\n"]},{"output_type": "display_data","data": {"text/plain": ["<IPython.core.display.HTML object>"],"text/html": ["\n"," <input type=\"file\" id=\"files-01711289-8cfe-4504-80ed-65a482b6a4c7\" name=\"files[]\" multiple disabled\n"," style=\"border:none\" />\n"," <output id=\"result-01711289-8cfe-4504-80ed-65a482b6a4c7\">\n"," Upload widget is only available when the cell has been executed in the\n"," current browser session. Please rerun this cell to enable.\n"," </output>\n"," <script>// Copyright 2017 Google LLC\n","//\n","// Licensed under the Apache License, Version 2.0 (the \"License\");\n","// you may not use this file except in compliance with the License.\n","// You may obtain a copy of the License at\n","//\n","// http://www.apache.org/licenses/LICENSE-2.0\n","//\n","// Unless required by applicable law or agreed to in writing, software\n","// distributed under the License is distributed on an \"AS IS\" BASIS,\n","// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n","// See the License for the specific language governing permissions and\n","// limitations under the License.\n","\n","/**\n"," * @fileoverview Helpers for google.colab Python module.\n"," */\n","(function(scope) {\n","function span(text, styleAttributes = {}) {\n"," const element = document.createElement('span');\n"," element.textContent = text;\n"," for (const key of Object.keys(styleAttributes)) {\n"," element.style[key] = styleAttributes[key];\n"," }\n"," return element;\n","}\n","\n","// Max number of bytes which will be uploaded at a time.\n","const MAX_PAYLOAD_SIZE = 100 * 1024;\n","\n","function _uploadFiles(inputId, outputId) {\n"," const steps = uploadFilesStep(inputId, outputId);\n"," const outputElement = document.getElementById(outputId);\n"," // Cache steps on the outputElement to make it available for the next call\n"," // to uploadFilesContinue from Python.\n"," outputElement.steps = steps;\n","\n"," return _uploadFilesContinue(outputId);\n","}\n","\n","// This is roughly an async generator (not supported in the browser yet),\n","// where there are multiple asynchronous steps and the Python side is going\n","// to poll for completion of each step.\n","// This uses a Promise to block the python side on completion of each step,\n","// then passes the result of the previous step as the input to the next step.\n","function _uploadFilesContinue(outputId) {\n"," const outputElement = document.getElementById(outputId);\n"," const steps = outputElement.steps;\n","\n"," const next = steps.next(outputElement.lastPromiseValue);\n"," return Promise.resolve(next.value.promise).then((value) => {\n"," // Cache the last promise value to make it available to the next\n"," // step of the generator.\n"," outputElement.lastPromiseValue = value;\n"," return next.value.response;\n"," });\n","}\n","\n","/**\n"," * Generator function which is called between each async step of the upload\n"," * process.\n"," * @param {string} inputId Element ID of the input file picker element.\n"," * @param {string} outputId Element ID of the output display.\n"," * @return {!Iterable<!Object>} Iterable of next steps.\n"," */\n","function* uploadFilesStep(inputId, outputId) {\n"," const inputElement = document.getElementById(inputId);\n"," inputElement.disabled = false;\n","\n"," const outputElement = document.getElementById(outputId);\n"," outputElement.innerHTML = '';\n","\n"," const pickedPromise = new Promise((resolve) => {\n"," inputElement.addEventListener('change', (e) => {\n"," resolve(e.target.files);\n"," });\n"," });\n","\n"," const cancel = document.createElement('button');\n"," inputElement.parentElement.appendChild(cancel);\n"," cancel.textContent = 'Cancel upload';\n"," const cancelPromise = new Promise((resolve) => {\n"," cancel.onclick = () => {\n"," resolve(null);\n"," };\n"," });\n","\n"," // Wait for the user to pick the files.\n"," const files = yield {\n"," promise: Promise.race([pickedPromise, cancelPromise]),\n"," response: {\n"," action: 'starting',\n"," }\n"," };\n","\n"," cancel.remove();\n","\n"," // Disable the input element since further picks are not allowed.\n"," inputElement.disabled = true;\n","\n"," if (!files) {\n"," return {\n"," response: {\n"," action: 'complete',\n"," }\n"," };\n"," }\n","\n"," for (const file of files) {\n"," const li = document.createElement('li');\n"," li.append(span(file.name, {fontWeight: 'bold'}));\n"," li.append(span(\n"," `(${file.type || 'n/a'}) - ${file.size} bytes, ` +\n"," `last modified: ${\n"," file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() :\n"," 'n/a'} - `));\n"," const percent = span('0% done');\n"," li.appendChild(percent);\n","\n"," outputElement.appendChild(li);\n","\n"," const fileDataPromise = new Promise((resolve) => {\n"," const reader = new FileReader();\n"," reader.onload = (e) => {\n"," resolve(e.target.result);\n"," };\n"," reader.readAsArrayBuffer(file);\n"," });\n"," // Wait for the data to be ready.\n"," let fileData = yield {\n"," promise: fileDataPromise,\n"," response: {\n"," action: 'continue',\n"," }\n"," };\n","\n"," // Use a chunked sending to avoid message size limits. See b/62115660.\n"," let position = 0;\n"," do {\n"," const length = Math.min(fileData.byteLength - position, MAX_PAYLOAD_SIZE);\n"," const chunk = new Uint8Array(fileData, position, length);\n"," position += length;\n","\n"," const base64 = btoa(String.fromCharCode.apply(null, chunk));\n"," yield {\n"," response: {\n"," action: 'append',\n"," file: file.name,\n"," data: base64,\n"," },\n"," };\n","\n"," let percentDone = fileData.byteLength === 0 ?\n"," 100 :\n"," Math.round((position / fileData.byteLength) * 100);\n"," percent.textContent = `${percentDone}% done`;\n","\n"," } while (position < fileData.byteLength);\n"," }\n","\n"," // All done.\n"," yield {\n"," response: {\n"," action: 'complete',\n"," }\n"," };\n","}\n","\n","scope.google = scope.google || {};\n","scope.google.colab = scope.google.colab || {};\n","scope.google.colab._files = {\n"," _uploadFiles,\n"," _uploadFilesContinue,\n","};\n","})(self);\n","</script> "]},"metadata": {}},{"output_type": "stream","name": "stdout","text": ["Saving kaggle_india_accidents.csv to kaggle_india_accidents.csv\n","✅ Uploaded kaggle_india_accidents.csv\n"]}]},{"cell_type": "markdown","metadata": {},"source": ["## 📖 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."]},{6 unmodified lines"id": "4HztHudkL-4I","outputId": "c7c242da-9ff8-43f7-aa30-65260e9e11f6"},"outputs": [{"output_type": "stream","name": "stderr","text": ["/tmp/ipykernel_3268/1948449410.py:3: DtypeWarning: Columns (8,10,28,29) have mixed types. Specify dtype option on import or set low_memory=False.\n"," df = pd.read_csv(filename)\n"]},{"output_type": "stream","name": "stdout","text": ["Loaded accidents dataset with 1048575 rows.\n"]}],"source": ["# Cell 1 — Read baseline datasets\n","import pandas as pd, json\n",6 unmodified lines"cell_type": "markdown","metadata": {},"source": ["## 📊 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."]},{"cell_type": "code","source": ["# Cell 2 — Generate Summary JSON\n","state_col = next((c for c in df.columns if 'state' in c), None)\n",9 unmodified lines"\n","from google.colab import files\n","files.download('accidents_summary.json')\n"],"metadata": {"colab": {"base_uri": "https://localhost:8080/","height": 17},"id": "IgLUOAYzQBEv","outputId": "8edb7410-47fb-40bb-cdc9-7920ce04ab94"},"execution_count": null,"outputs": [{"output_type": "display_data","data": {"text/plain": ["<IPython.core.display.Javascript object>"],"application/javascript": ["\n"," async function download(id, filename, size) {\n"," if (!google.colab.kernel.accessAllowed) {\n"," return;\n"," }\n"," const div = document.createElement('div');\n"," const label = document.createElement('label');\n"," label.textContent = `Downloading \"${filename}\": `;\n"," div.appendChild(label);\n"," const progress = document.createElement('progress');\n"," progress.max = size;\n"," div.appendChild(progress);\n"," document.body.appendChild(div);\n","\n"," const buffers = [];\n"," let downloaded = 0;\n","\n"," const channel = await google.colab.kernel.comms.open(id);\n"," // Send a message to notify the kernel that we're ready.\n"," channel.send({})\n","\n"," for await (const message of channel.messages) {\n"," // Send a message to notify the kernel that we're ready.\n"," channel.send({})\n"," if (message.buffers) {\n"," for (const buffer of message.buffers) {\n"," buffers.push(buffer);\n"," downloaded += buffer.byteLength;\n"," progress.value = downloaded;\n"," }\n"," }\n"," }\n"," const blob = new Blob(buffers, {type: 'application/binary'});\n"," const a = document.createElement('a');\n"," a.href = window.URL.createObjectURL(blob);\n"," a.download = filename;\n"," div.appendChild(a);\n"," a.click();\n"," div.remove();\n"," }\n"," "]},"metadata": {}},{"output_type": "display_data","data": {"text/plain": ["<IPython.core.display.Javascript object>"],"application/javascript": ["download(\"download_2b3f12d6-506f-4044-ae13-0e57fca04323\", \"accidents_summary.json\", 34)"]},"metadata": {}}]},{"cell_type": "markdown","metadata": {},"source": ["## 📍 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 |"]},{"cell_type": "code","source": ["# Cell 3 — Process raw GPS tags into hotspot clusters\n","lat_col = next((c for c in df.columns if 'lat' in c), None)\n",12 unmodified lines" files.download('blackspot_seed.csv')\n","else:\n"," print(\"⚠️ No Latitude/Longitude column found in dataset, skipping cluster generation.\")\n"],"metadata": {"id": "m_EfTgwrQKqn","outputId": "8bbe7036-74e1-4b45-87af-c7991f50a72a","colab": {"base_uri": "https://localhost:8080/","height": 34}},"execution_count": null,"outputs": [{"output_type": "stream","name": "stdout","text": ["✅ Generated blackspot_seed.csv with 4134 clusters\n"]},{"output_type": "display_data","data": {"text/plain": ["<IPython.core.display.Javascript object>"],"application/javascript": ["\n"," async function download(id, filename, size) {\n"," if (!google.colab.kernel.accessAllowed) {\n"," return;\n"," }\n"," const div = document.createElement('div');\n"," const label = document.createElement('label');\n"," label.textContent = `Downloading \"${filename}\": `;\n"," div.appendChild(label);\n"," const progress = document.createElement('progress');\n"," progress.max = size;\n"," div.appendChild(progress);\n"," document.body.appendChild(div);\n","\n"," const buffers = [];\n"," let downloaded = 0;\n","\n"," const channel = await google.colab.kernel.comms.open(id);\n"," // Send a message to notify the kernel that we're ready.\n"," channel.send({})\n","\n"," for await (const message of channel.messages) {\n"," // Send a message to notify the kernel that we're ready.\n"," channel.send({})\n"," if (message.buffers) {\n"," for (const buffer of message.buffers) {\n"," buffers.push(buffer);\n"," downloaded += buffer.byteLength;\n"," progress.value = downloaded;\n"," }\n"," }\n"," }\n"," const blob = new Blob(buffers, {type: 'application/binary'});\n"," const a = document.createElement('a');\n"," a.href = window.URL.createObjectURL(blob);\n"," a.download = filename;\n"," div.appendChild(a);\n"," a.click();\n"," div.remove();\n"," }\n"," "]},"metadata": {}},{"output_type": "display_data","data": {"text/plain": ["<IPython.core.display.Javascript object>"],"application/javascript": ["download(\"download_62de5a95-9cc1-4094-b715-fd75a0df45d2\", \"blackspot_seed.csv\", 84624)"]},"metadata": {}}]}]}12345678910111213141516171819202122232425262728293031323334353637383940413 unmodified lines4546474849505152535455565758596061626364656667686 unmodified lines757677787980816 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131141159 unmodified lines12512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615712 unmodified lines170171172173174175176177178179180181182183184185186187188189190{"cells": [{"cell_type": "markdown","metadata": {},"source": ["# Accident EDA & Blackspot Hotspot Generator\n","\n","**Output:** `accidents_summary.json` + `blackspot_seed.csv` -> seeded to the backend database\n","\n","This notebook processes the Kaggle India Road Accidents dataset\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 x 30+ columns\n","\n","### Pipeline\n","`Raw CSV -> Normalize columns -> State summary -> GPS cluster -> blackspot_seed.csv`"]},{"cell_type": "markdown","metadata": {},"source": ["## Step 0 - Upload Accidents Dataset\n","\n","Upload `kaggle_india_accidents.csv` from:\n","`chatbot_service/data/accidents/kaggle_india_accidents.csv`"]},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/",3 unmodified lines"id": "wTQPiBKuOGj6","outputId": "567b68a9-fb9e-43b3-faae-75d66a415c7e"},"outputs": [],"source": ["# Cell 0 — Upload Dataset\n","from google.colab import files\n","print(\"▶ UPLOAD your accidents CSV dataset NOW:\")\n","uploaded = files.upload()\n","filename = list(uploaded.keys())[0]\n","print(f\"✅ Uploaded {filename}\")\n"]},{"cell_type": "markdown","metadata": {},"source": ["## 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."]},{6 unmodified lines"id": "4HztHudkL-4I","outputId": "c7c242da-9ff8-43f7-aa30-65260e9e11f6"},"outputs": [],"source": ["# Cell 1 — Read baseline datasets\n","import pandas as pd, json\n",6 unmodified lines"cell_type": "markdown","metadata": {},"source": ["## 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."]},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/","height": 17},"id": "IgLUOAYzQBEv","outputId": "8edb7410-47fb-40bb-cdc9-7920ce04ab94"},"outputs": [],"source": ["# Cell 2 — Generate Summary JSON\n","state_col = next((c for c in df.columns if 'state' in c), None)\n",9 unmodified lines"\n","from google.colab import files\n","files.download('accidents_summary.json')\n"]},{"cell_type": "markdown","metadata": {},"source": ["## Step 3 - Generate GPS Blackspot Clusters\n","\n","Groups accident records by rounded GPS coordinates (2 decimal places = ~1km^2),\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."]},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/","height": 34},"id": "m_EfTgwrQKqn","outputId": "8bbe7036-74e1-4b45-87af-c7991f50a72a"},"outputs": [],"source": ["# Cell 3 — Process raw GPS tags into hotspot clusters\n","lat_col = next((c for c in df.columns if 'lat' in c), None)\n",12 unmodified lines" files.download('blackspot_seed.csv')\n","else:\n"," print(\"⚠️ No Latitude/Longitude column found in dataset, skipping cluster generation.\")\n"]}],"metadata": {"colab": {"provenance": []},"kernelspec": {"display_name": "Python 3","name": "python3"},"language_info": {"name": "python"}},"nbformat": 4,"nbformat_minor": 0}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011114 unmodified lines1261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721 unmodified line1741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112128 unmodified lines221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309{"nbformat": 4,"nbformat_minor": 0,"metadata": {"colab": {"provenance": []},"kernelspec": {"name": "python3","display_name": "Python 3"},"language_info": {"name": "python"}},"cells": [{"cell_type": "markdown","metadata": {},"source": ["# ⚡ 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`."]},{"cell_type": "markdown","metadata": {},"source": ["## 🔧 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"]},{"cell_type": "code","execution_count": null,"metadata": {"id": "3o_vWikZQvNu","colab": {"base_uri": "https://localhost:8080/"},"collapsed": true,"outputId": "93304cbf-747d-46f7-b4c3-7ceeb5be730a"},"outputs": [{"output_type": "stream","name": "stdout","text": ["\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m317.2/317.2 kB\u001b[0m \u001b[31m5.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m17.6/17.6 MB\u001b[0m \u001b[31m39.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h✅ Toolkit installed\n"]}],"source": ["# Cell 1 — Install ML Toolkit\n","!pip install scikit-learn skl2onnx pandas numpy -q\n","print(\"✅ Toolkit installed\")\n"]},{"cell_type": "markdown","metadata": {},"source": ["## 🏗️ 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."]},{"cell_type": "code","source": ["# Cell 2 — Build synthetic data matching sensor ingestion structure\n","import pandas as pd, numpy as np\n",14 unmodified lines"y = df['high_risk']\n","\n","print(\"✅ Data matrix ready. Rows:\", len(X))\n"],"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"id": "9Z-Ne1O6RWL4","outputId": "54542fc2-6ea3-443c-8660-20c5c04f1f32"},"execution_count": null,"outputs": [{"output_type": "stream","name": "stdout","text": ["✅ Data matrix ready. Rows: 5000\n"]}]},{"cell_type": "markdown","metadata": {},"source": ["## 🎯 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"]},{"cell_type": "code","source": ["# Cell 3 — Train the GradientBoosting Classifier\n","from sklearn.ensemble import GradientBoostingClassifier\n","\n","model = GradientBoostingClassifier(n_estimators=50, max_depth=4)\n","model.fit(X, y)\n","print(\"✅ Risk AI Training finished\")\n"],"metadata": {"colab": {"base_uri": "https://localhost:8080/"1 unmodified line"id": "u44C8piURguc","outputId": "1c4cd374-a46b-4585-fc76-3bf53a455a36"},"execution_count": null,"outputs": [{"output_type": "stream","name": "stdout","text": ["✅ Risk AI Training finished\n"]}]},{"cell_type": "markdown","metadata": {},"source": ["## 📦 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"]},{"cell_type": "code","source": ["# Cell 4 — Package as ONNX and Export\n","from skl2onnx import convert_sklearn\n",8 unmodified lines"\n","print(f\"✅ Executed. Output size: {len(onx.SerializeToString())//1024} KB\")\n","files.download('risk_model.onnx')\n"],"metadata": {"colab": {"base_uri": "https://localhost:8080/","height": 34},"id": "6P3PgQeLRk3l","outputId": "60c8d868-91d5-411a-ec9d-5eed21132fb4"},"execution_count": null,"outputs": [{"output_type": "stream","name": "stdout","text": ["✅ Executed. Output size: 21 KB\n"]},{"output_type": "display_data","data": {"text/plain": ["<IPython.core.display.Javascript object>"],"application/javascript": ["\n"," async function download(id, filename, size) {\n"," if (!google.colab.kernel.accessAllowed) {\n"," return;\n"," }\n"," const div = document.createElement('div');\n"," const label = document.createElement('label');\n"," label.textContent = `Downloading \"${filename}\": `;\n"," div.appendChild(label);\n"," const progress = document.createElement('progress');\n"," progress.max = size;\n"," div.appendChild(progress);\n"," document.body.appendChild(div);\n","\n"," const buffers = [];\n"," let downloaded = 0;\n","\n"," const channel = await google.colab.kernel.comms.open(id);\n"," // Send a message to notify the kernel that we're ready.\n"," channel.send({})\n","\n"," for await (const message of channel.messages) {\n"," // Send a message to notify the kernel that we're ready.\n"," channel.send({})\n"," if (message.buffers) {\n"," for (const buffer of message.buffers) {\n"," buffers.push(buffer);\n"," downloaded += buffer.byteLength;\n"," progress.value = downloaded;\n"," }\n"," }\n"," }\n"," const blob = new Blob(buffers, {type: 'application/binary'});\n"," const a = document.createElement('a');\n"," a.href = window.URL.createObjectURL(blob);\n"," a.download = filename;\n"," div.appendChild(a);\n"," a.click();\n"," div.remove();\n"," }\n"," "]},"metadata": {}},{"output_type": "display_data","data": {"text/plain": ["<IPython.core.display.Javascript object>"],"application/javascript": ["download(\"download_59bb67d1-88b7-4e30-b14c-3e17e37cdf7b\", \"risk_model.onnx\", 22021)"]},"metadata": {}}]}]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989914 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381 unmodified line1401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861878 unmodified lines196197198199200201202203204205206207208209210211212213214215216{"cells": [{"cell_type": "markdown","metadata": {"id": "oTSGY7DGoU40"},"source": ["# Road Risk Scoring Model - ONNX Training Pipeline\n","\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","Synthetic data generation -> GBM training -> ONNX conversion -> Download\n","\n","> The model runs entirely client-side in the SafeVisionAI PWA using onnxruntime-web."]},{"cell_type": "markdown","metadata": {"id": "n-fQwvTSpkuQ"},"source": ["## 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"]},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"collapsed": true,"id": "3o_vWikZQvNu","outputId": "93304cbf-747d-46f7-b4c3-7ceeb5be730a"},"outputs": [],"source": ["# Cell 1 — Install ML Toolkit#\n","!pip install scikit-learn skl2onnx pandas numpy -q\n","print(\"✅ Toolkit installed\")\n"]},{"cell_type": "markdown","metadata": {"id": "qfw5vFUup0FI"},"source": ["## 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."]},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"id": "9Z-Ne1O6RWL4","outputId": "54542fc2-6ea3-443c-8660-20c5c04f1f32"},"outputs": [],"source": ["# Cell 2 — Build synthetic data matching sensor ingestion structure\n","import pandas as pd, numpy as np\n",14 unmodified lines"y = df['high_risk']\n","\n","print(\"✅ Data matrix ready. Rows:\", len(X))\n"]},{"cell_type": "markdown","metadata": {"id": "VPDAt6HIp99N"},"source": ["## 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"]},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/"1 unmodified line"id": "u44C8piURguc","outputId": "1c4cd374-a46b-4585-fc76-3bf53a455a36"},"outputs": [],"source": ["# Cell 3 — Train the GradientBoosting Classifier\n","from sklearn.ensemble import GradientBoostingClassifier\n","\n","model = GradientBoostingClassifier(n_estimators=50, max_depth=4)\n","model.fit(X, y)\n","print(\"✅ Risk AI Training finished\")\n"]},{"cell_type": "markdown","metadata": {"id": "W8suzsAJqEom"},"source": ["## 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","frontend/public/models/risk_model.onnx\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"]},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/","height": 34},"id": "6P3PgQeLRk3l","outputId": "60c8d868-91d5-411a-ec9d-5eed21132fb4"},"outputs": [],"source": ["# Cell 4 — Package as ONNX and Export\n","from skl2onnx import convert_sklearn\n",8 unmodified lines"\n","print(f\"✅ Executed. Output size: {len(onx.SerializeToString())//1024} KB\")\n","files.download('risk_model.onnx')\n"]}],"metadata": {"colab": {"provenance": []},"kernelspec": {"display_name": "Python 3","name": "python3"},"language_info": {"name": "python"}},"nbformat": 4,"nbformat_minor": 0}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152533 unmodified lines5758596061626364657 unmodified lines73747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135217 unmodified lines370371372373374{"nbformat": 4,"nbformat_minor": 0,"metadata": {"colab": {"provenance": []},"kernelspec": {"name": "python3","display_name": "Python 3"},"language_info": {"name": "python"}},"cells": [{"cell_type": "markdown","metadata": {},"source": ["# 🛣️ 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","```"]},{"cell_type": "markdown","metadata": {},"source": ["## 📦 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",3 unmodified lines"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)"]},{7 unmodified lines"id": "RjBm7RAZO-O0","outputId": "beacaaad-3b29-4737-8664-ee8c2d92a645"},"outputs": [{"output_type": "stream","name": "stdout","text": ["▶ UPLOAD your toll_plazas.csv NOW:\n"]},{"output_type": "display_data","data": {"text/plain": ["<IPython.core.display.HTML object>"],"text/html": ["\n"," <input type=\"file\" id=\"files-0ae94269-bb4f-4460-9755-4fbbca3368bb\" name=\"files[]\" multiple disabled\n"," style=\"border:none\" />\n"," <output id=\"result-0ae94269-bb4f-4460-9755-4fbbca3368bb\">\n"," Upload widget is only available when the cell has been executed in the\n"," current browser session. Please rerun this cell to enable.\n"," </output>\n"," <script>// Copyright 2017 Google LLC\n","//\n","// Licensed under the Apache License, Version 2.0 (the \"License\");\n","// you may not use this file except in compliance with the License.\n","// You may obtain a copy of the License at\n","//\n","// http://www.apache.org/licenses/LICENSE-2.0\n","//\n","// Unless required by applicable law or agreed to in writing, software\n","// distributed under the License is distributed on an \"AS IS\" BASIS,\n","// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n","// See the License for the specific language governing permissions and\n","// limitations under the License.\n","\n","/**\n"," * @fileoverview Helpers for google.colab Python module.\n"," */\n","(function(scope) {\n","function span(text, styleAttributes = {}) {\n"," const element = document.createElement('span');\n"," element.textContent = text;\n"," for (const key of Object.keys(styleAttributes)) {\n"," element.style[key] = styleAttributes[key];\n"," }\n"," return element;\n","}\n","\n","// Max number of bytes which will be uploaded at a time.\n","const MAX_PAYLOAD_SIZE = 100 * 1024;\n","\n","function _uploadFiles(inputId, outputId) {\n"," const steps = uploadFilesStep(inputId, outputId);\n"," const outputElement = document.getElementById(outputId);\n"," // Cache steps on the outputElement to make it available for the next call\n"," // to uploadFilesContinue from Python.\n"," outputElement.steps = steps;\n","\n"," return _uploadFilesContinue(outputId);\n","}\n","\n","// This is roughly an async generator (not supported in the browser yet),\n","// where there are multiple asynchronous steps and the Python side is going\n","// to poll for completion of each step.\n","// This uses a Promise to block the python side on completion of each step,\n","// then passes the result of the previous step as the input to the next step.\n","function _uploadFilesContinue(outputId) {\n"," const outputElement = document.getElementById(outputId);\n"," const steps = outputElement.steps;\n","\n"," const next = steps.next(outputElement.lastPromiseValue);\n"," return Promise.resolve(next.value.promise).then((value) => {\n"," // Cache the last promise value to make it available to the next\n"," // step of the generator.\n"," outputElement.lastPromiseValue = value;\n"," return next.value.response;\n"," });\n","}\n","\n","/**\n"," * Generator function which is called between each async step of the upload\n"," * process.\n"," * @param {string} inputId Element ID of the input file picker element.\n"," * @param {string} outputId Element ID of the output display.\n"," * @return {!Iterable<!Object>} Iterable of next steps.\n"," */\n","function* uploadFilesStep(inputId, outputId) {\n"," const inputElement = document.getElementById(inputId);\n"," inputElement.disabled = false;\n","\n"," const outputElement = document.getElementById(outputId);\n"," outputElement.innerHTML = '';\n","\n"," const pickedPromise = new Promise((resolve) => {\n"," inputElement.addEventListener('change', (e) => {\n"," resolve(e.target.files);\n"," });\n"," });\n","\n"," const cancel = document.createElement('button');\n"," inputElement.parentElement.appendChild(cancel);\n"," cancel.textContent = 'Cancel upload';\n"," const cancelPromise = new Promise((resolve) => {\n"," cancel.onclick = () => {\n"," resolve(null);\n"," };\n"," });\n","\n"," // Wait for the user to pick the files.\n"," const files = yield {\n"," promise: Promise.race([pickedPromise, cancelPromise]),\n"," response: {\n"," action: 'starting',\n"," }\n"," };\n","\n"," cancel.remove();\n","\n"," // Disable the input element since further picks are not allowed.\n"," inputElement.disabled = true;\n","\n"," if (!files) {\n"," return {\n"," response: {\n"," action: 'complete',\n"," }\n"," };\n"," }\n","\n"," for (const file of files) {\n"," const li = document.createElement('li');\n"," li.append(span(file.name, {fontWeight: 'bold'}));\n"," li.append(span(\n"," `(${file.type || 'n/a'}) - ${file.size} bytes, ` +\n"," `last modified: ${\n"," file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() :\n"," 'n/a'} - `));\n"," const percent = span('0% done');\n"," li.appendChild(percent);\n","\n"," outputElement.appendChild(li);\n","\n"," const fileDataPromise = new Promise((resolve) => {\n"," const reader = new FileReader();\n"," reader.onload = (e) => {\n"," resolve(e.target.result);\n"," };\n"," reader.readAsArrayBuffer(file);\n"," });\n"," // Wait for the data to be ready.\n"," let fileData = yield {\n"," promise: fileDataPromise,\n"," response: {\n"," action: 'continue',\n"," }\n"," };\n","\n"," // Use a chunked sending to avoid message size limits. See b/62115660.\n"," let position = 0;\n"," do {\n"," const length = Math.min(fileData.byteLength - position, MAX_PAYLOAD_SIZE);\n"," const chunk = new Uint8Array(fileData, position, length);\n"," position += length;\n","\n"," const base64 = btoa(String.fromCharCode.apply(null, chunk));\n"," yield {\n"," response: {\n"," action: 'append',\n"," file: file.name,\n"," data: base64,\n"," },\n"," };\n","\n"," let percentDone = fileData.byteLength === 0 ?\n"," 100 :\n"," Math.round((position / fileData.byteLength) * 100);\n"," percent.textContent = `${percentDone}% done`;\n","\n"," } while (position < fileData.byteLength);\n"," }\n","\n"," // All done.\n"," yield {\n"," response: {\n"," action: 'complete',\n"," }\n"," };\n","}\n","\n","scope.google = scope.google || {};\n","scope.google.colab = scope.google.colab || {};\n","scope.google.colab._files = {\n"," _uploadFiles,\n"," _uploadFilesContinue,\n","};\n","})(self);\n","</script> "]},"metadata": {}},{"output_type": "stream","name": "stdout","text": ["Saving toll_plazas.csv to toll_plazas (1).csv\n"]},{"output_type": "display_data","data": {"text/plain": ["<IPython.core.display.Javascript object>"],"application/javascript": ["\n"," async function download(id, filename, size) {\n"," if (!google.colab.kernel.accessAllowed) {\n"," return;\n"," }\n"," const div = document.createElement('div');\n"," const label = document.createElement('label');\n"," label.textContent = `Downloading \"${filename}\": `;\n"," div.appendChild(label);\n"," const progress = document.createElement('progress');\n"," progress.max = size;\n"," div.appendChild(progress);\n"," document.body.appendChild(div);\n","\n"," const buffers = [];\n"," let downloaded = 0;\n","\n"," const channel = await google.colab.kernel.comms.open(id);\n"," // Send a message to notify the kernel that we're ready.\n"," channel.send({})\n","\n"," for await (const message of channel.messages) {\n"," // Send a message to notify the kernel that we're ready.\n"," channel.send({})\n"," if (message.buffers) {\n"," for (const buffer of message.buffers) {\n"," buffers.push(buffer);\n"," downloaded += buffer.byteLength;\n"," progress.value = downloaded;\n"," }\n"," }\n"," }\n"," const blob = new Blob(buffers, {type: 'application/binary'});\n"," const a = document.createElement('a');\n"," a.href = window.URL.createObjectURL(blob);\n"," a.download = filename;\n"," div.appendChild(a);\n"," a.click();\n"," div.remove();\n"," }\n"," "]},"metadata": {}},{"output_type": "display_data","data": {"text/plain": ["<IPython.core.display.Javascript object>"],"application/javascript": ["download(\"download_210eae57-c408-497c-977e-ce6e97b30a77\", \"toll_plazas_lite.json\", 65010)"]},"metadata": {}}],"source": ["# Cell 1 — Toll Plazas Lite\n","import pandas as pd, json\n",17 unmodified lines"files.download('toll_plazas_lite.json')\n"]}]}1234567891011121314151617181920212223242526272829303132333 unmodified lines373839404142437 unmodified lines5152535455565717 unmodified lines75767778798081828384858687888990919293{"cells": [{"cell_type": "markdown","metadata": {},"source": ["# Roads & Toll Plaza Data Processing\n","\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","`toll_plazas.csv -> Select key columns -> Rename headers -> Export toll_plazas_lite.json`"]},{"cell_type": "markdown","metadata": {},"source": ["## Step 1 - Upload & Process Toll Plaza CSV\n","\n","Upload `toll_plazas.csv` from `backend/data/roads/toll_plazas.csv`\n","\n","The processing pipeline:\n","1. Reads the CSV with `pandas`\n",3 unmodified lines"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."]},{7 unmodified lines"id": "RjBm7RAZO-O0","outputId": "beacaaad-3b29-4737-8664-ee8c2d92a645"},"outputs": [],"source": ["# Cell 1 — Toll Plazas Lite\n","import pandas as pd, json\n",17 unmodified lines"files.download('toll_plazas_lite.json')\n"]}],"metadata": {"colab": {"provenance": []},"kernelspec": {"display_name": "Python 3","name": "python3"},"language_info": {"name": "python"}},"nbformat": 4,"nbformat_minor": 0}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546478 unmodified lines565758596061626364656667686970717273747576777879808182838485868 unmodified lines95969798991001011021031041051061071081091101111121131141151162 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591602 unmodified lines1631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012 unmodified lines2042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334341 unmodified line4364374384394404414424434444454464474484494504514524534544554564574584594604614624634647 unmodified lines47247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951015 unmodified lines5265275285295305315325335345355365375385395405415425435445455465475485495505515525535545554 unmodified lines5605615625635645658 unmodified lines5745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206219 unmodified lines63163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410452 unmodified lines1048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120{"nbformat": 4,"nbformat_minor": 0,"metadata": {"colab": {"provenance": [],"gpuType": "T4"},"kernelspec": {"name": "python3","display_name": "Python 3"},"language_info": {"name": "python"},"accelerator": "GPU"},"cells": [{"cell_type": "markdown","metadata": {},"source": ["# 🚗 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"]},{8 unmodified lines"id": "uwTMRE_8C740","outputId": "ecfb62d6-9b10-4bc0-caa0-971da9a80c3e"},"outputs": [{"output_type": "display_data","data": {"text/plain": ["<IPython.core.display.Javascript object>"],"application/javascript": ["\n"," function ClickConnect(){\n"," document.querySelector('#top-toolbar > colab-connect-button').click()\n"," }\n"," setInterval(ClickConnect, 60000)\n"]},"metadata": {}},{"output_type": "stream","name": "stdout","text": ["Anti-disconnect activated\n"]}],"source": ["import time\n","from IPython.display import Javascript\n",8 unmodified lines},{"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","source": ["!pip install ultralytics roboflow -q\n","!pip install onnx onnxruntime -q"],"metadata": {"colab": {"base_uri": "https://localhost:8080/"2 unmodified lines"id": "I0GBSI74DVJI","outputId": "a71f5e00-bbe6-458c-c79d-5e9d75c8931f"},"execution_count": null,"outputs": [{"output_type": "stream","name": "stdout","text": ["\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/1.2 MB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[91m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[91m╸\u001b[0m \u001b[32m1.2/1.2 MB\u001b[0m \u001b[31m54.2 MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.2/1.2 MB\u001b[0m \u001b[31m34.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h\u001b[?25l \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/169.5 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m169.5/169.5 kB\u001b[0m \u001b[31m17.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m66.8/66.8 kB\u001b[0m \u001b[31m6.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m49.9/49.9 MB\u001b[0m \u001b[31m20.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.5/1.5 MB\u001b[0m \u001b[31m77.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m5.5/5.5 MB\u001b[0m \u001b[31m130.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m17.6/17.6 MB\u001b[0m \u001b[31m92.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m17.2/17.2 MB\u001b[0m \u001b[31m20.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h"]}]},{"cell_type": "markdown","metadata": {},"source": ["## ✅ Step 2 — Verify GPU & Import YOLO\n","\n","Confirms that the Tesla T4 GPU is available and the Ultralytics framework is ready."]},{"cell_type": "code","source": ["\n","import os\n","from ultralytics import YOLO\n","print(\"✅ Ultralytics ready, CUDA:\", os.popen(\"nvidia-smi --query-gpu=name --format=csv,noheader\").read().strip())"],"metadata": {"colab": {"base_uri": "https://localhost:8080/"2 unmodified lines"id": "yJoIU507DcKF","outputId": "e92f642d-1464-45e4-ec35-cd3c7eb402bf"},"execution_count": null,"outputs": [{"output_type": "stream","name": "stdout","text": ["Creating new Ultralytics Settings v0.0.6 file ✅ \n","View Ultralytics Settings with 'yolo settings' or at '/root/.config/Ultralytics/settings.json'\n","Update Settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'. For help see https://docs.ultralytics.com/quickstart/#ultralytics-settings.\n","✅ Ultralytics ready, CUDA: Tesla T4\n"]}]},{"cell_type": "markdown","metadata": {},"source": ["## 📁 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)."]},{"cell_type": "code","source": ["from google.colab import files\n","uploaded = files.upload()"],"metadata": {"colab": {"base_uri": "https://localhost:8080/",2 unmodified lines"id": "t7uQDAFzDeaJ","outputId": "e5e7f1b4-8a1d-4d91-b2a9-feddd6783794"},"execution_count": null,"outputs": [{"output_type": "display_data","data": {"text/plain": ["<IPython.core.display.HTML object>"],"text/html": ["\n"," <input type=\"file\" id=\"files-24ea8cd9-a427-4ce7-9646-b6a5625d2fc4\" name=\"files[]\" multiple disabled\n"," style=\"border:none\" />\n"," <output id=\"result-24ea8cd9-a427-4ce7-9646-b6a5625d2fc4\">\n"," Upload widget is only available when the cell has been executed in the\n"," current browser session. Please rerun this cell to enable.\n"," </output>\n"," <script>// Copyright 2017 Google LLC\n","//\n","// Licensed under the Apache License, Version 2.0 (the \"License\");\n","// you may not use this file except in compliance with the License.\n","// You may obtain a copy of the License at\n","//\n","// http://www.apache.org/licenses/LICENSE-2.0\n","//\n","// Unless required by applicable law or agreed to in writing, software\n","// distributed under the License is distributed on an \"AS IS\" BASIS,\n","// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n","// See the License for the specific language governing permissions and\n","// limitations under the License.\n","\n","/**\n"," * @fileoverview Helpers for google.colab Python module.\n"," */\n","(function(scope) {\n","function span(text, styleAttributes = {}) {\n"," const element = document.createElement('span');\n"," element.textContent = text;\n"," for (const key of Object.keys(styleAttributes)) {\n"," element.style[key] = styleAttributes[key];\n"," }\n"," return element;\n","}\n","\n","// Max number of bytes which will be uploaded at a time.\n","const MAX_PAYLOAD_SIZE = 100 * 1024;\n","\n","function _uploadFiles(inputId, outputId) {\n"," const steps = uploadFilesStep(inputId, outputId);\n"," const outputElement = document.getElementById(outputId);\n"," // Cache steps on the outputElement to make it available for the next call\n"," // to uploadFilesContinue from Python.\n"," outputElement.steps = steps;\n","\n"," return _uploadFilesContinue(outputId);\n","}\n","\n","// This is roughly an async generator (not supported in the browser yet),\n","// where there are multiple asynchronous steps and the Python side is going\n","// to poll for completion of each step.\n","// This uses a Promise to block the python side on completion of each step,\n","// then passes the result of the previous step as the input to the next step.\n","function _uploadFilesContinue(outputId) {\n"," const outputElement = document.getElementById(outputId);\n"," const steps = outputElement.steps;\n","\n"," const next = steps.next(outputElement.lastPromiseValue);\n"," return Promise.resolve(next.value.promise).then((value) => {\n"," // Cache the last promise value to make it available to the next\n"," // step of the generator.\n"," outputElement.lastPromiseValue = value;\n"," return next.value.response;\n"," });\n","}\n","\n","/**\n"," * Generator function which is called between each async step of the upload\n"," * process.\n"," * @param {string} inputId Element ID of the input file picker element.\n"," * @param {string} outputId Element ID of the output display.\n"," * @return {!Iterable<!Object>} Iterable of next steps.\n"," */\n","function* uploadFilesStep(inputId, outputId) {\n"," const inputElement = document.getElementById(inputId);\n"," inputElement.disabled = false;\n","\n"," const outputElement = document.getElementById(outputId);\n"," outputElement.innerHTML = '';\n","\n"," const pickedPromise = new Promise((resolve) => {\n"," inputElement.addEventListener('change', (e) => {\n"," resolve(e.target.files);\n"," });\n"," });\n","\n"," const cancel = document.createElement('button');\n"," inputElement.parentElement.appendChild(cancel);\n"," cancel.textContent = 'Cancel upload';\n"," const cancelPromise = new Promise((resolve) => {\n"," cancel.onclick = () => {\n"," resolve(null);\n"," };\n"," });\n","\n"," // Wait for the user to pick the files.\n"," const files = yield {\n"," promise: Promise.race([pickedPromise, cancelPromise]),\n"," response: {\n"," action: 'starting',\n"," }\n"," };\n","\n"," cancel.remove();\n","\n"," // Disable the input element since further picks are not allowed.\n"," inputElement.disabled = true;\n","\n"," if (!files) {\n"," return {\n"," response: {\n"," action: 'complete',\n"," }\n"," };\n"," }\n","\n"," for (const file of files) {\n"," const li = document.createElement('li');\n"," li.append(span(file.name, {fontWeight: 'bold'}));\n"," li.append(span(\n"," `(${file.type || 'n/a'}) - ${file.size} bytes, ` +\n"," `last modified: ${\n"," file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() :\n"," 'n/a'} - `));\n"," const percent = span('0% done');\n"," li.appendChild(percent);\n","\n"," outputElement.appendChild(li);\n","\n"," const fileDataPromise = new Promise((resolve) => {\n"," const reader = new FileReader();\n"," reader.onload = (e) => {\n"," resolve(e.target.result);\n"," };\n"," reader.readAsArrayBuffer(file);\n"," });\n"," // Wait for the data to be ready.\n"," let fileData = yield {\n"," promise: fileDataPromise,\n"," response: {\n"," action: 'continue',\n"," }\n"," };\n","\n"," // Use a chunked sending to avoid message size limits. See b/62115660.\n"," let position = 0;\n"," do {\n"," const length = Math.min(fileData.byteLength - position, MAX_PAYLOAD_SIZE);\n"," const chunk = new Uint8Array(fileData, position, length);\n"," position += length;\n","\n"," const base64 = btoa(String.fromCharCode.apply(null, chunk));\n"," yield {\n"," response: {\n"," action: 'append',\n"," file: file.name,\n"," data: base64,\n"," },\n"," };\n","\n"," let percentDone = fileData.byteLength === 0 ?\n"," 100 :\n"," Math.round((position / fileData.byteLength) * 100);\n"," percent.textContent = `${percentDone}% done`;\n","\n"," } while (position < fileData.byteLength);\n"," }\n","\n"," // All done.\n"," yield {\n"," response: {\n"," action: 'complete',\n"," }\n"," };\n","}\n","\n","scope.google = scope.google || {};\n","scope.google.colab = scope.google.colab || {};\n","scope.google.colab._files = {\n"," _uploadFiles,\n"," _uploadFilesContinue,\n","};\n","})(self);\n","</script> "]},"metadata": {}},{"output_type": "stream","name": "stdout","text": ["Saving archive.zip to archive.zip\n"]}]},{"cell_type": "markdown","metadata": {},"source": ["## 📦 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."]},{"cell_type": "code","source": ["# Cell 3 — Extract the main zipped dataset\n","import zipfile\n","\n","with zipfile.ZipFile('/content/archive.zip', 'r') as z:\n"," z.extractall('/content/pothole_data')\n","print(\"✅ archive.zip extracted successfully\")\n"],"metadata": {"colab": {"base_uri": "https://localhost:8080/"1 unmodified line"id": "MdUI5xwtK6fp","outputId": "945affb4-bba0-496f-c1f6-9429cad842eb"},"execution_count": null,"outputs": [{"output_type": "stream","name": "stdout","text": ["✅ archive.zip extracted successfully\n"]}]},{"cell_type": "markdown","metadata": {},"source": ["## 🗂️ 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."]},{"cell_type": "code","source": ["# Cell 4 — Setup master directory structure for merged datasets\n","import os, shutil\n",7 unmodified lines"for p in [merged_train_img, merged_train_lbl, merged_val_img, merged_val_lbl]:\n"," os.makedirs(p, exist_ok=True)\n","print(\"✅ Master directories created\")\n"],"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"id": "RMlyOEcEK-Zz","outputId": "bd472e3d-d1be-4d07-daaa-db42568eb77c"},"execution_count": null,"outputs": [{"output_type": "stream","name": "stdout","text": ["✅ Master directories created\n"]}]},{"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","\n","> ✅ Result: **2,009 training images** merged from road_damage_2025."]},{"cell_type": "code","source": ["# Cell 5 — Copy all images and labels into the merged folder (Bulletproof Search)\n","# List of directories containing datasets (Assuming they are available in /content/)\n",15 unmodified lines" shutil.copy(lbl, merged_train_lbl)\n","\n","print('✅ Merging complete. Total train images:', len(list(Path(merged_train_img).glob('*.jpg'))))\n"],"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"id": "lJZFF47NLEFJ","outputId": "04ff65e2-a9c7-4ce6-d2dd-11d1139a6a8f"},"execution_count": null,"outputs": [{"output_type": "stream","name": "stdout","text": ["✅ Merging complete. Total train images: 2009\n"]}]},{"cell_type": "markdown","metadata": {},"source": ["## 📝 Step 7 — Write `data.yaml`\n","\n","Creates the YOLO dataset configuration file defining:\n","- 3 detection classes: `['pothole', 'crack', 'manhole']`\n",4 unmodified lines},{"cell_type": "code","source": ["# Cell 6 — Create data.yaml mapping to our 3 classes\n","data_yaml = \"\"\"\n",8 unmodified lines" f.write(data_yaml)\n","\n","print(\"✅ data.yaml written\")\n"],"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"id": "f5Cmy0iuMZSC","outputId": "15593ba5-a0b6-46f9-a751-367262c4f65f"},"execution_count": null,"outputs": [{"output_type": "stream","name": "stdout","text": ["✅ data.yaml written\n"]}]},{"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": ["# Cell 7 — Train (45-60 min on T4 GPU)\n","model = YOLO('yolov8n.pt')\n",9 unmodified lines" save=True,\n",")\n","print(\"✅ YOLO Training Finished\")\n"],"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"id": "kXWxRFmaMcyE","outputId": "66b2cdd5-193d-4946-cbaf-b39dc5fa24ae","collapsed": true},"execution_count": null,"outputs": [{"output_type": "stream","name": "stdout","text": ["Ultralytics 8.4.37 🚀 Python-3.12.13 torch-2.10.0+cu128 CUDA:0 (Tesla T4, 14913MiB)\n","\u001b[34m\u001b[1mengine/trainer: \u001b[0magnostic_nms=False, amp=True, angle=1.0, augment=False, auto_augment=randaugment, batch=16, bgr=0.0, box=7.5, cache=False, cfg=None, classes=None, close_mosaic=10, cls=0.5, cls_pw=0.0, compile=False, conf=None, copy_paste=0.0, copy_paste_mode=flip, cos_lr=False, cutmix=0.0, data=/content/pothole.yaml, degrees=0.0, deterministic=True, device=0, dfl=1.5, dnn=False, dropout=0.0, dynamic=False, embed=None, end2end=None, epochs=50, erasing=0.4, exist_ok=False, fliplr=0.5, flipud=0.0, format=torchscript, fraction=1.0, freeze=None, half=False, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, imgsz=640, int8=False, iou=0.7, keras=False, kobj=1.0, line_width=None, lr0=0.01, lrf=0.01, mask_ratio=4, max_det=300, mixup=0.0, mode=train, model=yolov8n.pt, momentum=0.937, mosaic=1.0, multi_scale=0.0, name=pothole_v12, nbs=64, nms=False, opset=None, optimize=False, optimizer=auto, overlap_mask=True, patience=100, perspective=0.0, plots=True, pose=12.0, pretrained=True, profile=False, project=/content/runs/detect, rect=False, resume=False, retina_masks=False, rle=1.0, save=True, save_conf=False, save_crop=False, save_dir=/content/runs/detect/pothole_v12, save_frames=False, save_json=False, save_period=-1, save_txt=False, scale=0.5, seed=0, shear=0.0, show=False, show_boxes=True, show_conf=True, show_labels=True, simplify=True, single_cls=False, source=None, split=val, stream_buffer=False, task=detect, time=None, tracker=botsort.yaml, translate=0.1, val=True, verbose=True, vid_stride=1, visualize=False, warmup_bias_lr=0.1, warmup_epochs=3.0, warmup_momentum=0.8, weight_decay=0.0005, workers=8, workspace=None\n","Overriding model.yaml nc=80 with nc=3\n","\n"," from n params module arguments \n"," 0 -1 1 464 ultralytics.nn.modules.conv.Conv [3, 16, 3, 2] \n"," 1 -1 1 4672 ultralytics.nn.modules.conv.Conv [16, 32, 3, 2] \n"," 2 -1 1 7360 ultralytics.nn.modules.block.C2f [32, 32, 1, True] \n"," 3 -1 1 18560 ultralytics.nn.modules.conv.Conv [32, 64, 3, 2] \n"," 4 -1 2 49664 ultralytics.nn.modules.block.C2f [64, 64, 2, True] \n"," 5 -1 1 73984 ultralytics.nn.modules.conv.Conv [64, 128, 3, 2] \n"," 6 -1 2 197632 ultralytics.nn.modules.block.C2f [128, 128, 2, True] \n"," 7 -1 1 295424 ultralytics.nn.modules.conv.Conv [128, 256, 3, 2] \n"," 8 -1 1 460288 ultralytics.nn.modules.block.C2f [256, 256, 1, True] \n"," 9 -1 1 164608 ultralytics.nn.modules.block.SPPF [256, 256, 5] \n"," 10 -1 1 0 torch.nn.modules.upsampling.Upsample [None, 2, 'nearest'] \n"," 11 [-1, 6] 1 0 ultralytics.nn.modules.conv.Concat [1] \n"," 12 -1 1 148224 ultralytics.nn.modules.block.C2f [384, 128, 1] \n"," 13 -1 1 0 torch.nn.modules.upsampling.Upsample [None, 2, 'nearest'] \n"," 14 [-1, 4] 1 0 ultralytics.nn.modules.conv.Concat [1] \n"," 15 -1 1 37248 ultralytics.nn.modules.block.C2f [192, 64, 1] \n"," 16 -1 1 36992 ultralytics.nn.modules.conv.Conv [64, 64, 3, 2] \n"," 17 [-1, 12] 1 0 ultralytics.nn.modules.conv.Concat [1] \n"," 18 -1 1 123648 ultralytics.nn.modules.block.C2f [192, 128, 1] \n"," 19 -1 1 147712 ultralytics.nn.modules.conv.Conv [128, 128, 3, 2] \n"," 20 [-1, 9] 1 0 ultralytics.nn.modules.conv.Concat [1] \n"," 21 -1 1 493056 ultralytics.nn.modules.block.C2f [384, 256, 1] \n"," 22 [15, 18, 21] 1 751897 ultralytics.nn.modules.head.Detect [3, 16, None, [64, 128, 256]] \n","Model summary: 130 layers, 3,011,433 parameters, 3,011,417 gradients, 8.2 GFLOPs\n","\n","Transferred 319/355 items from pretrained weights\n","Freezing layer 'model.22.dfl.conv.weight'\n","\u001b[34m\u001b[1mAMP: \u001b[0mrunning Automatic Mixed Precision (AMP) checks...\n","\u001b[34m\u001b[1mAMP: \u001b[0mchecks passed ✅\n","\u001b[34m\u001b[1mtrain: \u001b[0mFast image access ✅ (ping: 0.0±0.0 ms, read: 1748.1±478.9 MB/s, size: 91.3 KB)\n","\u001b[K\u001b[34m\u001b[1mtrain: \u001b[0mScanning /content/merged/train/labels.cache... 2009 images, 0 backgrounds, 0 corrupt: 100% ━━━━━━━━━━━━ 2009/2009 702.2Mit/s 0.0s\n","\u001b[34m\u001b[1malbumentations: \u001b[0mBlur(p=0.01, blur_limit=(3, 7)), MedianBlur(p=0.01, blur_limit=(3, 7)), ToGray(p=0.01, method='weighted_average', num_output_channels=3), CLAHE(p=0.01, clip_limit=(1.0, 4.0), tile_grid_size=(8, 8))\n","\u001b[34m\u001b[1mval: \u001b[0mFast image access ✅ (ping: 0.0±0.0 ms, read: 602.0±531.0 MB/s, size: 96.3 KB)\n","\u001b[K\u001b[34m\u001b[1mval: \u001b[0mScanning /content/merged/train/labels.cache... 2009 images, 0 backgrounds, 0 corrupt: 100% ━━━━━━━━━━━━ 2009/2009 98.0Mit/s 0.0s\n","\u001b[34m\u001b[1moptimizer:\u001b[0m 'optimizer=auto' found, ignoring 'lr0=0.01' and 'momentum=0.937' and determining best 'optimizer', 'lr0' and 'momentum' automatically... \n","\u001b[34m\u001b[1moptimizer:\u001b[0m AdamW(lr=0.001429, momentum=0.9) with parameter groups 57 weight(decay=0.0), 64 weight(decay=0.0005), 63 bias(decay=0.0)\n","Plotting labels to /content/runs/detect/pothole_v12/labels.jpg... \n","Image sizes 640 train, 640 val\n","Using 2 dataloader workers\n","Logging results to \u001b[1m/content/runs/detect/pothole_v12\u001b[0m\n","Starting training for 50 epochs...\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 1/50 2.07G 2.461 3.585 1.815 42 640: 100% ━━━━━━━━━━━━ 126/126 2.6it/s 48.6s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.5s\n"," all 2009 4737 0.294 0.193 0.145 0.0462\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 2/50 2.18G 2.278 2.788 1.713 39 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 42.4s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.0it/s 15.7s\n"," all 2009 4737 0.314 0.26 0.225 0.0889\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 3/50 2.18G 2.302 2.577 1.706 39 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 42.3s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.3it/s 14.7s\n"," all 2009 4737 0.346 0.319 0.254 0.0951\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 4/50 2.18G 2.292 2.446 1.713 26 640: 100% ━━━━━━━━━━━━ 126/126 3.2it/s 39.8s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.2it/s 15.0s\n"," all 2009 4737 0.345 0.347 0.292 0.114\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 5/50 2.18G 2.235 2.342 1.692 37 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 41.5s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.2it/s 15.2s\n"," all 2009 4737 0.371 0.323 0.285 0.116\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 6/50 2.18G 2.198 2.251 1.665 25 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 42.3s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.2it/s 14.9s\n"," all 2009 4737 0.405 0.399 0.345 0.146\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 7/50 2.18G 2.178 2.215 1.644 39 640: 100% ━━━━━━━━━━━━ 126/126 3.1it/s 40.6s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.5s\n"," all 2009 4737 0.383 0.412 0.367 0.15\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 8/50 2.18G 2.165 2.176 1.62 39 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 41.3s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.2it/s 15.1s\n"," all 2009 4737 0.36 0.426 0.381 0.16\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 9/50 2.18G 2.125 2.129 1.607 25 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 41.7s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.3s\n"," all 2009 4737 0.411 0.429 0.392 0.162\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 10/50 2.18G 2.13 2.077 1.599 52 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 42.2s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.2it/s 15.1s\n"," all 2009 4737 0.454 0.414 0.408 0.174\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 11/50 2.18G 2.074 2.036 1.575 43 640: 100% ━━━━━━━━━━━━ 126/126 3.2it/s 39.8s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.3s\n"," all 2009 4737 0.426 0.441 0.402 0.17\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 12/50 2.18G 2.083 2.026 1.576 28 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 42.1s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.2it/s 15.0s\n"," all 2009 4737 0.445 0.442 0.405 0.171\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 13/50 2.18G 2.068 2 1.57 41 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 41.6s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.3it/s 14.8s\n"," all 2009 4737 0.442 0.45 0.418 0.18\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 14/50 2.18G 2.054 1.98 1.556 43 640: 100% ━━━━━━━━━━━━ 126/126 3.2it/s 39.7s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.0it/s 15.7s\n"," all 2009 4737 0.4 0.465 0.423 0.167\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 15/50 2.18G 2.062 1.97 1.549 29 640: 100% ━━━━━━━━━━━━ 126/126 3.1it/s 40.4s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.3s\n"," all 2009 4737 0.486 0.481 0.455 0.2\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 16/50 2.18G 2.017 1.908 1.536 36 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 41.6s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.2it/s 15.0s\n"," all 2009 4737 0.507 0.494 0.476 0.211\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 17/50 2.18G 2.008 1.91 1.533 35 640: 100% ━━━━━━━━━━━━ 126/126 3.1it/s 40.9s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.2it/s 15.1s\n"," all 2009 4737 0.506 0.502 0.484 0.214\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 18/50 2.18G 2.014 1.871 1.512 43 640: 100% ━━━━━━━━━━━━ 126/126 3.1it/s 41.0s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.3it/s 14.7s\n"," all 2009 4737 0.511 0.482 0.476 0.219\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 19/50 2.18G 2 1.871 1.514 36 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 42.4s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.0it/s 15.8s\n"," all 2009 4737 0.519 0.512 0.49 0.215\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 20/50 2.18G 1.971 1.848 1.496 33 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 41.8s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.3s\n"," all 2009 4737 0.544 0.52 0.522 0.233\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 21/50 2.18G 1.973 1.843 1.501 42 640: 100% ━━━━━━━━━━━━ 126/126 3.1it/s 40.6s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.3s\n"," all 2009 4737 0.528 0.532 0.528 0.244\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 22/50 2.18G 1.966 1.798 1.489 25 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 41.3s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.2it/s 15.1s\n"," all 2009 4737 0.528 0.524 0.514 0.233\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 23/50 2.18G 1.962 1.804 1.492 29 640: 100% ━━━━━━━━━━━━ 126/126 2.9it/s 42.8s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.2it/s 15.2s\n"," all 2009 4737 0.504 0.51 0.505 0.239\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 24/50 2.18G 1.948 1.791 1.48 52 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 42.3s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.2s\n"," all 2009 4737 0.534 0.549 0.551 0.258\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 25/50 2.18G 1.949 1.755 1.471 53 640: 100% ━━━━━━━━━━━━ 126/126 3.1it/s 40.5s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.0it/s 15.6s\n"," all 2009 4737 0.581 0.543 0.558 0.263\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 26/50 2.18G 1.946 1.761 1.454 36 640: 100% ━━━━━━━━━━━━ 126/126 3.1it/s 41.2s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.2it/s 15.1s\n"," all 2009 4737 0.587 0.547 0.565 0.266\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 27/50 2.18G 1.888 1.715 1.438 36 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 42.1s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.5s\n"," all 2009 4737 0.589 0.551 0.578 0.28\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 28/50 2.18G 1.93 1.705 1.444 41 640: 100% ━━━━━━━━━━━━ 126/126 3.1it/s 41.2s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.5s\n"," all 2009 4737 0.606 0.563 0.592 0.283\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 29/50 2.18G 1.879 1.654 1.431 44 640: 100% ━━━━━━━━━━━━ 126/126 3.1it/s 40.5s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.4s\n"," all 2009 4737 0.58 0.564 0.578 0.274\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 30/50 2.18G 1.877 1.658 1.432 36 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 42.1s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.3s\n"," all 2009 4737 0.621 0.585 0.607 0.3\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 31/50 2.18G 1.877 1.637 1.422 45 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 42.4s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.0it/s 15.6s\n"," all 2009 4737 0.621 0.595 0.626 0.309\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 32/50 2.18G 1.856 1.636 1.417 55 640: 100% ━━━━━━━━━━━━ 126/126 2.9it/s 42.8s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.3it/s 14.6s\n"," all 2009 4737 0.622 0.607 0.627 0.314\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 33/50 2.18G 1.861 1.607 1.408 31 640: 100% ━━━━━━━━━━━━ 126/126 3.1it/s 40.9s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.2it/s 14.9s\n"," all 2009 4737 0.643 0.601 0.635 0.311\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 34/50 2.18G 1.847 1.612 1.4 48 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 42.5s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.4s\n"," all 2009 4737 0.648 0.625 0.659 0.328\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 35/50 2.18G 1.81 1.578 1.393 48 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 42.0s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.0it/s 15.6s\n"," all 2009 4737 0.637 0.64 0.659 0.334\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 36/50 2.18G 1.837 1.554 1.398 42 640: 100% ━━━━━━━━━━━━ 126/126 3.1it/s 41.0s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.4s\n"," all 2009 4737 0.659 0.639 0.674 0.342\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 37/50 2.18G 1.828 1.573 1.39 34 640: 100% ━━━━━━━━━━━━ 126/126 3.1it/s 40.6s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.4s\n"," all 2009 4737 0.662 0.613 0.66 0.334\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 38/50 2.18G 1.798 1.516 1.373 45 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 42.3s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.3s\n"," all 2009 4737 0.661 0.641 0.678 0.35\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 39/50 2.18G 1.801 1.518 1.373 50 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 42.2s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.0it/s 15.9s\n"," all 2009 4737 0.68 0.64 0.692 0.36\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 40/50 2.18G 1.773 1.485 1.36 44 640: 100% ━━━━━━━━━━━━ 126/126 3.1it/s 40.2s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.2it/s 15.0s\n"," all 2009 4737 0.675 0.655 0.7 0.359\n","Closing dataloader mosaic\n","\u001b[34m\u001b[1malbumentations: \u001b[0mBlur(p=0.01, blur_limit=(3, 7)), MedianBlur(p=0.01, blur_limit=(3, 7)), ToGray(p=0.01, method='weighted_average', num_output_channels=3), CLAHE(p=0.01, clip_limit=(1.0, 4.0), tile_grid_size=(8, 8))\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 41/50 2.18G 1.765 1.475 1.409 13 640: 100% ━━━━━━━━━━━━ 126/126 3.0it/s 41.6s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.3it/s 14.7s\n"," all 2009 4737 0.677 0.635 0.684 0.352\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 42/50 2.18G 1.732 1.417 1.393 14 640: 100% ━━━━━━━━━━━━ 126/126 3.4it/s 36.7s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.4it/s 14.4s\n"," all 2009 4737 0.705 0.658 0.716 0.375\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 43/50 2.18G 1.709 1.389 1.379 27 640: 100% ━━━━━━━━━━━━ 126/126 3.3it/s 38.5s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.3it/s 14.8s\n"," all 2009 4737 0.704 0.664 0.718 0.376\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 44/50 2.18G 1.698 1.365 1.381 18 640: 100% ━━━━━━━━━━━━ 126/126 3.5it/s 36.4s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.3it/s 14.7s\n"," all 2009 4737 0.732 0.66 0.729 0.38\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 45/50 2.18G 1.679 1.353 1.373 23 640: 100% ━━━━━━━━━━━━ 126/126 3.4it/s 37.4s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.1it/s 15.2s\n"," all 2009 4737 0.733 0.675 0.74 0.401\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 46/50 2.18G 1.678 1.335 1.358 20 640: 100% ━━━━━━━━━━━━ 126/126 3.4it/s 36.6s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.3it/s 14.6s\n"," all 2009 4737 0.739 0.676 0.747 0.402\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 47/50 2.18G 1.66 1.34 1.36 18 640: 100% ━━━━━━━━━━━━ 126/126 3.4it/s 37.0s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.3it/s 14.6s\n"," all 2009 4737 0.743 0.687 0.761 0.412\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 48/50 2.18G 1.661 1.296 1.346 22 640: 100% ━━━━━━━━━━━━ 126/126 3.3it/s 37.8s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.2it/s 15.0s\n"," all 2009 4737 0.747 0.688 0.762 0.415\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 49/50 2.18G 1.616 1.276 1.33 17 640: 100% ━━━━━━━━━━━━ 126/126 3.5it/s 36.3s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.3it/s 14.5s\n"," all 2009 4737 0.75 0.696 0.767 0.422\n","\n"," Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size\n","\u001b[K 50/50 2.18G 1.613 1.265 1.325 15 640: 100% ━━━━━━━━━━━━ 126/126 3.3it/s 38.5s\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 4.2it/s 15.0s\n"," all 2009 4737 0.75 0.712 0.775 0.427\n","\n","50 epochs completed in 0.787 hours.\n","Optimizer stripped from /content/runs/detect/pothole_v12/weights/last.pt, 6.2MB\n","Optimizer stripped from /content/runs/detect/pothole_v12/weights/best.pt, 6.2MB\n","\n","Validating /content/runs/detect/pothole_v12/weights/best.pt...\n","Ultralytics 8.4.37 🚀 Python-3.12.13 torch-2.10.0+cu128 CUDA:0 (Tesla T4, 14913MiB)\n","Model summary (fused): 73 layers, 3,006,233 parameters, 0 gradients, 8.1 GFLOPs\n","\u001b[K Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 63/63 3.7it/s 17.1s\n"," all 2009 4737 0.75 0.712 0.774 0.426\n"," pothole 795 1261 0.692 0.638 0.71 0.363\n"," crack 1375 2519 0.693 0.623 0.697 0.382\n"," manhole 759 957 0.865 0.874 0.917 0.535\n","Speed: 0.1ms preprocess, 1.6ms inference, 0.0ms loss, 1.7ms postprocess per image\n","Results saved to \u001b[1m/content/runs/detect/pothole_v12\u001b[0m\n","✅ YOLO Training Finished\n"]}]},{"cell_type": "code","source": ["# Cell 8 — Export ONNX\n","best_model = YOLO('/content/runs/detect/pothole_v1/weights/best.pt')\n","best_model.export(format='onnx', imgsz=640, opset=12, simplify=True)\n","best_model.export(format='torchscript')\n","print(\"✅ ONNX models generated\")\n"],"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"id": "53VaY29vfU3S","outputId": "43484095-f9d9-43bd-efbf-cef0b272448a"},"execution_count": null,"outputs": [{"output_type": "stream","name": "stdout","text": ["Ultralytics 8.4.37 🚀 Python-3.12.13 torch-2.10.0+cu128 CPU (Intel Xeon CPU @ 2.00GHz)\n","💡 ProTip: Export to OpenVINO format for best performance on Intel hardware. Learn more at https://docs.ultralytics.com/integrations/openvino/\n","Model summary (fused): 73 layers, 3,006,233 parameters, 0 gradients, 8.1 GFLOPs\n","\n","\u001b[34m\u001b[1mPyTorch:\u001b[0m starting from '/content/runs/detect/pothole_v1/weights/best.pt' with input shape (1, 3, 640, 640) BCHW and output shape(s) (1, 7, 8400) (5.9 MB)\n","\u001b[31m\u001b[1mrequirements:\u001b[0m Ultralytics requirements ['onnxslim>=0.1.71', 'onnxruntime-gpu'] not found, attempting AutoUpdate...\n","Using Python 3.12.13 environment at: /usr\n","Resolved 12 packages in 446ms\n","Prepared 3 packages in 4.89s\n","Installed 3 packages in 39ms\n"," + colorama==0.4.6\n"," + onnxruntime-gpu==1.24.4\n"," + onnxslim==0.1.91\n","\n","\u001b[31m\u001b[1mrequirements:\u001b[0m AutoUpdate success ✅ 6.3s\n","WARNING ⚠️ \u001b[31m\u001b[1mrequirements:\u001b[0m \u001b[1mRestart runtime or rerun command for updates to take effect\u001b[0m\n","\n","\n","\u001b[34m\u001b[1mONNX:\u001b[0m starting export with onnx 1.21.0 opset 12...\n","\u001b[34m\u001b[1mONNX:\u001b[0m slimming with onnxslim 0.1.91...\n","\u001b[34m\u001b[1mONNX:\u001b[0m export success ✅ 7.9s, saved as '/content/runs/detect/pothole_v1/weights/best.onnx' (11.7 MB)\n","\n","Export complete (9.3s)\n","Results saved to \u001b[1m/content/runs/detect/pothole_v1/weights\u001b[0m\n","Predict: yolo predict task=detect model=/content/runs/detect/pothole_v1/weights/best.onnx imgsz=640 \n","Validate: yolo val task=detect model=/content/runs/detect/pothole_v1/weights/best.onnx imgsz=640 data=/content/pothole.yaml \n","Visualize: https://netron.app\n","Ultralytics 8.4.37 🚀 Python-3.12.13 torch-2.10.0+cu128 CPU (Intel Xeon CPU @ 2.00GHz)\n","Model summary (fused): 73 layers, 3,006,233 parameters, 0 gradients, 8.1 GFLOPs\n","\n","\u001b[34m\u001b[1mPyTorch:\u001b[0m starting from '/content/runs/detect/pothole_v1/weights/best.pt' with input shape (1, 3, 640, 640) BCHW and output shape(s) (1, 7, 8400) (5.9 MB)\n","\n","\u001b[34m\u001b[1mTorchScript:\u001b[0m starting export with torch 2.10.0+cu128...\n","\u001b[34m\u001b[1mTorchScript:\u001b[0m export success ✅ 1.9s, saved as '/content/runs/detect/pothole_v1/weights/best.torchscript' (11.9 MB)\n","\n","Export complete (2.3s)\n","Results saved to \u001b[1m/content/runs/detect/pothole_v1/weights\u001b[0m\n","Predict: yolo predict task=detect model=/content/runs/detect/pothole_v1/weights/best.torchscript imgsz=640 \n","Validate: yolo val task=detect model=/content/runs/detect/pothole_v1/weights/best.torchscript imgsz=640 data=/content/pothole.yaml \n","Visualize: https://netron.app\n","✅ ONNX models generated\n"]}]},{"cell_type": "code","source": ["# Cell 9 — Download the weights\n","import shutil\n","from google.colab import files\n","shutil.make_archive('/content/pothole_weights', 'zip', '/content/runs/detect/pothole_v1/weights')\n","files.download('/content/pothole_weights.zip')\n"],"metadata": {"colab": {"base_uri": "https://localhost:8080/",2 unmodified lines"id": "SEZ7OyABfs_3","outputId": "e237add9-7506-4af3-cae3-8827fb64c9fc"},"execution_count": null,"outputs": [{"output_type": "display_data","data": {"text/plain": ["<IPython.core.display.Javascript object>"],"application/javascript": ["\n"," async function download(id, filename, size) {\n"," if (!google.colab.kernel.accessAllowed) {\n"," return;\n"," }\n"," const div = document.createElement('div');\n"," const label = document.createElement('label');\n"," label.textContent = `Downloading \"${filename}\": `;\n"," div.appendChild(label);\n"," const progress = document.createElement('progress');\n"," progress.max = size;\n"," div.appendChild(progress);\n"," document.body.appendChild(div);\n","\n"," const buffers = [];\n"," let downloaded = 0;\n","\n"," const channel = await google.colab.kernel.comms.open(id);\n"," // Send a message to notify the kernel that we're ready.\n"," channel.send({})\n","\n"," for await (const message of channel.messages) {\n"," // Send a message to notify the kernel that we're ready.\n"," channel.send({})\n"," if (message.buffers) {\n"," for (const buffer of message.buffers) {\n"," buffers.push(buffer);\n"," downloaded += buffer.byteLength;\n"," progress.value = downloaded;\n"," }\n"," }\n"," }\n"," const blob = new Blob(buffers, {type: 'application/binary'});\n"," const a = document.createElement('a');\n"," a.href = window.URL.createObjectURL(blob);\n"," a.download = filename;\n"," div.appendChild(a);\n"," a.click();\n"," div.remove();\n"," }\n"," "]},"metadata": {}},{"output_type": "display_data","data": {"text/plain": ["<IPython.core.display.Javascript object>"],"application/javascript": ["download(\"download_2729bae4-56fd-42a8-8baf-585fe75b983c\", \"pothole_weights.zip\", 32567058)"]},"metadata": {}}]}]}123456789101112131415161718192021222324252627282930313233343536378 unmodified lines464748495051528 unmodified lines616263646566676869707172737475767778792 unmodified lines8283848586878889909192939495969798991001011021031041051061071082 unmodified lines1111121131141151161171181191201211221231241251261271281291301311321331341351361371381392 unmodified lines1421431441451461471481491501511521531541551561571581591601611621631641651661671681 unmodified line1701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112127 unmodified lines22022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225315 unmodified lines2692702712722732742752762772782792802812822834 unmodified lines2882892902912922932942952962972982993003013028 unmodified lines3113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413429 unmodified lines3523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014022 unmodified lines405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434{"cells": [{"cell_type": "markdown","metadata": {"id": "v_iQK6_S0_pc"},"source": ["# YOLOv8 Pothole & Road Damage Detector Training\n","\n","**Output:** `best.onnx` -> deployed to `frontend/public/models/best.onnx`\n","\n","This notebook trains a YOLOv8 nano model to detect road damage (potholes, cracks, manholes)\n","using a custom Roboflow dataset merged with the Kaggle RDD2022 dataset.\n","\n","---\n","### Dataset\n","- **Source 1:** Custom Roboflow Pothole Dataset (v3)\n","- **Source 2:** Kaggle RDD2022 (Road Damage Detection 2022)\n","- **Total Images:** ~2,000+\n","- **Classes:** `0: pothole`, `1: crack`, `2: manhole`\n","\n","### Pipeline\n","`Roboflow + Kaggle Data -> Merge -> YOLOv8n Train (50 epochs) -> ONNX Export`"]},{"cell_type": "markdown","metadata": {"id": "SAAYhbS5pEM1"},"source": ["## Pre-requisite - Anti-Disconnect Script\n","Keeps the Colab session alive during long vector embedding processes."]},{8 unmodified lines"id": "uwTMRE_8C740","outputId": "ecfb62d6-9b10-4bc0-caa0-971da9a80c3e"},"outputs": [],"source": ["import time\n","from IPython.display import Javascript\n",8 unmodified lines},{"cell_type": "markdown","metadata": {"id": "Pg1-Sr4T0_pk"},"source": ["## Step 1 - Install Dependencies\n","\n","Installs `ultralytics` for YOLOv8 training, `roboflow` for dataset download,\n","and `onnx` tools for the final model export."]},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/"2 unmodified lines"id": "I0GBSI74DVJI","outputId": "a71f5e00-bbe6-458c-c79d-5e9d75c8931f"},"outputs": [],"source": ["!pip install ultralytics roboflow -q\n","!pip install onnx onnxruntime -q"]},{"cell_type": "markdown","metadata": {"id": "Gyy-NB5t0_qK"},"source": ["## Step 2 - Check GPU\n","\n","Verifies that CUDA is available and the GPU is correctly mapped.\n","Essential for accelerating YOLO training."]},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/"2 unmodified lines"id": "yJoIU507DcKF","outputId": "e92f642d-1464-45e4-ec35-cd3c7eb402bf"},"outputs": [],"source": ["\n","import os\n","from ultralytics import YOLO\n","print(\"✅ Ultralytics ready, CUDA:\", os.popen(\"nvidia-smi --query-gpu=name --format=csv,noheader\").read().strip())"]},{"cell_type": "markdown","metadata": {"id": "Tfz0yuQJ0_qL"},"source": ["## Step 3 - Download Base Dataset (Roboflow)\n","\n","Downloads the initial custom dataset containing labeled potholes,\n","cracks, and manholes."]},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/",2 unmodified lines"id": "t7uQDAFzDeaJ","outputId": "e5e7f1b4-8a1d-4d91-b2a9-feddd6783794"},"outputs": [],"source": ["from google.colab import files\n","uploaded = files.upload()"]},{"cell_type": "markdown","metadata": {"id": "9-YN4Yie0_qM"},"source": ["## Step 4 - Download Kaggle RDD2022 Dataset\n","\n","Fetches the massive Road Damage Detection dataset from Kaggle to supplement\n","the Roboflow dataset and improve model generalization."]},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/"1 unmodified line"id": "MdUI5xwtK6fp","outputId": "945affb4-bba0-496f-c1f6-9429cad842eb"},"outputs": [],"source": ["# Cell 3 — Extract the main zipped dataset\n","import zipfile\n","\n","with zipfile.ZipFile('/content/archive.zip', 'r') as z:\n"," z.extractall('/content/pothole_data')\n","print(\"✅ archive.zip extracted successfully\")\n"]},{"cell_type": "markdown","metadata": {"id": "2cwRMkKa0_qN"},"source": ["## Step 5 - Standardize Kaggle Labels\n","\n","The Kaggle dataset uses 4 classes (`D00, D10, D20, D40`).\n","This step maps them to our custom 3 classes:\n","- `D00` (Longitudinal Crack) -> `1` (crack)\n","- `D10` (Transverse Crack) -> `1` (crack)\n","- `D20` (Alligator Crack) -> `1` (crack)\n","- `D40` (Pothole) -> `0` (pothole)"]},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"id": "RMlyOEcEK-Zz","outputId": "bd472e3d-d1be-4d07-daaa-db42568eb77c"},"outputs": [],"source": ["# Cell 4 — Setup master directory structure for merged datasets\n","import os, shutil\n",7 unmodified lines"for p in [merged_train_img, merged_train_lbl, merged_val_img, merged_val_lbl]:\n"," os.makedirs(p, exist_ok=True)\n","print(\"✅ Master directories created\")\n"]},{"cell_type": "markdown","metadata": {"id": "371UYSus0_qO"},"source": ["## Step 6 - Merge Datasets\n","\n","Iterates through both the Roboflow and Kaggle dataset directories,\n","checks for corresponding images and standardized label files, and\n","then copies them all into the master `merged/train/` directory.\n","\n","> Result: **2,009 training images** merged."]},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"id": "lJZFF47NLEFJ","outputId": "04ff65e2-a9c7-4ce6-d2dd-11d1139a6a8f"},"outputs": [],"source": ["# Cell 5 — Copy all images and labels into the merged folder (Bulletproof Search)\n","# List of directories containing datasets (Assuming they are available in /content/)\n",15 unmodified lines" shutil.copy(lbl, merged_train_lbl)\n","\n","print('✅ Merging complete. Total train images:', len(list(Path(merged_train_img).glob('*.jpg'))))\n"]},{"cell_type": "markdown","metadata": {"id": "IPleZZ6U0_qP"},"source": ["## Step 7 - Write `data.yaml`\n","\n","Creates the YOLO dataset configuration file defining:\n","- 3 detection classes: `['pothole', 'crack', 'manhole']`\n",4 unmodified lines},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"id": "f5Cmy0iuMZSC","outputId": "15593ba5-a0b6-46f9-a751-367262c4f65f"},"outputs": [],"source": ["# Cell 6 — Create data.yaml mapping to our 3 classes\n","data_yaml = \"\"\"\n",8 unmodified lines" f.write(data_yaml)\n","\n","print(\"✅ data.yaml written\")\n"]},{"cell_type": "markdown","metadata": {"id": "DfzFlcQy0_qP"},"source": ["## Step 8 - Train YOLOv8n (50 Epochs) & Export ONNX\n","\n","Trains YOLOv8 nano on the merged dataset.\n","**It will then export to ONNX and download the final model.**"]},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"collapsed": true,"id": "kXWxRFmaMcyE","outputId": "66b2cdd5-193d-4946-cbaf-b39dc5fa24ae"},"outputs": [],"source": ["# Cell 7 — Train (45-60 min on T4 GPU)\n","model = YOLO('yolov8n.pt')\n",9 unmodified lines" save=True,\n",")\n","print(\"✅ YOLO Training Finished\")\n"]},{"cell_type": "markdown","metadata": {"id": "vHVZjW4w4Zd6"},"source": ["### Step 8.1 - Export to ONNX & TorchScript\n","Exports the trained YOLOv8 model to ONNX and TorchScript formats for deployment."]},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/"},"collapsed": true,"id": "53VaY29vfU3S","outputId": "43484095-f9d9-43bd-efbf-cef0b272448a"},"outputs": [],"source": ["# Cell 8 — Export ONNX\n","best_model = YOLO('/content/runs/detect/pothole_v1/weights/best.pt')\n","best_model.export(format='onnx', imgsz=640, opset=12, simplify=True)\n","best_model.export(format='torchscript')\n","print(\"✅ ONNX models generated\")\n"]},{"cell_type": "markdown","metadata": {"id": "G8eMKCO24oWA"},"source": ["### Step 8.2 - Download the Final Model\n","Zips the training results and downloads the final weights and ONNX models to your local machine."]},{"cell_type": "code","execution_count": null,"metadata": {"colab": {"base_uri": "https://localhost:8080/",2 unmodified lines"id": "SEZ7OyABfs_3","outputId": "e237add9-7506-4af3-cae3-8827fb64c9fc"},"outputs": [],"source": ["# Cell 9 — Download the weights\n","import shutil\n","from google.colab import files\n","shutil.make_archive('/content/pothole_weights', 'zip', '/content/runs/detect/pothole_v1/weights')\n","files.download('/content/pothole_weights.zip')\n"]}],"metadata": {"accelerator": "GPU","colab": {"gpuType": "T4","provenance": []},"kernelspec": {"display_name": "Python 3","name": "python3"},"language_info": {"name": "python"}},"nbformat": 4,"nbformat_minor": 0}
1# backend/data scripts — pure Python data transforms (no DB required)1# scripts/data — pure Python data scripts (no DB required)8 unmodified lines910111213141553 unmodified lines6970717273747533 unmodified lines1091101111121131141158 unmodified linesfrom typing import IterableROOT_DIR = Path(__file__).resolve().parents[1]DEFAULT_ENDPOINTS = ('https://overpass-api.de/api/interpreter','https://overpass.kumi.systems/api/interpreter',53 unmodified lines)def fetch_elements(query: str, *, endpoint: str | None, timeout: int) -> list[dict]:payload = urllib.parse.urlencode({'data': query}).encode('utf-8')endpoints = [endpoint] if endpoint else list(DEFAULT_ENDPOINTS)last_error: Exception | None = None33 unmodified linesreturn ', '.join(part for part in parts if part)def normalize_row(element: dict, *, default_type: str, fallback_name: str) -> dict | None:lat, lon = extract_point(element)if lat is None or lon is None:return None8 unmodified lines9101112131453 unmodified lines6869707172737433 unmodified lines1081091101111121131148 unmodified linesfrom typing import IterableDEFAULT_ENDPOINTS = ('https://overpass-api.de/api/interpreter','https://overpass.kumi.systems/api/interpreter',53 unmodified lines)def fetch_elements(query: str, *, endpoint: str | None, timeout: int, **kwargs) -> list[dict]:payload = urllib.parse.urlencode({'data': query}).encode('utf-8')endpoints = [endpoint] if endpoint else list(DEFAULT_ENDPOINTS)last_error: Exception | None = None33 unmodified linesreturn ', '.join(part for part in parts if part)def normalize_row(element: dict, *, default_type: str, fallback_name: str, **kwargs) -> dict | None:lat, lon = extract_point(element)if lat is None or lon is None:return None
7 unmodified lines8910111213147 unmodified linesimport shutilimport structimport sysimport tempfileimport zipfilefrom pathlib import Path7 unmodified lines89101112137 unmodified linesimport shutilimport structimport sysimport zipfilefrom pathlib import Path
3 unmodified lines456789103 unmodified lineslogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')LOGGER = logging.getLogger(__name__)from _overpass_utils import ROOT_DIR, build_arg_parser, build_india_query, fetch_elements, normalize_row, write_rowsDEFAULT_OUTPUT = ROOT_DIR / 'chatbot_service' / 'data' / 'emergency' / 'ambulance_stations.csv'3 unmodified lines456789101112133 unmodified lineslogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')LOGGER = logging.getLogger(__name__)from pathlib import PathROOT_DIR = Path(__file__).resolve().parents[2]from _overpass_utils import build_arg_parser, build_india_query, fetch_elements, normalize_row, write_rowsDEFAULT_OUTPUT = ROOT_DIR / 'chatbot_service' / 'data' / 'emergency' / 'ambulance_stations.csv'
3 unmodified lines456789103 unmodified lineslogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')LOGGER = logging.getLogger(__name__)from _overpass_utils import ROOT_DIR, build_arg_parser, build_india_query, fetch_elements, normalize_row, write_rowsDEFAULT_OUTPUT = ROOT_DIR / 'chatbot_service' / 'data' / 'hospitals' / 'blood_bank_directory.csv'3 unmodified lines456789101112133 unmodified lineslogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')LOGGER = logging.getLogger(__name__)from pathlib import PathROOT_DIR = Path(__file__).resolve().parents[2]from _overpass_utils import build_arg_parser, build_india_query, fetch_elements, normalize_row, write_rowsDEFAULT_OUTPUT = ROOT_DIR / 'chatbot_service' / 'data' / 'hospitals' / 'blood_bank_directory.csv'
3 unmodified lines456789103 unmodified lineslogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')LOGGER = logging.getLogger(__name__)from _overpass_utils import ROOT_DIR, build_arg_parser, build_india_query, fetch_elements, normalize_row, write_rowsDEFAULT_OUTPUT = ROOT_DIR / 'chatbot_service' / 'data' / 'emergency' / 'fire_stations.csv'3 unmodified lines456789101112133 unmodified lineslogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')LOGGER = logging.getLogger(__name__)from pathlib import PathROOT_DIR = Path(__file__).resolve().parents[2]from _overpass_utils import build_arg_parser, build_india_query, fetch_elements, normalize_row, write_rowsDEFAULT_OUTPUT = ROOT_DIR / 'chatbot_service' / 'data' / 'emergency' / 'fire_stations.csv'
3 unmodified lines456789103 unmodified lineslogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')LOGGER = logging.getLogger(__name__)from _overpass_utils import ROOT_DIR, build_arg_parser, build_india_query, fetch_elements, normalize_row, write_rowsDEFAULT_OUTPUT = ROOT_DIR / 'chatbot_service' / 'data' / 'hospitals' / 'hospital_directory.csv'3 unmodified lines456789101112133 unmodified lineslogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')LOGGER = logging.getLogger(__name__)from pathlib import PathROOT_DIR = Path(__file__).resolve().parents[2]from _overpass_utils import build_arg_parser, build_india_query, fetch_elements, normalize_row, write_rowsDEFAULT_OUTPUT = ROOT_DIR / 'chatbot_service' / 'data' / 'hospitals' / 'hospital_directory.csv'
3 unmodified lines456789103 unmodified lineslogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')LOGGER = logging.getLogger(__name__)from _overpass_utils import ROOT_DIR, build_arg_parser, build_india_query, fetch_elements, normalize_row, write_rowsDEFAULT_OUTPUT = ROOT_DIR / 'chatbot_service' / 'data' / 'emergency' / 'police_stations.csv'3 unmodified lines456789101112133 unmodified lineslogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')LOGGER = logging.getLogger(__name__)from pathlib import PathROOT_DIR = Path(__file__).resolve().parents[2]from _overpass_utils import build_arg_parser, build_india_query, fetch_elements, normalize_row, write_rowsDEFAULT_OUTPUT = ROOT_DIR / 'chatbot_service' / 'data' / 'emergency' / 'police_stations.csv'
README.md+18-8
notebooks/Accident_EDA_&_Hotspot_Generator_chatbot_service_data_accidents_3.ipynb+66-445
notebooks/ChromaDB_RAG_Vectorstore_Build_chatbot_service_data_chroma_db_2.ipynb
notebooks/Risk_Model_ONNX_Training_frontend_public_models_5.ipynb+93-186
notebooks/Roads_Data_Processing_backend_data_4.ipynb+25-306
notebooks/YOLOv8_Pothole_Detector_Training_frontend_public_models_1.ipynb+191-877
scripts/backend/data/__init__.pyAdded+1
scripts/scripts/data/__init__.pyAdded+1
scripts/scripts/data/_overpass_utils.py+2-3
scripts/scripts/data/bootstrap_local_data.py-1
scripts/scripts/data/fetch_ambulance.py+4-1
scripts/scripts/data/fetch_blood_banks.py+4-1
scripts/scripts/data/fetch_fire.py+4-1
scripts/scripts/data/fetch_hospitals.py+4-1
scripts/scripts/data/fetch_police.py+4-1