Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112135 unmodified lines192021222324252627282930313233343536373839404142434445464748495051525354551 unmodified line575859606162636465666768697071727374757677787980818283841 unmodified line868788899091929394959697981 unmodified line100101102103104105106107import 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 Audio-to-Text Function ----------def transcribe_audio(file_path):try:print(f"📂 Processing audio: {file_path}")5 unmodified linesexcept Exception as e:return f"❌ ERROR: {str(e)}"# ---------- 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 2 ----------def save_background(info, user_profile):user_profile["field"] = inforeturn "Awesome! Type 'start' below to begin your interview.", user_profile# ---------- Step 3 ----------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_historymessages = [{"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})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_history# ---------- Handle Audio Input ----------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)# ---------- Gradio UI ----------with gr.Blocks() as demo:user_profile = gr.State({"interview_type": "", "field": ""})chat_history = gr.State([])gr.Markdown('<img src="Take1.jpeg" alt="Banner" style="width: 100%; max-width: 600px;">')gr.Markdown("# 🎤 Welcome to Intervu")# Step 1: Choose Interview Typegr.Markdown("### Step 1: Choose Interview Type")with gr.Row():with gr.Column():btn1 = gr.Button("Behavioral")btn2 = gr.Button("Technical")btn3 = gr.Button("College / Scholarship")type_output = gr.Textbox(label="Bot response", interactive=False)btn1.click(set_type, inputs=[gr.Textbox(value="Behavioral", visible=False), user_profile], outputs=[type_output, user_profile])btn2.click(set_type, inputs=[gr.Textbox(value="Technical", visible=False), user_profile], outputs=[type_output, user_profile])btn3.click(set_type, inputs=[gr.Textbox(value="College", 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")1 unmodified linebackground_btn.click(save_background, inputs=[background, user_profile], outputs=[background_output, user_profile])# Step 3: Interview Chatgr.Markdown("### Step 3: Start Interview")chatbot = gr.Chatbot(label="Interview Bot")with gr.Row():msg = gr.Textbox(label="Your message")audio_input = gr.Audio(type="filepath", label="🎙️ Upload or Record your answer")with gr.Row():send_btn = gr.Button("Send Text")1 unmodified linesend_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)# ---------- Launch App ----------demo.launch()1234567891011121314155 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141 unmodified line1161171181191201211221231241251261271281291301311321331341351361371381391401411 unmodified line1431441451461471481491501511521531541 unmodified line156157158159160161162163# importsimport gradio as grfrom huggingface_hub import InferenceClientimport 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}")5 unmodified linesexcept 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()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':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("❌"):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([])gr.Markdown("# Welcome to Intervu")gr.Image(value="images.JPEG", show_label=False, width=200)gr.Markdown("### Step 1: Choose Interview Type")with 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])gr.Markdown("### Step 2: Enter Your Background")background = gr.Textbox(label="Your background and field/goal")background_btn = gr.Button("Submit")1 unmodified linebackground_btn.click(save_background, inputs=[background, user_profile], outputs=[background_output, user_profile])gr.Markdown("### Step 3: Start Interview")chatbot = gr.Chatbot(label="Interview Bot")with gr.Row():msg = gr.Textbox(label="Your message")audio_input = gr.Audio(type="filepath", label="🎧 Upload or Record your answer")with gr.Row():send_btn = gr.Button("Send Text")1 unmodified linesend_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)if __name__ == "__main__":demo.launch()
app.py+86-30