Spaces:
Runtime error
Runtime error
Update app.py
Browse files12345 unmodified lines10111213141516171819202122232425262728293031323334353637383940414243444546474849506 unmodified lines575859606162636 unmodified lines70717273747576777879808182832 unmodified lines86878889909192939495969798991001011022 unmodified lines10510610710810911011137 unmodified lines14915015115215315415515 unmodified lines1711721731741751761771781791801811 unmodified line18318418518618718818919019119219319412 unmodified lines207208209210211212213214215216217218219220221222223224225226227228229230# importsimport gradio as grfrom huggingface_hub import InferenceClientimport re5 unmodified linesimport torchvision.models as modelsfrom PIL import Image# Load ResNet18 modelmodel = models.resnet18(weights=models.ResNet18_Weights.IMAGENET1K_V1)model.fc = torch.nn.Linear(model.fc.in_features, 2) # Adjust for two classesmodel.eval()# Define image transformationtransform = transforms.Compose([transforms.Resize((224, 224)),transforms.ToTensor()])# Function to classify posture imagesdef classify_image(image):if image is None:return "No image provided! Please upload or capture an image."image = transform(image).unsqueeze(0)output = model(image)_, predicted = torch.max(output, 1)return ("Good Posture! Sit exactly like that for your Interview!"if predicted.item() == 0else "Bad Posture, you should think of sitting a little straighter or more in frame for your real interview.")# Set up Gradio interfaceiface = gr.Interface(fn=classify_image, inputs=gr.Image(type="pil"), outputs="text")iface.launch()# uploading and cleaning the knowledge txt filedef 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:6 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")2 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# 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})15 unmodified linesif 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([])gr.Markdown("# Welcome to Intervu")gr.Image(value="images.JPEG", show_label=False, width=200)gr.Markdown("### Step 1: Choose Interview Type")12 unmodified linesbackground = 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])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")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()12345 unmodified lines101112131415161718192021222324252627282930313233343536376 unmodified lines4445464748496 unmodified lines5657585960616263642 unmodified lines67686970717273747576777879808182838485868788899091929394952 unmodified lines989910010110210337 unmodified lines14114214314414514615 unmodified lines1621631641651661671681691701711721 unmodified line17417517617717817918018118218318418518612 unmodified lines199200201202203204205206207208209210211212213214215216217218219220221222223224# --- IMPORTS ---import gradio as grfrom huggingface_hub import InferenceClientimport re5 unmodified linesimport torchvision.models as modelsfrom PIL import Image# --- LOAD MODELS ---# HuggingFace Zephyr Model for Chatclient = InferenceClient("HuggingFaceH4/zephyr-7b-beta")# Whisper Model for Audio-to-Textwhisper_model = whisper.load_model("base")# ResNet18 Model for Posture Classificationmodel = models.resnet18(weights=models.ResNet18_Weights.IMAGENET1K_V1)model.fc = torch.nn.Linear(model.fc.in_features, 2)model.eval()transform = transforms.Compose([transforms.Resize((224, 224)),transforms.ToTensor()])# --- LOAD QUESTIONS ---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:6 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"])]}# --- AUDIO TRANSCRIPTION ---def transcribe_audio(file_path):try:audio = AudioSegment.from_file(file_path)converted_path = "converted.wav"audio.export(converted_path, format="wav")2 unmodified linesexcept Exception as e:return f"β ERROR: {str(e)}"# --- POSTURE CLASSIFICATION ---def classify_image(image):if image is None:return "No image provided! Please upload or capture an image."image = transform(image).unsqueeze(0)output = model(image)_, predicted = torch.max(output, 1)return ("β Good Posture! Sit exactly like that for your Interview!"if predicted.item() == 0else "β οΈ Bad Posture β try sitting straighter or more centered for your real interview.")# --- INTERVIEW LOGIC ---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})15 unmodified linesif 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)# AUDIO HANDLINGdef 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 INTERFACE ---with 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")12 unmodified linesbackground = 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])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")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)# β Step 4: Webcam Posture Checkgr.Markdown("### Step 4: Webcam Posture Check")webcam = gr.Image(source="webcam", type="pil", label="Capture Posture")posture_output = gr.Textbox(label="Posture Feedback")posture_btn = gr.Button("Analyze Posture")posture_btn.click(classify_image, inputs=[webcam], outputs=[posture_output])# LAUNCHdemo.launch()
app.py+40-46