Spaces:
Sleeping
Sleeping
add speech
Browse files
app.py
CHANGED
@@ -6,10 +6,14 @@ import numpy as np
|
|
6 |
from sentence_transformers import SentenceTransformer
|
7 |
from sklearn.metrics.pairwise import cosine_similarity
|
8 |
import torch
|
|
|
9 |
|
10 |
# Set up OpenAI client
|
11 |
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
12 |
|
|
|
|
|
|
|
13 |
# Check if GPU is available
|
14 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
15 |
print(f"Using device: {device}")
|
@@ -46,24 +50,17 @@ if "generated_question" not in st.session_state:
|
|
46 |
if "debug_logs" not in st.session_state:
|
47 |
st.session_state.debug_logs = [] # Stores debug logs for toggling
|
48 |
|
|
|
|
|
|
|
49 |
# Function to find the top 1 most similar question based on user input
|
50 |
def find_top_question(query):
|
51 |
-
# Generate embedding for the query
|
52 |
query_embedding = model.encode(query, convert_to_tensor=True, device=device).cpu().numpy()
|
53 |
-
|
54 |
-
# Reshape query_embedding to ensure it is a 2D array
|
55 |
query_embedding = query_embedding.reshape(1, -1) # Reshape to (1, n_features)
|
56 |
-
|
57 |
-
|
58 |
-
similarities = cosine_similarity(query_embedding, embeddings).flatten() # Flatten to get a 1D array of similarities
|
59 |
-
|
60 |
-
# Get the index of the most similar result (top 1)
|
61 |
-
top_index = similarities.argsort()[-1] # Index of highest similarity
|
62 |
-
|
63 |
-
# Retrieve metadata for the top result
|
64 |
top_result = metadata.iloc[top_index].copy()
|
65 |
top_result['similarity_score'] = similarities[top_index]
|
66 |
-
|
67 |
return top_result
|
68 |
|
69 |
# Function to generate response using OpenAI API with debugging logs
|
@@ -78,24 +75,48 @@ def generate_response(messages):
|
|
78 |
|
79 |
return response.choices[0].message.content
|
80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
# User input form for generating a new question
|
82 |
with st.form(key="input_form"):
|
83 |
-
company = st.text_input("Company", value="Google")
|
84 |
-
difficulty = st.selectbox("Difficulty", ["Easy", "Medium", "Hard"], index=1)
|
85 |
-
topic = st.text_input("Topic (e.g., Backtracking)", value="Backtracking")
|
86 |
|
87 |
generate_button = st.form_submit_button(label="Generate")
|
88 |
|
89 |
if generate_button:
|
90 |
-
# Clear session state and start fresh with follow-up mode disabled
|
91 |
st.session_state.messages = []
|
92 |
st.session_state.follow_up_mode = False
|
93 |
|
94 |
-
# Create a query from user inputs and find the most relevant question
|
95 |
query = f"{company} {difficulty} {topic}"
|
96 |
top_question = find_top_question(query)
|
97 |
|
98 |
-
# Prepare a detailed prompt for GPT using the top question's details
|
99 |
detailed_prompt = (
|
100 |
f"Transform this LeetCode question into a real-world interview scenario:\n\n"
|
101 |
f"**Company**: {top_question['company']}\n"
|
@@ -106,76 +127,68 @@ if generate_button:
|
|
106 |
f"\nPlease create a real-world interview question based on this information."
|
107 |
)
|
108 |
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
# Store generated question in session state for persistence in sidebar and follow-up conversation state
|
113 |
-
st.session_state.generated_question = response
|
114 |
-
|
115 |
-
# Add the generated question to the conversation history as an assistant message (to make it part of follow-up conversations)
|
116 |
-
st.session_state.messages.append({"role": "assistant", "content": response})
|
117 |
|
118 |
-
|
|
|
119 |
st.session_state.follow_up_mode = True
|
120 |
|
121 |
-
# Display chat messages from history on app rerun (for subsequent conversation)
|
122 |
for message in st.session_state.messages:
|
123 |
with st.chat_message(message["role"]):
|
124 |
st.markdown(message["content"])
|
125 |
|
126 |
-
# Chatbox for subsequent conversations with assistant (follow-up mode)
|
127 |
if st.session_state.follow_up_mode:
|
128 |
if user_input := st.chat_input("Continue your conversation or ask follow-up questions here:"):
|
129 |
-
# Display user message in chat message container and add to session history
|
130 |
with st.chat_message("user"):
|
131 |
st.markdown(user_input)
|
132 |
|
133 |
st.session_state.messages.append({"role": "user", "content": user_input})
|
134 |
|
135 |
-
|
136 |
-
# including the generated question in context.
|
137 |
-
assistant_response = generate_response(
|
138 |
[{"role": "assistant", "content": technical_interviewer_prompt}] + st.session_state.messages
|
139 |
)
|
140 |
|
|
|
|
|
141 |
with st.chat_message("assistant"):
|
142 |
-
st.markdown(
|
|
|
|
|
|
|
143 |
|
144 |
-
st.session_state.messages.append({"role": "assistant", "content":
|
145 |
-
|
146 |
-
# Sidebar
|
147 |
-
st.sidebar
|
148 |
-
|
149 |
-
st.
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
st.
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
st.
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
st.sidebar.success("Code executed successfully!")
|
179 |
-
|
180 |
-
except Exception as e:
|
181 |
-
st.sidebar.error(f"Error: {e}")
|
|
|
6 |
from sentence_transformers import SentenceTransformer
|
7 |
from sklearn.metrics.pairwise import cosine_similarity
|
8 |
import torch
|
9 |
+
import requests
|
10 |
|
11 |
# Set up OpenAI client
|
12 |
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
13 |
|
14 |
+
# Set up ElevenLabs API key
|
15 |
+
ELEVENLABS_API_KEY = "your_api_key"
|
16 |
+
|
17 |
# Check if GPU is available
|
18 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
19 |
print(f"Using device: {device}")
|
|
|
50 |
if "debug_logs" not in st.session_state:
|
51 |
st.session_state.debug_logs = [] # Stores debug logs for toggling
|
52 |
|
53 |
+
if "code_output" not in st.session_state:
|
54 |
+
st.session_state.code_output = None # Stores the output of executed Python code
|
55 |
+
|
56 |
# Function to find the top 1 most similar question based on user input
|
57 |
def find_top_question(query):
|
|
|
58 |
query_embedding = model.encode(query, convert_to_tensor=True, device=device).cpu().numpy()
|
|
|
|
|
59 |
query_embedding = query_embedding.reshape(1, -1) # Reshape to (1, n_features)
|
60 |
+
similarities = cosine_similarity(query_embedding, embeddings).flatten()
|
61 |
+
top_index = similarities.argsort()[-1]
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
top_result = metadata.iloc[top_index].copy()
|
63 |
top_result['similarity_score'] = similarities[top_index]
|
|
|
64 |
return top_result
|
65 |
|
66 |
# Function to generate response using OpenAI API with debugging logs
|
|
|
75 |
|
76 |
return response.choices[0].message.content
|
77 |
|
78 |
+
# Function to generate audio using ElevenLabs API
|
79 |
+
def generate_audio(text):
|
80 |
+
url = "https://api.elevenlabs.io/v1/text-to-speech"
|
81 |
+
headers = {
|
82 |
+
"xi-api-key": ELEVENLABS_API_KEY,
|
83 |
+
"content-type": "application/json"
|
84 |
+
}
|
85 |
+
payload = {
|
86 |
+
"text": text,
|
87 |
+
"voice_id": "21m00tcm4tlvdq8ikwam", # Default voice ID; replace with desired voice ID.
|
88 |
+
"voice_settings": {
|
89 |
+
"similarity_boost": 0.85,
|
90 |
+
"stability": 0.5
|
91 |
+
}
|
92 |
+
}
|
93 |
+
|
94 |
+
response = requests.post(url, headers=headers, json=payload)
|
95 |
+
|
96 |
+
if response.status_code == 200:
|
97 |
+
audio_file_path = f"assistant_response.mp3"
|
98 |
+
with open(audio_file_path, "wb") as audio_file:
|
99 |
+
audio_file.write(response.content)
|
100 |
+
return audio_file_path
|
101 |
+
else:
|
102 |
+
st.error(f"Error generating audio: {response.status_code} - {response.text}")
|
103 |
+
return None
|
104 |
+
|
105 |
# User input form for generating a new question
|
106 |
with st.form(key="input_form"):
|
107 |
+
company = st.text_input("Company", value="Google")
|
108 |
+
difficulty = st.selectbox("Difficulty", ["Easy", "Medium", "Hard"], index=1)
|
109 |
+
topic = st.text_input("Topic (e.g., Backtracking)", value="Backtracking")
|
110 |
|
111 |
generate_button = st.form_submit_button(label="Generate")
|
112 |
|
113 |
if generate_button:
|
|
|
114 |
st.session_state.messages = []
|
115 |
st.session_state.follow_up_mode = False
|
116 |
|
|
|
117 |
query = f"{company} {difficulty} {topic}"
|
118 |
top_question = find_top_question(query)
|
119 |
|
|
|
120 |
detailed_prompt = (
|
121 |
f"Transform this LeetCode question into a real-world interview scenario:\n\n"
|
122 |
f"**Company**: {top_question['company']}\n"
|
|
|
127 |
f"\nPlease create a real-world interview question based on this information."
|
128 |
)
|
129 |
|
130 |
+
response_text = generate_response([{"role": "assistant", "content": question_generation_prompt}, {"role": "user", "content": detailed_prompt}])
|
131 |
+
|
132 |
+
st.session_state.generated_question = response_text
|
|
|
|
|
|
|
|
|
|
|
133 |
|
134 |
+
st.session_state.messages.append({"role": "assistant", "content": response_text})
|
135 |
+
|
136 |
st.session_state.follow_up_mode = True
|
137 |
|
|
|
138 |
for message in st.session_state.messages:
|
139 |
with st.chat_message(message["role"]):
|
140 |
st.markdown(message["content"])
|
141 |
|
|
|
142 |
if st.session_state.follow_up_mode:
|
143 |
if user_input := st.chat_input("Continue your conversation or ask follow-up questions here:"):
|
|
|
144 |
with st.chat_message("user"):
|
145 |
st.markdown(user_input)
|
146 |
|
147 |
st.session_state.messages.append({"role": "user", "content": user_input})
|
148 |
|
149 |
+
assistant_response_text = generate_response(
|
|
|
|
|
150 |
[{"role": "assistant", "content": technical_interviewer_prompt}] + st.session_state.messages
|
151 |
)
|
152 |
|
153 |
+
assistant_audio_path = generate_audio(assistant_response_text)
|
154 |
+
|
155 |
with st.chat_message("assistant"):
|
156 |
+
st.markdown(assistant_response_text)
|
157 |
+
if assistant_audio_path:
|
158 |
+
audio_bytes = open(assistant_audio_path, "rb").read()
|
159 |
+
st.audio(audio_bytes, format="audio/mp3")
|
160 |
|
161 |
+
st.session_state.messages.append({"role": "assistant", "content": assistant_response_text})
|
162 |
+
|
163 |
+
# Left Sidebar: Generated Question and Code Box
|
164 |
+
with st.sidebar:
|
165 |
+
# Top Half: Generated Question
|
166 |
+
st.markdown("## Generated Question")
|
167 |
+
if st.session_state.generated_question:
|
168 |
+
st.markdown(st.session_state.generated_question)
|
169 |
+
else:
|
170 |
+
st.markdown("_No question generated yet._")
|
171 |
+
|
172 |
+
# Divider between sections
|
173 |
+
st.markdown("---")
|
174 |
+
|
175 |
+
# Bottom Half: Python Code Box
|
176 |
+
st.markdown("## Python Code Interpreter")
|
177 |
+
|
178 |
+
code_input = st.text_area("Write your Python code here:")
|
179 |
+
|
180 |
+
col1, col2 = st.columns(2)
|
181 |
+
|
182 |
+
with col1:
|
183 |
+
if st.button("Run Code"):
|
184 |
+
try:
|
185 |
+
exec_globals = {}
|
186 |
+
exec(code_input, exec_globals) # Execute user-provided code safely within its own scope.
|
187 |
+
output_key_values = {k: v for k, v in exec_globals.items() if k != "__builtins__"}
|
188 |
+
if output_key_values:
|
189 |
+
output_strs = [f"{key}: {value}" for key, value in output_key_values.items()]
|
190 |
+
output_display_strs = "\n".join(output_strs)
|
191 |
+
output_display_strs += "\nCode executed successfully!"
|
192 |
+
print(output_display_strs)
|
193 |
+
|
194 |
+
except Exception as e:
|
|
|
|
|
|
|
|