DhruvDecoder commited on
Commit
795c8db
·
verified ·
1 Parent(s): 1d4e8a4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -26
app.py CHANGED
@@ -1,61 +1,116 @@
 
1
  import requests
2
  import os
 
3
  import tempfile
4
  from fpdf import FPDF
5
- import streamlit as st
6
- from pytube import YouTube
7
 
8
- os.environ['TOGETHER_API_KEY'] = 'ef5312e1d4bffafb5daf8ee0d632feb1aa94a021d020f4d0e6f6ded5b0795cc4'
 
9
  together_api_key = os.environ.get("TOGETHER_API_KEY")
10
- headers = {
11
- "Authorization": f"Bearer {together_api_key}",
12
- "Content-Type": "application/json"
 
 
 
13
  }
14
 
15
  def generate_sentiment_score(input_text, parameters):
16
  prompt = f'''
17
  You are an experienced interview reviewer and consultant for a reputable company. Your role is to evaluate the sentiment displayed by job candidates during their interviews based on the transcripts of their responses.
18
- The parameters to evaluate are: {', '.join(parameters)}.
19
- Provide a sentiment score on a scale of 1-5 for each parameter.
 
 
 
 
 
 
20
  '''
 
 
 
 
 
 
21
  data = {
22
- "model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
23
- "prompt": prompt,
24
  "temperature": 0.0,
25
  "max_tokens": 1024
26
  }
27
- response = requests.post("https://api.together.xyz/inference", headers=headers, json=data)
 
 
28
  if response.status_code == 200:
29
  return response.json()['output']['choices'][0]['text']
30
  else:
31
- print(f"Error: {response.status_code} - {response.text}")
32
 
33
  def generate_detailed_feedback(input_text, parameters):
34
  prompt = f'''
35
- Provide a detailed analysis of the candidate's responses based on the following parameters: {', '.join(parameters)}.
36
- Include specific examples, quotes, and adjectives from the transcript that support your analysis. Summarize the candidate's overall sentiment and demeanor.
 
37
  '''
 
 
 
 
 
 
38
  data = {
39
- "model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
40
- "prompt": prompt,
41
  "temperature": 0.0,
42
- "max_tokens": 1024
43
  }
44
- response = requests.post("https://api.together.xyz/inference", headers=headers, json=data)
 
 
45
  if response.status_code == 200:
46
  return response.json()['output']['choices'][0]['text']
47
  else:
48
- print(f"Error: {response.status_code} - {response.text}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
  def transcript(video_link):
51
  try:
52
  yt = YouTube(video_link)
53
  stream = yt.streams.filter(only_audio=True).first()
54
  temp_file_path = stream.download()
55
- with open(temp_file_path, 'rb') as audio_data:
56
- total_transcript = (openai.Audio.transcribe("whisper-1", audio_data))["text"]
 
 
 
 
57
  os.remove(temp_file_path)
58
- return total_transcript
 
 
59
  except Exception as e:
60
  print(f"Error: {e}")
61
  return None
@@ -65,6 +120,31 @@ def main():
65
  st.title("Insight Hire")
66
  st.write("Analyze interview transcripts or videos to gain valuable insights into candidate sentiment.")
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  input_option = st.radio("Select input type", ("Text", "YouTube Video Link"))
69
 
70
  input_text = ""
@@ -87,7 +167,9 @@ def main():
87
  with st.spinner("Generating sentiment scores..."):
88
  sentiment_scores = generate_sentiment_score(input_text, parameters)
89
  sentiment_scores = sentiment_scores.strip().split("\n")
 
90
  st.subheader("Sentiment Scores")
 
91
  for score in sentiment_scores:
92
  if ":" in score:
93
  param, score_value = score.split(":")
@@ -96,22 +178,25 @@ def main():
96
  if param in parameters:
97
  try:
98
  score_value = float(score_value.split("/")[0].strip())
 
99
  if score_value >= 4:
100
- color = "#2ca02c"
101
  elif score_value >= 3:
102
- color = "#ff7f0e"
103
  else:
104
- color = "#d62728"
105
  st.markdown(f"**{param}**: <span style='color: {color}'>{score_value}/5</span>", unsafe_allow_html=True)
106
  except ValueError:
107
  pass
108
 
109
  if valid_scores:
 
110
  with st.spinner("Generating detailed feedback..."):
111
  detailed_feedback = generate_detailed_feedback(input_text, parameters)
112
  st.subheader("Detailed Feedback")
113
  st.write(detailed_feedback)
114
 
 
115
  temp_txt_path = tempfile.mktemp(suffix=".txt")
116
  with open(temp_txt_path, 'w') as f:
117
  f.write(detailed_feedback)
@@ -143,7 +228,7 @@ def main():
143
 
144
  if __name__ == "__main__":
145
  main()
146
-
147
 
148
 
149
 
 
1
+ import streamlit as st
2
  import requests
3
  import os
4
+ from pytube import YouTube
5
  import tempfile
6
  from fpdf import FPDF
7
+ import time
 
8
 
9
+ # Together.ai API configuration
10
+ os.environ['TOGETHER_API_KEY'] = os.environ.get('TOGETHER_API_KEY')
11
  together_api_key = os.environ.get("TOGETHER_API_KEY")
12
+ together_url = "https://api.together.xyz/inference"
13
+
14
+ # AssemblyAI API configuration
15
+ assembly_base_url = "https://api.assemblyai.com/v2"
16
+ assembly_headers = {
17
+ "authorization": os.environ.get('ASSEMBLYAI_API_KEY')
18
  }
19
 
20
  def generate_sentiment_score(input_text, parameters):
21
  prompt = f'''
22
  You are an experienced interview reviewer and consultant for a reputable company. Your role is to evaluate the sentiment displayed by job candidates during their interviews based on the transcripts of their responses.
23
+ The hiring team has provided you with an interview transcript and has asked you to analyze the candidate's sentiment for the following parameters: {', '.join(parameters)}. Your assessment will help the team make more informed hiring decisions and identify candidates who demonstrate genuine positive sentiment towards the role and the company.
24
+ The parameters to evaluate are:
25
+ {', '.join(parameters)}.
26
+ To complete this task, you will:
27
+ 1. Carefully review the provided interview transcript.
28
+ 2. Consider phrases, word choices, or patterns of speech that convey positive or negative sentiment for each parameter.
29
+ 3. Based on your analysis, provide a sentiment score on a scale of 1-5 for each parameter, with 1 being extremely negative and 5 being extremely positive.
30
+ Provide your scores in the format: Parameter: Score.
31
  '''
32
+
33
+ headers = {
34
+ "Authorization": f"Bearer {together_api_key}",
35
+ "Content-Type": "application/json"
36
+ }
37
+
38
  data = {
39
+ "model": "togethercomputer/llama-2-70b-chat",
40
+ "prompt": f"[INST]{prompt}\n\n{input_text}[/INST]",
41
  "temperature": 0.0,
42
  "max_tokens": 1024
43
  }
44
+
45
+ response = requests.post(together_url, headers=headers, json=data)
46
+
47
  if response.status_code == 200:
48
  return response.json()['output']['choices'][0]['text']
49
  else:
50
+ raise Exception(f"Error: {response.status_code} - {response.text}")
51
 
52
  def generate_detailed_feedback(input_text, parameters):
53
  prompt = f'''
54
+ As an experienced interview reviewer, provide a detailed analysis of the candidate's responses based on the following parameters: {', '.join(parameters)}.
55
+
56
+ Include specific examples, quotes, and adjectives from the transcript that support your analysis. Offer actionable insights and recommendations for the hiring team to make informed decisions. Summarize the candidate's overall sentiment and demeanor.
57
  '''
58
+
59
+ headers = {
60
+ "Authorization": f"Bearer {together_api_key}",
61
+ "Content-Type": "application/json"
62
+ }
63
+
64
  data = {
65
+ "model": "togethercomputer/llama-2-70b-chat",
66
+ "prompt": f"[INST]{prompt}\n\n{input_text}[/INST]",
67
  "temperature": 0.0,
68
+ "max_tokens": 2048
69
  }
70
+
71
+ response = requests.post(together_url, headers=headers, json=data)
72
+
73
  if response.status_code == 200:
74
  return response.json()['output']['choices'][0]['text']
75
  else:
76
+ raise Exception(f"Error: {response.status_code} - {response.text}")
77
+
78
+ def upload_to_assemblyai(file_path):
79
+ with open(file_path, "rb") as f:
80
+ response = requests.post(f"{assembly_base_url}/upload", headers=assembly_headers, data=f)
81
+ return response.json().get("upload_url")
82
+
83
+ def transcribe_with_assemblyai(upload_url):
84
+ data = {
85
+ "audio_url": upload_url
86
+ }
87
+ response = requests.post(f"{assembly_base_url}/transcript", json=data, headers=assembly_headers)
88
+ transcript_id = response.json().get("id")
89
+
90
+ while True:
91
+ response = requests.get(f"{assembly_base_url}/transcript/{transcript_id}", headers=assembly_headers)
92
+ result = response.json()
93
+ if result['status'] == 'completed':
94
+ return result['text']
95
+ elif result['status'] == 'failed':
96
+ raise Exception("Transcription failed")
97
+ time.sleep(5)
98
 
99
  def transcript(video_link):
100
  try:
101
  yt = YouTube(video_link)
102
  stream = yt.streams.filter(only_audio=True).first()
103
  temp_file_path = stream.download()
104
+
105
+ print(f"Video '{yt.title}.mp4' downloaded successfully!")
106
+
107
+ upload_url = upload_to_assemblyai(temp_file_path)
108
+ transcription_text = transcribe_with_assemblyai(upload_url)
109
+
110
  os.remove(temp_file_path)
111
+
112
+ return transcription_text
113
+
114
  except Exception as e:
115
  print(f"Error: {e}")
116
  return None
 
120
  st.title("Insight Hire")
121
  st.write("Analyze interview transcripts or videos to gain valuable insights into candidate sentiment.")
122
 
123
+ st.sidebar.markdown("## About")
124
+ st.sidebar.markdown("""
125
+ <div style='color: #1f77b4; font-weight: bold;'>Streamline Your Interview Evaluation</div>
126
+ - Get data-driven sentiment scores for key parameters
127
+ - Identify top candidates based on sentiment analysis
128
+ - Make informed hiring decisions with actionable insights
129
+ """, unsafe_allow_html=True)
130
+
131
+ st.sidebar.markdown("<hr>", unsafe_allow_html=True) # Horizontal separator
132
+
133
+ st.sidebar.markdown("## Tips")
134
+ st.sidebar.markdown("""
135
+ <div style='color: #2ca02c; font-weight: bold;'>📝 Input Preparation</div>
136
+ - Provide clear interview transcripts or valid video links
137
+ - Specify relevant parameters for sentiment analysis
138
+ """, unsafe_allow_html=True)
139
+
140
+ st.sidebar.markdown("<hr>", unsafe_allow_html=True) # Horizontal separator
141
+
142
+ st.sidebar.markdown("## About Me")
143
+ st.sidebar.markdown("""
144
+ <div style='color: #d62728; font-weight: bold;'>👋 Hi, I'm Dhruv!</div>
145
+ I want to make a real impact in the field of AI/ML . My main interest lies in model building and deployment. I'm passionate about leveraging cutting-edge technologies to solve real-world problems.
146
+ """, unsafe_allow_html=True)
147
+
148
  input_option = st.radio("Select input type", ("Text", "YouTube Video Link"))
149
 
150
  input_text = ""
 
167
  with st.spinner("Generating sentiment scores..."):
168
  sentiment_scores = generate_sentiment_score(input_text, parameters)
169
  sentiment_scores = sentiment_scores.strip().split("\n")
170
+
171
  st.subheader("Sentiment Scores")
172
+ valid_scores = []
173
  for score in sentiment_scores:
174
  if ":" in score:
175
  param, score_value = score.split(":")
 
178
  if param in parameters:
179
  try:
180
  score_value = float(score_value.split("/")[0].strip())
181
+ valid_scores.append((param, score_value))
182
  if score_value >= 4:
183
+ color = "#2ca02c" # Green
184
  elif score_value >= 3:
185
+ color = "#ff7f0e" # Orange
186
  else:
187
+ color = "#d62728" # Red
188
  st.markdown(f"**{param}**: <span style='color: {color}'>{score_value}/5</span>", unsafe_allow_html=True)
189
  except ValueError:
190
  pass
191
 
192
  if valid_scores:
193
+ # Generate detailed feedback
194
  with st.spinner("Generating detailed feedback..."):
195
  detailed_feedback = generate_detailed_feedback(input_text, parameters)
196
  st.subheader("Detailed Feedback")
197
  st.write(detailed_feedback)
198
 
199
+ # Provide an option to download detailed feedback as a .txt or .pdf file
200
  temp_txt_path = tempfile.mktemp(suffix=".txt")
201
  with open(temp_txt_path, 'w') as f:
202
  f.write(detailed_feedback)
 
228
 
229
  if __name__ == "__main__":
230
  main()
231
+
232
 
233
 
234