n0v33n commited on
Commit
8fbc17c
Β·
1 Parent(s): eb92ba2

add gradio app

Browse files
Files changed (1) hide show
  1. gradioapp.py +401 -0
gradioapp.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import re
4
+ import pandas as pd
5
+ import random
6
+ import warnings
7
+ from dotenv import load_dotenv
8
+ from langchain_tavily import TavilySearch
9
+ import google.generativeai as genai
10
+ import gdown
11
+ import gradio as gr
12
+
13
+ warnings.filterwarnings("ignore")
14
+
15
+ load_dotenv()
16
+ TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
17
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
18
+
19
+ user_sessions = {}
20
+ if not GOOGLE_API_KEY:
21
+ raise ValueError("GOOGLE_API_KEY environment variable is required.")
22
+
23
+ genai.configure(api_key=GOOGLE_API_KEY)
24
+
25
+ # β€”β€”β€” Load or fallback LeetCode data β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
26
+ GOOGLE_SHEET_URL = "https://docs.google.com/spreadsheets/d/1KK9Mnm15hV3ALJo-quJndftWfaujJ7K2_zHMCTo5mGE/"
27
+ FILE_ID = GOOGLE_SHEET_URL.split("/d/")[1].split("/")[0]
28
+ DOWNLOAD_URL = f"https://drive.google.com/uc?export=download&id={FILE_ID}"
29
+ OUTPUT_FILE = "leetcode_downloaded.xlsx"
30
+
31
+ try:
32
+ print("Downloading LeetCode data...")
33
+ gdown.download(DOWNLOAD_URL, OUTPUT_FILE, quiet=False)
34
+ LEETCODE_DATA = pd.read_excel(OUTPUT_FILE)
35
+ print(f"Loaded {len(LEETCODE_DATA)} problems")
36
+ except Exception:
37
+ print("Failed to download/read. Using fallback.")
38
+ LEETCODE_DATA = pd.DataFrame([
39
+ {"problem_no": 3151, "problem_level": "Easy", "problem_statement": "special array",
40
+ "problem_link": "https://leetcode.com/problems/special-array-i/?envType=daily-question&envId=2025-06-01"},
41
+ {"problem_no": 1752, "problem_level": "Easy", "problem_statement": "check if array is sorted and rotated",
42
+ "problem_link": "https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/?envType=daily-question&envId=2025-06-01"},
43
+ {"problem_no": 3105, "problem_level": "Easy", "problem_statement": "longest strictly increasing or strictly decreasing subarray",
44
+ "problem_link": "https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray/?envType=daily-question&envId=2025-06-01"},
45
+ {"problem_no": 1, "problem_level": "Easy", "problem_statement": "two sum",
46
+ "problem_link": "https://leetcode.com/problems/two-sum/"},
47
+ {"problem_no": 2, "problem_level": "Medium", "problem_statement": "add two numbers",
48
+ "problem_link": "https://leetcode.com/problems/add-two-numbers/"},
49
+ {"problem_no": 3, "problem_level": "Medium", "problem_statement": "longest substring without repeating characters",
50
+ "problem_link": "https://leetcode.com/problems/longest-substring-without-repeating-characters/"},
51
+ {"problem_no": 4, "problem_level": "Hard", "problem_statement": "median of two sorted arrays",
52
+ "problem_link": "https://leetcode.com/problems/median-of-two-sorted-arrays/"},
53
+ {"problem_no": 5, "problem_level": "Medium", "problem_statement": "longest palindromic substring",
54
+ "problem_link": "https://leetcode.com/problems/longest-palindromic-substring/"}
55
+ ])
56
+
57
+ # β€”β€”β€” Helpers & Tools β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
58
+
59
+ QUESTION_TYPE_MAPPING = {
60
+ "easy": "Easy", "Easy": "Easy",
61
+ "medium": "Medium", "Medium": "Medium",
62
+ "hard": "Hard", "Hard": "Hard"
63
+ }
64
+
65
+ def preprocess_query(query: str) -> str:
66
+ for k, v in QUESTION_TYPE_MAPPING.items():
67
+ query = re.sub(rf'\b{k}\b', v, query, flags=re.IGNORECASE)
68
+ query = re.sub(r'\bproblem\s*(\d+)', r'Problem_\1', query, flags=re.IGNORECASE)
69
+ query = re.sub(r'\bquestion\s*(\d+)', r'Problem_\1', query, flags=re.IGNORECASE)
70
+ query = re.sub(r'\b(find|search)\s+interview\s+questions\s+for\s+', '', query, flags=re.IGNORECASE)
71
+ query = re.sub(r'\binterview\s+questions\b', '', query, flags=re.IGNORECASE).strip()
72
+ return query
73
+
74
+ def get_daily_coding_question(query: str = "") -> dict:
75
+ try:
76
+ response = "**Daily Coding Questions**\n\n"
77
+
78
+ m = re.search(r'Problem_(\d+)', query, re.IGNORECASE)
79
+ if m:
80
+ df = LEETCODE_DATA[LEETCODE_DATA['problem_no'] == int(m.group(1))]
81
+ if not df.empty:
82
+ p = df.iloc[0]
83
+ response += (
84
+ f"**Problem {p['problem_no']}**\n"
85
+ f"Level: {p['problem_level']}\n"
86
+ f"Statement: {p['problem_statement']}\n"
87
+ f"Link: {p['problem_link']}\n\n"
88
+ )
89
+ return {"status": "success", "response": response}
90
+ else:
91
+ return {"status": "error", "response": "Problem not found"}
92
+
93
+ if query.strip():
94
+ df = LEETCODE_DATA[LEETCODE_DATA['problem_statement'].str.contains(query, case=False, na=False)]
95
+ else:
96
+ df = LEETCODE_DATA
97
+
98
+ easy_questions = df[df['problem_level'] == 'Easy'].sample(min(3, len(df[df['problem_level'] == 'Easy'])))
99
+ medium_questions = df[df['problem_level'] == 'Medium'].sample(min(1, len(df[df['problem_level'] == 'Medium'])))
100
+ hard_questions = df[df['problem_level'] == 'Hard'].sample(min(1, len(df[df['problem_level'] == 'Hard'])))
101
+
102
+ response += "**Easy Questions**\n"
103
+ for i, p in enumerate(easy_questions.itertuples(), 1):
104
+ response += (
105
+ f"{i}. Problem {p.problem_no}: {p.problem_statement}\n"
106
+ f" Level: {p.problem_level}\n"
107
+ f" Link: {p.problem_link}\n\n"
108
+ )
109
+
110
+ response += "**Medium Question**\n"
111
+ for p in medium_questions.itertuples():
112
+ response += (
113
+ f"Problem {p.problem_no}: {p.problem_statement}\n"
114
+ f"Level: {p.problem_level}\n"
115
+ f"Link: {p.problem_link}\n\n"
116
+ )
117
+
118
+ response += "**Hard Question**\n"
119
+ for p in hard_questions.itertuples():
120
+ response += (
121
+ f"Problem {p.problem_no}: {p.problem_statement}\n"
122
+ f"Level: {p.problem_level}\n"
123
+ f"Link: {p.problem_link}\n"
124
+ )
125
+
126
+ return {"status": "success", "response": response}
127
+ except Exception as e:
128
+ return {"status": "error", "response": f"Error: {e}"}
129
+
130
+ def fetch_interview_questions(query: str) -> dict:
131
+ if not TAVILY_API_KEY:
132
+ return {"status": "error", "response": "Tavily API key not configured"}
133
+
134
+ if not query.strip() or query.lower() in ["a", "interview", "question", "questions"]:
135
+ return {"status": "error", "response": "Please provide a specific topic for interview questions (e.g., 'Python', 'data structures', 'system design')."}
136
+
137
+ try:
138
+ tavily = TavilySearch(api_key=TAVILY_API_KEY, max_results=5)
139
+ search_query = f"{query} interview questions -inurl:(signup | login)"
140
+ print(f"Executing Tavily search for: {search_query}")
141
+
142
+ results = tavily.invoke(search_query)
143
+ print(f"Raw Tavily results: {results}")
144
+
145
+ if not results or not isinstance(results, list) or len(results) == 0:
146
+ return {"status": "success", "response": "No relevant interview questions found. Try a more specific topic or different keywords."}
147
+
148
+ resp = "**Interview Questions Search Results for '{}':**\n\n".format(query)
149
+ for i, r in enumerate(results, 1):
150
+ if isinstance(r, dict):
151
+ title = r.get('title', 'No title')
152
+ url = r.get('url', 'No URL')
153
+ content = r.get('content', '')
154
+ content = content[:200] + '…' if len(content) > 200 else content or "No preview available"
155
+ resp += f"{i}. **{title}**\n URL: {url}\n Preview: {content}\n\n"
156
+ else:
157
+ resp += f"{i}. {str(r)[:200]}{'…' if len(str(r)) > 200 else ''}\n\n"
158
+
159
+ return {"status": "success", "response": resp}
160
+
161
+ except Exception as e:
162
+ print(f"Tavily search failed: {str(e)}")
163
+ return {"status": "error", "response": f"Search failed: {str(e)}"}
164
+
165
+ def simulate_mock_interview(query: str, user_id: str = "default") -> dict:
166
+ qtype = "mixed"
167
+ if re.search(r'HR|Behavioral|hr|behavioral', query, re.IGNORECASE): qtype = "HR"
168
+ if re.search(r'Technical|System Design|technical|coding', query, re.IGNORECASE): qtype = "Technical"
169
+
170
+ if "interview question" in query.lower() and qtype == "mixed":
171
+ qtype = "HR"
172
+
173
+ if qtype == "HR":
174
+ hr_questions = [
175
+ "Tell me about yourself.",
176
+ "What is your greatest weakness?",
177
+ "Describe a challenge you overcame.",
178
+ "Why do you want to work here?",
179
+ "Where do you see yourself in 5 years?",
180
+ "Why are you leaving your current job?",
181
+ "Describe a time when you had to work with a difficult team member.",
182
+ "What are your salary expectations?",
183
+ "Tell me about a time you failed.",
184
+ "What motivates you?",
185
+ "How do you handle stress and pressure?",
186
+ "Describe your leadership style."
187
+ ]
188
+ q = random.choice(hr_questions)
189
+ return {"status": "success", "response": (
190
+ f"**Mock Interview (HR/Behavioral)**\n\n**Question:** {q}\n\nπŸ’‘ **Tips:**\n"
191
+ f"- Use the STAR method (Situation, Task, Action, Result)\n"
192
+ f"- Provide specific examples from your experience\n"
193
+ f"- Keep your answer concise but detailed\n\n**Your turn to answer!**"
194
+ )}
195
+ else:
196
+ p = LEETCODE_DATA.sample(1).iloc[0]
197
+ return {"status": "success", "response": (
198
+ f"**Mock Interview (Technical)**\n\n**Problem:** {p['problem_statement'].title()}\n"
199
+ f"**Difficulty:** {p['problem_level']}\n**Link:** {p['problem_link']}\n\nπŸ’‘ **Tips:**\n"
200
+ f"- Think out loud as you solve\n"
201
+ f"- Ask clarifying questions\n"
202
+ f"- Discuss time/space complexity\n\n**Explain your approach!**"
203
+ )}
204
+
205
+ # β€”β€”β€” The Enhanced InterviewPrepAgent β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
206
+
207
+ class InterviewPrepAgent:
208
+ def __init__(self):
209
+ self.model = genai.GenerativeModel('gemini-1.5-flash')
210
+ self.tools = {
211
+ "get_daily_coding_question": get_daily_coding_question,
212
+ "fetch_interview_questions": fetch_interview_questions,
213
+ "simulate_mock_interview": simulate_mock_interview
214
+ }
215
+ self.instruction_text = """
216
+ You are an interview preparation assistant. Analyze the user's query and determine which tool to use.
217
+
218
+ Available tools:
219
+ 1. get_daily_coding_question - For coding practice, LeetCode problems, daily questions
220
+ 2. fetch_interview_questions - For searching interview questions on specific topics
221
+ 3. simulate_mock_interview - For mock interview practice (HR/behavioral or technical)
222
+
223
+ Instructions:
224
+ - If user asks for coding questions, daily questions, LeetCode problems, practice problems -> use get_daily_coding_question
225
+ - If user asks for interview questions on specific topics (e.g., Python, data structures) without "mock" or "simulate" -> use fetch_interview_questions
226
+ - If user asks for mock interview, interview simulation, practice interview, or HR/behavioral questions -> use simulate_mock_interview
227
+ - If user explicitly mentions "HR" or "behavioral" -> use simulate_mock_interview with HR focus
228
+
229
+ Respond ONLY with valid JSON in this exact format:
230
+ {"tool": "tool_name", "args": {"param1": "value1", "param2": "value2"}}
231
+
232
+ User Query: {query}
233
+ """
234
+
235
+ def _classify_intent(self, query: str) -> tuple[str, dict]:
236
+ query_lower = query.lower()
237
+
238
+ # Prioritize HR/behavioral for explicit mentions
239
+ if any(keyword in query_lower for keyword in ["hr", "behavioral", "give hr questions", "give behavioral questions"]):
240
+ return "simulate_mock_interview", {"query": query, "user_id": "default"}
241
+
242
+ # Handle mock interview or simulation requests
243
+ if any(keyword in query_lower for keyword in ["mock interview", "practice interview", "interview simulation", "simulate_mock_interview"]):
244
+ return "simulate_mock_interview", {"query": query, "user_id": "default"}
245
+
246
+ # Handle coding-related queries
247
+ if any(keyword in query_lower for keyword in ["daily", "coding question", "leetcode", "practice problem", "coding practice"]):
248
+ problem_match = re.search(r'problem\s*(\d+)', query_lower)
249
+ if problem_match:
250
+ return "get_daily_coding_question", {"query": f"Problem_{problem_match.group(1)}"}
251
+
252
+ if "easy" in query_lower:
253
+ return "get_daily_coding_question", {"query": "Easy"}
254
+ elif "medium" in query_lower:
255
+ return "get_daily_coding_question", {"query": "Medium"}
256
+ elif "hard" in query_lower:
257
+ return "get_daily_coding_question", {"query": "Hard"}
258
+
259
+ return "get_daily_coding_question", {"query": ""}
260
+
261
+ # Handle topic-specific interview questions
262
+ if any(keyword in query_lower for keyword in ["search interview questions", "find interview questions", "interview prep resources"]) or \
263
+ "interview" in query_lower:
264
+ return "fetch_interview_questions", {"query": query}
265
+
266
+ # Fallback to LLM classification
267
+ try:
268
+ prompt = self.instruction_text.format(query=query)
269
+ response = self.model.generate_content(prompt)
270
+ result = json.loads(response.text.strip())
271
+ tool_name = result.get("tool")
272
+ args = result.get("args", {})
273
+ return tool_name, args
274
+ except Exception as e:
275
+ print(f"LLM classification failed: {e}")
276
+ return "get_daily_coding_question", {"query": ""}
277
+
278
+ def process_query(self, query: str, user_id: str = "default", session_id: str = "default") -> str:
279
+ if not GOOGLE_API_KEY:
280
+ return "Error: Google API not configured."
281
+
282
+ session_key = f"{user_id}_{session_id}"
283
+ user_sessions.setdefault(session_key, {"history": []})
284
+
285
+ tool_name, args = self._classify_intent(query)
286
+
287
+ if tool_name not in self.tools:
288
+ return f"I couldn't understand your request. Please try asking for:\n- Daily coding question\n- Mock interview\n- Interview questions for a specific topic"
289
+
290
+ result = self.tools[tool_name](**args)
291
+
292
+ user_sessions[session_key]["history"].append({
293
+ "query": query,
294
+ "response": result["response"]
295
+ })
296
+
297
+ return result["response"]
298
+
299
+ # β€”β€”β€” Gradio Interface β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
300
+
301
+ agent = InterviewPrepAgent()
302
+
303
+ def chat_interface(message, history):
304
+ """Handle chat messages and return response"""
305
+ try:
306
+ # Preprocess the query
307
+ processed_query = preprocess_query(message)
308
+
309
+ # Get response from agent
310
+ response = agent.process_query(processed_query, user_id="gradio_user", session_id="session_1")
311
+
312
+ return response
313
+ except Exception as e:
314
+ return f"Sorry, I encountered an error: {str(e)}"
315
+
316
+ def create_examples():
317
+ """Create example messages for the interface"""
318
+ return [
319
+ ["Give me a daily coding question"],
320
+ ["I want to practice mock interview"],
321
+ ["Find interview questions for Python"],
322
+ ["Give me HR interview questions"],
323
+ ["Technical mock interview"],
324
+ ["Search interview questions for data structures"],
325
+ ]
326
+
327
+ # Create the Gradio interface
328
+ with gr.Blocks(
329
+ title="Interview Prep Assistant",
330
+ theme=gr.themes.Soft(),
331
+ css="""
332
+ .gradio-container {
333
+ max-width: 900px !important;
334
+ }
335
+ .chat-message {
336
+ font-size: 14px !important;
337
+ }
338
+ """
339
+ ) as interface:
340
+
341
+ gr.Markdown(
342
+ """
343
+ # 🎯 Interview Prep Assistant
344
+
345
+ Your AI-powered interview preparation companion! I can help you with:
346
+
347
+ - **Daily Coding Questions** - Get LeetCode problems for practice
348
+ - **Mock Interviews** - Practice HR/behavioral or technical interviews
349
+ - **Interview Questions** - Search for specific topic-based interview questions
350
+
351
+ Just type your request below and I'll help you prepare for your next interview!
352
+ """
353
+ )
354
+
355
+ # Create the chat interface
356
+ chatbot = gr.ChatInterface(
357
+ fn=chat_interface,
358
+ title="Chat with Interview Prep Assistant",
359
+ description="Ask me for coding questions, mock interviews, or interview preparation resources!",
360
+ examples=create_examples(),
361
+ textbox=gr.Textbox(
362
+ placeholder="Type your message here... (e.g., 'Give me a daily coding question')",
363
+ container=False,
364
+ scale=7
365
+ ),
366
+ chatbot=gr.Chatbot(
367
+ height=500,
368
+ show_label=False,
369
+ container=True
370
+ )
371
+ )
372
+
373
+ # Add footer with information
374
+ gr.Markdown(
375
+ """
376
+ ---
377
+ ### πŸ’‘ Tips for using the Interview Prep Assistant:
378
+
379
+ - **For coding practice**: "daily coding question", "easy coding problem", "leetcode problem 1"
380
+ - **For mock interviews**: "mock interview", "HR interview", "technical interview"
381
+ - **For topic research**: "Python interview questions", "system design interview questions"
382
+
383
+ ### πŸ“Š System Status:
384
+ - Google API: βœ… Configured
385
+ - LeetCode Problems: {} loaded
386
+ - Tavily Search: {} Available
387
+ """.format(
388
+ len(LEETCODE_DATA),
389
+ "βœ…" if TAVILY_API_KEY else "❌"
390
+ )
391
+ )
392
+
393
+ # Launch the interface
394
+ if __name__ == "__main__":
395
+ interface.launch(
396
+ # server_name="0.0.0.0",
397
+ server_port=8000,
398
+ share=False,
399
+ show_error=True,
400
+ quiet=False
401
+ )