Imarticuslearning commited on
Commit
3c51494
·
verified ·
1 Parent(s): bd4bac8

Upload app.py

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