Imarticuslearning commited on
Commit
7772256
·
verified ·
1 Parent(s): a7caa60

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +176 -0
app.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import time
4
+ from dotenv import load_dotenv
5
+ import streamlit as st
6
+ from gtts import gTTS
7
+ import PyPDF2
8
+ import google.generativeai as genai
9
+ import speech_recognition as sr
10
+
11
+ # Load API key
12
+ load_dotenv()
13
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
14
+
15
+ # Initialize session state
16
+ for key, default in {
17
+ "generated_questions": [],
18
+ "current_question_index": 0,
19
+ "answers": [],
20
+ "evaluation_feedback": "",
21
+ "overall_score": 0,
22
+ "percentage_score": 0,
23
+ "is_recording": False,
24
+ "question_played": False,
25
+ "selected_domain": ""
26
+ }.items():
27
+ if key not in st.session_state:
28
+ st.session_state[key] = default
29
+
30
+ # Extract text from PDF
31
+ def extract_pdf_text(uploaded_file):
32
+ pdf_reader = PyPDF2.PdfReader(uploaded_file)
33
+ return "".join(page.extract_text() or "" for page in pdf_reader.pages).strip()
34
+
35
+ # Generate interview questions
36
+ def get_questions(prompt, input_text, num_questions=3):
37
+ model = genai.GenerativeModel('gemini-1.5-pro-latest')
38
+ response = model.generate_content([prompt, input_text])
39
+ questions = [q.strip("* ") for q in response.text.strip().split("\n") if q.strip() and "question" not in q.lower()]
40
+ return questions[:num_questions]
41
+
42
+ # Evaluate candidate answers
43
+ def evaluate_answers():
44
+ model = genai.GenerativeModel('gemini-1.5-pro-latest')
45
+
46
+ prompt = """
47
+ You are an expert interview evaluator. Assess responses based on:
48
+ - Conceptual Understanding
49
+ - Communication Skills
50
+ - Clarity & Depth of Explanation
51
+ - Use of Real-World Examples
52
+ - Logical Flow
53
+
54
+ Provide a score (out of 10) and an evaluation summary.
55
+
56
+ **Format:**
57
+ **Overall Score:** x/10
58
+ **Evaluation Summary:**
59
+ - Concept Understanding: ...
60
+ - Communication: ...
61
+ - Depth of Explanation: ...
62
+ - Examples: ...
63
+ - Logical Flow: ...
64
+ """
65
+
66
+ candidate_responses = "\n\n".join(
67
+ [f"Q: {entry['question']}\nA: {entry['response']}" for entry in st.session_state["answers"]]
68
+ )
69
+
70
+ full_prompt = f"{prompt}\n\nCandidate Responses:\n{candidate_responses}"
71
+ response = model.generate_content(full_prompt)
72
+
73
+ st.session_state["evaluation_feedback"] = response.text.strip()
74
+
75
+ score_match = re.search(r"\*\*Overall Score:\*\* (\d+)/10", response.text)
76
+ st.session_state["overall_score"] = int(score_match.group(1)) if score_match else 0
77
+ st.session_state["percentage_score"] = st.session_state["overall_score"] * 10
78
+
79
+ # Convert question to speech and allow manual playback
80
+ def generate_question_audio(question):
81
+ tts = gTTS(text=question, lang="en")
82
+ tts.save("question.mp3")
83
+
84
+ # Streamlit UI
85
+ st.set_page_config(page_title="GrillMaster", layout="wide")
86
+ st.sidebar.header("Imarticus GrillMaster")
87
+
88
+ # Domain selection
89
+ st.sidebar.subheader("Select Interview Domain:")
90
+ col1, col2 = st.sidebar.columns(2)
91
+
92
+ if col1.button("Analytics"):
93
+ st.session_state["selected_domain"] = "Analytics"
94
+ if col2.button("Finance"):
95
+ st.session_state["selected_domain"] = "Finance"
96
+
97
+ if not st.session_state["selected_domain"]:
98
+ st.warning("Please select a domain to proceed.")
99
+ st.stop()
100
+
101
+ # Sidebar options
102
+ section_choice = st.sidebar.radio("Choose Input Type:", ("Resume", "Job Description", "Skills"))
103
+
104
+ # Skill options based on domain
105
+ if st.session_state["selected_domain"] == "Analytics":
106
+ skill_options = ["Python", "SQL", "Machine Learning", "Statistics", "Business Analytics"]
107
+ elif st.session_state["selected_domain"] == "Finance":
108
+ skill_options = ["Fund Accounting", "Investment Banking", "Derivatives"]
109
+
110
+ input_text = ""
111
+ if section_choice == "Resume":
112
+ uploaded_file = st.sidebar.file_uploader("Upload Resume:", type=["pdf", "txt"])
113
+ if uploaded_file:
114
+ input_text = extract_pdf_text(uploaded_file)
115
+ elif section_choice == "Job Description":
116
+ input_text = st.sidebar.text_area("Paste Job Description:")
117
+ elif section_choice == "Skills":
118
+ input_text = st.sidebar.selectbox("Select a Skill:", skill_options)
119
+
120
+ difficulty_level = st.sidebar.selectbox("Select Difficulty Level:", ["Beginner", "Intermediate", "Advanced"])
121
+ num_questions = st.sidebar.slider("Number of Questions:", 1, 10, 3)
122
+
123
+
124
+
125
+ # Generate Questions
126
+ if st.sidebar.button("Generate Questions"):
127
+ prompt = f"""
128
+ You are an expert interviewer conducting a {difficulty_level} level {st.session_state['selected_domain']} interview.
129
+ Ask {num_questions} clear and direct {st.session_state['selected_domain']}-related questions.
130
+ """
131
+
132
+ st.session_state["generated_questions"] = get_questions(prompt, input_text, num_questions)
133
+ st.session_state["current_question_index"] = 0
134
+ st.session_state["answers"] = []
135
+ st.session_state["evaluation_feedback"] = ""
136
+ st.session_state["question_played"] = False
137
+ st.rerun()
138
+
139
+ # Display Current Question
140
+ if st.session_state["generated_questions"]:
141
+ q_index = st.session_state["current_question_index"]
142
+
143
+ if q_index < len(st.session_state["generated_questions"]):
144
+ question = st.session_state["generated_questions"][q_index]
145
+ generate_question_audio(question)
146
+ st.audio("question.mp3", format="audio/mp3")
147
+ st.write(f"**{question}**", unsafe_allow_html=True)
148
+
149
+ recognizer = sr.Recognizer()
150
+
151
+ if st.button("Start Recording"):
152
+ st.session_state["is_recording"] = True
153
+ with sr.Microphone() as source:
154
+ st.write("🎤 Listening... Speak your answer.")
155
+ try:
156
+ audio = recognizer.listen(source, timeout=60)
157
+ response_text = recognizer.recognize_google(audio)
158
+ st.session_state["answers"].append({"question": question, "response": response_text})
159
+ st.session_state["is_recording"] = False
160
+ except sr.UnknownValueError:
161
+ st.write("Could not understand the audio. Try again.")
162
+
163
+ if st.button("Stop Recording"):
164
+ st.session_state["is_recording"] = False
165
+
166
+ if st.button("➡️ Next Question"):
167
+ st.session_state["current_question_index"] += 1
168
+ st.session_state["question_played"] = False
169
+ st.rerun()
170
+ else:
171
+ evaluate_answers()
172
+ st.subheader("📊 Complete Mock Interview Summary")
173
+ st.write(f"**Overall Score:** {st.session_state['overall_score']} / 10")
174
+ st.write(f"**Percentage Score:** {st.session_state['percentage_score']:.2f}%")
175
+ st.progress(st.session_state["percentage_score"] / 100)
176
+ st.write(st.session_state["evaluation_feedback"], unsafe_allow_html=True)