Spaces:
Runtime error
Runtime error
Update app.py
Browse files123451 unmodified line7891011121310 unmodified lines2425262728296 unmodified lines363738394041424344454647484950515253545556575859606162632 unmodified lines66676869707137 unmodified lines1091101111121131149 unmodified lines1241251261271281291301311321331341351361371381391401411421431441451461471481491501511521 unmodified line15415515615715815931 unmodified lines191192193194195196197198# 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()10 unmodified linesall_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',6 unmodified lines"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()2 unmodified lineschat_history.append((message, bot_msg))return chat_historyif message_lower == 'start':interview_type = user_profile['interview_type']selected_questions = questions_by_type.get(interview_type, [])37 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})9 unmodified linesfeedback = []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([])31 unmodified linessend_btn = gr.Button("Send Text")audio_btn = gr.Button("Send Audio")send_btn.click(respond, inputs=[msg, chat_history, user_profile], outputs=[chatbot], queue=False)send_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()12341 unmodified line678910111210 unmodified lines232425262728296 unmodified lines3637383940414243444546474849505152535455565758596061626364656667682 unmodified lines7172737475767737 unmodified lines1151161171181191201219 unmodified lines1311321331341351361371381391401411421431441451461471 unmodified line14915015115215315415531 unmodified lines187188189190191192193194195196# 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()10 unmodified linesall_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',6 unmodified lines"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)}"# 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# step 3def respond(message, chat_history, user_profile):message_lower = message.strip().lower()2 unmodified lineschat_history.append((message, bot_msg))return chat_history# interview processif message_lower == 'start':interview_type = user_profile['interview_type']selected_questions = questions_by_type.get(interview_type, [])37 unmodified lineschat_history.append((message, feedback))return chat_history# starting the chatbotmessages = [{"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})9 unmodified linesfeedback = []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)# handle audio inputdef 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)# creating the visual elementswith gr.Blocks() as demo:user_profile = gr.State({"interview_type": "", "field": "", "interview_in_progress": False})chat_history = gr.State([])31 unmodified linessend_btn = gr.Button("Send Text")audio_btn = gr.Button("Send Audio")send_btn.click(respond, inputs=[msg, chat_history, user_profile], outputs=[chatbot], queue=False)send_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+18-20