File size: 7,050 Bytes
26ac873
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
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)