GrillMaster / new_app.py
Imarticuslearning's picture
Upload new_app.py
26ac873 verified
import os
import re
import time
from dotenv import load_dotenv
import streamlit as st
from gtts import gTTS
import PyPDF2
import google.generativeai as genai
import speech_recognition as sr
# Load API key
load_dotenv()
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
# Initialize session state
if "generated_questions" not in st.session_state:
st.session_state["generated_questions"] = []
if "current_question_index" not in st.session_state:
st.session_state["current_question_index"] = 0
if "answers" not in st.session_state:
st.session_state["answers"] = []
if "evaluation_feedback" not in st.session_state:
st.session_state["evaluation_feedback"] = ""
if "overall_score" not in st.session_state:
st.session_state["overall_score"] = 0
if "percentage_score" not in st.session_state:
st.session_state["percentage_score"] = 0
if "is_recording" not in st.session_state:
st.session_state["is_recording"] = False
if "question_played" not in st.session_state:
st.session_state["question_played"] = False
# Extract text from PDF
def extract_pdf_text(uploaded_file):
pdf_reader = PyPDF2.PdfReader(uploaded_file)
text = ''.join(page.extract_text() or "" for page in pdf_reader.pages)
return text.strip()
# Generate conceptual interview questions
def get_questions(prompt, input_text, num_questions=3):
model = genai.GenerativeModel('gemini-1.5-pro-latest')
response = model.generate_content([prompt, input_text])
questions = [q.strip("* ") for q in response.text.strip().split("\n") if q.strip() and "question" not in q.lower()]
return questions[:num_questions]
# Evaluate answers automatically
def evaluate_answers():
model = genai.GenerativeModel('gemini-1.5-pro-latest')
prompt = """
You are an expert interview evaluator. Assess the responses based on:
- Conceptual Understanding
- Communication Skills
- Clarity & Depth of Explanation
- Use of Real-World Examples
- Logical Flow
Provide an evaluation summary with a score out of 10.
Format:
**Overall Score:** x/10
**Evaluation Summary:**
- Concept Understanding: ...
- Communication: ...
- Depth of Explanation: ...
- Examples: ...
- Logical Flow: ...
"""
candidate_responses = "\n\n".join(
[f"Q: {entry['question']}\nA: {entry['response']}" for entry in st.session_state["answers"]]
)
full_prompt = f"{prompt}\n\nCandidate Responses:\n{candidate_responses}"
response = model.generate_content(full_prompt)
st.session_state["evaluation_feedback"] = response.text.strip()
score_match = re.search(r"\*\*Overall Score:\*\* (\d+)/10", response.text)
if score_match:
st.session_state["overall_score"] = int(score_match.group(1))
st.session_state["percentage_score"] = st.session_state["overall_score"] * 10
else:
st.session_state["overall_score"] = 0
st.session_state["percentage_score"] = 0
# Function to convert question to speech
def speak_question(question):
if not st.session_state["question_played"]:
tts = gTTS(text=question, lang="en")
tts.save("question.mp3")
st.audio("question.mp3", format="audio/mp3", autoplay=True)
st.session_state["question_played"] = True
# Streamlit UI Enhancements
st.set_page_config(page_title="πŸ”₯🎯 GrillMaster", layout="wide")
st.sidebar.header("πŸ”₯🎯 Imarticus GrillMaster")
num_questions = st.sidebar.slider("Number of Questions:", 1, 10, 3)
difficulty_level = st.sidebar.selectbox("Select Difficulty Level:", ["Beginner", "Intermediate", "Advance"])
section_choice = st.sidebar.radio("Choose Input Type:", ("Resume", "Job Description", "Skills"))
input_text = ""
if section_choice == "Resume":
uploaded_file = st.sidebar.file_uploader("Upload Resume:", type=["pdf", "txt"])
if uploaded_file:
input_text = extract_pdf_text(uploaded_file)
elif section_choice == "Job Description":
input_text = st.sidebar.text_area("Paste Job Description:")
elif section_choice == "Skills":
input_text = st.sidebar.selectbox("Select a Skill:", ["Python", "SQL", "Machine Learning", "Statistics", "Business Analytics"])
if st.sidebar.button("Generate Questions"):
prompt =f"""
You are a trainer conducting a beginner-level mock interview.
Ask {num_questions} direct and fundamental questions related to {input_text}.
Keep them concise and focused on key concepts, similar to:
- Difference between DDL and DML
- Types of Joins in SQL
- Primary Key vs Foreign Key
- Loops in Python
Ensure the questions are clear, to the point, and suitable for a {difficulty_level} level interview.
"""
st.session_state["generated_questions"] = get_questions(prompt, input_text, num_questions)
st.session_state["current_question_index"] = 0
st.session_state["answers"] = []
st.session_state["evaluation_feedback"] = ""
st.session_state["question_played"] = False
st.rerun()
# Display Current Question
if st.session_state["generated_questions"]:
q_index = st.session_state["current_question_index"]
if q_index < len(st.session_state["generated_questions"]):
question = st.session_state["generated_questions"][q_index]
#st.subheader(f"Q{q_index + 1}:")
st.write(f"**{question}**", unsafe_allow_html=True)
speak_question(question)
recognizer = sr.Recognizer()
if st.button("Start Recording"):
st.session_state["is_recording"] = True
with sr.Microphone() as source:
st.write("🎀 Listening... Speak your answer.")
try:
audio = recognizer.listen(source, timeout=60)
response_text = recognizer.recognize_google(audio)
st.session_state["answers"].append({"question": question, "response": response_text})
st.session_state["is_recording"] = False
except sr.UnknownValueError:
st.write("Could not understand the audio. Try again.")
if st.button("Stop Recording"):
st.session_state["is_recording"] = False
if st.button("➑️ Next Question"):
st.session_state["current_question_index"] += 1
st.session_state["question_played"] = False
st.rerun()
else:
evaluate_answers()
st.subheader("πŸ“Š Complete Mock Interview Summary")
st.write(f"**Overall Score:** {st.session_state['overall_score']} / 10")
st.write(f"**Percentage Score:** {st.session_state['percentage_score']:.2f}%")
st.progress(st.session_state["percentage_score"] / 100)
st.write(st.session_state["evaluation_feedback"], unsafe_allow_html=True)