ChatNix / chatnix.py
mostafa202555's picture
Upload chatnix.py
621de6f verified
Raw History Blame Contribute Delete
35.3 kB
"""
╔═══════════════════════════════════════════════════════════════╗
β•‘ ChatNix Code β•‘
β•‘ A fully local LLM β€” No API, No Downloads β•‘
β•‘ Built with: n-gram LM + TF-IDF + Neural Net (numpy/sklearn) β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
"""
import re
import sys
import math
import random
import string
import pickle
import os
from collections import defaultdict, Counter
from datetime import datetime
try:
import numpy as np
except ImportError:
print("[!] numpy not found. Installing...")
os.system("pip install numpy --break-system-packages -q")
import numpy as np
try:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
except ImportError:
print("[!] scikit-learn not found. Installing...")
os.system("pip install scikit-learn --break-system-packages -q")
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
# ─────────────────────────────────────────────
# KNOWLEDGE BASE (built-in, no downloads)
# ─────────────────────────────────────────────
KNOWLEDGE_BASE = [
# Python
("what is python", "Python is a high-level, interpreted programming language known for its simple, readable syntax. It supports multiple paradigms including procedural, object-oriented, and functional programming. Python is widely used in web development, data science, machine learning, and automation."),
("python syntax", "Python uses indentation to define code blocks instead of braces. Variables are dynamically typed. Functions are defined with 'def', classes with 'class'. Common data types include int, float, str, list, tuple, dict, and set."),
("python list", "A Python list is an ordered, mutable collection. You create one with square brackets: my_list = [1, 2, 3]. Lists support indexing, slicing, append(), remove(), pop(), sort(), and many other methods."),
("python dictionary", "A Python dictionary stores key-value pairs. Created with curly braces: my_dict = {'key': 'value'}. Access values with dict['key']. Methods include .keys(), .values(), .items(), .get(), .update()."),
("python function", "Define a Python function using 'def name(params): body'. Functions can have default arguments, *args for variable positional args, and **kwargs for keyword args. Use 'return' to send back a value."),
("python class", "A Python class is defined with 'class ClassName:'. The __init__ method is the constructor. Use 'self' to refer to instance attributes. Inheritance is done with 'class Child(Parent):'."),
("python loop", "Python has two main loops: 'for item in iterable:' iterates over a sequence, and 'while condition:' runs while a condition is True. Use 'break' to exit, 'continue' to skip, and 'else' for post-loop logic."),
("python exception", "Handle exceptions with try/except blocks. 'try:' wraps risky code, 'except ExceptionType as e:' catches it, 'finally:' always runs. Raise exceptions with 'raise ValueError(\"message\")'."),
("python file", "Open files with open('path', mode). Modes: 'r' read, 'w' write, 'a' append, 'b' binary. Use 'with open(...) as f:' for automatic closing. Methods: f.read(), f.readline(), f.readlines(), f.write()."),
("python import", "Import modules with 'import module' or 'from module import name'. Standard library includes os, sys, math, random, datetime, json, re, collections, itertools, functools, pathlib."),
("python lambda", "Lambda creates anonymous functions: lambda x: x * 2. Often used with map(), filter(), sorted(). Example: sorted(items, key=lambda x: x[1])."),
("python comprehension", "List comprehension: [expr for item in iterable if condition]. Dict comprehension: {k: v for k, v in pairs}. Set comprehension: {x for x in items}. Generator: (x for x in items)."),
("python decorator", "Decorators modify functions using @syntax. They wrap a function to add behavior. Example: @staticmethod, @classmethod, @property. Custom decorators are functions that return functions."),
("python generator", "Generators use 'yield' to produce values lazily. They save memory for large sequences. Create with a function using yield or a generator expression (x for x in range(1000000))."),
("python async", "Python async/await enables asynchronous programming. Define async functions with 'async def'. Use 'await' for async calls. Run with asyncio.run(). Great for I/O-bound tasks."),
# Data Structures
("what is a stack", "A stack is a LIFO (Last In, First Out) data structure. Elements are pushed onto the top and popped from the top. In Python, use a list as a stack: stack.append(x) to push, stack.pop() to pop."),
("what is a queue", "A queue is a FIFO (First In, First Out) data structure. Elements are added to the back and removed from the front. Use collections.deque for O(1) operations: deque.append() and deque.popleft()."),
("what is a linked list", "A linked list is a sequence of nodes where each node contains data and a pointer to the next node. Unlike arrays, insertion/deletion is O(1) if you have the node, but access is O(n)."),
("what is a binary tree", "A binary tree is a hierarchical data structure where each node has at most two children (left and right). Special forms include BST (ordered), AVL (balanced), and heaps (priority queues)."),
("what is a hash table", "A hash table maps keys to values using a hash function. Provides O(1) average-case lookup, insertion, and deletion. Python's dict is a hash table. Handles collisions via chaining or open addressing."),
("what is a graph", "A graph consists of vertices (nodes) and edges (connections). Can be directed or undirected, weighted or unweighted. Common algorithms: BFS, DFS, Dijkstra's, Bellman-Ford, Floyd-Warshall."),
# Algorithms
("what is sorting", "Sorting algorithms arrange elements in order. Common ones: Bubble O(nΒ²), Selection O(nΒ²), Insertion O(nΒ²), Merge O(n log n), Quick O(n log n) average, Heap O(n log n). Python uses Timsort, a hybrid merge+insertion sort."),
("what is binary search", "Binary search finds an element in a sorted array in O(log n) time. It repeatedly divides the search space in half by comparing the target to the middle element. Requires the array to be sorted first."),
("what is recursion", "Recursion is when a function calls itself with a smaller subproblem. Requires a base case to stop. Used in tree traversal, divide-and-conquer (merge sort, quicksort), dynamic programming, backtracking."),
("what is dynamic programming", "Dynamic programming solves complex problems by breaking them into overlapping subproblems and storing results (memoization/tabulation). Used in: Fibonacci, knapsack, longest common subsequence, shortest paths."),
("what is big o notation", "Big O notation describes algorithm time/space complexity. O(1) constant, O(log n) logarithmic, O(n) linear, O(n log n) linearithmic, O(nΒ²) quadratic, O(2^n) exponential. Describes worst-case growth rate."),
# Machine Learning
("what is machine learning", "Machine learning is a subset of AI where systems learn patterns from data without explicit programming. Types: supervised (labeled data), unsupervised (unlabeled), reinforcement (reward-based), semi-supervised."),
("what is neural network", "A neural network is inspired by the brain. It consists of layers of nodes (neurons) with weighted connections. Input layer receives data, hidden layers transform it, output layer produces results. Trained via backpropagation."),
("what is deep learning", "Deep learning uses neural networks with many hidden layers. Excels at pattern recognition in images, text, and audio. Key architectures: CNN (images), RNN/LSTM (sequences), Transformer (NLP), GAN (generation)."),
("what is overfitting", "Overfitting is when a model memorizes training data but fails on new data. Solutions: more data, regularization (L1/L2), dropout, early stopping, cross-validation, simpler model architecture."),
("what is gradient descent", "Gradient descent minimizes a loss function by iteratively adjusting weights in the direction of the negative gradient. Variants: batch, stochastic (SGD), mini-batch. With momentum: Adam, RMSprop, AdaGrad."),
("what is nlp", "Natural Language Processing enables computers to understand human language. Tasks: tokenization, POS tagging, NER, parsing, sentiment analysis, machine translation, summarization, question answering."),
("what is a transformer", "The Transformer architecture uses self-attention to process sequences in parallel. Introduced in 'Attention Is All You Need' (2017). Foundation of BERT, GPT, T5, and most modern LLMs. No recurrence needed."),
("what is reinforcement learning", "Reinforcement learning trains agents by rewarding good actions and penalizing bad ones. Key concepts: agent, environment, state, action, reward, policy, value function. Algorithms: Q-learning, PPO, A3C, DQN."),
# Web Development
("what is html", "HTML (HyperText Markup Language) structures web pages. Uses tags like <html>, <head>, <body>, <div>, <p>, <a>, <img>, <form>. HTML5 added semantic tags: <header>, <nav>, <main>, <section>, <article>, <footer>."),
("what is css", "CSS (Cascading Style Sheets) styles HTML elements. Selectors target elements. Properties set styles. Box model: content, padding, border, margin. Flexbox and Grid for layout. Media queries for responsiveness."),
("what is javascript", "JavaScript is the language of the web. Runs in browsers and (with Node.js) servers. Dynamically typed, prototype-based. Supports async programming with Promises and async/await. Frameworks: React, Vue, Angular."),
("what is rest api", "REST (Representational State Transfer) is an architectural style for APIs. Uses HTTP methods: GET (read), POST (create), PUT (update), DELETE (remove). Stateless, uses JSON/XML. Resources identified by URLs."),
("what is http", "HTTP (HyperText Transfer Protocol) is the foundation of web communication. Status codes: 2xx success, 3xx redirect, 4xx client error, 5xx server error. HTTP/2 added multiplexing. HTTPS adds TLS encryption."),
# Databases
("what is sql", "SQL (Structured Query Language) manages relational databases. Key commands: SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER. Joins: INNER, LEFT, RIGHT, FULL. Supports transactions, indexes, views, stored procedures."),
("what is nosql", "NoSQL databases store non-relational data. Types: document (MongoDB), key-value (Redis), column-family (Cassandra), graph (Neo4j). Better for unstructured data, horizontal scaling, and flexible schemas."),
("what is a database index", "A database index speeds up queries by creating a lookup structure (often a B-tree). Makes reads faster but writes slower. Create on frequently queried columns. Composite indexes cover multiple columns."),
# General CS
("what is an api", "An API (Application Programming Interface) defines how software components communicate. Specifies methods, data formats, and conventions. Types: REST, GraphQL, gRPC, WebSocket, library APIs. Enables modular, reusable systems."),
("what is git", "Git is a distributed version control system. Key commands: init, clone, add, commit, push, pull, branch, merge, rebase, stash. GitHub/GitLab host remote repositories. Branches enable parallel development."),
("what is docker", "Docker packages applications with their dependencies into containers. Containers are lightweight and portable. Key concepts: image, container, Dockerfile, docker-compose, volume, network. Ensures consistency across environments."),
("what is object oriented programming", "OOP organizes code around objects with data (attributes) and behavior (methods). Four pillars: Encapsulation (bundling), Abstraction (hiding complexity), Inheritance (reusing code), Polymorphism (multiple forms)."),
("what is functional programming", "Functional programming treats computation as math functions. Key concepts: pure functions (no side effects), immutability, higher-order functions, recursion, function composition. Languages: Haskell, Erlang. Python/JS support it."),
("what is a compiler", "A compiler translates source code to machine code. Phases: lexing (tokens), parsing (AST), semantic analysis, optimization, code generation. Examples: GCC, Clang. Interpreters execute code directly line-by-line."),
("what is memory management", "Memory management allocates and frees memory. Stack is for local variables (auto-managed). Heap is for dynamic allocation. Python uses garbage collection (reference counting + cyclic GC). C/C++ require manual management."),
("what is concurrency", "Concurrency is handling multiple tasks that may overlap in time. Parallelism is simultaneous execution. Python: threading (I/O-bound), multiprocessing (CPU-bound), asyncio (async I/O). GIL limits true thread parallelism."),
("what is a design pattern", "Design patterns are reusable solutions to common problems. Creational: Singleton, Factory, Builder. Structural: Adapter, Decorator, Proxy. Behavioral: Observer, Strategy, Command, Iterator, Template Method."),
("what is linux", "Linux is an open-source Unix-like OS kernel. Distributions: Ubuntu, Debian, Fedora, Arch, CentOS. Key concepts: shell, filesystem hierarchy, permissions (chmod/chown), processes, pipes, redirection, package managers."),
("what is an operating system", "An OS manages hardware resources and provides services to applications. Components: kernel, process manager, memory manager, file system, device drivers, scheduler. Examples: Linux, Windows, macOS, Android."),
("what is networking", "Computer networking connects devices to share resources. Protocols: TCP/IP, UDP, HTTP, DNS, DHCP, FTP, SSH. OSI model has 7 layers. Concepts: IP addressing, subnetting, routing, NAT, firewall, VPN."),
("what is encryption", "Encryption converts plaintext to ciphertext to protect data. Symmetric (same key): AES. Asymmetric (public/private key pair): RSA, ECC. Hashing (one-way): SHA-256, bcrypt. TLS uses both for secure connections."),
("what is a virtual machine", "A VM emulates a complete computer system in software. Allows multiple OS instances on one host. Uses a hypervisor (VMware, VirtualBox, KVM). Heavier than containers but stronger isolation."),
# Math
("what is calculus", "Calculus studies continuous change. Differential calculus: derivatives measure rates of change, find extrema. Integral calculus: integrals measure accumulation, compute areas. Fundamental theorem connects them."),
("what is linear algebra", "Linear algebra studies vectors, matrices, and linear transformations. Key concepts: vectors, matrices, determinant, eigenvalues/eigenvectors, dot product, matrix multiplication. Foundation of ML and computer graphics."),
("what is probability", "Probability quantifies uncertainty. P(A) is between 0 and 1. Rules: addition (P(AβˆͺB)), multiplication (P(A∩B)), Bayes' theorem: P(A|B)=P(B|A)P(A)/P(B). Distributions: normal, binomial, Poisson, uniform."),
("what is statistics", "Statistics analyzes data. Descriptive: mean, median, mode, variance, standard deviation. Inferential: hypothesis testing, confidence intervals, p-values, regression. Types: frequentist vs Bayesian."),
# Greetings / meta
("hello", "Hello! I'm ChatNix, a fully local AI assistant. I can help with Python, algorithms, machine learning, data structures, web development, databases, math, and general CS topics. What would you like to learn?"),
("hi", "Hi there! I'm ChatNix Code β€” your local AI, no internet needed. Ask me about programming, algorithms, ML, or any CS topic!"),
("who are you", "I'm ChatNix Code β€” a fully local, offline AI language model. I use n-gram language modeling, TF-IDF retrieval, and a small neural network built from scratch with numpy and scikit-learn. No APIs, no cloud, all local!"),
("what can you do", "I can answer questions about: Python programming, data structures and algorithms, machine learning and deep learning, web development, databases, operating systems, networking, math (calculus, linear algebra, probability), and general computer science topics."),
("help", "Sure! Ask me any question about programming or computer science. Examples: 'What is a binary tree?', 'Explain Python decorators', 'What is gradient descent?', 'How does Docker work?', 'What is Big O notation?'"),
("thank you", "You're welcome! Feel free to ask more questions anytime. I'm always here and fully offline!"),
("thanks", "Glad I could help! Ask me anything else about programming or CS."),
("bye", "Goodbye! ChatNix will be here whenever you need it β€” no internet required!"),
("what is chatnix", "ChatNix Code is a local AI assistant built with Python using ML and NLP techniques: n-gram language models for text generation, TF-IDF vectors for semantic retrieval, cosine similarity for matching, and a numpy neural network for classification β€” all without any external API."),
]
# ─────────────────────────────────────────────
# N-GRAM LANGUAGE MODEL
# ─────────────────────────────────────────────
class NGramLanguageModel:
"""Builds an n-gram model from the knowledge base for text generation."""
def __init__(self, n=3):
self.n = n
self.ngrams = defaultdict(Counter)
self.vocab = set()
def _tokenize(self, text):
text = text.lower()
tokens = re.findall(r"\b\w+\b|[.,!?]", text)
return ['<s>'] * (self.n - 1) + tokens + ['</s>']
def train(self, texts):
for text in texts:
tokens = self._tokenize(text)
self.vocab.update(tokens)
for i in range(len(tokens) - self.n + 1):
context = tuple(tokens[i:i + self.n - 1])
next_word = tokens[i + self.n - 1]
self.ngrams[context][next_word] += 1
def _prob(self, context, word, smoothing=0.1):
ctx = tuple(context)
total = sum(self.ngrams[ctx].values()) + smoothing * len(self.vocab)
count = self.ngrams[ctx].get(word, 0) + smoothing
return count / total
def generate(self, seed_text="", max_tokens=40, temperature=0.7):
tokens = self._tokenize(seed_text) if seed_text else ['<s>'] * (self.n - 1)
tokens = tokens[-(self.n - 1):]
result = []
for _ in range(max_tokens):
ctx = tuple(tokens[-(self.n - 1):])
candidates = list(self.ngrams.get(ctx, {}).keys())
if not candidates or '</s>' in (tokens[-1],):
break
# Temperature sampling
weights = []
for c in candidates:
p = self._prob(ctx, c)
weights.append(p ** (1.0 / max(temperature, 0.01)))
total_w = sum(weights)
weights = [w / total_w for w in weights]
chosen = random.choices(candidates, weights=weights, k=1)[0]
if chosen == '</s>':
break
result.append(chosen)
tokens.append(chosen)
return ' '.join(result)
# ─────────────────────────────────────────────
# TINY NEURAL NETWORK (numpy only)
# ─────────────────────────────────────────────
class TinyNN:
"""3-layer MLP for intent classification, built from scratch with numpy."""
def __init__(self, input_dim, hidden_dim=64, output_dim=10, lr=0.01):
scale1 = np.sqrt(2.0 / input_dim)
scale2 = np.sqrt(2.0 / hidden_dim)
self.W1 = np.random.randn(input_dim, hidden_dim) * scale1
self.b1 = np.zeros((1, hidden_dim))
self.W2 = np.random.randn(hidden_dim, hidden_dim) * scale2
self.b2 = np.zeros((1, hidden_dim))
self.W3 = np.random.randn(hidden_dim, output_dim) * scale2
self.b3 = np.zeros((1, output_dim))
self.lr = lr
def _relu(self, x):
return np.maximum(0, x)
def _softmax(self, x):
e = np.exp(x - x.max(axis=1, keepdims=True))
return e / e.sum(axis=1, keepdims=True)
def forward(self, X):
self.z1 = X @ self.W1 + self.b1
self.a1 = self._relu(self.z1)
self.z2 = self.a1 @ self.W2 + self.b2
self.a2 = self._relu(self.z2)
self.z3 = self.a2 @ self.W3 + self.b3
self.a3 = self._softmax(self.z3)
return self.a3
def _cross_entropy(self, probs, y):
n = y.shape[0]
log_probs = -np.log(probs[np.arange(n), y] + 1e-9)
return log_probs.mean()
def backward(self, X, y):
n = X.shape[0]
# Output layer gradient
dz3 = self.a3.copy()
dz3[np.arange(n), y] -= 1
dz3 /= n
dW3 = self.a2.T @ dz3
db3 = dz3.sum(axis=0, keepdims=True)
# Hidden layer 2
da2 = dz3 @ self.W3.T
dz2 = da2 * (self.z2 > 0)
dW2 = self.a1.T @ dz2
db2 = dz2.sum(axis=0, keepdims=True)
# Hidden layer 1
da1 = dz2 @ self.W2.T
dz1 = da1 * (self.z1 > 0)
dW1 = X.T @ dz1
db1 = dz1.sum(axis=0, keepdims=True)
# Update
self.W3 -= self.lr * dW3
self.b3 -= self.lr * db3
self.W2 -= self.lr * dW2
self.b2 -= self.lr * db2
self.W1 -= self.lr * dW1
self.b1 -= self.lr * db1
def train_step(self, X, y):
probs = self.forward(X)
loss = self._cross_entropy(probs, y)
self.backward(X, y)
return loss
def predict(self, X):
return self.forward(X).argmax(axis=1)
# ─────────────────────────────────────────────
# CHATNIX ENGINE
# ─────────────────────────────────────────────
class ChatNix:
"""
ChatNix Code β€” local LLM combining:
1. TF-IDF retrieval for finding the best knowledge entry
2. N-gram LM for contextual text generation
3. Tiny NN for intent classification
4. Rule-based fallback with NLP techniques
"""
def __init__(self):
self.version = "1.0.0"
self.history = []
self._boot()
def _boot(self):
print("\n" + "═" * 60)
print(" β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•—β–ˆβ–ˆβ•—β–ˆβ–ˆβ•— β–ˆβ–ˆβ•—")
print(" β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•")
print(" β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ•”β• ")
print(" β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β–ˆβ–ˆβ•— ")
print(" β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•šβ–ˆβ–ˆβ•—")
print(" β•šβ•β•β•β•β•β•β•šβ•β• β•šβ•β•β•šβ•β• β•šβ•β• β•šβ•β• β•šβ•β• β•šβ•β•β•β•šβ•β•β•šβ•β• β•šβ•β•")
print(" C O D E v1.0.0")
print(" Fully Local Β· No API Β· No Downloads")
print("═" * 60)
print("\n[*] Booting ChatNix engine...")
self._build_tfidf()
self._build_ngram()
self._build_nn()
print("[βœ“] All systems online. Type 'help' to start.\n")
# ── TF-IDF Retrieval ──────────────────────────────────────────
def _build_tfidf(self):
print(" β†’ Building TF-IDF retrieval index...", end=" ", flush=True)
self.kb_questions = [q for q, _ in KNOWLEDGE_BASE]
self.kb_answers = [a for _, a in KNOWLEDGE_BASE]
all_docs = self.kb_questions + [a[:200] for a in self.kb_answers]
self.vectorizer = TfidfVectorizer(
ngram_range=(1, 2),
max_features=5000,
sublinear_tf=True,
strip_accents='unicode',
analyzer='word',
stop_words='english'
)
self.vectorizer.fit(all_docs)
self.kb_vectors = self.vectorizer.transform(self.kb_questions)
print("done")
def _retrieve(self, query, top_k=3):
q_vec = self.vectorizer.transform([query])
sims = cosine_similarity(q_vec, self.kb_vectors).flatten()
top_indices = sims.argsort()[::-1][:top_k]
return [(idx, sims[idx]) for idx in top_indices]
# ── N-Gram Language Model ──────────────────────────────────────
def _build_ngram(self):
print(" β†’ Training n-gram language model...", end=" ", flush=True)
self.lm = NGramLanguageModel(n=3)
all_texts = [a for _, a in KNOWLEDGE_BASE]
self.lm.train(all_texts)
print("done")
# ── Tiny Neural Network ────────────────────────────────────────
def _build_nn(self):
print(" β†’ Training intent classifier (neural net)...", end=" ", flush=True)
# Intent categories
self.intents = [
"python", "data_structure", "algorithm", "ml_ai",
"web", "database", "system", "math", "greeting", "other"
]
intent_keywords = {
"python": ["python", "def", "class", "list", "dict", "lambda", "decorator", "generator", "async", "import", "loop", "function", "exception"],
"data_structure": ["stack", "queue", "linked", "tree", "graph", "hash", "array", "heap", "trie", "map"],
"algorithm": ["sort", "search", "binary", "recursion", "dynamic", "greedy", "complexity", "big o", "bfs", "dfs", "algorithm"],
"ml_ai": ["machine learning", "neural", "deep learning", "gradient", "overfitting", "nlp", "transformer", "reinforcement", "model", "training", "ai"],
"web": ["html", "css", "javascript", "http", "rest", "api", "frontend", "backend", "web", "browser", "server"],
"database": ["sql", "nosql", "database", "query", "index", "mongo", "postgres", "table", "schema"],
"system": ["linux", "os", "operating", "memory", "concurrency", "thread", "process", "docker", "git", "compiler", "network"],
"math": ["calculus", "algebra", "probability", "statistics", "matrix", "vector", "derivative", "integral", "math"],
"greeting": ["hello", "hi", "who are you", "help", "bye", "thanks", "thank", "chatnix", "what can you"],
"other": [],
}
# Build training data from KB using TF-IDF features
train_questions = self.kb_questions * 3 # augment
train_labels = []
for q in train_questions:
q_lower = q.lower()
best = "other"
best_score = 0
for intent, kws in intent_keywords.items():
score = sum(1 for kw in kws if kw in q_lower)
if score > best_score:
best_score = score
best = intent
train_labels.append(self.intents.index(best))
X = self.vectorizer.transform(train_questions).toarray().astype(np.float32)
y = np.array(train_labels)
# Limit feature dim for speed
self.nn_feat_dim = min(X.shape[1], 512)
# PCA-lite: take top columns by variance
variances = X.var(axis=0)
self.top_feat_idx = np.argsort(variances)[::-1][:self.nn_feat_dim]
X = X[:, self.top_feat_idx]
self.nn = TinyNN(
input_dim=self.nn_feat_dim,
hidden_dim=128,
output_dim=len(self.intents),
lr=0.05
)
# Train
for _ in range(200):
self.nn.train_step(X, y)
print("done")
def _classify_intent(self, query):
x = self.vectorizer.transform([query]).toarray().astype(np.float32)
x = x[:, self.top_feat_idx]
pred = self.nn.predict(x)[0]
return self.intents[pred]
# ── Response Generation ────────────────────────────────────────
def _preprocess(self, text):
text = text.lower().strip()
text = re.sub(r"[^\w\s]", " ", text)
text = re.sub(r"\s+", " ", text)
return text
def _generate_response(self, query):
clean_q = self._preprocess(query)
intent = self._classify_intent(clean_q)
results = self._retrieve(clean_q, top_k=3)
best_idx, best_sim = results[0]
# High confidence: direct retrieval
if best_sim > 0.35:
base_answer = self.kb_answers[best_idx]
# Maybe blend with #2 if very close
if len(results) > 1 and results[1][1] > 0.25:
second_answer = self.kb_answers[results[1][0]]
# Add a supplementary sentence
extra = self._extract_first_sentence(second_answer)
if extra and extra not in base_answer:
base_answer = base_answer + " " + extra
return base_answer, best_sim, intent
# Medium confidence: augment with n-gram generation
elif best_sim > 0.15:
base_answer = self.kb_answers[best_idx]
seed = ' '.join(clean_q.split()[:3])
generated = self.lm.generate(seed, max_tokens=20, temperature=0.8)
if generated and len(generated) > 10:
return base_answer, best_sim, intent
return base_answer, best_sim, intent
# Low confidence: fallback
else:
return self._fallback(clean_q, intent), 0.0, intent
def _extract_first_sentence(self, text):
parts = re.split(r'(?<=[.!?])\s+', text)
return parts[0] if parts else ""
def _fallback(self, query, intent):
intent_hints = {
"python": "Could you be more specific? I know Python syntax, functions, classes, loops, exceptions, file I/O, decorators, generators, async, and more.",
"data_structure": "I know about stacks, queues, linked lists, trees, graphs, hash tables, and heaps. Try asking about one of those!",
"algorithm": "I can explain sorting, searching, recursion, dynamic programming, and complexity. What specifically are you curious about?",
"ml_ai": "I know about ML, neural networks, deep learning, gradient descent, NLP, transformers, and reinforcement learning. Ask away!",
"web": "I can help with HTML, CSS, JavaScript, HTTP, REST APIs, and web concepts. What would you like to know?",
"database": "I know SQL, NoSQL, indexing, and database design. Try asking 'What is SQL?' or 'What is NoSQL?'",
"system": "I can explain Linux, OS concepts, memory, concurrency, Docker, Git, compilers, and networking.",
"math": "I know calculus, linear algebra, probability, and statistics. What math topic interests you?",
"greeting": "Hello! I'm ChatNix Code. Ask me about Python, algorithms, ML, web dev, databases, or any CS topic!",
"other": f"I'm not sure I have information on '{query}'. I specialize in Python, algorithms, ML/AI, web dev, databases, OS, networking, and math. Try rephrasing!"
}
return intent_hints.get(intent, intent_hints["other"])
# ── Main Chat Interface ────────────────────────────────────────
def _format_response(self, text, intent, sim):
lines = []
words = text.split()
line = ""
for word in words:
if len(line) + len(word) + 1 > 78:
lines.append(line)
line = word
else:
line = (line + " " + word).strip()
if line:
lines.append(line)
return "\n".join(" " + l for l in lines)
def chat(self, user_input):
if not user_input.strip():
return " (empty input β€” ask me anything!)"
# Special commands
cmd = user_input.strip().lower()
if cmd in ("exit", "quit", "q"):
print("\n [ChatNix] Goodbye! Stay curious. πŸ‘‹\n")
sys.exit(0)
if cmd == "history":
if not self.history:
return " No conversation history yet."
out = "\n ── Conversation History ──\n"
for i, (q, _) in enumerate(self.history[-5:], 1):
out += f" {i}. You: {q}\n"
return out
if cmd == "clear":
self.history.clear()
return " [ChatNix] History cleared."
if cmd in ("version", "ver"):
return f" ChatNix Code v{self.version} β€” 100% local, 0% cloud"
response, sim, intent = self._generate_response(user_input)
self.history.append((user_input, response))
return self._format_response(response, intent, sim)
def run(self):
print(" Commands: 'exit' quit Β· 'history' last 5 Β· 'clear' reset Β· 'version'\n")
print("─" * 60)
while True:
try:
user_input = input("\n You Β» ").strip()
print()
t0 = datetime.now()
response = self.chat(user_input)
elapsed = (datetime.now() - t0).total_seconds()
print(f" ChatNix Β»\n{response}")
print(f"\n {'─'*54} {elapsed:.2f}s")
except (KeyboardInterrupt, EOFError):
print("\n\n [ChatNix] Shutting down. Goodbye!\n")
break
# ─────────────────────────────────────────────
# ENTRY POINT
# ─────────────────────────────────────────────
if __name__ == "__main__":
random.seed(42)
np.random.seed(42)
bot = ChatNix()
bot.run()