Spaces:
Runtime error
Runtime error
Update app.py
Browse files12341 unmodified line67891011123 unmodified lines1617181920212223242526273 unmodified lines31323334353637383940414243444546474849505152535455565758596061626364656645 unmodified lines1121131141151161171185 unmodified lines1241251261271281291301311321331341351361371381391401411421431441451461471481491501 unmodified line15215315415515615715835 unmodified lines194195196197# importsimport gradio as grfrom huggingface_hub import InferenceClientimport re1 unmodified lineimport whisperfrom pydub import AudioSegment# uploading and cleaning the knowledge txt filedef load_questions(file_path):with open(file_path, 'r') as f:data = f.read()3 unmodified linesfor block in question_blocks:parts = block.split('Possible Answers:')question_text = parts[0].strip()questions.append({'question': question_text})return questionsall_questions = load_questions('knowledge.txt')# creating the questions based on each interviewquestions_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',3 unmodified lines'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"])]}# 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)}"# step 1def 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# updated step 3def respond(message, chat_history, user_profile):message_lower = message.strip().lower()45 unmodified lineschat_history.append((message, feedback))return chat_history# chatbot fallbackmessages = [{"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})5 unmodified lineschat_history.append((message, bot_msg))return chat_history# updated feedback using modeldef generate_feedback(user_profile):questions = user_profile.get('questions', [])answers = user_profile.get('user_answers', [])feedback = []for i, (question, user_answer) in enumerate(zip(questions, answers)):prompt = (f"You are an expert interviewer. Please evaluate the following response:\n\n"f"Question: {question['question']}\n"f"Candidate's Answer: {user_answer}\n\n"f"Give a brief, constructive evaluation. Say whether it's a strong, okay, or weak answer and what could be improved.")response = client.text_generation(prompt, max_new_tokens=200)evaluation = response.strip()feedback.append(f"Question {i+1}:\n{evaluation}\n")return "\n".join(feedback)# handle audiodef handle_audio(audio_file, chat_history, user_profile):transcribed = transcribe_audio(audio_file)if transcribed.startswith("β"):1 unmodified linereturn chat_historyreturn respond(transcribed, chat_history, user_profile)# UIwith gr.Blocks() as demo:user_profile = gr.State({"interview_type": "", "field": "", "interview_in_progress": False})chat_history = gr.State([])35 unmodified linessend_btn.click(lambda: "", None, msg, queue=False)audio_btn.click(handle_audio, inputs=[audio_input, chat_history, user_profile], outputs=[chatbot], queue=False)demo.launch()123451 unmodified line789101112133 unmodified lines171819202122232425262728293 unmodified lines3334353637383940414243444546474849505152535455565758596061626345 unmodified lines1091101111121131145 unmodified lines1201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521 unmodified line15415515615715815935 unmodified lines195196197198# Updated full code with safe feedback handlingimport gradio as grfrom huggingface_hub import InferenceClientimport re1 unmodified lineimport whisperfrom pydub import AudioSegment# Load and parse the knowledge filedef load_questions(file_path):with open(file_path, 'r') as f:data = f.read()3 unmodified linesfor 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')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',3 unmodified lines'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")whisper_model = whisper.load_model("base")def transcribe_audio(file_path):try:print(f"\U0001F4C2 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"\u274C ERROR: {str(e)}"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()45 unmodified lineschat_history.append((message, feedback))return chat_historymessages = [{"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})5 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', [])if not questions or not answers:return "β οΈ Feedback unavailable: Make sure you've completed the interview first."for i, user_ans in enumerate(answers):if i >= len(questions):feedback.append(f"β οΈ No matching question for answer {i+1}.")continuecorrect_answers = questions[i].get('answers', [])if not correct_answers:feedback.append(f"β No expected answers listed for question {i+1}.")continuematch = 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)def handle_audio(audio_file, chat_history, user_profile):transcribed = transcribe_audio(audio_file)if transcribed.startswith("β"):1 unmodified linereturn chat_historyreturn respond(transcribed, chat_history, user_profile)with gr.Blocks() as demo:user_profile = gr.State({"interview_type": "", "field": "", "interview_in_progress": False})chat_history = gr.State([])35 unmodified linessend_btn.click(lambda: "", None, msg, queue=False)audio_btn.click(handle_audio, inputs=[audio_input, chat_history, user_profile], outputs=[chatbot], queue=False)demo.launch()
app.py+29-28