charantejapolavarapu commited on
Commit
e33280f
·
verified ·
1 Parent(s): 8626077

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -105
app.py CHANGED
@@ -1,130 +1,115 @@
1
  import gradio as gr
2
  import requests
3
  import os
4
- import random
5
  import re
6
 
 
 
7
  HF_TOKEN = os.getenv("HF_TOKEN")
8
 
9
- API_URL = "https://api-inference.huggingface.co/models/microsoft/DialoGPT-medium"
10
-
11
- headers = {
12
- "Authorization": f"Bearer {HF_TOKEN}"
13
- }
14
-
15
- # ----------------------------
16
- # AI Question Generator
17
- # ----------------------------
18
- def generate_question(role, difficulty, resume_text):
19
- base_prompt = f"Generate one {difficulty} level technical interview question for a {role} role."
20
-
21
- if resume_text.strip() != "":
22
- base_prompt += f" The candidate resume mentions: {resume_text}. Ask a question based on that."
23
 
 
 
24
  payload = {
25
- "inputs": base_prompt,
26
- "parameters": {"max_new_tokens": 100}
27
  }
28
-
29
- response = requests.post(API_URL, headers=headers, json=payload)
30
-
31
- if response.status_code != 200:
32
- return "Error generating question."
33
-
34
- result = response.json()
35
-
36
- if isinstance(result, list):
37
- return result[0]["generated_text"]
38
-
39
- return "Could not generate question."
40
-
41
 
42
  # ----------------------------
43
- # AI Answer Evaluation + Score
44
  # ----------------------------
45
- def evaluate_answer(answer):
46
- feedback_prompt = f"""
47
- Evaluate this interview answer.
48
- Give:
49
- 1. Short feedback
50
- 2. Score out of 10
51
 
52
- Answer: {answer}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  """
54
-
55
- payload = {
56
- "inputs": feedback_prompt,
57
- "parameters": {"max_new_tokens": 150}
58
- }
59
-
60
- response = requests.post(API_URL, headers=headers, json=payload)
61
-
62
- if response.status_code != 200:
63
- return "Error generating feedback.", "0/10"
64
-
65
- result = response.json()
66
-
67
- if isinstance(result, list):
68
- text = result[0]["generated_text"]
69
-
70
- # Try extracting score
71
- score_match = re.search(r"\b([0-9]|10)/10\b", text)
72
- score = score_match.group(0) if score_match else "N/A"
73
-
74
- return text, score
75
-
76
- return "Could not evaluate.", "0/10"
77
-
78
 
79
  # ----------------------------
80
- # Gradio UI
81
  # ----------------------------
82
- with gr.Blocks() as demo:
83
- gr.Markdown("# 🤖 Smart Interview Simulator (AI Voice Bot)")
84
- gr.Markdown("AI-powered role-based interview practice with scoring and resume-based questions.")
85
-
86
- with gr.Row():
87
- role = gr.Textbox(label="Job Role (e.g., Data Scientist)")
88
- difficulty = gr.Dropdown(
89
- ["Easy", "Medium", "Hard"],
90
- label="Select Difficulty",
91
- value="Medium"
92
- )
93
-
94
- resume_input = gr.Textbox(
95
- label="Paste Resume Skills / Summary (Optional)",
96
- lines=4
97
- )
98
-
99
- question_output = gr.Textbox(label="Interview Question", lines=3)
100
-
101
- generate_btn = gr.Button("Generate Question")
102
 
103
- gr.Markdown("## 🎤 Answer Section")
104
-
105
- audio_input = gr.Audio(
106
- sources=["microphone"],
107
- type="filepath",
108
- label="Speak Your Answer (Voice Input)"
109
- )
110
 
111
- answer_input = gr.Textbox(label="OR Type Your Answer", lines=4)
112
-
113
- evaluate_btn = gr.Button("Evaluate Answer")
 
 
 
 
 
 
114
 
115
- feedback_output = gr.Textbox(label="AI Feedback", lines=5)
116
- score_output = gr.Textbox(label="Score")
117
 
118
- generate_btn.click(
119
- generate_question,
120
- inputs=[role, difficulty, resume_input],
121
- outputs=question_output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  )
123
-
124
- evaluate_btn.click(
125
- evaluate_answer,
126
- inputs=answer_input,
127
- outputs=[feedback_output, score_output]
128
  )
129
 
130
- demo.launch()
 
 
1
  import gradio as gr
2
  import requests
3
  import os
 
4
  import re
5
 
6
+ # We use Mistral because DialoGPT is for chatting, while Mistral follows instructions
7
+ API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
8
  HF_TOKEN = os.getenv("HF_TOKEN")
9
 
10
+ headers = {"Authorization": f"Bearer {HF_TOKEN}"}
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ def query_llm(prompt):
13
+ """Helper function to send prompts to the Hugging Face API."""
14
  payload = {
15
+ "inputs": f"<s>[INST] {prompt} [/INST]",
16
+ "parameters": {"max_new_tokens": 250, "temperature": 0.7}
17
  }
18
+ try:
19
+ response = requests.post(API_URL, headers=headers, json=payload)
20
+ result = response.json()
21
+
22
+ if isinstance(result, list) and "generated_text" in result[0]:
23
+ # Clean the output to remove the prompt markers
24
+ full_text = result[0]["generated_text"]
25
+ return full_text.split("[/INST]")[-1].strip()
26
+
27
+ return "The AI is still warming up. Please wait 30 seconds and try again."
28
+ except Exception as e:
29
+ return f"Error: Could not connect to AI (Check your HF_TOKEN). {str(e)}"
 
30
 
31
  # ----------------------------
32
+ # AI Logic Functions
33
  # ----------------------------
 
 
 
 
 
 
34
 
35
+ def generate_question(role, difficulty, resume_text):
36
+ if not role:
37
+ return "Please enter a Job Role first!"
38
+
39
+ prompt = f"Act as a professional recruiter. Generate one {difficulty} level technical interview question for a {role} role."
40
+ if resume_text.strip():
41
+ prompt += f" Based on this resume context: {resume_text}"
42
+
43
+ return query_llm(prompt)
44
+
45
+ def evaluate_answer(question, answer):
46
+ if not answer or len(answer) < 5:
47
+ return "Please provide a more detailed answer for evaluation.", "N/A"
48
+
49
+ prompt = f"""
50
+ Interviewer Question: {question}
51
+ Candidate Answer: {answer}
52
+
53
+ Task: Critically evaluate this answer.
54
+ 1. Give constructive feedback.
55
+ 2. Provide a score out of 10.
56
+ Format your response with the score clearly at the end as 'Final Score: X/10'.
57
  """
58
+
59
+ feedback = query_llm(prompt)
60
+
61
+ # Extract score using regex (looks for X/10)
62
+ score_match = re.search(r"(\d+/10)", feedback)
63
+ score = score_match.group(1) if score_match else "Score not generated"
64
+
65
+ return feedback, score
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  # ----------------------------
68
+ # Gradio UI Design
69
  # ----------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
72
+ gr.Markdown("# 🤖 Smart Interview Simulator")
73
+ gr.Markdown("Practice your interview skills with AI-generated questions and real-time feedback.")
 
 
 
 
74
 
75
+ with gr.Row():
76
+ with gr.Column():
77
+ role_input = gr.Textbox(label="Target Job Role", placeholder="e.g., Python Developer")
78
+ diff_input = gr.Dropdown(["Easy", "Medium", "Hard"], label="Level", value="Medium")
79
+ resume_input = gr.Textbox(label="Resume Summary (Optional)", lines=3)
80
+ gen_btn = gr.Button("Generate Interview Question", variant="primary")
81
+
82
+ with gr.Column():
83
+ question_box = gr.Textbox(label="AI Question", lines=5, interactive=False)
84
 
85
+ gr.Markdown("---")
 
86
 
87
+ with gr.Row():
88
+ with gr.Column():
89
+ gr.Markdown("### Your Response")
90
+ # Note: For voice input to work, Gradio handles the file,
91
+ # but you would need a transcription model (like Whisper) to convert audio to text.
92
+ # For now, we will focus on the text input.
93
+ ans_input = gr.Textbox(label="Type your answer here", lines=5)
94
+ eval_btn = gr.Button("Submit for Evaluation", variant="secondary")
95
+
96
+ with gr.Column():
97
+ gr.Markdown("### Results")
98
+ feedback_box = gr.Textbox(label="AI Feedback", lines=5)
99
+ score_box = gr.Label(label="Final Score")
100
+
101
+ # Button actions
102
+ gen_btn.click(
103
+ fn=generate_question,
104
+ inputs=[role_input, diff_input, resume_input],
105
+ outputs=question_box
106
  )
107
+
108
+ eval_btn.click(
109
+ fn=evaluate_answer,
110
+ inputs=[question_box, ans_input],
111
+ outputs=[feedback_box, score_box]
112
  )
113
 
114
+ if __name__ == "__main__":
115
+ demo.launch()