rishabhpr commited on
Commit
da578f7
·
verified ·
1 Parent(s): b0ff7a0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +113 -96
app.py CHANGED
@@ -6,7 +6,6 @@ import numpy as np
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"))
@@ -16,8 +15,8 @@ device = "cuda" if torch.cuda.is_available() else "cpu"
16
  print(f"Using device: {device}")
17
 
18
  # Load metadata and embeddings (ensure these files are in your working directory or update paths)
19
- metadata_path = 'question_metadata.csv'
20
- embeddings_path = 'question_dataset_embeddings.npy'
21
 
22
  metadata = pd.read_csv(metadata_path)
23
  embeddings = np.load(embeddings_path)
@@ -38,94 +37,65 @@ st.title("Real-World Programming Question Mock Interview")
38
  if "messages" not in st.session_state:
39
  st.session_state.messages = []
40
 
 
 
 
41
  if "generated_question" not in st.session_state:
42
- st.session_state.generated_question = None
43
 
44
- if "code_output" not in st.session_state:
45
- st.session_state.code_output = ""
46
 
47
- if "evaluation_output" not in st.session_state:
48
- st.session_state.evaluation_output = ""
 
 
 
 
 
49
 
50
- # Sidebar layout for Generated Question and Code Box
51
- st.sidebar.markdown("## Generated Question")
52
- if st.session_state.generated_question:
53
- st.sidebar.markdown(st.session_state.generated_question)
54
- else:
55
- st.sidebar.markdown("_No question generated yet._")
56
 
57
- st.sidebar.markdown("---")
58
- st.sidebar.markdown("## Code Box")
59
 
60
- code_input = st.sidebar.text_area(
61
- label="Write your Python code here:",
62
- height=200,
63
- placeholder="Enter your code...",
64
- )
65
 
66
- col1, col2 = st.sidebar.columns(2)
67
 
68
- # Button to run code and display output
69
- if col1.button("Run Code"):
70
- try:
71
- exec_globals = {}
72
- exec(code_input, exec_globals)
73
- st.session_state.code_output = exec_globals.get("output", "Code executed successfully.")
74
- except Exception as e:
75
- st.session_state.code_output = f"Error: {str(e)}"
76
-
77
- # Button to evaluate code using OpenAI API
78
- if col2.button("Evaluate Code"):
79
- if not st.session_state.generated_question:
80
- st.sidebar.error("Generate a question first!")
81
- else:
82
- try:
83
- evaluation_prompt = (
84
- f"Question: {st.session_state.generated_question}\n\n"
85
- f"Code:\n{code_input}\n\n"
86
- f"Evaluate this code's correctness, efficiency, and style."
87
- )
88
- response = client.chat.completions.create(
89
- model="gpt-4",
90
- messages=[{"role": "user", "content": evaluation_prompt}],
91
- )
92
- evaluation_response = response.choices[0].message.content
93
- st.session_state.evaluation_output = evaluation_response
94
-
95
- # Add evaluation output to follow-up conversation
96
- st.session_state.messages.append({"role": "assistant", "content": evaluation_response})
97
- except Exception as e:
98
- st.sidebar.error(f"Error during evaluation: {str(e)}")
99
-
100
- # Display outputs below the main app content
101
- st.subheader("Code Output")
102
- st.text(st.session_state.code_output)
103
-
104
- st.subheader("Evaluation Output")
105
- st.text(st.session_state.evaluation_output)
106
-
107
- # Main app logic for generating questions and follow-up conversation remains unchanged.
108
  with st.form(key="input_form"):
109
- company = st.text_input("Company", value="Google")
110
- difficulty = st.selectbox("Difficulty", ["Easy", "Medium", "Hard"], index=1)
111
- topic = st.text_input("Topic (e.g., Backtracking)", value="Backtracking")
112
 
113
  generate_button = st.form_submit_button(label="Generate")
114
 
115
  if generate_button:
116
- query = f"{company} {difficulty} {topic}"
117
-
118
- def find_top_question(query):
119
- query_embedding = model.encode(query, convert_to_tensor=True, device=device).cpu().numpy()
120
- query_embedding = query_embedding.reshape(1, -1)
121
- similarities = cosine_similarity(query_embedding, embeddings).flatten()
122
- top_index = similarities.argsort()[-1]
123
- top_result = metadata.iloc[top_index].copy()
124
- top_result['similarity_score'] = similarities[top_index]
125
- return top_result
126
 
 
 
127
  top_question = find_top_question(query)
128
 
 
129
  detailed_prompt = (
130
  f"Transform this LeetCode question into a real-world interview scenario:\n\n"
131
  f"**Company**: {top_question['company']}\n"
@@ -136,29 +106,76 @@ if generate_button:
136
  f"\nPlease create a real-world interview question based on this information."
137
  )
138
 
139
- response_text = client.chat.completions.create(
140
- model="gpt-4",
141
- messages=[{"role": "assistant", "content": question_generation_prompt}, {"role": "user", "content": detailed_prompt}],
142
- ).choices[0].message.content
143
-
144
- st.session_state.generated_question = response_text
 
 
145
 
 
 
 
 
146
  for message in st.session_state.messages:
147
  with st.chat_message(message["role"]):
148
  st.markdown(message["content"])
149
 
150
- if user_input := st.chat_input("Continue your conversation or ask follow-up questions here:"):
151
- with st.chat_message("user"):
152
- st.markdown(user_input)
153
-
154
- assistant_response_text = client.chat.completions.create(
155
- model="gpt-4",
156
- messages=[{"role": "assistant", "content": technical_interviewer_prompt}] + [{"role": msg["role"], "content": msg["content"]} for msg in st.session_state.messages],
157
- ).choices[0].message.content
158
-
159
- with st.chat_message("assistant"):
160
- st.markdown(assistant_response_text)
161
-
162
- # Append to session state messages for persistence
163
- st.session_state.messages.append({"role": "user", "content": user_input})
164
- st.session_state.messages.append({"role": "assistant", "content": assistant_response_text})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"))
 
15
  print(f"Using device: {device}")
16
 
17
  # Load metadata and embeddings (ensure these files are in your working directory or update paths)
18
+ metadata_path = 'question_metadata.csv' # Update this path if needed
19
+ embeddings_path = 'question_dataset_embeddings.npy' # Update this path if needed
20
 
21
  metadata = pd.read_csv(metadata_path)
22
  embeddings = np.load(embeddings_path)
 
37
  if "messages" not in st.session_state:
38
  st.session_state.messages = []
39
 
40
+ if "follow_up_mode" not in st.session_state:
41
+ st.session_state.follow_up_mode = False # Tracks whether we're in follow-up mode
42
+
43
  if "generated_question" not in st.session_state:
44
+ st.session_state.generated_question = None # Stores the generated question for persistence
45
 
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
+ # Compute cosine similarity between query embedding and dataset embeddings
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
70
+ def generate_response(messages):
71
+ debug_log_entry = {"messages": messages}
72
+ st.session_state.debug_logs.append(debug_log_entry) # Store debug log
73
+
74
+ response = client.chat.completions.create(
75
+ model="o1-mini",
76
+ messages=messages,
77
+ )
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") # Default value: Google
84
+ difficulty = st.selectbox("Difficulty", ["Easy", "Medium", "Hard"], index=1) # Default: Medium
85
+ topic = st.text_input("Topic (e.g., Backtracking)", value="Backtracking") # Default: 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
  f"\nPlease create a real-world interview question based on this information."
107
  )
108
 
109
+ # Generate response using GPT-4 with detailed prompt and debugging logs
110
+ response = generate_response([{"role": "assistant", "content": question_generation_prompt}, {"role": "user", "content": detailed_prompt}])
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
+ # Enable follow-up mode after generating the initial question
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
+ # Generate assistant's response based on follow-up input using technical_interviewer_prompt as system prompt,
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(assistant_response)
143
+
144
+ st.session_state.messages.append({"role": "assistant", "content": assistant_response})
145
+
146
+ # Sidebar content to display persistent generated question (left sidebar)
147
+ st.sidebar.markdown("## Generated Question")
148
+ if st.session_state.generated_question:
149
+ st.sidebar.markdown(st.session_state.generated_question)
150
+ else:
151
+ st.sidebar.markdown("_No question generated yet._")
152
+
153
+ st.sidebar.markdown("""
154
+ ## About
155
+ This is a Real-World Interview Question Generator powered by OpenAI's API.
156
+ Enter a company name, topic, and level of difficulty, and it will transform a relevant question into a real-world interview scenario!
157
+ Continue chatting with the assistant in the chatbox below.
158
+ """)
159
+
160
+ # Right sidebar toggleable debug logs and code interpreter section
161
+ with st.expander("Debug Logs (Toggle On/Off)", expanded=False):
162
+ if len(st.session_state.debug_logs) > 0:
163
+ for log_entry in reversed(st.session_state.debug_logs): # Show most recent logs first
164
+ st.write(log_entry)
165
+
166
+ st.sidebar.markdown("---")
167
+ st.sidebar.markdown("## Python Code Interpreter")
168
+ code_input = st.sidebar.text_area("Write your Python code here:")
169
+ if st.sidebar.button("Run Code"):
170
+ try:
171
+ exec_globals = {}
172
+ exec(code_input, exec_globals) # Execute user-provided code safely within its own scope.
173
+ output_key = [k for k in exec_globals.keys() if k != "__builtins__"]
174
+ if output_key:
175
+ output_value = exec_globals[output_key[0]]
176
+ st.sidebar.success(f"Output: {output_value}")
177
+ else:
178
+ st.sidebar.success("Code executed successfully!")
179
+
180
+ except Exception as e:
181
+ st.sidebar.error(f"Error: {e}")