Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111213141516171 unmodified line1920212223242526272829303132333435363738394041425 unmodified lines484950515253545556575859605 unmodified lines666768697071727374757677787980818283848 unmodified lines939495969798993 unmodified lines103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234import gradio as grfrom 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")1 unmodified linereturn 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", []))):5 unmodified linesfeedback.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()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_historyif message_lower == 'start':5 unmodified linesintro = 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"):8 unmodified linesuser_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 response3 unmodified lines]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; }h1 { text-align: center; color: #2c3e50; }img { display: block; margin: auto; width: 100px; border-radius: 20px; }button {font-size: 16px;padding: 10px 20px;border-radius: 10px;border: 2px solid rgba(124, 248, 255, 0.4);background-color: rgba(124, 248, 255, 0.4);color: #fafdff;transition: all 0.2s ease;}button:hover {background-color: #49888f;border-color: #7cf8ff;transform: scale(1.05);}.gr-chatbot { background-color: white; border-radius: 15px; padding: 20px; }""") as demo:gr.Markdown("""<div style='width: 100%; text-align: center;'><img src="https://cdn-uploads.huggingface.co/production/uploads/6841b10b397a67a7c7a39b89/MTR_dMHte-RCIbyujLW83.png" style="width: 100%; height: auto; object-fit: contain;"></div>""")user_profile = gr.State({"interview_type": "", "field": "", "interview_in_progress": False})chat_history = gr.State([])#Headergr.Markdown("""<div style='font-family: 'Lato', sans-serif;text-align: center;padding: 30px;box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);margin-bottom: 20px;'><h1 style='font-size: 89.5px; color: #fafdff;'>Welcome to <b><span style='color: #7cf8ff;'>Intervu</span></b></h1><p style='font-size: 22.1px; color: #fafdff; margin-top: 30px; text-align: center; margin-bottom: 30px;'>Before you begin, complete Step 1 to select your interview type and Step 2 to enter your background. Practice is available through text, speech, or webcam.</p></div>""")# Step 1 - Choose Interview Type# gr.Markdown("### Step 1: Choose Interview Type")# with gr.Row():# btn1 = gr.Button("Technical")# btn2 = gr.Button("Competency-Based Interview")# btn3 = gr.Button("Case")# type_output = gr.Textbox(label="Bot response", interactive=False)with gr.Row():# LEFT SIDE: Transparent box with interview type buttonswith gr.Column(scale=2):gr.Markdown("""<div style="background: rgba(255, 255, 255, 0.1);padding: 20px;border-radius: 15px;backdrop-filter: blur(5px);box-shadow: 0 4px 10px rgba(0,0,0,0.2);"><h3>Step 1: Choose Interview Type</h3><p>Select the type of interview you want to practice.</p></div>""")btn1 = gr.Button("Technical")btn2 = gr.Button("Competency-Based Interview")btn3 = gr.Button("Case")# RIGHT SIDE: Bot response display (type_output)with gr.Column(scale=2):type_output = gr.Textbox(label="Bot Response", interactive=False)btn1.click(set_type, inputs=[gr.Textbox(value="Technical", visible=False), user_profile], outputs=[type_output, user_profile])btn2.click(set_type, inputs=[gr.Textbox(value="Competency-Based Interview", visible=False), user_profile], outputs=[type_output, user_profile])btn3.click(set_type, inputs=[gr.Textbox(value="Case", visible=False), user_profile], outputs=[type_output, user_profile])# Step 2 - Enter Backgroundgr.Markdown("### Step 2: Enter Your Background")background = gr.Textbox(label="Your background and field/goal")background_btn = gr.Button("Submit")background_output = gr.Textbox(label="Bot response", interactive=False)background_btn.click(save_background, inputs=[background, user_profile], outputs=[background_output, user_profile])# Step 3 - Chatbot Mode Selection# Step 3 - Chatbot Mode Selection# Step 3 - Chatbot Mode Selectiongr.Markdown("### Step 3: Choose Chat Mode")with gr.Tabs():with gr.Tab("Text Mode"):chatbot_text = gr.Chatbot(label="Interview Chat (Text Mode)")msg = gr.Textbox(label="Type 'start' to begin")send_btn = gr.Button("Send")send_btn.click(respond, inputs=[msg, chat_history, user_profile], outputs=[chatbot_text], queue=False)send_btn.click(lambda: "", None, msg, queue=False)with gr.Tab("Audio Mode"):chatbot_audio = gr.Chatbot(label="Interview Chat (Audio Mode)")audio_input = gr.Audio(source="microphone", type="filepath", label="Record Your Answer")audio_btn = gr.Button("Send Audio")audio_btn.click(handle_audio, inputs=[audio_input, chat_history, user_profile], outputs=[chatbot_audio], queue=False)demo.launch()1234567891011121314151 unmodified line171819202122232425262728293031323334353637383940415 unmodified lines47484950515253545556575859605 unmodified lines666768697071727374757677787980818283848586878 unmodified lines969798991001011021033 unmodified lines107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163import gradio as grfrom huggingface_hub import InferenceClientimport whisperfrom pydub import AudioSegment# Load modelsclient = InferenceClient("HuggingFaceH4/zephyr-7b-beta")whisper_model = whisper.load_model("base")# Whisper transcription functiondef transcribe_audio(file_path):try:audio = AudioSegment.from_file(file_path)converted_path = "converted.wav"audio.export(converted_path, format="wav")1 unmodified linereturn result["text"]except Exception as e:return f"❌ ERROR: {str(e)}"# Step 1: Set interview typedef 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 2: Save backgrounddef save_background(info, user_profile):user_profile["field"] = inforeturn "Awesome! Type 'start' below to begin your interview.", user_profile# Generate interview questiondef 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", []))):5 unmodified linesfeedback.append(f"Question {i+1}: {response.choices[0].message.content.strip()}")return "\n\n".join(feedback)# Chat logicdef 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({"role": "user", "content": message})chat_history.append({"role": "assistant", "content": bot_msg})return chat_historyif message_lower == 'start':5 unmodified linesintro = 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({"role": "user", "content": message})chat_history.append({"role": "assistant", "content": intro})chat_history.append({"role": "assistant", "content": 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({"role": "user", "content": message})chat_history.append({"role": "assistant", "content": bot_msg})return chat_historyif message_lower == 'feedback':feedback = generate_feedback_llm(user_profile)chat_history.append({"role": "user", "content": message})chat_history.append({"role": "assistant", "content": feedback})return chat_historyif user_profile.get("interview_in_progress"):8 unmodified linesuser_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({"role": "user", "content": message})chat_history.append({"role": "assistant", "content": bot_msg})return chat_history# fallback LLM response3 unmodified lines]response = client.chat_completion(messages, max_tokens=150, stream=False)bot_msg = response.choices[0].message.content.strip()chat_history.append({"role": "user", "content": message})chat_history.append({"role": "assistant", "content": 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({"role": "assistant", "content": transcribed})return chat_historyreturn respond(transcribed, chat_history, user_profile)# Gradio UIwith gr.Blocks(css="""body { background-color: #161b24; font-family: 'Nato', sans-serif !important; }""") as demo:gr.Markdown("# 🎤 Welcome to Intervu")user_profile = gr.State({"interview_type": "", "field": "", "interview_in_progress": False})chat_history = gr.State([])# Step 1with gr.Row():with gr.Column():btn1 = gr.Button("Technical")btn2 = gr.Button("Competency-Based Interview")btn3 = gr.Button("Case")type_output = gr.Textbox(label="Bot Response", interactive=False)btn1.click(set_type, inputs=[gr.Textbox(value="Technical", visible=False), user_profile], outputs=[type_output, user_profile])btn2.click(set_type, inputs=[gr.Textbox(value="Competency-Based Interview", visible=False), user_profile], outputs=[type_output, user_profile])btn3.click(set_type, inputs=[gr.Textbox(value="Case", visible=False), user_profile], outputs=[type_output, user_profile])# Step 2background = gr.Textbox(label="Your background and field/goal")background_btn = gr.Button("Submit")background_output = gr.Textbox(label="Bot response", interactive=False)background_btn.click(save_background, inputs=[background, user_profile], outputs=[background_output, user_profile])# Step 3 - Tabsgr.Markdown("### Choose Chat Mode")with gr.Tabs():with gr.Tab("Text Mode"):chatbot_text = gr.Chatbot(label="Interview Chat (Text Mode)", type="messages")msg = gr.Textbox(label="Type 'start' to begin")send_btn = gr.Button("Send")send_btn.click(respond, inputs=[msg, chat_history, user_profile], outputs=[chatbot_text], queue=False)send_btn.click(lambda: "", None, msg, queue=False)with gr.Tab("Audio Mode"):chatbot_audio = gr.Chatbot(label="Interview Chat (Audio Mode)", type="messages")audio_input = gr.Audio(type="filepath", label="Record Your Answer")audio_btn = gr.Button("Send Audio")audio_btn.click(handle_audio, inputs=[audio_input, chat_history, user_profile], outputs=[chatbot_audio], queue=False)demo.launch()
app.py+39-110