testing / app.py
KhaqanNasir's picture
Update app.py
156b0ac verified
import streamlit as st
import random
import time
from transformers import pipeline
import speech_recognition as sr
from streamlit_webrtc import webrtc_streamer, VideoTransformerBase
import numpy as np
import io
# Streamlit Configuration
st.set_page_config(page_title="Interview Copilot", layout="wide")
st.markdown(
"""
<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap');
html, body, [class*="css"] {
font-family: 'Poppins', sans-serif;
}
</style>
""", unsafe_allow_html=True)
# Page Title
st.title("πŸŽ™οΈ Interview Copilot")
st.write("### Conduct professional mock interviews, receive feedback, and ace your next job opportunity!")
# Step 1: Input Job Title
st.subheader("Step 1: Enter Job Details")
job_title = st.text_input("Enter Job Title:", placeholder="e.g., Data Scientist, Software Engineer")
job_description = st.text_area("Enter Job Description:", placeholder="Provide details about the role")
# Step 2: Upload CV
st.subheader("Step 2: Upload Your CV")
uploaded_cv = st.file_uploader("Upload Your CV (PDF or Text):", type=["pdf", "txt"])
if uploaded_cv:
cv_content = uploaded_cv.read().decode("utf-8") if uploaded_cv.type == "text/plain" else "Uploaded PDF file"
# Step 3: Start Interview
st.subheader("Step 3: Start the Interview")
if st.button("Start Interview"):
if not job_title or not job_description or not uploaded_cv:
st.error("Please fill in all the required fields (Job Title, Description, CV)!")
else:
# Predefined questions
questions = [
"Introduce yourself.",
"Why do you want this job?",
]
technical_questions = [
"Tell me about a challenging project you've worked on.",
f"What skills do you bring to the role of {job_title}?",
]
non_technical_questions = [
"How do you handle conflict in a team setting?",
"What are your strengths and weaknesses?",
]
# Add random questions to interview
random_questions = random.sample(technical_questions, 2) + random.sample(non_technical_questions, 2)
all_questions = questions + random_questions
# Session state to track question index and responses
if 'question_index' not in st.session_state:
st.session_state.question_index = 0
if 'responses' not in st.session_state:
st.session_state.responses = []
# Step 4: Question and Live Voice Response
current_question = all_questions[st.session_state.question_index]
st.write(f"**Question {st.session_state.question_index + 1}:** {current_question}")
st.write("🎀 Please record your answer using the microphone.")
# Initialize WebRTC for live audio capture
audio_recorder = webrtc_streamer(key="audio-recorder", video_transformer_factory=VideoTransformerBase)
if audio_recorder and audio_recorder.audio:
audio_data = audio_recorder.audio
audio_bytes = audio_data.tobytes() # Convert audio to byte format for processing
audio_file = io.BytesIO(audio_bytes) # Use BytesIO to simulate file for audio processing
# Process the audio
recognizer = sr.Recognizer()
try:
with sr.AudioFile(audio_file) as source:
audio_data = recognizer.record(source)
# Transcribe audio to text
transcript = recognizer.recognize_google(audio_data)
st.session_state.responses.append(transcript)
st.write(f"πŸ“ Transcribed Response: {transcript}")
# Proceed to next question or complete interview
if st.session_state.question_index < len(all_questions) - 1:
st.session_state.question_index += 1
else:
st.session_state.question_index = 0 # Reset to first question after the last one
# Show the next question or finish the interview
if len(st.session_state.responses) < len(all_questions):
st.experimental_rerun()
except sr.UnknownValueError:
st.error("Sorry, I couldn't understand the audio.")
except sr.RequestError as e:
st.error(f"Could not request results from Google Speech Recognition service; {e}")
# Show the evaluation once all responses are collected
if len(st.session_state.responses) == len(all_questions):
st.write("### Interview Completed!")
st.subheader("πŸ“Š Evaluation")
sentiment_analyzer = pipeline("sentiment-analysis")
positive_responses = sum(1 for response in st.session_state.responses if sentiment_analyzer(response)[0]["label"] == "POSITIVE")
# Score Calculation
score = (positive_responses / len(all_questions)) * 100
if score >= 70:
st.success(f"πŸŽ‰ Excellent! You scored {score:.2f}/100. You're ready for the job!")
else:
st.error(f"πŸ™ You scored {score:.2f}/100. Here's how you can improve:")
st.write("- Work on your communication clarity.")
st.write("- Practice using correct grammar and vocabulary.")
st.write("- Focus on pronunciation and speaking confidently.")
# CV Feedback
st.subheader("πŸ“„ CV Recommendations")
st.write("- Add quantifiable achievements to your CV.")
st.write("- Tailor your CV to the job description.")