hashirehtisham commited on
Commit
4e4077f
·
verified ·
1 Parent(s): 96db01e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -142
app.py CHANGED
@@ -95,38 +95,39 @@ footer {display:none !important}
95
  }
96
  """
97
 
98
- # Initialize the InferenceClient for chatbot
99
- client = InferenceClient(
100
- model="microsoft/phi-4",
101
- token=os.getenv("HF_TOKEN1")
102
- )
103
-
104
  # Global variable to store chat history for the current session
105
  current_chat_history = []
106
 
107
  # Define the function for chatbot response
108
  def respond(
109
  message,
110
- history,
111
  system_message,
112
  max_tokens,
113
  temperature,
114
  top_p,
 
115
  ):
116
  global current_chat_history
117
 
 
118
  messages = [{"role": "system", "content": system_message}]
119
-
120
- for val in history:
121
- if val[0]:
122
- messages.append({"role": "user", "content": val[0]})
123
- if val[1]:
124
- messages.append({"role": "assistant", "content": val[1]})
125
- current_chat_history.append(f"Assistant: {val[1]}")
126
 
 
 
 
 
 
 
 
 
 
 
127
  messages.append({"role": "user", "content": message})
128
  current_chat_history.append(f"User: {message}")
129
-
 
 
130
  response = ""
131
 
132
  for message in client.chat_completion(
@@ -136,7 +137,11 @@ def respond(
136
  temperature=temperature,
137
  top_p=top_p,
138
  ):
139
- token = message.choices[0].delta.content
 
 
 
 
140
  response += token
141
  yield response
142
 
@@ -156,41 +161,52 @@ def clear_chat_history():
156
  global current_chat_history
157
  current_chat_history.clear() # Clear the chat history
158
  return "Chat history cleared."
159
-
160
- def send_message(message, history, system_message, max_tokens, temperature, top_p):
161
- if message:
162
- history.append((message, ""))
163
- response = respond(
164
- message=message,
165
- history=history,
166
- system_message=system_message,
167
- max_tokens=max_tokens,
168
- temperature=temperature,
169
- top_p=top_p,
170
- )
171
- response_text = ""
172
- for r in response:
173
- response_text = r
174
- # Apply HTML formatting to headings
175
- formatted_response_text = response_text.replace(
176
- "Student's Primary Interest with Reason:", "<h2><strong>Student's Primary Interest with Reason</strong></h2>"
177
- ).replace(
178
- "Career Opportunities in the field:", "<h2><strong>Career Opportunities in the field</strong></h2>"
179
- ).replace(
180
- "Universities in Pakistan for related field:", "<h2><strong>Universities in Pakistan for related field</strong></h2>"
181
- ).replace(
182
- "Conclusion with name of field:", "<h2><strong>Conclusion with name of field</strong></h2>"
183
- )
184
- history[-1] = (message, formatted_response_text)
185
- return history, gr.update(value="")
186
 
187
  # Excel reading function
188
  def read_excel(file):
189
  df = pd.read_excel(file.name)
190
  return df.to_string()
191
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  # Create the Gradio interface
193
  with gr.Blocks(css=css) as demo:
 
 
 
 
 
 
 
 
 
 
 
194
  # Introduction Tab
195
  with gr.Tab("Career Compass"):
196
  with gr.Row(elem_id="image-container"):
@@ -204,10 +220,6 @@ with gr.Blocks(css=css) as demo:
204
  - **Streamlined Interface:** Simple and intuitive user experience.
205
  - **Detailed Reports:** Offers insights into suitable career paths, relevant universities, and job opportunities.
206
  - **General Guidance & Emotional Support:** Talk to AI for General Career Guidance and also lighten your mood.
207
- **Libraries Used:**
208
- - **Gradio:** For creating the user interface.
209
- - **Pandas:** For reading and analyzing Excel files.
210
- - **LLM model:** Microsoft's phi-4 For utilizing state-of-the-art language models.
211
 
212
  **How It Works:**
213
  - **Detailed Analysis**
@@ -215,113 +227,31 @@ with gr.Blocks(css=css) as demo:
215
  2. Input your query regarding career guidance.
216
  3. Get detailed recommendations and potential career paths.
217
  4. Download the Report!
218
- - **General Guidance & Emotional Support**
219
- 1. Enter your query and doubts about choosing University majors and Chatbot will guide you about the right choice.
220
- 2. Ask about Career Opportunities and scope of different fields to get unbaised AI analyzed answer and recommendations and potential career paths!
221
- 3. IF you ever feel sad, anxious or depressed, talk to Career Compass and it will console you like a friend.
222
  """)
223
 
224
  # Detailed Analysis Tab
225
  with gr.Tab("Detailed Analysis"):
226
  gr.Markdown("# Detailed Analysis")
227
- gr.Markdown("Get personalized career guidance based on academic performance and extracurricular activities with Detailed Analysis.\n<div style='color: green;'>Developed by Hashir Ehtisham</div>")
228
-
229
- system_message_career = gr.Textbox(value=system_message, visible=False)
230
- chatbot_career = gr.Chatbot()
231
- msg_career = gr.Textbox(label="Enter the Excel Copied Data here")
232
-
233
- with gr.Row():
234
- clear_career = gr.Button("New Chat")
235
- download_button = gr.Button("Download Chat History")
236
- submit_career = gr.Button("Submit")
237
-
238
- with gr.Row():
239
- download_output = gr.File(label="Download")
240
- download_button.click(download_chat_history, outputs=download_output)
241
-
242
- with gr.Row():
243
- clear_button = gr.Button("Clear Chat History")
244
- status_output = gr.Textbox(label="Status", interactive=False) # Add a Textbox for status output
245
- clear_button.click(clear_chat_history, outputs=status_output) # Use the status Textbox for output
246
-
247
- with gr.Accordion("Additional Inputs", open=False):
248
- max_tokens_career = gr.Slider(minimum=1, maximum=2048, value=1024, step=1, label="Max new tokens")
249
- temperature_career = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature")
250
- top_p_career = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)")
251
-
252
- def respond_wrapper_career(message, chat_history, system_message_val, max_tokens_val, temperature_val, top_p_val):
253
- chat_history, _ = send_message(
254
- message=message,
255
- history=chat_history,
256
- system_message=system_message_val,
257
- max_tokens=max_tokens_val,
258
- temperature=temperature_val,
259
- top_p=top_p_val,
260
- )
261
- return gr.update(value=chat_history), gr.update(value="")
262
-
263
- submit_career.click(
264
- respond_wrapper_career,
265
- inputs=[msg_career, chatbot_career, system_message_career, max_tokens_career, temperature_career, top_p_career],
266
- outputs=[chatbot_career, msg_career],
267
- )
268
-
269
- clear_career.click(lambda: None, None, chatbot_career, queue=False)
270
-
271
  # File Upload Tab
272
  with gr.Tab("Upload Data"):
273
  gr.Markdown("# Upload Data")
274
- gr.Markdown("Upload your academic record along with extracurricular activities here and then copy & paste it in Detailed Analysis Tab.\n<div style='color: green;'>Don't worry if your extracted data appears a bit strange. 😉 </div> \n<div style='color: green;'>Developed by Hashir Ehtisham</div>")
275
  file_input = gr.File(label="Upload Excel file")
276
  excel_output = gr.Textbox(label="Excel Content")
277
  file_input.change(read_excel, inputs=file_input, outputs=excel_output)
278
 
279
- # Simple Chatbot Tab (new tab integration)
280
  with gr.Tab("General Guidance & Emotional Support"):
281
  gr.Markdown("# General Guidance & Emotional Support")
282
- gr.Markdown("""
283
- A compassionate career counseling chatbot providing personalized guidance on career paths and emotional support for your journey.
284
- <div style='color: green;'>Developed by Hashir Ehtisham</div>
285
- """)
286
-
287
- system_message_simple = gr.Textbox(value="You are an AI powered chatbot named as Career Compass built by Hashir Ehtisham who is a student of APS DHA II Sec -D to help students, teachers, and parents find the best career paths based on students' interests and academic performance.", visible=False)
288
- chatbot_simple = gr.Chatbot()
289
- msg_simple = gr.Textbox(label="Type a message")
290
-
291
- with gr.Row():
292
- clear_simple = gr.Button("Clear")
293
- submit_simple = gr.Button("Submit")
294
-
295
- with gr.Accordion("Additional Inputs", open=False):
296
- max_tokens_simple = gr.Slider(minimum=1, maximum=2048, value=1024, step=1, label="Max new tokens")
297
- temperature_simple = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature")
298
- top_p_simple = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)")
299
-
300
- def respond_wrapper_simple(message, chat_history, system_message_val, max_tokens_val, temperature_val, top_p_val):
301
- chat_history, _ = send_message(
302
- message=message,
303
- history=chat_history,
304
- system_message=system_message_val,
305
- max_tokens=max_tokens_val,
306
- temperature=temperature_val,
307
- top_p=top_p_val,
308
- )
309
- return chat_history
310
-
311
- submit_simple.click(
312
- respond_wrapper_simple,
313
- inputs=[
314
- msg_simple,
315
- chatbot_simple,
316
- system_message_simple,
317
- max_tokens_simple,
318
- temperature_simple,
319
- top_p_simple,
320
- ],
321
- outputs=[chatbot_simple],
322
- )
323
-
324
- clear_simple.click(lambda: None, None, chatbot_simple)
325
 
326
- # Launch the Gradio app
327
- demo.launch()
 
95
  }
96
  """
97
 
 
 
 
 
 
 
98
  # Global variable to store chat history for the current session
99
  current_chat_history = []
100
 
101
  # Define the function for chatbot response
102
  def respond(
103
  message,
104
+ history, # gr.ChatInterface uses list of dicts format
105
  system_message,
106
  max_tokens,
107
  temperature,
108
  top_p,
109
+ hf_token: gr.OAuthToken,
110
  ):
111
  global current_chat_history
112
 
113
+ # Build messages list for the API
114
  messages = [{"role": "system", "content": system_message}]
 
 
 
 
 
 
 
115
 
116
+ # Add conversation history (gr.ChatInterface uses list of dicts format)
117
+ for msg in history:
118
+ messages.append(msg)
119
+ # Also add to our text history for download
120
+ if msg["role"] == "user":
121
+ current_chat_history.append(f"User: {msg['content']}")
122
+ elif msg["role"] == "assistant":
123
+ current_chat_history.append(f"Assistant: {msg['content']}")
124
+
125
+ # Add current message
126
  messages.append({"role": "user", "content": message})
127
  current_chat_history.append(f"User: {message}")
128
+
129
+ client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
130
+
131
  response = ""
132
 
133
  for message in client.chat_completion(
 
137
  temperature=temperature,
138
  top_p=top_p,
139
  ):
140
+ choices = message.choices
141
+ token = ""
142
+ if len(choices) and choices[0].delta.content:
143
+ token = choices[0].delta.content
144
+
145
  response += token
146
  yield response
147
 
 
161
  global current_chat_history
162
  current_chat_history.clear() # Clear the chat history
163
  return "Chat history cleared."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
 
165
  # Excel reading function
166
  def read_excel(file):
167
  df = pd.read_excel(file.name)
168
  return df.to_string()
169
 
170
+ # Create the main chatbot interface using gr.ChatInterface for the Detailed Analysis tab
171
+ def create_career_chatbot():
172
+ return gr.ChatInterface(
173
+ respond,
174
+ type="messages",
175
+ additional_inputs=[
176
+ gr.Textbox(value=system_message, label="System message", visible=False),
177
+ gr.Slider(minimum=1, maximum=2048, value=1024, step=1, label="Max new tokens", visible=False),
178
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature", visible=False),
179
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)", visible=False),
180
+ ],
181
+ )
182
+
183
+ # Create the simple chatbot interface for General Guidance tab
184
+ def create_simple_chatbot():
185
+ return gr.ChatInterface(
186
+ respond,
187
+ type="messages",
188
+ additional_inputs=[
189
+ gr.Textbox(value="You are an AI powered chatbot named as Career Compass built by Hashir Ehtisham who is a Computer Engineering student of NUST CEME to help students, teachers, and parents find the best career paths based on students' interests and academic performance.",
190
+ label="System message", visible=False),
191
+ gr.Slider(minimum=1, maximum=2048, value=1024, step=1, label="Max new tokens", visible=False),
192
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature", visible=False),
193
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)", visible=False),
194
+ ],
195
+ )
196
+
197
  # Create the Gradio interface
198
  with gr.Blocks(css=css) as demo:
199
+ # Add login button to sidebar
200
+ with gr.Sidebar():
201
+ gr.LoginButton()
202
+ download_button = gr.Button("Download Chat History")
203
+ clear_button = gr.Button("Clear Chat History")
204
+ status_output = gr.Textbox(label="Status", interactive=False)
205
+ download_output = gr.File(label="Download")
206
+
207
+ download_button.click(download_chat_history, outputs=download_output)
208
+ clear_button.click(clear_chat_history, outputs=status_output)
209
+
210
  # Introduction Tab
211
  with gr.Tab("Career Compass"):
212
  with gr.Row(elem_id="image-container"):
 
220
  - **Streamlined Interface:** Simple and intuitive user experience.
221
  - **Detailed Reports:** Offers insights into suitable career paths, relevant universities, and job opportunities.
222
  - **General Guidance & Emotional Support:** Talk to AI for General Career Guidance and also lighten your mood.
 
 
 
 
223
 
224
  **How It Works:**
225
  - **Detailed Analysis**
 
227
  2. Input your query regarding career guidance.
228
  3. Get detailed recommendations and potential career paths.
229
  4. Download the Report!
230
+ - **General Guidance & Emotional Support**
231
+ 1. Enter your query and doubts about choosing University majors.
232
+ 2. Ask about Career Opportunities and scope of different fields.
233
+ 3. Get unbiased AI analyzed answers and recommendations!
234
  """)
235
 
236
  # Detailed Analysis Tab
237
  with gr.Tab("Detailed Analysis"):
238
  gr.Markdown("# Detailed Analysis")
239
+ gr.Markdown("Get personalized career guidance based on academic performance and extracurricular activities.\n<div style='color: green;'>Developed by Hashir Ehtisham</div>")
240
+ career_chatbot = create_career_chatbot()
241
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  # File Upload Tab
243
  with gr.Tab("Upload Data"):
244
  gr.Markdown("# Upload Data")
245
+ gr.Markdown("Upload your academic record along with extracurricular activities here.\n<div style='color: green;'>Don't worry if your extracted data appears a bit strange. 😉 </div> \n<div style='color: green;'>Developed by Hashir Ehtisham</div>")
246
  file_input = gr.File(label="Upload Excel file")
247
  excel_output = gr.Textbox(label="Excel Content")
248
  file_input.change(read_excel, inputs=file_input, outputs=excel_output)
249
 
250
+ # Simple Chatbot Tab
251
  with gr.Tab("General Guidance & Emotional Support"):
252
  gr.Markdown("# General Guidance & Emotional Support")
253
+ gr.Markdown("A compassionate career counseling chatbot providing personalized guidance on career paths and emotional support. \n<div style='color: green;'>Developed by Hashir Ehtisham</div>")
254
+ simple_chatbot = create_simple_chatbot()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
 
256
+ if __name__ == "__main__":
257
+ demo.launch()