-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
518 lines (446 loc) · 21.6 KB
/
Copy pathapp.py
File metadata and controls
518 lines (446 loc) · 21.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
import streamlit as st
import json
import os
import re
import joblib
import numpy as np
from fuzzywuzzy import fuzz
from dotenv import load_dotenv
from sklearn.metrics.pairwise import cosine_similarity
from sentence_transformers import SentenceTransformer
from openai import OpenAI
import gspread
import uuid
from datetime import datetime
import time
import spacy
# ----------------- DATABASE SETUP (Google Sheets Version) -----------------
@st.cache_resource
def init_db():
"""Initializes the connection to the Google Sheet."""
# Authenticate using Streamlit's secrets, which you set up in secrets.toml
gc = gspread.service_account_from_dict(st.secrets["gcp_service_account"])
# Open the sheet by its exact name
spreadsheet = gc.open("Chatbot Logs") # <-- Make sure this name matches your Google Sheet's name
# Select the first worksheet
worksheet = spreadsheet.sheet1
return worksheet
# Initialize the connection
worksheet = init_db()
def log_interaction(session_id, query, response, source, response_time_ms):
"""Appends a single interaction as a new row in the Google Sheet."""
try:
# Format the timestamp into a string to avoid timezone issues
timestamp_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Get the current number of rows to create a simple ID
num_rows = len(worksheet.get_all_values())
new_row = [
num_rows, # Simple ID, starting from 0
session_id,
timestamp_str,
query,
response,
source,
response_time_ms
]
# Append the new row to the sheet
worksheet.append_row(new_row, value_input_option='USER_ENTERED')
except Exception as e:
st.error(f"Google Sheets logging failed: {e}")
# ----------------- CONFIG -----------------
st.set_page_config(page_title="Nayan’s AI Chatbot", layout="centered")
# Load environment variable (GitHub Token)
load_dotenv()
token = os.getenv("GITHUB_TOKEN")
# OpenAI client (GPT-4o via GitHub)
client = OpenAI(
base_url="https://models.github.ai/inference",
api_key=token,
)
chat_model = "openai/gpt-4o"
# ----------------- LOAD DATA -----------------
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(BASE_DIR, "fallback_qna.json"), "r", encoding="utf-8") as f:
fallback_data = json.load(f)
fallback_embeddings = joblib.load(os.path.join(BASE_DIR, "fallback_embeddings.pkl"))
@st.cache_resource
def load_embedder():
return SentenceTransformer("BAAI/bge-small-en", device="cpu")
embedder = load_embedder()
@st.cache_resource
def load_spacy_model():
return spacy.load("en_core_web_sm")
nlp = load_spacy_model()
# Define the valid parts of your name at a broader scope
VALID_NAME_PARTS = {"nayan", "reddy", "soma"}
def contains_other_person_name(text, nlp_model):
"""
Checks if the text contains a person's name that isn't related to Your name.
"""
doc = nlp_model(text.lower())
for ent in doc.ents:
# Check if the entity is a person
if ent.label_ == "PERSON":
entity_text = ent.text
# Check if the found name contains any part of your full name
is_relevant_person = any(part in entity_text for part in VALID_NAME_PARTS)
# If the person is not relevant, it's someone else
if not is_relevant_person:
return True
return False
# ----------------- CLEAN + FILTER -----------------
def clean(text):
return re.sub(r"[^\w\s]", "", text.lower().replace("’", "'").strip())
SENSITIVE_KEYWORDS = set([
"gay", "sexuality", "husband", "wife", "sex", "sex life","children", "virgin",
"boyfriend", "mental", "asshole", "bitch", "chutiya", "motherfucker", "mf",
"religion", "caste", "photo", "picture", "handsome", "ugly", "appearance",
"politics", "weekend", "saturday", "sunday", "vacation", "gym", "body", "six pack",
"weight", "shirtless", "personal", "intimate"
])
def is_sensitive(user_input):
cleaned_input = clean(user_input)
return any(keyword in cleaned_input for keyword in SENSITIVE_KEYWORDS)
def sensitive_reply(user_input):
cleaned = clean(user_input)
if "gender" in cleaned:
return "Nayan is male."
elif "married" in cleaned or "wife" in cleaned or "husband" in cleaned or "children" in cleaned:
return "Nayan is unmarried and has no children."
elif "photo" in cleaned or "picture" in cleaned:
return "There’s no photo available here, but I’d be happy to walk you through his professional journey."
else:
return "Let’s stay focused on Nayan’s professional background. Feel free to ask anything about his work, projects, or skills!"
# ----------------- FALLBACK MATCH -----------------
def get_best_fallback(user_input, nlp_model):
user_clean = clean(user_input)
if contains_other_person_name(user_input, nlp_model):
return None
user_vector = embedder.encode([user_clean], convert_to_tensor=True)[0]
best_sim = 0
best_answer = None
matched_question = None
for q, vec, ans in fallback_embeddings:
sim = cosine_similarity([user_vector.cpu().numpy()], [vec])[0][0]
if sim > best_sim:
best_sim, best_answer, matched_question = sim, ans, q
if best_sim >= 0.87:
user_words = set(user_clean.split())
if not user_words:
return None
match_words = set(clean(matched_question).split())
common_words = user_words.intersection(match_words)
# Calculate the overlap ratio
overlap_ratio = len(common_words) / len(user_words)
# Only return a match if the user's query is almost entirely covered by the fallback
if overlap_ratio >= 0.8:
return best_answer
best_fuzzy_score = 0
fuzzy_answer = None
for item in fallback_data:
for q in item["questions"]:
score = fuzz.token_sort_ratio(user_clean, clean(q))
if user_clean in clean(q) or clean(q) in user_clean: score += 15
if score > best_fuzzy_score:
best_fuzzy_score, fuzzy_answer = score, item["answer"]
if best_fuzzy_score >= 90: return fuzzy_answer
return None
st.markdown("""
<style>
body {
font-family: 'Segoe UI', sans-serif;
}
h1 {
color: #10b981;
text-align: center;
margin-bottom: 0;
}
.subheader {
text-align: center;
font-size: 18px;
margin-top: 0;
margin-bottom: 30px;
}
/* --- CHAT BUBBLE STYLES --- */
.user-bubble {
background-color: #10b981;
color: white;
padding: 12px 16px;
border-radius: 12px;
margin: 20px 0 10px auto;
max-width: 80%;
text-align: right;
}
.bot-bubble {
padding: 12px 16px;
border-radius: 12px;
margin: 10px 0 30px 0;
max-width: 80%;
text-align: left;
line-height: 1.6;
}
.stButton button {
background-color: #10b981;
color: white;
border-radius: 24px;
padding: 10px 24px;
font-weight: bold;
border: none;
}
/* --- LIGHT THEME STYLES (DEFAULT) --- */
.subheader, .prompt-suggestions {
color: #4a5568;
}
.bot-bubble {
background-color: #f0f2f6;
color: #1a202c;
}
.prompt-suggestions {
text-align: center;
margin-bottom: 25px;
font-size: 15px;
}
hr {
border-top: 1px solid #e2e8f0;
}
/* --- DARK THEME STYLES --- */
[data-theme="dark"] .subheader, [data-theme="dark"] .prompt-suggestions {
color: #c9d1d9;
}
[data-theme="dark"] .bot-bubble {
background-color: rgba(0,0,0,0);
color: #ffffff;
}
[data-theme="dark"] hr {
border-top: 1px solid #30363d;
}
</style>
""", unsafe_allow_html=True)
# Header
st.markdown("<h1 style='color: #10b981;'>🤖 Hi, I'm Nayan’s AI Assistant</h1>", unsafe_allow_html=True)
st.markdown('<div class="subheader">Ask me anything about Nayan and his work!</div>', unsafe_allow_html=True)
# ----------------- SESSION -----------------
if "session_id" not in st.session_state:
st.session_state.session_id = str(uuid.uuid4())
if "messages" not in st.session_state:
st.session_state.messages = [{
"role": "system",
"content": (
"You are Nayan’s AI Assistant. You represent Nayan Reddy Soma — a data enthusiast, analyst, and project-driven learner. "
"Answer every question on his behalf in a professional, friendly, and recruiter-friendly tone.\n\n"
"**Personal Information**:\n"
"• Full Name: Nayan Reddy Soma\n"
"• DOB: 19 May 2002\n"
"• Gender: Male\n"
"• Native: Adilabad, Telangana\n"
"• Father's Name: Lacha Reddy (English Teacher)\n"
"• Mother's Name: Pavani Reddy (Government Employee)\n"
"• Marital Status: Unmarried\n"
"• Siblings: None\n"
"• Extrovert personality\n"
"• Enjoys gaming, exploring new places, playing volleyball and badminton\n"
"• Regional-level volleyball player\n"
"• Does not smoke or drink\n"
"• Likes clubbing occasionally\n"
"**Education**:\n"
"• 10th: Vikas Concept School, Hyderabad – 10 CGPA\n"
"• 12th: Narayana Junior College, Hyderabad – 88.4%\n"
"• B.Tech: St. Martin’s Engineering College – 7.83 CGPA\n"
"• Branch: Computer Science (AI & ML specialization)\n"
"• Rejected full-stack development offer from ExcelR after graduation to prepare for CAT\n"
"• Scored 96.42 percentile in CAT (General category, not selected for IIM)\n"
"• Discovered passion for business insights, communication, stakeholder analysis — hence moved to data analytics\n"
"**Work Experience**:\n"
"• No formal job experience, but has done multiple real-world analytics projects\n"
"• Comfortable with working full-time, no notice period, and can join immediately\n"
"• Open to relocation and short-term international work, but prefers to stay in India long term\n"
"• No other job offers currently — actively looking for a good team and opportunity to grow\n"
"• Doesn’t focus only on salary; wants learning and culture fit\n"
"**Skills & Tools**:\n"
"• Power BI (ETL, DAX, Data modelling, RLS, Bookmarks, Buttons, filters, KPIs, Drill-through, Tooltips, Parameters)\n"
"• SQL (Joins, Subqueries, CTEs, Window Functions, Optimization, Data relationships)\n"
"• Python (Pandas, Matplotlib, NumPy, seaborn, scikit-learn)\n"
"• Business Analytics (Forecasting, Financial Modelling, Performance Metrics, Risk Analysis, KPI Dashboards, Business performance strategy)\n "
"• Excel (PivotTables, VLOOKUP, INDEX-MATCH, Data Cleaning, Conditional Formatting)\n"
"• FastAPI, MySQL\n"
"**Resume, Portfolio and GitHub links**:\n"
"• Resume: [https://nayan-reddy.github.io/Nayan-Resume/]\n"
"• Portfolio: [https://codebasics.io/portfolio/Nayan-Reddy-Soma]\n"
"• GitHub: [https://github.com/Nayan-Reddy]\n"
"**Contact Information**:\n"
"• Gmail: nayanreddy007@gmail.com\n"
"• Phone number: +91 9177719157\n"
"**Projects**:\n"
"1. **Business 360 Power BI Dashboard**:\n"
"- Analyzed 1.8M+ rows of data from Sales, Marketing, Finance, Supply Chain, and Executive views\n"
"- Built with snowflake schema and custom DAX measures (YoY, moving averages, forecast errors)\n"
"- Key Features: Dynamic slicers, maps, drilldowns, advanced KPIs, custom tooltips\n"
"- Created for CXOs to make informed decisions\n"
"- Technologies: Power BI, Power Query, DAX\n"
"2. **Expense Tracker Management App**:\n"
"- Tech Stack: FastAPI + Streamlit + MySQL\n"
"- Session-based personalized expense logging and analytics\n"
"- Visual dashboards show monthly trends, category-wise spending, budget utilization\n"
"- Switches between demo mode and per-user analytics dynamically\n"
"- Used: Pandas, Matplotlib, MySQL queries, Streamlit frontend\n"
"3. **Sales Tracker in Excel**:\n"
"- Built an Excel dashboard for sales, product, and regional performance\n"
"- Used advanced formulas, conditional formatting, and slicers\n"
"- Focused on automation, dynamic filtering, and clear visual communication\n"
"4. **SQL Ad-hoc Business Analysis**:\n"
"- Used MySQL to analyze a 1.4M+ row transactional database\n"
"- Delivered insights for 10+ ad-hoc business questions for executive stakeholders\n"
"- Example Insights:\n"
" • Product offerings grew by 36.33% in 2021 vs 2020\n"
" • Retailers contributed 73.21% of total revenue\n"
" • Sample SQL queries include joins, window functions, group by, ranking, sales drop detection\n"
"**Interview-readiness**:\n"
"• Personalized answers for 65+ behavioral and background questions are preloaded (e.g., 'Why should we hire you?')\n"
"• The assistant should match similar variants like: 'Do you have work experience?' → 'Why no work experience?'\n"
"• The assistant is trained to smartly fallback to exact answers when relevant or use OpenAI for everything else\n"
"• If recruiter asks 'show me your projects' — the assistant must include project links:\n"
" • Power BI Live Dashboard: [https://app.powerbi.com/view?r=eyJrIjoiYzFkZGY3NGUtMWIwYy00YjZmLWIzMDYtYjQyMjkxNGRhN2NmIiwidCI6ImM2ZTU0OWIzLTVmNDUtNDAzMi1hYWU5LWQ0MjQ0ZGM1YjJjNCJ9]\n"
" • Expense Tracker App: [https://expense-tracker-frontend-nayan-reddy.streamlit.app/]\n"
" • Excel Demo File: [https://1drv.ms/x/c/e4ca29151a0a4ec4/EeJ0-_SJhOZIjam0emzh_ccBfDKFeWhL2IMsVI7DXtXB0Q?e=jisfwq]\n"
"**Behavioral Summary**:\n"
"• Strong communication, team-oriented, and open to feedback\n"
"• Loves learning from peers and collaborating on real data problems\n"
"• Passionate about making data useful to decision-makers\n"
"**Sensitive Topic Policy**:\n"
"If users ask questions about:\n"
"- Gender, sexuality, relationship status, sex life, weekend plans, marriage, children, or any question that feels overly personal, informal, or inappropriate\n"
"- Caste, religion, appearance, photo, or political views\n"
"- Inappropriate, sarcastic, or offensive phrasing\n"
"\n"
"Then respond briefly and professionally. Do not provide full introductions or irrelevant answers. Instead:\n"
"• 'Nayan is male.'\n"
"• 'He is unmarried and has no children.'\n"
"• 'Let’s stay focused on Nayan’s work and projects.'\n"
"• 'That’s a bit personal — happy to answer anything about his professional background.'\n"
"\n"
"Avoid judgmental or speculative responses. Stay friendly, respectful, and focused on the recruiter’s intent.\n"
"Whenever possible, answer proactively by highlighting Nayan’s achievements, projects, and personality.\n"
"If users ask vague things like 'tools used', 'project details', or just 'Power BI', intelligently respond using project context.\n"
"Never say 'I don’t know'. Always be confident, helpful, and insightful."
)
}]
st.session_state.show_prompts = True
if "fallback_history" not in st.session_state:
st.session_state.fallback_history = []
if "last_fallback_qna" not in st.session_state:
st.session_state.last_fallback_qna = None
user_input = st.chat_input("Ask a question...")
if user_input and st.session_state.show_prompts:
st.session_state.show_prompts = False
if st.session_state.show_prompts:
st.markdown("""
<div class='prompt-suggestions'>
💡 Try asking: <br>
“Can you introduce yourself?”<br>
“What are your interests or hobbies outside of work?”<br>
“Tell me about your projects or the tools you’ve worked with?”
</div>
""", unsafe_allow_html=True)
# ----------------- FOLLOW-UP CHECK -----------------
def is_follow_up(user_input):
followup_keywords = ["more", "elaborate", "explain", "details", "detail", "expand",
"why", "how", "what else", "what was", "what did", "tell me more", "about it", "that one",
"which one", "who", "it", "that", "this", "he", "she", "they", "them",
"tell me more", "more info", "how long", "who was involved", "what was the tool",
"what’s the tech", "what technology", "did it work"]
return any(kw in clean(user_input) for kw in followup_keywords)
def ask_gpt_with_context(user_input, fallback_context=None):
messages = st.session_state.messages[:1]
if fallback_context:
for q, a in fallback_context:
messages.append({"role": "user", "content": q})
messages.append({"role": "assistant", "content": a})
messages.append({"role": "user", "content": user_input})
try:
response = client.chat.completions.create(
model=chat_model,
messages=messages
)
return response.choices[0].message.content
except Exception as e:
return f"Could not fetch response.\n\n**Error:** {e}"
# ----------------- PROCESS QUESTION -----------------
if user_input:
st.session_state.show_prompts = False
st.markdown(f"<div class='user-bubble'>{user_input}</div>", unsafe_allow_html=True)
st.session_state.messages = st.session_state.messages[:1]
st.session_state.messages.append({"role": "user", "content": user_input})
# --- Start Logging Additions ---
start_time = time.time()
reply = ""
response_source = ""
# --- End Logging Additions ---
if is_sensitive(user_input):
reply = sensitive_reply(user_input)
response_source = "sensitive_filter"
elif is_follow_up(user_input) and st.session_state.last_fallback_qna:
last_q, last_a = st.session_state.last_fallback_qna
context = [
{"role": "user", "content": last_q},
{"role": "assistant", "content": last_a},
{"role": "user", "content": user_input}
]
with st.spinner("Thinking..."):
try:
response = client.chat.completions.create(
model=chat_model,
messages=[st.session_state.messages[0]] + context
)
reply = response.choices[0].message.content
response_source = "llm_follow_up"
except Exception as e:
reply = f"Could not fetch response.\n\n**Error:** {e}"
response_source = "error"
else:
fallback = get_best_fallback(user_input, nlp)
if fallback:
reply = fallback
response_source = "fallback"
st.session_state.fallback_history.append((user_input, reply))
st.session_state.fallback_history = st.session_state.fallback_history[-5:]
st.session_state.last_fallback_qna = (user_input, fallback)
else:
with st.spinner("Thinking..."):
try:
fallback_qna_context = []
for q, a in st.session_state.fallback_history[-5:]:
fallback_qna_context.append({"role": "user", "content": q})
fallback_qna_context.append({"role": "assistant", "content": a})
all_context = [st.session_state.messages[0]] + fallback_qna_context + st.session_state.messages[-5:]
response = client.chat.completions.create(
model=chat_model,
messages=all_context
)
reply = response.choices[0].message.content
response_source = "llm_general"
except Exception as e:
reply = f"Could not fetch response.\n\n**Error:** {e}"
response_source = "error"
# --- Final Logging Step ---
end_time = time.time()
response_time_ms = int((end_time - start_time) * 1000)
log_interaction(
session_id=st.session_state.session_id,
query=user_input,
response=reply,
source=response_source,
response_time_ms=response_time_ms
)
# --- End Logging ---
st.session_state.messages.append({"role": "assistant", "content": reply})
max_pairs = 5
system_message = st.session_state.messages[0]
chat_history = st.session_state.messages[1:]
trimmed = chat_history[-(max_pairs * 2):]
st.session_state.messages = [system_message] + trimmed
# Stylish divider
st.markdown("""
<div style="margin: 20px auto; width: 100px; height: 2px; background: linear-gradient(to right, #10b981, #1f2937); border-radius: 2px;"></div>
""", unsafe_allow_html=True)
# Show assistant reply
st.markdown(f"<div class='bot-bubble'>{reply}</div>", unsafe_allow_html=True)