Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234561 unmodified line8910111213145 unmodified lines20212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121133 unmodified lines1171181191201211221231241251261271281291301311321331341351361371384 unmodified lines143144145146147148149150151152153154155156157158159160161162163164165166167import gradio as grfrom huggingface_hub import InferenceClientimport re# ---- Load and parse questions from knowledge.txt ----def load_questions(file_path):1 unmodified linedata = f.read()question_blocks = re.split(r'Question:\s*', data)[1:]questions = []for block in question_blocks:parts = block.split('Possible Answers:')5 unmodified linesall_questions = load_questions('knowledge.txt')# ---- Simple way to assign questions to interview types ----# You can replace this later with better taggingquestions_by_type = {'Technical': [q for q in all_questions if any(keyword in q['question'].lower() for keyword in ['function', 'linked list', 'url', 'rest', 'graphql', 'garbage', 'cap theorem', 'sql', 'hash table','stack', 'queue', 'recursion', 'reverse', 'bfs', 'dfs', 'time complexity', 'binary search tree','web application', 'chat system', 'load balancing', 'caching', 'normalization', 'acid', 'indexing','sql injection', 'https', 'xss', 'hash', 'vulnerabilities'])],'Competency-Based Interview': [q for q in all_questions if any(keyword in q['question'].lower() for keyword in ["Debugging","Learning Fast","Deadlines","Teamwork","Leadership","Mistake Recovery","Conflict Management","Decision Making"])],'Case': [q for q in all_questions if any(keyword in q['question'].lower() for keyword in ["A/B Testing","Financial Modeling","Automation","Data Analysis","Regression","Business Opportunity","Stakeholder Alignment"])]}# ---- Hugging Face Client ----client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")# ---- Interview type selection ----def set_type(choice, user_profile):user_profile["interview_type"] = choicereturn "Great! Whatβs your background and what field/role are you aiming for?", user_profile# ---- Save background ----def save_background(info, user_profile):user_profile["field"] = inforeturn "Awesome! Type 'start' below to begin your interview.", user_profile# ---- Main respond logic ----def respond(message, chat_history, user_profile):if not user_profile.get("interview_type") or not user_profile.get("field"):bot_msg = "Please finish steps 1 and 2 before starting the interview."chat_history.append((message, bot_msg))return chat_history# Start interview logicif message.strip().lower() == 'start':interview_type = user_profile['interview_type']selected_questions = questions_by_type.get(interview_type, [])user_profile['questions'] = selected_questionsuser_profile['current_q'] = 0user_profile['user_answers'] = []if not selected_questions:bot_msg = "No questions available for this interview type."else:bot_msg = f"First question: {selected_questions[0]['question']}"chat_history.append((message, bot_msg))return chat_history# If interview is ongoing# if user_profile.get("questions"):# q_index = user_profile['current_q']# user_profile['user_answers'].append(message)# q_index += 1# user_profile['current_q'] = q_index# if q_index < len(user_profile['questions']):# bot_msg = f"Next question: {user_profile['questions'][q_index]['question']}"# else:# bot_msg = "Interview complete! Type 'feedback' if you'd like me to analyze your answers."# chat_history.append((message, bot_msg))# return chat_historyif user_profile.get("questions"):# --- NEW STOP LOGIC ---if message.strip().lower() == 'stop':bot_msg = "Thank you for chatting with Intervu! The interview has been stopped. Type 'feedback' if you'd like me to analyze your answers."chat_history.append((message, bot_msg))user_profile['questions'] = [] # clear questions list to stopreturn chat_history# Existing interview logic continues here:q_index = user_profile['current_q']user_profile['user_answers'].append(message)3 unmodified linesif q_index < len(user_profile['questions']):bot_msg = f"Next question: {user_profile['questions'][q_index]['question']}"else:bot_msg = "Interview complete! Type 'feedback' if you'd like me to analyze your answers."chat_history.append((message, bot_msg))return chat_history# Handle feedback requestif message.strip().lower() == 'feedback':feedback = generate_feedback(user_profile)chat_history.append((message, feedback))return chat_history# Default fallbackmessages = [{"role": "system", "content": f"You are a professional interviewer conducting a {user_profile['interview_type']} interview for a candidate in the {user_profile['field']} field."}]for q, a in chat_history:messages.append({"role": "user", "content": q})messages.append({"role": "assistant", "content": a})4 unmodified lineschat_history.append((message, bot_msg))return chat_history# ---- Simple feedback function (keyword based for now) ----def generate_feedback(user_profile):feedback = []questions = user_profile.get('questions', [])answers = user_profile.get('user_answers', [])for i, user_ans in enumerate(answers):correct_answers = questions[i]['answers']match = any(ans.lower() in user_ans.lower() for ans in correct_answers)if match:fb = f"Question {i+1}: β Good job! You covered key points."else:fb = f"Question {i+1}: β You missed some key points: {correct_answers[0]}"feedback.append(fb)return "\n".join(feedback)# ---- Gradio Interface ----with gr.Blocks() as demo:user_profile = gr.State({"interview_type": "", "field": ""})chat_history = gr.State([])gr.Markdown("# π€ Welcome to Intervu")12345671 unmodified line910111213145 unmodified lines2021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081823 unmodified lines86878889909192939495969798991001011021034 unmodified lines108109110111112113114115116117118119120121122123124125126127128129130import gradio as grfrom huggingface_hub import InferenceClientimport reimport random# ---- Load and parse questions from knowledge.txt ----def load_questions(file_path):1 unmodified linedata = f.read()question_blocks = re.split(r'Question:\s*', data)[1:]questions = []for block in question_blocks:parts = block.split('Possible Answers:')5 unmodified linesall_questions = load_questions('knowledge.txt')# ---- Tagging ----questions_by_type = {'Technical': [q for q in all_questions if any(keyword in q['question'].lower() for keyword in ['function', 'linked list', 'url', 'rest', 'graphql', 'garbage', 'cap theorem', 'sql', 'hash table','stack', 'queue', 'recursion', 'reverse', 'bfs', 'dfs', 'time complexity', 'binary search tree','web application', 'chat system', 'load balancing', 'caching', 'normalization', 'acid', 'indexing','sql injection', 'https', 'xss', 'hash', 'vulnerabilities'])],'Competency-Based Interview': [q for q in all_questions if any(keyword in q['question'].lower() for keyword in ["debugging", "learning", "deadlines", "teamwork", "leadership", "mistake", "conflict", "decision"])],'Case': [q for q in all_questions if any(keyword in q['question'].lower() for keyword in ["testing", "financial", "automation", "analysis", "regression", "business", "stakeholder"])]}client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")# ---- Logic functions ----def set_type(choice, user_profile):user_profile["interview_type"] = choicereturn "Great! Whatβs your background and what field/role are you aiming for?", user_profiledef save_background(info, user_profile):user_profile["field"] = inforeturn "Awesome! Type 'start' below to begin your interview.", user_profiledef respond(message, chat_history, user_profile):message_lower = message.strip().lower()if not user_profile.get("interview_type") or not user_profile.get("field"):bot_msg = "Please finish steps 1 and 2 before starting the interview."chat_history.append((message, bot_msg))return chat_history# Start interview logicif message_lower == 'start':interview_type = user_profile['interview_type']selected_questions = questions_by_type.get(interview_type, [])random.shuffle(selected_questions)selected_questions = selected_questions[:10]user_profile['questions'] = selected_questionsuser_profile['current_q'] = 0user_profile['user_answers'] = []user_profile['interview_in_progress'] = Trueintro = f"Welcome to your {interview_type} interview for a {user_profile['field']} position. I will ask you up to 10 questions. Type 'stop' anytime to end."first_q = f"First question: {selected_questions[0]['question']}"chat_history.append((message, intro))chat_history.append(("", first_q))return chat_historyif message_lower == 'stop' and user_profile.get("interview_in_progress"):user_profile['interview_in_progress'] = Falsebot_msg = "Interview stopped. Type 'feedback' if you'd like me to analyze your answers. Thanks for interviewing with Intervu!"chat_history.append((message, bot_msg))return chat_historyif user_profile.get("interview_in_progress"):q_index = user_profile['current_q']user_profile['user_answers'].append(message)3 unmodified linesif q_index < len(user_profile['questions']):bot_msg = f"Next question: {user_profile['questions'][q_index]['question']}"else:user_profile['interview_in_progress'] = Falsebot_msg = "Interview complete! Type 'feedback' if you'd like me to analyze your answers. Thanks for interviewing with Intervu!"chat_history.append((message, bot_msg))return chat_historyif message_lower == 'feedback':feedback = generate_feedback(user_profile)chat_history.append((message, feedback))return chat_history# fallback small talkmessages = [{"role": "system", "content": f"You are a professional interviewer conducting a {user_profile['interview_type']} interview for a candidate in {user_profile['field']}."}]for q, a in chat_history:messages.append({"role": "user", "content": q})messages.append({"role": "assistant", "content": a})4 unmodified lineschat_history.append((message, bot_msg))return chat_historydef generate_feedback(user_profile):feedback = []questions = user_profile.get('questions', [])answers = user_profile.get('user_answers', [])for i, user_ans in enumerate(answers):correct_answers = questions[i]['answers']match = any(ans.lower() in user_ans.lower() for ans in correct_answers)if match:fb = f"Question {i+1}: β Good job!"else:fb = f"Question {i+1}: β Missed some key points: {correct_answers[0]}"feedback.append(fb)return "\n".join(feedback)# ---- Gradio UI ----with gr.Blocks() as demo:user_profile = gr.State({"interview_type": "", "field": "", "interview_in_progress": False})chat_history = gr.State([])gr.Markdown("# π€ Welcome to Intervu")
app.py+36-73