CUDA28 commited on
Commit
556c1d7
·
1 Parent(s): e53a22f

Initial clean deploy of CppSensei

Browse files
Files changed (10) hide show
  1. .gitignore +4 -0
  2. Dockerfile +13 -0
  3. app.py +130 -0
  4. chatbot.py +92 -0
  5. data/data.txt +169 -0
  6. documents.txt +122 -0
  7. embeddings.py +34 -0
  8. requirements.txt +6 -0
  9. static/favicon.svg +1 -0
  10. templates/index.html +382 -0
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ vector.index
2
+ __pycache__/
3
+ *.pyc
4
+ .env
Dockerfile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY requirements.txt .
6
+
7
+ RUN pip install --no-cache-dir -r requirements.txt
8
+
9
+ COPY . .
10
+
11
+ EXPOSE 7860
12
+
13
+ CMD ["gunicorn", "app:app", "--bind", "0.0.0.0:7860", "--workers", "1"]
app.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ # Auto build FAISS index if not present
4
+ if not os.path.exists("vector.index"):
5
+ print("vector.index not found. Building embeddings...")
6
+ os.system("python embeddings.py")
7
+
8
+ import smtplib
9
+ from email.mime.text import MIMEText
10
+ from flask import Flask, request, jsonify, render_template
11
+
12
+ from sentence_transformers import SentenceTransformer
13
+ import faiss
14
+ import numpy as np
15
+ from transformers import pipeline
16
+
17
+ from dotenv import load_dotenv
18
+ import os
19
+
20
+ app = Flask(__name__)
21
+ load_dotenv()
22
+
23
+ @app.route("/")
24
+ def home():
25
+ return render_template("index.html")
26
+
27
+ print("Loading embedding model...")
28
+ embedder = SentenceTransformer("all-MiniLM-L6-v2")
29
+
30
+ print("Loading vector database...")
31
+ index = faiss.read_index("vector.index")
32
+
33
+ with open("documents.txt", "r", encoding="utf-8") as f:
34
+ documents = [line.strip() for line in f.readlines()]
35
+
36
+ print("Loading language model...")
37
+ qa_model = pipeline(
38
+ "text2text-generation",
39
+ model="google/flan-t5-base",
40
+ max_new_tokens=120
41
+ )
42
+
43
+ def ask_bot(question, top_k=3, similarity_threshold=1.0):
44
+
45
+ greetings = [
46
+ "hi", "hello", "hey", "hii", "hola",
47
+ "good morning", "good evening", "good afternoon"
48
+ ]
49
+
50
+ if question.lower().strip() in greetings:
51
+ return "Hi 👋 I’m your C++ assistant. What’s on your mind today?"
52
+
53
+ # Normal RAG flow
54
+ q_embedding = embedder.encode([question])
55
+ distances, indices = index.search(np.array(q_embedding), top_k)
56
+
57
+ if distances[0][0] > similarity_threshold:
58
+ return "I don't know based on the given data."
59
+
60
+ context = "\n".join([documents[i] for i in indices[0]])
61
+
62
+ prompt = f"""
63
+ Answer the question ONLY using the context below.
64
+ If the answer is not present, reply exactly:
65
+ I don't know based on the given data.
66
+
67
+ Context:
68
+ {context}
69
+
70
+ Question:
71
+ {question}
72
+
73
+ Answer:
74
+ """
75
+
76
+ output = qa_model(prompt)[0]["generated_text"].strip()
77
+ return output
78
+
79
+
80
+ @app.route("/ask", methods=["POST"])
81
+ def ask():
82
+ data = request.json
83
+ question = data.get("question", "")
84
+
85
+ if not question:
86
+ return jsonify({"answer": "Please provide a question."})
87
+
88
+ answer = ask_bot(question)
89
+ return jsonify({"answer": answer})
90
+
91
+
92
+ # -------------------------------
93
+ @app.route("/feedback", methods=["POST"])
94
+ def feedback():
95
+ data = request.json
96
+ message = data.get("feedback", "")
97
+ user_email = data.get("email", "Not provided")
98
+
99
+ YOUR_EMAIL = os.getenv("EMAIL")
100
+ YOUR_APP_PASSWORD = os.getenv("EMAIL_PASSWORD")
101
+
102
+ msg = MIMEText(f"""
103
+ New Feedback Received from C++ Bot 🚀
104
+
105
+ User Email: {user_email}
106
+
107
+ Feedback:
108
+ {message}
109
+ """)
110
+
111
+ msg["Subject"] = "New Feedback from C++ Bot"
112
+ msg["From"] = YOUR_EMAIL
113
+ msg["To"] = YOUR_EMAIL
114
+
115
+ try:
116
+ server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
117
+ server.login(YOUR_EMAIL, YOUR_APP_PASSWORD)
118
+ server.send_message(msg)
119
+ server.quit()
120
+ return jsonify({"status": "success"})
121
+ except Exception as e:
122
+ print("Email error:", e)
123
+ return jsonify({"status": "error"})
124
+
125
+
126
+ import os
127
+
128
+ if __name__ == "__main__":
129
+ port = int(os.environ.get("PORT", 7860))
130
+ app.run(host="0.0.0.0", port=port)
chatbot.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sentence_transformers import SentenceTransformer
2
+ import faiss
3
+ import numpy as np
4
+ from transformers import pipeline
5
+
6
+ # -------------------------------
7
+ # Load embedding model
8
+ # -------------------------------
9
+ print("Loading embedding model...")
10
+ embedder = SentenceTransformer("all-MiniLM-L6-v2")
11
+
12
+ # -------------------------------
13
+ # Load vector database
14
+ # -------------------------------
15
+ print("Loading vector database...")
16
+ index = faiss.read_index("vector.index")
17
+
18
+ # -------------------------------
19
+ # Load stored documents
20
+ # -------------------------------
21
+ with open("documents.txt", "r", encoding="utf-8") as f:
22
+ documents = [line.strip() for line in f.readlines()]
23
+
24
+ # -------------------------------
25
+ # Load language model (correct pipeline)
26
+ # -------------------------------
27
+ print("Loading language model...")
28
+ qa_model = pipeline(
29
+ "text2text-generation",
30
+ model="google/flan-t5-base",
31
+ max_new_tokens=120
32
+ )
33
+
34
+ # -------------------------------
35
+ # Core QA function (SAFE VERSION)
36
+ # -------------------------------
37
+ def ask_bot(question, top_k=3, similarity_threshold=1.0):
38
+ # Embed the question
39
+ q_embedding = embedder.encode([question])
40
+
41
+ # Search similar docs
42
+ distances, indices = index.search(np.array(q_embedding), top_k)
43
+
44
+ # If the closest result is too far → no relevant answer
45
+ if distances[0][0] > similarity_threshold:
46
+ return "I don't know based on the given data."
47
+
48
+ # Retrieve context
49
+ context = "\n".join([documents[i] for i in indices[0]])
50
+
51
+ # Build strict prompt
52
+ prompt = f"""
53
+ You are a domain question answering assistant.
54
+ Use ONLY the context below.
55
+ If the answer is not clearly present in the context, reply exactly:
56
+ I don't know based on the given data.
57
+
58
+ Context:
59
+ {context}
60
+
61
+ Question:
62
+ {question}
63
+
64
+ Answer:
65
+ """
66
+
67
+ # Generate answer
68
+ output = qa_model(prompt)[0]["generated_text"].strip()
69
+
70
+ # Extra safety: if model still copies context, block it
71
+ if output.lower().startswith("flask") or output.lower().startswith("react") or output.lower().startswith("seo"):
72
+ # crude but effective safety fallback
73
+ if question.lower() not in context.lower():
74
+ return "I don't know based on the given data."
75
+
76
+ return output
77
+
78
+
79
+ # -------------------------------
80
+ # Chat loop
81
+ # -------------------------------
82
+ print("\nAI Agent ready. Type 'exit' to quit.\n")
83
+
84
+ while True:
85
+ question = input("Ask: ")
86
+
87
+ if question.lower() in ["exit", "quit"]:
88
+ print("Goodbye!")
89
+ break
90
+
91
+ answer = ask_bot(question)
92
+ print("\nBot:", answer, "\n")
data/data.txt ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ C++ is a general purpose programming language developed by Bjarne Stroustrup as an extension of the C language.
2
+ C++ supports procedural programming, object oriented programming, and generic programming.
3
+ C++ is widely used in system programming, game development, embedded systems, and competitive programming.
4
+
5
+ A variable in C++ is a named memory location used to store data.
6
+ Common data types in C++ include int, float, double, char, and bool.
7
+ The size of an int is typically 4 bytes on most systems.
8
+
9
+ The const keyword is used to declare variables whose values cannot be changed.
10
+ The auto keyword allows the compiler to deduce the type of a variable automatically.
11
+
12
+ Operators in C++ include arithmetic, relational, logical, bitwise, assignment, and conditional operators.
13
+ Arithmetic operators perform addition, subtraction, multiplication, division, and modulus operations.
14
+
15
+ Control statements include if, else, switch, for, while, and do while.
16
+ The break statement terminates a loop or switch statement.
17
+ The continue statement skips the current iteration of a loop.
18
+
19
+ A function is a block of code that performs a specific task.
20
+ The main function is the entry point of a C++ program.
21
+ Function overloading allows multiple functions with the same name but different parameters.
22
+
23
+ An array is a collection of elements of the same data type stored in contiguous memory locations.
24
+ Array indexing in C++ starts from zero.
25
+ A multidimensional array is an array of arrays.
26
+
27
+ A pointer is a variable that stores the memory address of another variable.
28
+ The address-of operator is represented by the ampersand symbol.
29
+ The dereference operator is represented by the asterisk symbol.
30
+ A null pointer does not point to any valid memory location.
31
+
32
+ Dynamic memory allocation is performed using new and delete operators.
33
+ The new operator allocates memory on the heap.
34
+ The delete operator deallocates memory previously allocated with new.
35
+
36
+ A reference is an alias for an existing variable and must be initialized at declaration.
37
+ References cannot be reassigned after initialization.
38
+
39
+ A structure is a user defined data type that groups variables of different data types.
40
+ Members of a structure are accessed using the dot operator.
41
+
42
+ A class is a blueprint for creating objects.
43
+ An object is an instance of a class.
44
+ Access specifiers include public, private, and protected.
45
+
46
+ Encapsulation binds data and methods together and hides implementation details.
47
+ Abstraction exposes only essential features and hides complex implementation.
48
+ Inheritance allows a class to derive properties and methods from another class.
49
+ Polymorphism allows the same function to behave differently in different contexts.
50
+
51
+ A constructor is a special member function called when an object is created.
52
+ A destructor is a special member function called when an object is destroyed.
53
+ Constructors do not have a return type and have the same name as the class.
54
+
55
+ The this pointer holds the address of the current object.
56
+ Static data members are shared among all objects of a class.
57
+
58
+ A virtual function supports runtime polymorphism.
59
+ A base class pointer can point to a derived class object.
60
+
61
+ The Standard Template Library provides containers, algorithms, and iterators.
62
+ Common STL containers include vector, list, deque, stack, queue, priority_queue, set, map, and unordered_map.
63
+
64
+ A vector is a dynamic array that resizes automatically.
65
+ A list is a doubly linked list implementation.
66
+ A deque allows insertion and deletion at both ends.
67
+
68
+ A stack is a linear data structure that follows the Last In First Out principle.
69
+ Common stack operations include push, pop, top, and isEmpty.
70
+ A queue is a linear data structure that follows the First In First Out principle.
71
+ Common queue operations include enqueue, dequeue, front, and rear.
72
+
73
+ A priority queue stores elements such that the highest priority element is removed first.
74
+ A circular queue connects the end of the queue back to the front.
75
+
76
+ A linked list is a linear data structure where elements are connected using pointers.
77
+ A singly linked list contains nodes with data and a pointer to the next node.
78
+ A doubly linked list contains pointers to both next and previous nodes.
79
+ A circular linked list connects the last node back to the first node.
80
+
81
+ A tree is a hierarchical data structure consisting of nodes and edges.
82
+ The root is the topmost node in a tree.
83
+ A binary tree is a tree where each node has at most two children.
84
+ A binary search tree stores elements such that left subtree values are smaller and right subtree values are larger.
85
+
86
+ Tree traversal methods include inorder, preorder, and postorder traversal.
87
+ A heap is a complete binary tree that satisfies the heap property.
88
+ A max heap stores the largest element at the root.
89
+ A min heap stores the smallest element at the root.
90
+
91
+ A graph is a collection of vertices and edges.
92
+ Graphs can be directed or undirected.
93
+ Graph traversal methods include breadth first search and depth first search.
94
+
95
+ Searching algorithms include linear search and binary search.
96
+ Sorting algorithms include bubble sort, selection sort, insertion sort, merge sort, quick sort, and heap sort.
97
+
98
+ The time complexity of binary search is O(log n).
99
+ The time complexity of merge sort is O(n log n).
100
+
101
+ An iterator is an object used to traverse elements of a container.
102
+ The begin function returns an iterator to the first element.
103
+ The end function returns an iterator to one past the last element.
104
+
105
+ The string class stores sequences of characters.
106
+ The length of a string can be obtained using size or length functions.
107
+
108
+ Exception handling uses try, catch, and throw keywords.
109
+ An exception represents an error condition during program execution.
110
+
111
+ File handling is performed using ifstream, ofstream, and fstream classes.
112
+ The ifstream class reads from files.
113
+ The ofstream class writes to files.
114
+
115
+ Templates allow writing generic functions and classes.
116
+ A function template defines a generic function.
117
+ A class template defines a generic class.
118
+
119
+ Namespaces prevent name conflicts in large programs.
120
+ The std namespace contains standard library identifiers.
121
+
122
+ Inline functions reduce function call overhead by expanding code at the call site.
123
+ The mutable keyword allows modification of class members in const functions.
124
+
125
+ The sizeof operator returns the size of a variable or data type in bytes.
126
+ The typedef keyword creates an alias for an existing data type.
127
+
128
+ The volatile keyword indicates that a variable may change unexpectedly.
129
+ The friend keyword allows access to private members of a class.
130
+
131
+ Lambda expressions are anonymous functions introduced in C++11.
132
+ Smart pointers include unique_ptr, shared_ptr, and weak_ptr.
133
+ RAII ensures resource acquisition and release using object lifetime.
134
+
135
+ Move semantics transfers resources efficiently using move constructors.
136
+ The std::move function converts an lvalue into an rvalue reference.
137
+
138
+ The constexpr keyword evaluates expressions at compile time.
139
+ The nullptr keyword represents a null pointer constant.
140
+
141
+ Enum class provides scoped and strongly typed enumerations.
142
+ The using keyword creates type aliases and imports names.
143
+
144
+ The iostream library provides input and output using cin and cout.
145
+ The endl manipulator inserts a newline and flushes the output buffer.
146
+
147
+ The compilation process includes preprocessing, compilation, linking, and execution.
148
+ The linker combines object files and resolves references.
149
+
150
+ Multiple inheritance allows a class to inherit from multiple base classes.
151
+ Virtual inheritance avoids duplication in diamond inheritance problems.
152
+
153
+ A pure virtual function makes a class abstract.
154
+ An abstract class cannot be instantiated.
155
+
156
+ The static_cast operator performs compile time type conversion.
157
+ The dynamic_cast operator performs runtime type checking.
158
+
159
+ Const correctness prevents modification of data using const qualifiers.
160
+
161
+ The thread library provides multithreading support.
162
+ A mutex protects shared data from concurrent access.
163
+ The lock_guard class manages mutex locking automatically.
164
+
165
+ The chrono library measures time and durations.
166
+ The filesystem library performs file system operations.
167
+
168
+ Fast input output techniques improve competitive programming performance.
169
+ The ios_base::sync_with_stdio function disables synchronization with C IO for faster execution.
documents.txt ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ C++ is a general purpose programming language developed by Bjarne Stroustrup as an extension of the C language.
2
+ C++ supports procedural programming, object oriented programming, and generic programming.
3
+ C++ is widely used in system programming, game development, embedded systems, and competitive programming.
4
+ A variable in C++ is a named memory location used to store data.
5
+ Common data types in C++ include int, float, double, char, and bool.
6
+ The size of an int is typically 4 bytes on most systems.
7
+ The const keyword is used to declare variables whose values cannot be changed.
8
+ The auto keyword allows the compiler to deduce the type of a variable automatically.
9
+ Operators in C++ include arithmetic, relational, logical, bitwise, assignment, and conditional operators.
10
+ Arithmetic operators perform addition, subtraction, multiplication, division, and modulus operations.
11
+ Control statements include if, else, switch, for, while, and do while.
12
+ The break statement terminates a loop or switch statement.
13
+ The continue statement skips the current iteration of a loop.
14
+ A function is a block of code that performs a specific task.
15
+ The main function is the entry point of a C++ program.
16
+ Function overloading allows multiple functions with the same name but different parameters.
17
+ An array is a collection of elements of the same data type stored in contiguous memory locations.
18
+ Array indexing in C++ starts from zero.
19
+ A multidimensional array is an array of arrays.
20
+ A pointer is a variable that stores the memory address of another variable.
21
+ The address-of operator is represented by the ampersand symbol.
22
+ The dereference operator is represented by the asterisk symbol.
23
+ A null pointer does not point to any valid memory location.
24
+ Dynamic memory allocation is performed using new and delete operators.
25
+ The new operator allocates memory on the heap.
26
+ The delete operator deallocates memory previously allocated with new.
27
+ A reference is an alias for an existing variable and must be initialized at declaration.
28
+ References cannot be reassigned after initialization.
29
+ A structure is a user defined data type that groups variables of different data types.
30
+ Members of a structure are accessed using the dot operator.
31
+ A class is a blueprint for creating objects.
32
+ An object is an instance of a class.
33
+ Access specifiers include public, private, and protected.
34
+ Encapsulation binds data and methods together and hides implementation details.
35
+ Abstraction exposes only essential features and hides complex implementation.
36
+ Inheritance allows a class to derive properties and methods from another class.
37
+ Polymorphism allows the same function to behave differently in different contexts.
38
+ A constructor is a special member function called when an object is created.
39
+ A destructor is a special member function called when an object is destroyed.
40
+ Constructors do not have a return type and have the same name as the class.
41
+ The this pointer holds the address of the current object.
42
+ Static data members are shared among all objects of a class.
43
+ A virtual function supports runtime polymorphism.
44
+ A base class pointer can point to a derived class object.
45
+ The Standard Template Library provides containers, algorithms, and iterators.
46
+ Common STL containers include vector, list, deque, stack, queue, priority_queue, set, map, and unordered_map.
47
+ A vector is a dynamic array that resizes automatically.
48
+ A list is a doubly linked list implementation.
49
+ A deque allows insertion and deletion at both ends.
50
+ A stack is a linear data structure that follows the Last In First Out principle.
51
+ Common stack operations include push, pop, top, and isEmpty.
52
+ A queue is a linear data structure that follows the First In First Out principle.
53
+ Common queue operations include enqueue, dequeue, front, and rear.
54
+ A priority queue stores elements such that the highest priority element is removed first.
55
+ A circular queue connects the end of the queue back to the front.
56
+ A linked list is a linear data structure where elements are connected using pointers.
57
+ A singly linked list contains nodes with data and a pointer to the next node.
58
+ A doubly linked list contains pointers to both next and previous nodes.
59
+ A circular linked list connects the last node back to the first node.
60
+ A tree is a hierarchical data structure consisting of nodes and edges.
61
+ The root is the topmost node in a tree.
62
+ A binary tree is a tree where each node has at most two children.
63
+ A binary search tree stores elements such that left subtree values are smaller and right subtree values are larger.
64
+ Tree traversal methods include inorder, preorder, and postorder traversal.
65
+ A heap is a complete binary tree that satisfies the heap property.
66
+ A max heap stores the largest element at the root.
67
+ A min heap stores the smallest element at the root.
68
+ A graph is a collection of vertices and edges.
69
+ Graphs can be directed or undirected.
70
+ Graph traversal methods include breadth first search and depth first search.
71
+ Searching algorithms include linear search and binary search.
72
+ Sorting algorithms include bubble sort, selection sort, insertion sort, merge sort, quick sort, and heap sort.
73
+ The time complexity of binary search is O(log n).
74
+ The time complexity of merge sort is O(n log n).
75
+ An iterator is an object used to traverse elements of a container.
76
+ The begin function returns an iterator to the first element.
77
+ The end function returns an iterator to one past the last element.
78
+ The string class stores sequences of characters.
79
+ The length of a string can be obtained using size or length functions.
80
+ Exception handling uses try, catch, and throw keywords.
81
+ An exception represents an error condition during program execution.
82
+ File handling is performed using ifstream, ofstream, and fstream classes.
83
+ The ifstream class reads from files.
84
+ The ofstream class writes to files.
85
+ Templates allow writing generic functions and classes.
86
+ A function template defines a generic function.
87
+ A class template defines a generic class.
88
+ Namespaces prevent name conflicts in large programs.
89
+ The std namespace contains standard library identifiers.
90
+ Inline functions reduce function call overhead by expanding code at the call site.
91
+ The mutable keyword allows modification of class members in const functions.
92
+ The sizeof operator returns the size of a variable or data type in bytes.
93
+ The typedef keyword creates an alias for an existing data type.
94
+ The volatile keyword indicates that a variable may change unexpectedly.
95
+ The friend keyword allows access to private members of a class.
96
+ Lambda expressions are anonymous functions introduced in C++11.
97
+ Smart pointers include unique_ptr, shared_ptr, and weak_ptr.
98
+ RAII ensures resource acquisition and release using object lifetime.
99
+ Move semantics transfers resources efficiently using move constructors.
100
+ The std::move function converts an lvalue into an rvalue reference.
101
+ The constexpr keyword evaluates expressions at compile time.
102
+ The nullptr keyword represents a null pointer constant.
103
+ Enum class provides scoped and strongly typed enumerations.
104
+ The using keyword creates type aliases and imports names.
105
+ The iostream library provides input and output using cin and cout.
106
+ The endl manipulator inserts a newline and flushes the output buffer.
107
+ The compilation process includes preprocessing, compilation, linking, and execution.
108
+ The linker combines object files and resolves references.
109
+ Multiple inheritance allows a class to inherit from multiple base classes.
110
+ Virtual inheritance avoids duplication in diamond inheritance problems.
111
+ A pure virtual function makes a class abstract.
112
+ An abstract class cannot be instantiated.
113
+ The static_cast operator performs compile time type conversion.
114
+ The dynamic_cast operator performs runtime type checking.
115
+ Const correctness prevents modification of data using const qualifiers.
116
+ The thread library provides multithreading support.
117
+ A mutex protects shared data from concurrent access.
118
+ The lock_guard class manages mutex locking automatically.
119
+ The chrono library measures time and durations.
120
+ The filesystem library performs file system operations.
121
+ Fast input output techniques improve competitive programming performance.
122
+ The ios_base::sync_with_stdio function disables synchronization with C IO for faster execution.
embeddings.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sentence_transformers import SentenceTransformer
2
+ import faiss
3
+ import numpy as np
4
+ import os
5
+
6
+ # Load embedding model
7
+ print("Loading embedding model...")
8
+ model = SentenceTransformer("all-MiniLM-L6-v2")
9
+
10
+ # Load training data
11
+ data_path = "data/data.txt"
12
+
13
+ with open(data_path, "r", encoding="utf-8") as f:
14
+ documents = [line.strip() for line in f.readlines() if line.strip()]
15
+
16
+ print(f"Loaded {len(documents)} documents")
17
+
18
+ # Create embeddings
19
+ print("Creating embeddings...")
20
+ embeddings = model.encode(documents)
21
+
22
+ # Create FAISS index
23
+ dimension = embeddings.shape[1]
24
+ index = faiss.IndexFlatL2(dimension)
25
+ index.add(np.array(embeddings))
26
+
27
+ # Save index and documents
28
+ faiss.write_index(index, "vector.index")
29
+
30
+ with open("documents.txt", "w", encoding="utf-8") as f:
31
+ for doc in documents:
32
+ f.write(doc + "\n")
33
+
34
+ print("Vector database created successfully!")
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ sentence-transformers
2
+ faiss-cpu
3
+ python-dotenv
4
+ transformers
5
+ torch
6
+ gunicorn
static/favicon.svg ADDED
templates/index.html ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>CPP Bot</title>
7
+ <link rel="icon" type="image/svg+xml" href="{{ url_for('static', filename='favicon.svg') }}">
8
+ <link rel="alternate icon" href="{{ url_for('static', filename='favicon.ico') }}">
9
+ <link rel="apple-touch-icon" href="{{ url_for('static', filename='favicon.png') }}">
10
+
11
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap" rel="stylesheet">
12
+
13
+ <style>
14
+ * { box-sizing: border-box; font-family: "Inter", sans-serif; }
15
+
16
+ body {
17
+ margin: 0;
18
+ height: 100vh;
19
+ background: radial-gradient(circle at top, #0f172a, #020617);
20
+ display: flex;
21
+ justify-content: center;
22
+ align-items: center;
23
+ overflow: hidden;
24
+ color: #e5e7eb;
25
+ }
26
+
27
+ .card {
28
+ width: 420px;
29
+ height: 620px;
30
+ background: rgba(2, 6, 23, 0.88);
31
+ border-radius: 20px;
32
+ box-shadow: 0 30px 80px rgba(0, 0, 0, 0.6);
33
+ display: flex;
34
+ flex-direction: column;
35
+ overflow: hidden;
36
+ border: 1px solid rgba(148, 163, 184, 0.15);
37
+ backdrop-filter: blur(12px);
38
+ position: relative;
39
+ }
40
+
41
+ /* Header */
42
+ .header {
43
+ padding: 16px 20px;
44
+ background: linear-gradient(135deg, #38bdf8, #818cf8);
45
+ color: #020617;
46
+ font-weight: 800;
47
+ font-size: 1.4rem;
48
+ letter-spacing: 0.5px;
49
+ display: flex;
50
+ justify-content: space-between;
51
+ align-items: center;
52
+ }
53
+
54
+ .subtitle {
55
+ font-size: 0.75rem;
56
+ font-weight: 500;
57
+ opacity: 0.8;
58
+ margin-top: 2px;
59
+ }
60
+
61
+ .clear-btn {
62
+ background: none;
63
+ border: none;
64
+ font-size: 1.3rem;
65
+ cursor: pointer;
66
+ color: #020617;
67
+ }
68
+
69
+ /* Chat area */
70
+ #messages {
71
+ flex: 1;
72
+ padding: 20px;
73
+ overflow-y: auto;
74
+ display: flex;
75
+ flex-direction: column;
76
+ gap: 12px;
77
+ }
78
+
79
+ /* Message bubbles */
80
+ .bubble {
81
+ max-width: 80%;
82
+ padding: 12px 14px;
83
+ border-radius: 14px;
84
+ line-height: 1.4;
85
+ animation: fadeIn 0.3s ease;
86
+ }
87
+
88
+ .user {
89
+ align-self: flex-end;
90
+ background: linear-gradient(135deg, #38bdf8, #60a5fa);
91
+ color: #020617;
92
+ border-bottom-right-radius: 4px;
93
+ }
94
+
95
+ .bot {
96
+ align-self: flex-start;
97
+ background: #0f172a;
98
+ color: #a7f3d0;
99
+ border: 1px solid rgba(148, 163, 184, 0.15);
100
+ border-bottom-left-radius: 4px;
101
+ }
102
+
103
+ /* Input bar */
104
+ .input-bar {
105
+ display: flex;
106
+ padding: 14px;
107
+ border-top: 1px solid rgba(148, 163, 184, 0.15);
108
+ background: rgba(2, 6, 23, 0.95);
109
+ }
110
+
111
+ .input-bar input {
112
+ flex: 1;
113
+ padding: 10px 12px;
114
+ border-radius: 10px;
115
+ border: none;
116
+ outline: none;
117
+ background: #020617;
118
+ color: white;
119
+ font-size: 0.95rem;
120
+ }
121
+
122
+ .input-bar button {
123
+ margin-left: 10px;
124
+ padding: 10px 16px;
125
+ border-radius: 10px;
126
+ border: none;
127
+ cursor: pointer;
128
+ background: linear-gradient(135deg, #38bdf8, #818cf8);
129
+ color: #020617;
130
+ font-weight: 600;
131
+ transition: transform 0.2s ease, box-shadow 0.2s ease;
132
+ }
133
+
134
+ .input-bar button:hover {
135
+ transform: translateY(-2px);
136
+ box-shadow: 0 6px 20px rgba(56, 189, 248, 0.5);
137
+ }
138
+
139
+ /* Footer */
140
+ .footer {
141
+ padding: 10px 14px;
142
+ display: flex;
143
+ justify-content: space-between;
144
+ align-items: center;
145
+ border-top: 1px solid rgba(148, 163, 184, 0.15);
146
+ background: rgba(2, 6, 23, 0.95);
147
+ font-size: 0.75rem;
148
+ }
149
+
150
+ .footer button {
151
+ background: none;
152
+ border: none;
153
+ color: #93c5fd;
154
+ cursor: pointer;
155
+ margin-right: 10px;
156
+ }
157
+
158
+ .footer button:hover { text-decoration: underline; }
159
+
160
+ /* Buy Me a Coffee */
161
+ .coffee {
162
+ position: fixed;
163
+ bottom: 20px;
164
+ right: 20px;
165
+ background: #facc15;
166
+ color: #020617;
167
+ padding: 12px 16px;
168
+ border-radius: 30px;
169
+ font-weight: 700;
170
+ text-decoration: none;
171
+ box-shadow: 0 10px 30px rgba(250, 204, 21, 0.5);
172
+ transition: transform 0.2s ease;
173
+ z-index: 999;
174
+ }
175
+
176
+ .coffee:hover { transform: translateY(-3px) scale(1.05); }
177
+
178
+ /* Modals */
179
+ .modal {
180
+ position: fixed;
181
+ inset: 0;
182
+ background: rgba(0, 0, 0, 0.6);
183
+ display: none;
184
+ justify-content: center;
185
+ align-items: center;
186
+ z-index: 1000;
187
+ }
188
+
189
+ .modal-content {
190
+ width: 360px;
191
+ background: #020617;
192
+ padding: 20px;
193
+ border-radius: 14px;
194
+ border: 1px solid rgba(148, 163, 184, 0.2);
195
+ position: relative;
196
+ }
197
+
198
+ .close-modal {
199
+ position: absolute;
200
+ top: 10px;
201
+ right: 12px;
202
+ background: none;
203
+ border: none;
204
+ font-size: 1.2rem;
205
+ cursor: pointer;
206
+ color: #93c5fd;
207
+ }
208
+
209
+ .modal-content h3 { margin-top: 0; color: #38bdf8; }
210
+
211
+ .modal-content textarea,
212
+ .modal-content input {
213
+ width: 100%;
214
+ margin-top: 10px;
215
+ padding: 8px;
216
+ border-radius: 6px;
217
+ border: none;
218
+ outline: none;
219
+ background: #0f172a;
220
+ color: white;
221
+ }
222
+
223
+ .modal-content button.submit-btn {
224
+ margin-top: 12px;
225
+ padding: 8px 14px;
226
+ border-radius: 8px;
227
+ border: none;
228
+ cursor: pointer;
229
+ background: linear-gradient(135deg, #38bdf8, #818cf8);
230
+ color: #020617;
231
+ font-weight: 600;
232
+ }
233
+
234
+ @keyframes fadeIn {
235
+ from { opacity: 0; transform: translateY(4px); }
236
+ to { opacity: 1; transform: translateY(0); }
237
+ }
238
+ </style>
239
+ </head>
240
+ <body>
241
+
242
+ <div class="card">
243
+
244
+ <div class="header">
245
+ <div>
246
+ C++ Bot
247
+ <div class="subtitle">Domain‑Trained C++ AI Assistant</div>
248
+ </div>
249
+ <button class="clear-btn" onclick="clearChat()" title="Clear chat">🗑️</button>
250
+ </div>
251
+
252
+ <div id="messages"></div>
253
+
254
+ <div class="input-bar">
255
+ <input id="question" placeholder="Ask a C++ question…" />
256
+ <button onclick="sendQuestion()">Send</button>
257
+ </div>
258
+
259
+ <div class="footer">
260
+ <div>
261
+ <button onclick="openAbout()">About</button>
262
+ <button onclick="openFeedback()">Feedback</button>
263
+ </div>
264
+ <div>© 2026 C++ Bot</div>
265
+ </div>
266
+
267
+ </div>
268
+
269
+ <!-- Buy Me a Coffee -->
270
+ <a class="coffee" href="https://buymeacoffee.com/siddharthmishra?status=1" target="_blank">☕ Buy me a coffee</a>
271
+
272
+ <!-- About Modal -->
273
+ <div class="modal" id="aboutModal" onclick="backdropClose(event, 'aboutModal')">
274
+ <div class="modal-content">
275
+ <button class="close-modal" onclick="closeAbout()">✖</button>
276
+ <h3>About C++ Bot</h3>
277
+ <p>This is a domain‑trained AI assistant built using Retrieval Augmented Generation with FAISS, Transformers, and Flask. It answers only from a curated C++ knowledge base.</p>
278
+ </div>
279
+ </div>
280
+
281
+ <!-- Feedback Modal -->
282
+ <div class="modal" id="feedbackModal" onclick="backdropClose(event, 'feedbackModal')">
283
+ <div class="modal-content">
284
+ <button class="close-modal" onclick="closeFeedback()">✖</button>
285
+ <h3>Send Feedback</h3>
286
+ <input id="email" placeholder="Your email (optional)" />
287
+ <textarea id="feedback" rows="5" placeholder="Your suggestion or feedback..."></textarea>
288
+ <button class="submit-btn" onclick="submitFeedback()">Submit</button>
289
+ </div>
290
+ </div>
291
+
292
+ <script>
293
+ const messages = document.getElementById("messages");
294
+ const input = document.getElementById("question");
295
+
296
+ input.addEventListener("keydown", function (e) {
297
+ if (e.key === "Enter") sendQuestion();
298
+ });
299
+
300
+ document.addEventListener("keydown", function (e) {
301
+ if (e.key === "Escape") {
302
+ closeAbout();
303
+ closeFeedback();
304
+ }
305
+ });
306
+
307
+ function addMessage(text, type) {
308
+ const div = document.createElement("div");
309
+ div.className = `bubble ${type}`;
310
+ div.textContent = text;
311
+ messages.appendChild(div);
312
+ messages.scrollTop = messages.scrollHeight;
313
+ }
314
+
315
+ function clearChat() {
316
+ if (confirm("Clear the chat?")) {
317
+ messages.innerHTML = "";
318
+ }
319
+ }
320
+
321
+ async function sendQuestion() {
322
+ const question = input.value.trim();
323
+ if (!question) return;
324
+
325
+ addMessage(question, "user");
326
+ input.value = "";
327
+
328
+ const typing = document.createElement("div");
329
+ typing.className = "bubble bot";
330
+ typing.textContent = "AI is thinking…";
331
+ messages.appendChild(typing);
332
+ messages.scrollTop = messages.scrollHeight;
333
+
334
+ try {
335
+ const response = await fetch("/ask", {
336
+ method: "POST",
337
+ headers: { "Content-Type": "application/json" },
338
+ body: JSON.stringify({ question })
339
+ });
340
+
341
+ const data = await response.json();
342
+ messages.removeChild(typing);
343
+ addMessage(data.answer, "bot");
344
+
345
+ } catch (error) {
346
+ messages.removeChild(typing);
347
+ addMessage("Server error. Please try again.", "bot");
348
+ }
349
+ }
350
+
351
+ function openAbout() { document.getElementById("aboutModal").style.display = "flex"; }
352
+ function closeAbout() { document.getElementById("aboutModal").style.display = "none"; }
353
+ function openFeedback() { document.getElementById("feedbackModal").style.display = "flex"; }
354
+ function closeFeedback() { document.getElementById("feedbackModal").style.display = "none"; }
355
+
356
+ function backdropClose(event, modalId) {
357
+ if (event.target.id === modalId) {
358
+ document.getElementById(modalId).style.display = "none";
359
+ }
360
+ }
361
+
362
+ async function submitFeedback() {
363
+ const feedback = document.getElementById("feedback").value;
364
+ const email = document.getElementById("email").value;
365
+
366
+ if (!feedback) return alert("Please write some feedback first.");
367
+
368
+ await fetch("/feedback", {
369
+ method: "POST",
370
+ headers: { "Content-Type": "application/json" },
371
+ body: JSON.stringify({ feedback, email })
372
+ });
373
+
374
+ alert("Thank you for your feedback! 💙");
375
+ document.getElementById("feedback").value = "";
376
+ document.getElementById("email").value = "";
377
+ closeFeedback();
378
+ }
379
+ </script>
380
+
381
+ </body>
382
+ </html>