""" ╔═══════════════════════════════════════════════════════════════╗ ║ 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 , , ,
,

, , ,

. HTML5 added semantic tags:
,