Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647483 unmodified lines5253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251 unmodified linefrom huggingface_hub import InferenceClientimport reimport random# Load questions (your original backend)def load_questions(file_path):with open(file_path, 'r') as f:data = f.read()question_blocks = re.split(r'Question:\s*', data)[1:]questions = []for block in question_blocks:parts = block.split('Possible Answers:')question_text = parts[0].strip()answers_text = parts[1].strip()possible_answers = [ans.strip() for ans in re.split(r'\d+\.\s+', answers_text) if ans.strip()]questions.append({'question': question_text, 'answers': possible_answers})return questionsall_questions = load_questions('knowledge.txt')# Question categorization (same as your existing code)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")# Backend logic (all functions same as before — no changes)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()3 unmodified linesreturn chat_historyif 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."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)q_index += 1user_profile['current_q'] = q_indexif 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."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# Normal chatbot conversationmessages = [{"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})messages.append({"role": "user", "content": message})response = client.chat_completion(messages, max_tokens=150, stream=False)bot_msg = response.choices[0].message.contentchat_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 key points: {correct_answers[0]}"feedback.append(fb)return "\n".join(feedback)# The new Intervu 2.0 UI with your design!with gr.Blocks(css="""body { background-color: #161b24; font-family: 'Nato', sans-serif !important; }1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253543 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181 unmodified linefrom huggingface_hub import InferenceClientimport reimport randomimport whisperfrom pydub import AudioSegment# modelsclient = InferenceClient("HuggingFaceH4/zephyr-7b-beta")whisper_model = whisper.load_model("base")# whisper audio-to-text functiondef transcribe_audio(file_path):try:print(f"📂 Processing audio: {file_path}")audio = AudioSegment.from_file(file_path)converted_path = "converted.wav"audio.export(converted_path, format="wav")result = whisper_model.transcribe(converted_path, fp16=False)return result["text"]except Exception as e:return f"❌ ERROR: {str(e)}"# setting up the users profile (step 1)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# step 2def save_background(info, user_profile):user_profile["field"] = inforeturn "Awesome! Type 'start' below to begin your interview.", user_profile# generate question using LLMdef generate_question(user_profile):system_prompt = f"You are a professional interviewer conducting a {user_profile['interview_type']} interview for a candidate in {user_profile['field']}. Generate one thoughtful, clear, and concise interview question."messages = [{"role": "system", "content": system_prompt}]response = client.chat_completion(messages, max_tokens=100, stream=False)return response.choices[0].message.content.strip()# generate feedback using LLMdef generate_feedback_llm(user_profile):feedback = []for i, (question, answer) in enumerate(zip(user_profile.get("questions", []), user_profile.get("user_answers", []))):messages = [{"role": "system", "content": f"You are a professional interviewer providing feedback for a candidate's response in a {user_profile['interview_type']} interview for a {user_profile['field']} role."},{"role": "user", "content": f"Question: {question}\nAnswer: {answer}\nPlease give specific, constructive feedback."}]response = client.chat_completion(messages, max_tokens=150, stream=False)feedback.append(f"Question {i+1}: {response.choices[0].message.content.strip()}")return "\n\n".join(feedback)# step 3: interview loopdef respond(message, chat_history, user_profile):message_lower = message.strip().lower()3 unmodified linesreturn chat_historyif message_lower == 'start':user_profile['questions'] = []user_profile['user_answers'] = []user_profile['current_q'] = 0user_profile['interview_in_progress'] = Trueintro = f"Welcome to your {user_profile['interview_type']} interview for a {user_profile['field']} position. I will ask you up to 10 questions. Type 'stop' anytime to end."first_q = generate_question(user_profile)user_profile['questions'].append(first_q)chat_history.append((message, intro))chat_history.append(("", f"First question: {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 message_lower == 'feedback':feedback = generate_feedback_llm(user_profile)chat_history.append((message, feedback))return chat_historyif user_profile.get("interview_in_progress"):user_profile['user_answers'].append(message)user_profile['current_q'] += 1if user_profile['current_q'] < 10:next_q = generate_question(user_profile)user_profile['questions'].append(next_q)bot_msg = f"Next question: {next_q}"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_history# fallback LLM responsemessages = [{"role": "system", "content": f"You are a professional interviewer conducting a {user_profile['interview_type']} interview for a candidate in {user_profile['field']}."},{"role": "user", "content": message}]response = client.chat_completion(messages, max_tokens=150, stream=False)bot_msg = response.choices[0].message.content.strip()chat_history.append((message, bot_msg))return chat_history# handle audio inputdef handle_audio(audio_file, chat_history, user_profile):transcribed = transcribe_audio(audio_file)if transcribed.startswith("❌"):chat_history.append(("Audio input", transcribed))return chat_historyreturn respond(transcribed, chat_history, user_profile)# The new Intervu 2.0 UI with your design!with gr.Blocks(css="""body { background-color: #161b24; font-family: 'Nato', sans-serif !important; }
app.py+70-77