NiranjanRathod commited on
Commit
ff33dae
·
verified ·
1 Parent(s): 5c9d217

Upload 2 files

Browse files
Files changed (2) hide show
  1. Requirements.txt +6 -0
  2. app.py +223 -1
Requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio==4.29.0
2
+ gradio_client==0.16.1
3
+ openai-whisper
4
+ torch
5
+ transformers
6
+ ffmpeg-python
app.py CHANGED
@@ -1 +1,223 @@
1
- app.py
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+
5
+ os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
6
+
7
+ # Import libraries
8
+ import whisper
9
+ import gradio as gr
10
+ import torch
11
+ from transformers import BertTokenizer, BertForSequenceClassification, pipeline
12
+ from app.questions import get_question
13
+
14
+ # patch(niranjan)
15
+ try:
16
+ # original method
17
+ original_method = gr.Blocks.get_api_info
18
+
19
+ # Create a safer version of the method that catches the specific error
20
+ def safe_get_api_info(self):
21
+ try:
22
+ return original_method(self)
23
+ except TypeError as e:
24
+ print(f"API info generation error suppressed: {str(e)}", file=sys.stderr)
25
+ return {} # Return empty api
26
+
27
+
28
+ gr.Blocks.get_api_info = safe_get_api_info
29
+ print("Applied API info generation patch", file=sys.stderr)
30
+ except Exception as e:
31
+ print(f"Failed to apply patch: {str(e)}", file=sys.stderr)
32
+
33
+ # Load models
34
+ whisper_model = whisper.load_model("small")
35
+ confidence_model = BertForSequenceClassification.from_pretrained('RiteshAkhade/final_confidence')
36
+ confidence_tokenizer = BertTokenizer.from_pretrained('RiteshAkhade/final_confidence')
37
+ context_model = BertForSequenceClassification.from_pretrained('RiteshAkhade/context_model')
38
+ context_tokenizer = BertTokenizer.from_pretrained('RiteshAkhade/context_model')
39
+ emotion_pipe = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion", top_k=1)
40
+
41
+ # Emotion map with labels and emojis
42
+ interview_emotion_map = {
43
+ "joy": ("Confident", "🙂"),
44
+ "fear": ("Nervous", "😨"),
45
+ "sadness": ("Uncertain", "🙁"),
46
+ "anger": ("Frustrated", "😠"),
47
+ "surprise": ("Curious", "😮"),
48
+ "neutral": ("Calm", "😐"),
49
+ "disgust": ("Disengaged", "😒"),
50
+ }
51
+
52
+ # Static question sets
53
+ technical_questions = [get_question(i) for i in range(6)]
54
+ non_technical_questions = [
55
+ "Tell me about yourself.",
56
+ "What are your strengths and weaknesses?",
57
+ "Where do you see yourself in 5 years?",
58
+ "How do you handle stress or pressure?",
59
+ "Describe a time you faced a conflict and how you resolved it.",
60
+ "What motivates you to do your best?"
61
+ ]
62
+
63
+ # Index trackers
64
+ current_tech_index = 0
65
+ current_non_tech_index = 0
66
+
67
+ # Relevance prediction
68
+ def predict_relevance(question, answer):
69
+ if not answer.strip():
70
+ return "Irrelevant"
71
+ inputs = context_tokenizer(question, answer, return_tensors="pt", padding=True, truncation=True)
72
+ context_model.eval()
73
+ with torch.no_grad():
74
+ outputs = context_model(**inputs)
75
+ probabilities = torch.softmax(outputs.logits, dim=-1)
76
+ return "Relevant" if probabilities[0, 1] > 0.5 else "Irrelevant"
77
+
78
+ # Confidence prediction
79
+ def predict_confidence(question, answer, threshold=0.4):
80
+ if not isinstance(answer, str) or not answer.strip():
81
+ return "Not Confident"
82
+ inputs = confidence_tokenizer(question, answer, return_tensors="pt", padding=True, truncation=True)
83
+ confidence_model.eval()
84
+ with torch.no_grad():
85
+ outputs = confidence_model(**inputs)
86
+ probabilities = torch.softmax(outputs.logits, dim=-1)
87
+ return "Confident" if probabilities[0, 1].item() > threshold else "Not Confident"
88
+
89
+ # Emotion detection
90
+ def detect_emotion(answer):
91
+ if not answer.strip():
92
+ return "No Answer", ""
93
+ result = emotion_pipe(answer)
94
+ label = result[0][0]["label"].lower()
95
+ emotion_text, emoji = interview_emotion_map.get(label, ("Unknown", "❓"))
96
+ return emotion_text, emoji
97
+
98
+ # Question navigation (non-tech)
99
+ def show_non_tech_question():
100
+ global current_non_tech_index
101
+ return non_technical_questions[current_non_tech_index]
102
+
103
+ def next_non_tech_question():
104
+ global current_non_tech_index
105
+ current_non_tech_index = (current_non_tech_index + 1) % len(non_technical_questions)
106
+ return non_technical_questions[current_non_tech_index], None, "", ""
107
+
108
+ # Question navigation (tech)
109
+ def show_tech_question():
110
+ global current_tech_index
111
+ return technical_questions[current_tech_index]
112
+
113
+ def next_tech_question():
114
+ global current_tech_index
115
+ current_tech_index = (current_tech_index + 1) % len(technical_questions)
116
+ return technical_questions[current_tech_index], None, "", "", ""
117
+
118
+ # Transcribe + analyze (non-technical)
119
+ def transcribe_and_analyze_non_tech(audio, question):
120
+ try:
121
+ audio = whisper.load_audio(audio)
122
+ audio = whisper.pad_or_trim(audio)
123
+ mel = whisper.log_mel_spectrogram(audio).to(whisper_model.device)
124
+ result = whisper.decode(whisper_model, mel, whisper.DecodingOptions(fp16=False))
125
+ transcribed_text = result.text
126
+ emotion_text, emoji = detect_emotion(transcribed_text)
127
+ return transcribed_text, f"{emotion_text} {emoji}"
128
+ except Exception as e:
129
+ return f"Error: {str(e)}", "❓"
130
+
131
+ # Transcribe + analyze (technical)
132
+ def transcribe_and_analyze_tech(audio, question):
133
+ try:
134
+ audio = whisper.load_audio(audio)
135
+ audio = whisper.pad_or_trim(audio)
136
+ mel = whisper.log_mel_spectrogram(audio).to(whisper_model.device)
137
+ result = whisper.decode(whisper_model, mel, whisper.DecodingOptions(fp16=False))
138
+ transcribed_text = result.text
139
+ context_result = predict_relevance(question, transcribed_text)
140
+ confidence_result = predict_confidence(question, transcribed_text)
141
+ return transcribed_text, context_result, confidence_result
142
+ except Exception as e:
143
+ return f"Error: {str(e)}", "", ""
144
+
145
+ # UI layout
146
+ with gr.Blocks(css="textarea, .gr-box { font-size: 18px !important; }") as demo:
147
+ gr.HTML("<h1 style='text-align: center; font-size: 32px;'>INTERVIEW PREPARATION MODEL</h1>")
148
+
149
+ with gr.Tabs():
150
+
151
+ # NON-TECHNICAL TAB
152
+ with gr.Tab("Non-Technical"):
153
+ gr.Markdown("### Emotional Context Analysis (🧠 + 😊)")
154
+ question_display_1 = gr.Textbox(label="Interview Question", value=show_non_tech_question(), interactive=False)
155
+ audio_input_1 = gr.Audio(type="filepath", label="Record Your Answer")
156
+ transcribed_text_1 = gr.Textbox(label="Transcribed Answer", interactive=False, lines=4)
157
+ emotion_output = gr.Textbox(label="Detected Emotion", interactive=False)
158
+
159
+ audio_input_1.change(fn=transcribe_and_analyze_non_tech,
160
+ inputs=[audio_input_1, question_display_1],
161
+ outputs=[transcribed_text_1, emotion_output])
162
+
163
+ next_button_1 = gr.Button("Next Question")
164
+ next_button_1.click(fn=next_non_tech_question,
165
+ outputs=[question_display_1, audio_input_1, transcribed_text_1, emotion_output])
166
+
167
+ # TECHNICAL TAB
168
+ with gr.Tab("Technical"):
169
+ gr.Markdown("### Technical Question Analysis (🎓 + 🤖)")
170
+ question_display_2 = gr.Textbox(label="Interview Question", value=show_tech_question(), interactive=False)
171
+ audio_input_2 = gr.Audio(type="filepath", label="Record Your Answer")
172
+ transcribed_text_2 = gr.Textbox(label="Transcribed Answer", interactive=False, lines=4)
173
+ context_analysis_result = gr.Textbox(label="Context Analysis", interactive=False)
174
+ confidence_analysis_result = gr.Textbox(label="Confidence Analysis", interactive=False)
175
+
176
+ audio_input_2.change(fn=transcribe_and_analyze_tech,
177
+ inputs=[audio_input_2, question_display_2],
178
+ outputs=[transcribed_text_2, context_analysis_result, confidence_analysis_result])
179
+
180
+ next_button_2 = gr.Button("Next Question")
181
+ next_button_2.click(fn=next_tech_question,
182
+ outputs=[question_display_2, audio_input_2, transcribed_text_2,
183
+ context_analysis_result, confidence_analysis_result])
184
+
185
+ # Also patch the client utils function that's failing
186
+ try:
187
+ import gradio_client.utils
188
+
189
+ # Original function reference
190
+ original_json_schema = gradio_client.utils._json_schema_to_python_type
191
+
192
+ # patched version
193
+ def patched_json_schema(schema, defs=None):
194
+ try:
195
+ if isinstance(schema, bool):
196
+ return "bool"
197
+ return original_json_schema(schema, defs)
198
+ except Exception as e:
199
+ print(f"JSON schema conversion error suppressed: {str(e)}", file=sys.stderr)
200
+ return "any"
201
+
202
+ # Apply patch
203
+ gradio_client.utils._json_schema_to_python_type = patched_json_schema
204
+ print("Applied JSON schema conversion patch", file=sys.stderr)
205
+ except Exception as e:
206
+ print(f"Failed to apply client utils patch: {str(e)}", file=sys.stderr)
207
+
208
+ if __name__ == "__main__":
209
+ # Simple launch with error handling
210
+ try:
211
+ demo.launch(show_api=False)
212
+ except Exception as e:
213
+ print(f"Launch failed: {str(e)}", file=sys.stderr)
214
+
215
+ try:
216
+ demo.launch()
217
+ except Exception as e:
218
+ print(f"Minimal launch also failed: {str(e)}", file=sys.stderr)
219
+ # Create a minimal error app as last resort
220
+ with gr.Blocks() as error_app:
221
+ gr.Markdown("# Error Starting App")
222
+ gr.Markdown("The application encountered errors during startup. Please check the logs.")
223
+ error_app.launch()