Week5 Assignment (adding missing files)

This commit is contained in:
The Top Dev
2025-10-24 05:36:37 +03:00
parent b2071b0045
commit 341121c68e
33 changed files with 1430 additions and 0 deletions

View File

@@ -0,0 +1,407 @@
#!/usr/bin/env python3
"""
LangChain Integration for NTSA Knowledge Base
Provides advanced document processing and conversational AI capabilities
"""
import os
import json
from pathlib import Path
from typing import List, Dict, Any, Optional
from datetime import datetime
# Optional imports with fallbacks
try:
import plotly.graph_objects as go
import plotly.express as px
PLOTLY_AVAILABLE = True
except ImportError:
PLOTLY_AVAILABLE = False
try:
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
SKLEARN_AVAILABLE = True
except ImportError:
SKLEARN_AVAILABLE = False
try:
import numpy as np
NUMPY_AVAILABLE = True
except ImportError:
NUMPY_AVAILABLE = False
# LangChain imports
try:
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.vectorstores import Chroma
from langchain.chains import ConversationalRetrievalChain
from langchain.memory import ConversationBufferMemory
from langchain.llms import OpenAI
from langchain_openai import ChatOpenAI
LANGCHAIN_AVAILABLE = True
except ImportError:
LANGCHAIN_AVAILABLE = False
class LangChainKnowledgeBase:
"""Advanced knowledge base using LangChain for document processing and conversational AI"""
def __init__(self, knowledge_base_dir: str = "ntsa_comprehensive_knowledge_base",
vector_db_dir: str = "langchain_chroma_db"):
self.knowledge_base_dir = Path(knowledge_base_dir)
self.vector_db_dir = Path(vector_db_dir)
self.documents = []
self.vectorstore = None
self.qa_chain = None
self.memory = None
# Initialize components
self._setup_directories()
self._load_documents()
def _setup_directories(self):
"""Setup required directories"""
self.vector_db_dir.mkdir(exist_ok=True)
print(f"✅ Vector database directory: {self.vector_db_dir}")
def _load_documents(self):
"""Load documents from the knowledge base"""
print("📚 Loading documents from knowledge base...")
if not self.knowledge_base_dir.exists():
print(f"❌ Knowledge base directory not found: {self.knowledge_base_dir}")
return
documents = []
for md_file in self.knowledge_base_dir.rglob("*.md"):
try:
with open(md_file, 'r', encoding='utf-8') as f:
content = f.read()
documents.append({
'file': str(md_file),
'content': content,
'title': md_file.stem,
'category': md_file.parent.name
})
except Exception as e:
print(f"⚠️ Error reading {md_file}: {e}")
self.documents = documents
print(f"✅ Loaded {len(documents)} documents")
def create_vector_store(self, chunk_size: int = 1000, chunk_overlap: int = 200):
"""Create vector store from documents"""
if not LANGCHAIN_AVAILABLE:
print("❌ LangChain not available. Cannot create vector store.")
return False
if not self.documents:
print("❌ No documents loaded. Cannot create vector store.")
return False
try:
print("🔧 Creating vector store...")
# Split documents into chunks
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
length_function=len,
)
texts = []
metadatas = []
for doc in self.documents:
chunks = text_splitter.split_text(doc['content'])
for chunk in chunks:
texts.append(chunk)
metadatas.append({
'source': doc['file'],
'title': doc['title'],
'category': doc['category']
})
print(f"📄 Created {len(texts)} text chunks")
# Create embeddings
try:
embeddings = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)
print("✅ HuggingFace embeddings loaded")
except Exception as e:
print(f"⚠️ HuggingFace embeddings failed: {e}")
print("🔄 Using OpenAI embeddings as fallback...")
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
# Create vector store
self.vectorstore = Chroma.from_texts(
texts=texts,
embedding=embeddings,
metadatas=metadatas,
persist_directory=str(self.vector_db_dir)
)
# Persist the vector store
self.vectorstore.persist()
print(f"✅ Vector store created and persisted to {self.vector_db_dir}")
return True
except Exception as e:
print(f"❌ Error creating vector store: {e}")
return False
def load_existing_vector_store(self):
"""Load existing vector store"""
if not LANGCHAIN_AVAILABLE:
print("❌ LangChain not available. Cannot load vector store.")
return False
try:
print("📂 Loading existing vector store...")
# Create embeddings
try:
embeddings = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)
except Exception as e:
print(f"⚠️ HuggingFace embeddings failed: {e}")
print("🔄 Using OpenAI embeddings as fallback...")
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
# Load vector store
self.vectorstore = Chroma(
persist_directory=str(self.vector_db_dir),
embedding_function=embeddings
)
print("✅ Vector store loaded successfully")
return True
except Exception as e:
print(f"❌ Error loading vector store: {e}")
return False
def create_qa_chain(self, model_name: str = "gpt-3.5-turbo"):
"""Create question-answering chain"""
if not LANGCHAIN_AVAILABLE:
print("❌ LangChain not available. Cannot create QA chain.")
return False
if not self.vectorstore:
print("❌ Vector store not available. Cannot create QA chain.")
return False
try:
print(f"🔧 Creating QA chain with {model_name}...")
# Initialize LLM
llm = ChatOpenAI(
model_name=model_name,
temperature=0.7,
max_tokens=1000
)
# Create memory
self.memory = ConversationBufferMemory(
memory_key="chat_history",
return_messages=True
)
# Create QA chain
self.qa_chain = ConversationalRetrievalChain.from_llm(
llm=llm,
retriever=self.vectorstore.as_retriever(search_kwargs={"k": 3}),
memory=self.memory,
output_key="answer"
)
print("✅ QA chain created successfully")
return True
except Exception as e:
print(f"❌ Error creating QA chain: {e}")
return False
def ask_question(self, question: str) -> str:
"""Ask a question to the knowledge base"""
if not self.qa_chain:
return "❌ QA chain not available. Please create it first."
try:
result = self.qa_chain({"question": question})
return result["answer"]
except Exception as e:
return f"❌ Error answering question: {e}"
def search_documents(self, query: str, k: int = 5) -> List[Dict]:
"""Search documents using vector similarity"""
if not self.vectorstore:
return []
try:
results = self.vectorstore.similarity_search_with_score(query, k=k)
return [
{
"content": doc.page_content,
"metadata": doc.metadata,
"score": score
}
for doc, score in results
]
except Exception as e:
print(f"❌ Error searching documents: {e}")
return []
def visualize_embeddings(self, n_samples: int = 50, method: str = "tsne"):
"""Visualize document embeddings"""
if not PLOTLY_AVAILABLE:
print("❌ Plotly not available. Cannot create visualization.")
return
if not SKLEARN_AVAILABLE:
print("❌ Scikit-learn not available. Cannot create visualization.")
return
if not NUMPY_AVAILABLE:
print("❌ NumPy not available. Cannot create visualization.")
return
if not self.vectorstore:
print("❌ Vector store not available. Cannot create visualization.")
return
try:
print("📊 Visualizing embeddings...")
# Get all documents and embeddings
all_docs = self.vectorstore.get()
if not all_docs or not all_docs.get('embeddings'):
print("❌ No embeddings found in vector store.")
return
n_samples = min(n_samples, len(all_docs['ids']))
embeddings_array = np.array(all_docs['embeddings'][:n_samples])
texts = all_docs['documents'][:n_samples]
if method == "tsne":
# t-SNE dimensionality reduction
tsne = TSNE(n_components=2, random_state=42, perplexity=min(30, n_samples-1))
embeddings_2d = tsne.fit_transform(embeddings_array)
else:
# PCA dimensionality reduction
pca = PCA(n_components=2, random_state=42)
embeddings_2d = pca.fit_transform(embeddings_array)
# Create visualization
fig = go.Figure()
# Add scatter plot
fig.add_trace(go.Scatter(
x=embeddings_2d[:, 0],
y=embeddings_2d[:, 1],
mode='markers',
marker=dict(
size=8,
color=range(n_samples),
colorscale='Viridis',
showscale=True
),
text=[text[:100] + "..." if len(text) > 100 else text for text in texts],
hovertemplate='<b>%{text}</b><br>X: %{x}<br>Y: %{y}<extra></extra>'
))
fig.update_layout(
title=f"Document Embeddings Visualization ({method.upper()})",
xaxis_title="Dimension 1",
yaxis_title="Dimension 2",
showlegend=False
)
# Save and show
fig.write_html("embeddings_visualization.html")
fig.show()
print("✅ Embeddings visualization created and saved as 'embeddings_visualization.html'")
except Exception as e:
print(f"❌ Error creating visualization: {e}")
print("💡 This might be due to numpy compatibility issues.")
print("💡 Try using OpenAI embeddings instead of HuggingFace embeddings.")
def get_statistics(self) -> Dict[str, Any]:
"""Get knowledge base statistics"""
stats = {
"total_documents": len(self.documents),
"vector_store_available": self.vectorstore is not None,
"qa_chain_available": self.qa_chain is not None,
"categories": {}
}
# Count documents by category
for doc in self.documents:
category = doc.get('category', 'unknown')
if category not in stats['categories']:
stats['categories'][category] = 0
stats['categories'][category] += 1
return stats
def reset_memory(self):
"""Reset conversation memory"""
if self.memory:
self.memory.clear()
print("✅ Conversation memory cleared")
def main():
"""Main function to demonstrate the knowledge base"""
print("🚀 NTSA LangChain Knowledge Base")
print("=" * 50)
# Initialize knowledge base
kb = LangChainKnowledgeBase()
# Create vector store
if kb.create_vector_store():
print("✅ Vector store created successfully")
# Create QA chain
if kb.create_qa_chain():
print("✅ QA chain created successfully")
# Test the system
test_questions = [
"What is NTSA?",
"How do I apply for a driving license?",
"What services does NTSA provide?"
]
print("\n🤖 Testing QA system:")
for question in test_questions:
print(f"\nQ: {question}")
answer = kb.ask_question(question)
print(f"A: {answer[:200]}{'...' if len(answer) > 200 else ''}")
# Show statistics
stats = kb.get_statistics()
print(f"\n📊 Knowledge Base Statistics:")
print(f"Total documents: {stats['total_documents']}")
print(f"Categories: {stats['categories']}")
else:
print("❌ Failed to create QA chain")
else:
print("❌ Failed to create vector store")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,90 @@
# NTSA Knowledge Base Index
**Generated:** 2025-10-24 05:34:52
**Total Pages:** 15
## Services
- [NTSA | Keep our roads safe](ntsa_comprehensive_knowledge_base\services\ntsa_NTSA__Keep_our_roads_safe_f13d765c.md)
- URL: https://ntsa.go.ke
- Content: 6068 chars
- Depth: 0
- [NTSA | NTSA Services](ntsa_comprehensive_knowledge_base\services\ntsa_NTSA__NTSA_Services_7a9ee5d0.md)
- URL: https://ntsa.go.ke/services
- Content: 1994 chars
- Depth: 0
- [NTSA | Contact Us](ntsa_comprehensive_knowledge_base\services\ntsa_NTSA__Contact_Us_7bdb748a.md)
- URL: https://ntsa.go.ke/contact
- Content: 1587 chars
- Depth: 0
- [NTSA | Vehicles Services](ntsa_comprehensive_knowledge_base\services\ntsa_NTSA__Vehicles_Services_57ba53a1.md)
- URL: https://ntsa.go.ke/services/vehicles-services
- Content: 814 chars
- Depth: 1
- [NTSA | Frequently Asked Questions | NTSA Kenya](ntsa_comprehensive_knowledge_base\services\ntsa_NTSA__Frequently_Asked_Questions__NTSA_Kenya_291931bf.md)
- URL: https://ntsa.go.ke/faqs
- Content: 819 chars
- Depth: 1
- [NTSA | Privacy Policy | NTSA](ntsa_comprehensive_knowledge_base\services\ntsa_NTSA__Privacy_Policy__NTSA_68960874.md)
- URL: https://ntsa.go.ke/privacy-policy
- Content: 1130 chars
- Depth: 1
- [NTSA | Keep our roads safe](ntsa_comprehensive_knowledge_base\services\ntsa_NTSA__Keep_our_roads_safe_0a8e8522.md)
- URL: https://ntsa.go.ke/
- Content: 6068 chars
- Depth: 1
## About
- [NTSA | NTSA | About Us](ntsa_comprehensive_knowledge_base\about\ntsa_NTSA__NTSA__About_Us_05bb6415.md)
- URL: https://ntsa.go.ke/about
- Content: 1422 chars
- Depth: 0
- [NTSA | About Us - Who We Are](ntsa_comprehensive_knowledge_base\about\ntsa_NTSA__About_Us_-_Who_We_Are_47583408.md)
- URL: https://ntsa.go.ke/about/who-we-are
- Content: 2204 chars
- Depth: 1
## News
- [NTSA | Media Center - News & Updates](ntsa_comprehensive_knowledge_base\news\ntsa_NTSA__Media_Center_-_News__Updates_e765915c.md)
- URL: https://ntsa.go.ke/news
- Content: 2481 chars
- Depth: 0
- [NTSA | New Digital Licensing System Goes Live | NTSA Kenya](ntsa_comprehensive_knowledge_base\news\ntsa_NTSA__New_Digital_Licensing_System_Goes_Live__NTSA_50d5938e.md)
- URL: https://ntsa.go.ke/news/new-digital-licensing-system-goes-live
- Content: 1003 chars
- Depth: 1
- [NTSA | NTSA Launches New Road Safety Campaign | NTSA Kenya](ntsa_comprehensive_knowledge_base\news\ntsa_NTSA__NTSA_Launches_New_Road_Safety_Campaign__NTSA_63481444.md)
- URL: https://ntsa.go.ke/news/ntsa-launches-new-road-safety-campaign
- Content: 1113 chars
- Depth: 1
- [NTSA | 8th UN Global Road Safety Week Concludes with Nationwide Activities | NTSA Kenya](ntsa_comprehensive_knowledge_base\news\ntsa_NTSA__8th_UN_Global_Road_Safety_Week_Concludes_wit_9636f22e.md)
- URL: https://ntsa.go.ke/news/8th-un-global-road-safety-week-concludes-with-nationwide-activities
- Content: 1494 chars
- Depth: 1
## Tenders
- [NTSA | Tenders](ntsa_comprehensive_knowledge_base\tenders\ntsa_NTSA__Tenders_73ac6e93.md)
- URL: https://ntsa.go.ke/tenders
- Content: 354 chars
- Depth: 0
## Careers
- [Career Opportunities | NTSA](ntsa_comprehensive_knowledge_base\careers\ntsa_Career_Opportunities__NTSA_3e462d97.md)
- URL: https://ntsa.go.ke/careers
- Content: 477 chars
- Depth: 1

View File

@@ -0,0 +1,9 @@
# NTSA | About Us - Who We Are
**URL:** https://ntsa.go.ke/about/who-we-are
**Scraped:** 2025-10-24T05:34:27.946216
**Content Length:** 2204 characters
---
Who We AreThe National Transport and Safety Authority (NTSA) is Kenya's premier agency responsible for transport safety regulation and enforcement, dedicated to creating safer roads for all Kenyans.Established through an Act of Parliament; NTSA Act No. 33 of 2012, we are dedicated to harmonizing the operations of the key road transport departments and helping in effectively managing the road transport sub-sector and minimizing traffic accidents.Our Vision & MissionOur VisionTo establish a Safe, Reliable, and Efficient Road Transport System in Kenya.Our MissionThrough the planning, management, and regulation of the road transportation system, to continuously increase road safety for all users.Our Core ValuesCommitment to SafetyCustomer FocusProfessionalismTeamworkResource MobilisationIntegrity and AccountabilityOur Role1Implementing policies relating to road transport and safety2Registering and licensing motor vehicles3Conducting motor vehicle inspections and certification4Regulating public service vehicles5Advising the government on national road transport and safety matters6Developing and implementing road safety strategiesOur MandateThe National Transport and Safety Authority (NTSA) was established through an Act of Parliament; Act Number 33 of 2012. The Authority is responsible for:Implementation of policies relating to road transport and safetyRegistration and licensing of motor vehiclesConducting motor vehicle inspections and certificationRegulating public service vehiclesAdvising the government on national road transport and safety mattersDevelopment and implementation of road safety strategiesCollection and analysis of road safety dataOur Commitment"Safety on our roads is not just our responsibility, it's our commitment to every Kenyan family."We are committed to making Kenyan roads safe for all users through effective regulation, enforcement, and public education. Our team of dedicated professionals works tirelessly to ensure compliance with transport regulations and promote road safety awareness.Learn MoreJoin Us in Making Kenyan Roads SaferTogether, we can reduce road accidents and create a safer transport environment for all Kenyans.Contact UsOur Services

View File

@@ -0,0 +1,9 @@
# NTSA | NTSA | About Us
**URL:** https://ntsa.go.ke/about
**Scraped:** 2025-10-24T05:33:46.103216
**Content Length:** 1422 characters
---
About NTSAEnsuring Safety and Order on Kenyan RoadsOur MissionTo provide effective regulation and coordination of the road transport sector and ensure safety on our roads through implementation of innovative interventions and strict enforcement of traffic rules.Our VisionTo be the world's leading surface transport authority.Our Core ValuesIntegrityWe uphold honesty, transparency, and ethical conduct in all our operations.ProfessionalismWe maintain high standards of service delivery and expertise in our work.InnovationWe embrace creative solutions and modern technology to improve our services.Our MandateThe National Transport and Safety Authority (NTSA) was established through an Act of Parliament; Act Number 33 of 2012. The Authority is responsible for:Implementation of policies relating to road transport and safetyRegistration and licensing of motor vehiclesConducting motor vehicle inspections and certificationRegulating public service vehiclesAdvising the government on national road transport and safety mattersDevelopment and implementation of road safety strategiesCollection and analysis of road safety dataStrategic Objectives•Reduce road traffic crashes and fatalities•Enhance efficiency in transport services•Develop and implement integrated transport and safety systems•Strengthen institutional capacity•Enhance road user compliance with traffic laws•Promote stakeholder engagement and partnerships

View File

@@ -0,0 +1,9 @@
# Career Opportunities | NTSA
**URL:** https://ntsa.go.ke/careers
**Scraped:** 2025-10-24T05:34:32.578853
**Content Length:** 477 characters
---
Career OpportunitiesJoin our team and make a difference in transport safety and managementNo opportunities availableCheck back later for new career openings.Why Join NTSA?Make an ImpactBe part of a team that's improving road safety and transforming transportation in Kenya.Professional GrowthOpportunities for career advancement and continuous learning in a dynamic environment.Competitive BenefitsEnjoy competitive compensation and benefits designed to support your wellbeing.

View File

@@ -0,0 +1,132 @@
{
"scraping_info": {
"base_url": "https://ntsa.go.ke",
"total_pages_scraped": 15,
"failed_pages": 0,
"scraping_timestamp": "2025-10-24T05:34:52.991790",
"output_directory": "ntsa_comprehensive_knowledge_base"
},
"scraped_pages": [
{
"url": "https://ntsa.go.ke",
"title": "NTSA | Keep our roads safe",
"file_path": "ntsa_comprehensive_knowledge_base\\services\\ntsa_NTSA__Keep_our_roads_safe_f13d765c.md",
"category": "services",
"content_length": 6068,
"depth": 0
},
{
"url": "https://ntsa.go.ke/about",
"title": "NTSA | NTSA | About Us",
"file_path": "ntsa_comprehensive_knowledge_base\\about\\ntsa_NTSA__NTSA__About_Us_05bb6415.md",
"category": "about",
"content_length": 1422,
"depth": 0
},
{
"url": "https://ntsa.go.ke/services",
"title": "NTSA | NTSA Services",
"file_path": "ntsa_comprehensive_knowledge_base\\services\\ntsa_NTSA__NTSA_Services_7a9ee5d0.md",
"category": "services",
"content_length": 1994,
"depth": 0
},
{
"url": "https://ntsa.go.ke/contact",
"title": "NTSA | Contact Us",
"file_path": "ntsa_comprehensive_knowledge_base\\services\\ntsa_NTSA__Contact_Us_7bdb748a.md",
"category": "services",
"content_length": 1587,
"depth": 0
},
{
"url": "https://ntsa.go.ke/news",
"title": "NTSA | Media Center - News & Updates",
"file_path": "ntsa_comprehensive_knowledge_base\\news\\ntsa_NTSA__Media_Center_-_News__Updates_e765915c.md",
"category": "news",
"content_length": 2481,
"depth": 0
},
{
"url": "https://ntsa.go.ke/tenders",
"title": "NTSA | Tenders",
"file_path": "ntsa_comprehensive_knowledge_base\\tenders\\ntsa_NTSA__Tenders_73ac6e93.md",
"category": "tenders",
"content_length": 354,
"depth": 0
},
{
"url": "https://ntsa.go.ke/news/new-digital-licensing-system-goes-live",
"title": "NTSA | New Digital Licensing System Goes Live | NTSA Kenya",
"file_path": "ntsa_comprehensive_knowledge_base\\news\\ntsa_NTSA__New_Digital_Licensing_System_Goes_Live__NTSA_50d5938e.md",
"category": "news",
"content_length": 1003,
"depth": 1
},
{
"url": "https://ntsa.go.ke/news/ntsa-launches-new-road-safety-campaign",
"title": "NTSA | NTSA Launches New Road Safety Campaign | NTSA Kenya",
"file_path": "ntsa_comprehensive_knowledge_base\\news\\ntsa_NTSA__NTSA_Launches_New_Road_Safety_Campaign__NTSA_63481444.md",
"category": "news",
"content_length": 1113,
"depth": 1
},
{
"url": "https://ntsa.go.ke/news/8th-un-global-road-safety-week-concludes-with-nationwide-activities",
"title": "NTSA | 8th UN Global Road Safety Week Concludes with Nationwide Activities | NTSA Kenya",
"file_path": "ntsa_comprehensive_knowledge_base\\news\\ntsa_NTSA__8th_UN_Global_Road_Safety_Week_Concludes_wit_9636f22e.md",
"category": "news",
"content_length": 1494,
"depth": 1
},
{
"url": "https://ntsa.go.ke/about/who-we-are",
"title": "NTSA | About Us - Who We Are",
"file_path": "ntsa_comprehensive_knowledge_base\\about\\ntsa_NTSA__About_Us_-_Who_We_Are_47583408.md",
"category": "about",
"content_length": 2204,
"depth": 1
},
{
"url": "https://ntsa.go.ke/careers",
"title": "Career Opportunities | NTSA",
"file_path": "ntsa_comprehensive_knowledge_base\\careers\\ntsa_Career_Opportunities__NTSA_3e462d97.md",
"category": "careers",
"content_length": 477,
"depth": 1
},
{
"url": "https://ntsa.go.ke/services/vehicles-services",
"title": "NTSA | Vehicles Services",
"file_path": "ntsa_comprehensive_knowledge_base\\services\\ntsa_NTSA__Vehicles_Services_57ba53a1.md",
"category": "services",
"content_length": 814,
"depth": 1
},
{
"url": "https://ntsa.go.ke/faqs",
"title": "NTSA | Frequently Asked Questions | NTSA Kenya",
"file_path": "ntsa_comprehensive_knowledge_base\\services\\ntsa_NTSA__Frequently_Asked_Questions__NTSA_Kenya_291931bf.md",
"category": "services",
"content_length": 819,
"depth": 1
},
{
"url": "https://ntsa.go.ke/privacy-policy",
"title": "NTSA | Privacy Policy | NTSA",
"file_path": "ntsa_comprehensive_knowledge_base\\services\\ntsa_NTSA__Privacy_Policy__NTSA_68960874.md",
"category": "services",
"content_length": 1130,
"depth": 1
},
{
"url": "https://ntsa.go.ke/",
"title": "NTSA | Keep our roads safe",
"file_path": "ntsa_comprehensive_knowledge_base\\services\\ntsa_NTSA__Keep_our_roads_safe_0a8e8522.md",
"category": "services",
"content_length": 6068,
"depth": 1
}
],
"failed_urls": []
}

View File

@@ -0,0 +1,9 @@
# NTSA | 8th UN Global Road Safety Week Concludes with Nationwide Activities | NTSA Kenya
**URL:** https://ntsa.go.ke/news/8th-un-global-road-safety-week-concludes-with-nationwide-activities
**Scraped:** 2025-10-24T05:34:23.386582
**Content Length:** 1494 characters
---
Home/Media Center/News & Updates/8th UN Global Road Safety Week Concludes with Nationwide Activities Back to NewsMay 15, 20258th UN Global Road Safety Week Concludes with Nationwide ActivitiesNTSA wraps up a successful week of road safety awareness, engaging partners and communities across Kenya to promote the protection of vulnerable road users. Share:The 8th UN Global Road Safety Week concluded on a high note after a week of impactful and colorful activities held across the country. Led by the National Transport and Safety Authority (NTSA), the campaign saw active participation from Board Directors, Management, and officials who visited various regions to promote road safety awareness.Throughout the week, NTSA partnered with road safety actors, government agencies, and community stakeholders to sensitize the public—particularly vulnerable road users such as pedestrians and cyclists. The collaborative efforts aimed to reinforce the importance of safe mobility and reduce road-related injuries and fatalities.NTSA thanks all partners and participants for their commitment to making Kenyan roads safer for everyone. Related ArticlesKenya Recognized for Technological Advancement and Public Service Excellence at APSCA AwardsOct 13, 2025LIST OF APPROVED MOTOR VEHICLE BODY BUILDERS, CONFORMITY ASSESSORS AND SPEED LIMITERS SUPPLIERS IN KENYASep 01, 2025Operation Watoto Wafike Salama Free Motor Vehicle Inspection ClinicsAug 20, 2025Quick LinksAbout NTSAOur ServicesContact UsFAQs

View File

@@ -0,0 +1,9 @@
# NTSA | Media Center - News & Updates
**URL:** https://ntsa.go.ke/news
**Scraped:** 2025-10-24T05:34:04.407247
**Content Length:** 2481 characters
---
News & UpdatesStay informed with the latest news, announcements, and updates from NTSA Home/Media Center/News & UpdatesOct 13, 2025Kenya Recognized for Technological Advancement and Public Service Excellence at APSCA AwardsKenyas innovation in public service has earned continental acclaim at the APSCA Awards, with NTSA recognized for leading the nations digital transformation journey toward smarter, paperless governance.Read ArticleSep 01, 2025LIST OF APPROVED MOTOR VEHICLE BODY BUILDERS, CONFORMITY ASSESSORS AND SPEED LIMITERS SUPPLIERS IN KENYALIST OF APPROVED MOTOR VEHICLE BODY BUILDERS, CONFORMITY ASSESSORS AND SPEED LIMITERS SUPPLIERS IN KENYARead ArticleAug 20, 2025Operation Watoto Wafike Salama Free Motor Vehicle Inspection ClinicsNTSA is offering free motor vehicle inspection clinics for all school transport vehicles across its centres. The initiative aims to enhance the safety of children as schools reopen.Read ArticleAug 15, 2025IMPORTANT PUBLIC NOTICE: ROAD SAFETY AS SCHOOLS REOPENSafe, reliable school transport is mandatory as the new school term begins.Read ArticleJul 29, 2025IMPORTANT PUBLIC NOTICE FOR MOTOR VEHICLE / MOTORCYCLE OWNERSThe National Transport and Safety Authority has operationalized the Duty Update Module/Vehicle Records Update Tool to support all motor vehicle and motorcycle owners.Read ArticleJul 07, 2025PUBLIC NOTICE: EXTENSION OF COMMENTS AND PROPOSALS SUBMISSION DATE ON DRAFT TRAFFIC AND TRANSPORT REGULATIONS, 2025The deadline for submission of comments on the proposed 2025 Traffic & Transport Regulations has been extended to Tuesday, 22nd July 2025. All previous submissions must be re-sent using the prescribed formats to ensure proper review. Send comments to info@transport.go.ke, copy to comments@ntsa.go.ke.Read ArticleJun 11, 2025e-Agent Account Creation on the eCitizen PlatformThe e-Agent account feature on eCitizen enables streamlined bulk payments for institutions and agencies.Read ArticleJun 10, 2025Application for various NTSA services by National and County Government entitiesDedicated help desks are available at NTSA HQ, regional offices, and Huduma CentresRead ArticleJun 02, 2025Government Agencies, Ministries and State Departments Directed to Apply for Reflective Plates via NTSA PortalIn line with a government directive, all MDAs are required to apply for reflective plates through the NTSA portal. The application deadline is set for Friday, August 29, 2025.Read ArticlePrevious121 of 2Next

View File

@@ -0,0 +1,17 @@
# NTSA | NTSA Launches New Road Safety Campaign | NTSA Kenya
**URL:** https://ntsa.go.ke/news/ntsa-launches-new-road-safety-campaign
**Scraped:** 2025-10-24T05:34:18.816453
**Content Length:** 1113 characters
---
Home/Media Center/News & Updates/NTSA Launches New Road Safety Campaign Back to NewsDecember 22, 2024NTSA Launches New Road Safety CampaignNTSA launches a comprehensive six-month road safety campaign to reduce accidents and promote safer driving practices. Share:The National Transport and Safety Authority (NTSA) has today launched a comprehensive road safety campaign aimed at reducing road accidents and promoting safer driving practices across the country.
The campaign, which will run for the next six months, includes:
Public awareness programs
Enhanced enforcement measures
Collaboration with stakeholders
Use of technology for monitoring
This initiative comes as part of our ongoing commitment to making Kenyan roads safer for all users. Related ArticlesKenya Recognized for Technological Advancement and Public Service Excellence at APSCA AwardsOct 13, 2025LIST OF APPROVED MOTOR VEHICLE BODY BUILDERS, CONFORMITY ASSESSORS AND SPEED LIMITERS SUPPLIERS IN KENYASep 01, 2025Operation Watoto Wafike Salama Free Motor Vehicle Inspection ClinicsAug 20, 2025Quick LinksAbout NTSAOur ServicesContact UsFAQs

View File

@@ -0,0 +1,17 @@
# NTSA | New Digital Licensing System Goes Live | NTSA Kenya
**URL:** https://ntsa.go.ke/news/new-digital-licensing-system-goes-live
**Scraped:** 2025-10-24T05:34:14.170148
**Content Length:** 1003 characters
---
Home/Media Center/News & Updates/New Digital Licensing System Goes Live Back to NewsDecember 28, 2020New Digital Licensing System Goes LiveNTSA introduces a new digital licensing system to streamline services and improve efficiency. Share:NTSA has successfully launched its new digital licensing system, marking a significant step towards modernizing our services and improving efficiency.
The new system offers:
Online license applications and renewals
Digital payments
Real-time status tracking
Automated verification
This digital transformation will significantly reduce processing times and enhance service delivery to all Kenyans. Related ArticlesKenya Recognized for Technological Advancement and Public Service Excellence at APSCA AwardsOct 13, 2025LIST OF APPROVED MOTOR VEHICLE BODY BUILDERS, CONFORMITY ASSESSORS AND SPEED LIMITERS SUPPLIERS IN KENYASep 01, 2025Operation Watoto Wafike Salama Free Motor Vehicle Inspection ClinicsAug 20, 2025Quick LinksAbout NTSAOur ServicesContact UsFAQs

View File

@@ -0,0 +1,9 @@
# NTSA | Contact Us
**URL:** https://ntsa.go.ke/contact
**Scraped:** 2025-10-24T05:33:58.531154
**Content Length:** 1587 characters
---
Contact usWe'd love to hear from you. Our friendly team is always here to chat.Email usInquiries:info@ntsa.go.keComplaints:complaints@ntsa.go.keDL queries:dlqueries@ntsa.go.keIntegrity:integrity@ntsa.go.keCall usSafaricom:0709 932 000Telkom:020 6939 000Visit us316 Upper Hill Chambers,2nd Ngong Avenue,Upper Hill, Nairobi.Write to usNational Transport and Safety Authority,P.O Box 3602 - 00506,Nairobi.NTSA County OfficesThikaDeputy County Commissioners Offices, opposite Barclays Bank, next to Kiambu Lands Officeinfo@ntsa.go.ke0709 932 000NyeriRegional Commissioners Complex, Block C, Third floor, opposite the Nyeri Law Courtsinfo@ntsa.go.ke0709 932 000MeruImenti CDF Building, Ground Floorinfo@ntsa.go.ke0709 932 000EmbuMotor Vehicle Inspection, along Kiritiri Roadinfo@ntsa.go.ke0709 932 000NakuruMotor Vehicle Inspection Centre, along Nakuru Ravine Road, near Show Ground junctioninfo@ntsa.go.ke0709 932 000EldoretMotor Vehicle Inspection Centre, along Police Line Roadinfo@ntsa.go.ke0709 932 000KerichoKericho County Commissioner's compound, NTSA MVI Centreinfo@ntsa.go.ke0709 932 000KakamegaPostal, KRA Officesinfo@ntsa.go.ke0709 932 000KisiiMotor Vehicle Inspection Unit, along Kisii - Kilgoris Roadinfo@ntsa.go.ke0709 932 000KisumuMotor Vehicle Inspection Center, along Airport Roadinfo@ntsa.go.ke0709 932 000MachakosMachakos inspection Center, along people's park roadinfo@ntsa.go.ke0709 932 000VoiMotor Vehicle Inspection centreinfo@ntsa.go.ke0709 932 000MombasaMiritini MVImombasa.queries@ntsa.go.ke0709 932 000GarissaKRA Offices, 1st Floorinfo@ntsa.go.ke0709 932 000Find Us

View File

@@ -0,0 +1,9 @@
# NTSA | Frequently Asked Questions | NTSA Kenya
**URL:** https://ntsa.go.ke/faqs
**Scraped:** 2025-10-24T05:34:41.706480
**Content Length:** 819 characters
---
Frequently Asked QuestionsFind answers to common questions about NTSA services, licensing, vehicle registration, and road safety.All FAQsDriver LicensingVehicle RegistrationCorporate ServicesPSV & TransportRoad SafetyAll FAQsHow do I apply for Smart Driving LicenseHow do I renew my smart driving license?What documents do I need for vehicle registration?How do I transfer vehicle ownership?How do I register a transport company?What are the requirements for PSV operators?How do I apply for a PSV badge?How do I report unsafe driving behavior?How do I check my driving license status?How often should I have my vehicle inspected?What are the requirements for a fleet management system?Still have questions?If you couldn't find the answer to your question, please contact our customer support team. Call Us Contact Form

View File

@@ -0,0 +1,10 @@
# NTSA | Keep our roads safe
**URL:** https://ntsa.go.ke/
**Scraped:** 2025-10-24T05:34:50.569331
**Content Length:** 6068 characters
---
Inter-Agency Road Safety ConferenceInter-Agency Road Safety Conference graced by CS Ministry of Roads and Transport Davis ChirchirAccess ServicesWe care about keeping you safe on the roadsThe National Transport and Safety Authority continually improves accessibility and safety of Kenya's road transport system for all.Access ServicesTUVUKE SALAMA - Safe Crossings, Safer ChildrenTogether with our partners, we are championing for safer school crossing zones to save our children on the roads.Access ServicesQuick SearchFind a ServiceUse the quick search to find information or services instantly.SearchWelcome to The New and Improved NTSA Online ServicesAccess all NTSA services through your eCitizen account—everything you need in one place with one account. All the TIMS services and many more are available in our new and simple-to-use platform.Access ServicesLearn MoreLive Portal30+ ServicesOnline ServicesDiscover All NTSA Online ServicesWith over 30 services available online, explore what you can do on the new online portal.IndividualsLicenses & permitsVehiclesRegistration & transferService ProvidersOperators & dealersOrganizationsFleet managementOther NTSA ServicesQuick access to specialized servicesView AllUncollected Smart DL & PlatesSpeed Limiter ApplicationDealer & Garage LicenseConformity AssessorTransport Network CompanyNews & UpdatesLatest News & UpdatesStay informed with the latest announcements, initiatives, and updates from NTSAView All NewsOct 13, 2025Kenya Recognized for Technological Advancement and Public Service Excellence at APSCA AwardsKenyas innovation in public service has earned continental acclaim at the APSCA Awards, with NTSA recognized for leading the nations digital transformation journey toward smarter, paperless governance.Read Full StorySep 01, 2025LIST OF APPROVED MOTOR VEHICLE BODY BUILDERS, CONFORMITY ASSESSORS AND SPEED LIMITERS SUPPLIERS IN KENYALIST OF APPROVED MOTOR VEHICLE BODY BUILDERS, CONFORMITY ASSESSORS AND SPEED LIMITERS SUPPLIERS IN KENYARead Full StoryAug 20, 2025Operation Watoto Wafike Salama Free Motor Vehicle Inspection ClinicsNTSA is offering free motor vehicle inspection clinics for all school transport vehicles across its centres. The initiative aims to enhance the safety of children as schools reopen.Read Full StoryAug 15, 2025IMPORTANT PUBLIC NOTICE: ROAD SAFETY AS SCHOOLS REOPENSafe, reliable school transport is mandatory as the new school term begins.Read Full StoryJul 29, 2025IMPORTANT PUBLIC NOTICE FOR MOTOR VEHICLE / MOTORCYCLE OWNERSThe National Transport and Safety Authority has operationalized the Duty Update Module/Vehicle Records Update Tool to support all motor vehicle and motorcycle owners.Read Full StoryJul 07, 2025PUBLIC NOTICE: EXTENSION OF COMMENTS AND PROPOSALS SUBMISSION DATE ON DRAFT TRAFFIC AND TRANSPORT REGULATIONS, 2025The deadline for submission of comments on the proposed 2025 Traffic & Transport Regulations has been extended to Tuesday, 22nd July 2025. All previous submissions must be re-sent using the prescribed formats to ensure proper review. Send comments to info@transport.go.ke, copy to comments@ntsa.go.ke.Read Full StoryJun 11, 2025e-Agent Account Creation on the eCitizen PlatformThe e-Agent account feature on eCitizen enables streamlined bulk payments for institutions and agencies.Read Full StoryJun 10, 2025Application for various NTSA services by National and County Government entitiesDedicated help desks are available at NTSA HQ, regional offices, and Huduma CentresRead Full StoryJun 02, 2025Government Agencies, Ministries and State Departments Directed to Apply for Reflective Plates via NTSA PortalIn line with a government directive, all MDAs are required to apply for reflective plates through the NTSA portal. The application deadline is set for Friday, August 29, 2025.Read Full StoryMay 16, 2025NTSA Warns Public About Social Media ScamsNTSA Alerts Public on Social Media Scams :

View File

@@ -0,0 +1,10 @@
# NTSA | Keep our roads safe
**URL:** https://ntsa.go.ke
**Scraped:** 2025-10-24T05:33:40.256848
**Content Length:** 6068 characters
---
Inter-Agency Road Safety ConferenceInter-Agency Road Safety Conference graced by CS Ministry of Roads and Transport Davis ChirchirAccess ServicesWe care about keeping you safe on the roadsThe National Transport and Safety Authority continually improves accessibility and safety of Kenya's road transport system for all.Access ServicesTUVUKE SALAMA - Safe Crossings, Safer ChildrenTogether with our partners, we are championing for safer school crossing zones to save our children on the roads.Access ServicesQuick SearchFind a ServiceUse the quick search to find information or services instantly.SearchWelcome to The New and Improved NTSA Online ServicesAccess all NTSA services through your eCitizen account—everything you need in one place with one account. All the TIMS services and many more are available in our new and simple-to-use platform.Access ServicesLearn MoreLive Portal30+ ServicesOnline ServicesDiscover All NTSA Online ServicesWith over 30 services available online, explore what you can do on the new online portal.IndividualsLicenses & permitsVehiclesRegistration & transferService ProvidersOperators & dealersOrganizationsFleet managementOther NTSA ServicesQuick access to specialized servicesView AllUncollected Smart DL & PlatesSpeed Limiter ApplicationDealer & Garage LicenseConformity AssessorTransport Network CompanyNews & UpdatesLatest News & UpdatesStay informed with the latest announcements, initiatives, and updates from NTSAView All NewsOct 13, 2025Kenya Recognized for Technological Advancement and Public Service Excellence at APSCA AwardsKenyas innovation in public service has earned continental acclaim at the APSCA Awards, with NTSA recognized for leading the nations digital transformation journey toward smarter, paperless governance.Read Full StorySep 01, 2025LIST OF APPROVED MOTOR VEHICLE BODY BUILDERS, CONFORMITY ASSESSORS AND SPEED LIMITERS SUPPLIERS IN KENYALIST OF APPROVED MOTOR VEHICLE BODY BUILDERS, CONFORMITY ASSESSORS AND SPEED LIMITERS SUPPLIERS IN KENYARead Full StoryAug 20, 2025Operation Watoto Wafike Salama Free Motor Vehicle Inspection ClinicsNTSA is offering free motor vehicle inspection clinics for all school transport vehicles across its centres. The initiative aims to enhance the safety of children as schools reopen.Read Full StoryAug 15, 2025IMPORTANT PUBLIC NOTICE: ROAD SAFETY AS SCHOOLS REOPENSafe, reliable school transport is mandatory as the new school term begins.Read Full StoryJul 29, 2025IMPORTANT PUBLIC NOTICE FOR MOTOR VEHICLE / MOTORCYCLE OWNERSThe National Transport and Safety Authority has operationalized the Duty Update Module/Vehicle Records Update Tool to support all motor vehicle and motorcycle owners.Read Full StoryJul 07, 2025PUBLIC NOTICE: EXTENSION OF COMMENTS AND PROPOSALS SUBMISSION DATE ON DRAFT TRAFFIC AND TRANSPORT REGULATIONS, 2025The deadline for submission of comments on the proposed 2025 Traffic & Transport Regulations has been extended to Tuesday, 22nd July 2025. All previous submissions must be re-sent using the prescribed formats to ensure proper review. Send comments to info@transport.go.ke, copy to comments@ntsa.go.ke.Read Full StoryJun 11, 2025e-Agent Account Creation on the eCitizen PlatformThe e-Agent account feature on eCitizen enables streamlined bulk payments for institutions and agencies.Read Full StoryJun 10, 2025Application for various NTSA services by National and County Government entitiesDedicated help desks are available at NTSA HQ, regional offices, and Huduma CentresRead Full StoryJun 02, 2025Government Agencies, Ministries and State Departments Directed to Apply for Reflective Plates via NTSA PortalIn line with a government directive, all MDAs are required to apply for reflective plates through the NTSA portal. The application deadline is set for Friday, August 29, 2025.Read Full StoryMay 16, 2025NTSA Warns Public About Social Media ScamsNTSA Alerts Public on Social Media Scams :

View File

@@ -0,0 +1,9 @@
# NTSA | NTSA Services
**URL:** https://ntsa.go.ke/services
**Scraped:** 2025-10-24T05:33:50.657769
**Content Length:** 1994 characters
---
NTSA ServicesAccess all NTSA services through your eCitizen account—everything you need in one place with one account.Access Services PortalIndividuals ServicesManage your vehicle-related permits, licenses, and personal details with ease through your NTSA individual service account. This portal allows you to handle all aspects of vehicle ownership, including adding an organization or business to your profile.View Services Vehicles ServicesAdminister and update vehicle records, including inspections, permits, and modifications, via the NTSA portal. The platform ensures that all vehicle-related data is accurately maintained in accordance with regulatory standards.View Services Organisations ServicesEfficiently manage your fleet and driver operations through the NTSA portal, designed for seamless organizational oversight. This service facilitates the streamlined management of vehicles, ensuring compliance with national transport regulations.View Services Service Providers ServicesRegister and comply with NTSA's regulatory requirements through the NTSA Service Providers portal. This platform supports the registration of operators, SACCOs, and dealerships, ensuring alignment with national transport standards.View Services NTSA Service PortalOur new service portal provides a streamlined experience for all your NTSA service needs. Access vehicle registration, driver licensing, and more through your eCitizen account.✓Simplified user interface for easy navigation✓Secure payment processing✓Real-time application status updates✓Integrated with eCitizen for seamless experienceVisit Service PortalHow It Works01Create AccountSign up or log in to your eCitizen account to access NTSA services.02Select ServiceChoose from our range of services based on your needs.03Complete ProcessFollow the guided process, make payment, and track your application.Ready to Get Started?Access all NTSA services through our integrated service portal. Fast, secure, and convenient.Access Services Now

View File

@@ -0,0 +1,9 @@
# NTSA | Privacy Policy | NTSA
**URL:** https://ntsa.go.ke/privacy-policy
**Scraped:** 2025-10-24T05:34:46.121750
**Content Length:** 1130 characters
---
NTSA Privacy PolicyLast Updated: April 9, 20251.0 IntroductionThe National Transport and Safety Authority (NTSA) operates in a highly data-oriented environment which requires the processing and use of personal data in order to fulfil its core mandate of disseminating information to the public. NTSA is committed to high standards of privacy and security of your personal data as required under the Data Protection Act, 2019 and the regulations thereto.This Privacy Statement explains the personal data we collect, how we process it and for what purpose. It also describes how NTSA handles your data when you use any of our services and the controls NTSA has established to safeguard your data. The Privacy Statement applies to our visitors who either physically visit our premises or our website, users of any of Our Products and services, suppliers, agents, customers and all our stakeholders.2.0 Definition of terms3.0 Collection of Information4.0 Use of information5.0 Retention of Data6.0 Disclosure of Information7.0 Social media features and widgets8.0 Safeguarding and protection of your personal data9.0 How to Contact Us

View File

@@ -0,0 +1,9 @@
# NTSA | Vehicles Services
**URL:** https://ntsa.go.ke/services/vehicles-services
**Scraped:** 2025-10-24T05:34:37.062846
**Content Length:** 814 characters
---
Vehicles ServicesAdminister and update vehicle records, including inspections, permits, and modifications, via the NTSA portal. The platform ensures that all vehicle-related data is accurately maintained in accordance with regulatory standards.Available ServicesMotor Vehicle InspectionsThe Authority conducts inspection services to all Public Service Vehicles (PSV) and Commercial vehicles.How to Apply Motor Vehicle RegistrationThe authority registers vehicles and asigns number plates to the vehiclesHow to Apply Apply for Short Term RSLThe issuing of short-term Road Service License is meant to facilitate Public Service Vehicles to operate a route outside their licensed route for a specified short period of time not exceeding three (3) days. This application is done by the authorized personnel.How to Apply

View File

@@ -0,0 +1,9 @@
# NTSA | Tenders
**URL:** https://ntsa.go.ke/tenders
**Scraped:** 2025-10-24T05:34:09.765585
**Content Length:** 354 characters
---
Current TendersBrowse through our latest tenders and find opportunities to work with us.We regularly update this section with new tenders.NTSA/REG-018/2023-2024Reserved for: openREGISTRATION OF PROSPECTIVE SUPPLIERS FOR THE SUPPLY AND DELIVERY OF GOODS, WORKS, SERVICES, AND CONSULTANCIES FOR A PERIOD OF TWO YEARSClosing: 31 Jan 2027 at 05:00 pmDownload