VectorV17 commited on
Commit
69a56aa
·
verified ·
1 Parent(s): 15e5f37

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +225 -189
app.py CHANGED
@@ -1,216 +1,252 @@
1
- import os
2
- import datetime
3
- import warnings
4
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- # Suppress deprecation warnings for a cleaner console
7
- warnings.filterwarnings("ignore", category=UserWarning, module="langchain_community")
8
-
9
- from langchain_chroma import Chroma
10
- from langchain_huggingface import HuggingFaceEmbeddings
11
- from langchain_openai import ChatOpenAI
12
- from langchain_core.prompts import ChatPromptTemplate
13
- from langchain_core.output_parsers import StrOutputParser
14
- from dotenv import load_dotenv
15
- from langchain_huggingface import HuggingFaceEndpoint
16
- from langchain_core.prompts import PromptTemplate
17
-
18
-
19
- # Load Environment Variables
20
- load_dotenv()
21
- hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN")
22
-
23
- # -------------------------------------------------------------------------
24
- # 1. Setup Vector Store & Embeddings Pipeline
25
- # -------------------------------------------------------------------------
26
- print("Loading semantic embedding vectors...")
27
- embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
28
-
29
- simplilearn_faq_data = [
30
- "Simplilearn Refund Policy: Learners are entitled to a full 100% refund within 7 days of course purchase, provided they have not accessed more than 25% of the unlocked asynchronous content or attended any live virtual cohort sessions.",
31
- "Professional Certification Requirements: To unlock your official Simplilearn digital certificate, you must achieve a minimum score of 80% in the final course assessment and successfully submit all mandatory course projects.",
32
- "Live Virtual Class Attendance: If a student misses an interactive live session, high-definition cloud recordings are automatically processed and made available on the student LMS dashboard within 24 hours.",
33
- "Technical Support Availability: Technical assistance for cloud labs, environment resets, or workspace access is available 24/7. Students can raise a ticket via the 'Help and Support' tab or email support@simplilearn.com.",
34
- "Data Science Bootcamp Prerequisites: This flagship program spans 6 months. It requires basic exposure to high-school level mathematics and rudimentary programming logic (Python familiarity is highly recommended but not mandatory)."
35
- ]
36
-
37
- vectorstore = Chroma.from_texts(texts=simplilearn_faq_data, embedding=embeddings)
38
- retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 2})
39
-
40
- # -------------------------------------------------------------------------
41
- # 2. Setup Robust LLM Interface via OpenAI-Compatible Endpoint
42
- # -------------------------------------------------------------------------
43
-
44
- print("Configuring LLM Interface...")
45
-
46
- if not hf_token:
47
- print("⚠️ WARNING: HF_TOKEN is missing. The app will fail to generate responses.")
48
-
49
- # CORRECT CONFIGURATION: Pass cold-start directive via headers
50
- chatModel = HuggingFaceEndpoint(
51
- repo_id="mistralai/Mistral-7B-Instruct-v0.3",
52
- huggingfacehub_api_token=hf_token,
53
- temperature=0.3,
54
- max_new_tokens=400,
55
- headers={"X-Wait-For-Model": "true"} # Fixes the TypeError and handles cold starts gracefully
56
- )
57
-
58
- # Use a clean text template matching the non-chat model endpoint structure
59
- system_prompt = """You are the Simplilearn MOOC Support Agent, an advanced, polite, and professional AI learning assistant named Lane.
60
- Answer the student's inquiry accurately using ONLY the retrieved context below.
61
- If the answer cannot be found in the context, politely inform them that you only handle Simplilearn academic protocols and advise them to contact support@simplilearn.com.
62
-
63
- Context:
64
- {context}
65
-
66
- User Inquiry: {input}
67
-
68
- Lane's Response:"""
69
-
70
- prompt = PromptTemplate.from_template(system_prompt)
71
-
72
- def format_docs(docs):
73
- return "\n\n".join(doc.page_content for doc in docs)
74
-
75
- rag_chain = (
76
- {
77
- "context": lambda x: format_docs(retriever.invoke(x["input"])),
78
- "input": lambda x: x["input"]
79
- }
80
- | prompt
81
- | chatModel
82
- | StrOutputParser()
83
- )
84
-
85
- # -------------------------------------------------------------------------
86
- # 3. Application Core Logic
87
- # -------------------------------------------------------------------------
88
- def process_chat(message, history):
89
- if not message.strip():
90
- return "", history
91
-
92
- if history is None:
93
- history = []
94
-
95
- try:
96
- # Executes the RAG Chain
97
- bot_response = rag_chain.invoke({"input": message})
98
-
99
- except Exception as e:
100
- # Gracefully handle HF timeout/wake-up errors instead of crashing the UI
101
- bot_response = (
102
- f"⚠️ **Connection Status:**\n\n"
103
- f"`{str(e)}`\n\n"
104
- f"**Note:** The Hugging Face inference model is currently waking up. This takes about 30-60 seconds. Please wait a moment and try sending your message again!"
105
- )
106
 
107
- history.append({"role": "user", "content": message})
108
- history.append({"role": "assistant", "content": bot_response})
109
 
110
- return "", history
111
-
112
- def handle_quick_reply(button_text, history):
113
- return process_chat(button_text, history)
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
- # -------------------------------------------------------------------------
116
- # 4. Gradio Web Interface Layout
117
- # -------------------------------------------------------------------------
118
- # Improved CSS: Explicitly setting foreground text colors to prevent invisible text in dark mode
119
  custom_css = """
120
- .header-container { background-color: #f0f4f8 !important; padding: 25px; border-radius: 12px; margin-bottom: 20px; border: 1px solid #e2e8f0; }
121
- .header-container h1, .header-container p { color: #0f172a !important; }
122
- .meta-container { text-align: right; font-family: 'Georgia', serif; font-style: italic; }
123
- .meta-container h3 { color: #334155 !important; margin: 4px 0; }
124
- .sidebar-panel { background-color: #0f766e !important; color: white !important; padding: 25px; border-radius: 12px; text-align: center; }
125
- .sidebar-panel p, .sidebar-panel h2 { color: white !important; }
126
- .quick-btn { background-color: #f1f5f9 !important; border: 1px solid #cbd5e1 !important; color: #0f766e !important; font-weight: 600; }
127
- .quick-btn:hover { background-color: #e2e8f0 !important; }
128
- """
129
-
130
- # Native JS logic to toggle Gradio's standard dark mode class on the body
131
- toggle_js = """
132
- function() {
133
- document.body.classList.toggle('dark');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  }
135
  """
136
 
137
- with gr.Blocks(title="Simplilearn MOOC FAQ Agent") as demo:
 
138
 
139
- # TOP HEADER SECTION
140
- with gr.Row(elem_classes=["header-container"]):
141
- with gr.Column(scale=3):
142
- gr.Markdown("""
143
- # About Us
144
- At Simplilearn Agentic Hub, we are passionate about the power of structured education and its ability
145
- to transform careers. We are a leading knowledge processing framework dedicated to helping
146
- learners unlock the full potential of specialized MOOC educational pathways.
147
- """)
148
- with gr.Column(scale=2, elem_classes=["meta-container"]):
149
- current_date = datetime.datetime.now().strftime("%dth %B %Y | Time: %I:%M%p").lower()
150
- gr.Markdown(f"### {current_date}")
151
- mode_btn = gr.Button("☀️ 🌙 ➔ Change Mode (Day / Night)", variant="secondary", size="sm")
152
- mode_btn.click(fn=None, js=toggle_js)
153
 
154
- # MAIN WORKSPACE SECTION
155
  with gr.Row():
156
- # Chat interface
157
- with gr.Column(scale=4):
158
  chatbot = gr.Chatbot(
159
- label="Lane AI Support Stream",
160
- value=[{"role": "assistant", "content": "Hello! I'm Lane, your Simplilearn Support Agent. How can I assist you with your courses today?"}]
 
 
161
  )
162
 
163
  with gr.Row():
164
- user_input = gr.Textbox(
165
- show_label=False,
166
- placeholder="Ask Lane anything regarding Simplilearn policies...",
 
167
  scale=5
168
  )
169
- submit_btn = gr.Button("Send", variant="primary", scale=1)
170
 
171
- with gr.Row():
172
- btn_refund = gr.Button("What is the course refund policy?", elem_classes=["quick-btn"])
173
- btn_cert = gr.Button("How do I unlock my completion certificate?", elem_classes=["quick-btn"])
 
 
 
 
 
 
 
 
 
 
 
 
174
 
175
- # Agent Sidebar Identity
176
- with gr.Column(scale=2, elem_classes=["sidebar-panel"]):
177
- gr.HTML("""
178
- <div style='margin-top: 10px;'>
179
- <img src='https://cdn-icons-png.flaticon.com/512/4712/4712010.png' alt='Lane Avatar' style='width:120px; height:120px; object-fit:cover; margin:0 auto 15px auto; border: 4px solid #ffffff; border-radius: 50%; background-color: white;'>
180
- <h2 style='margin-bottom: 5px; font-size: 24px; font-weight: bold;'>Lane <span style='background-color:#ffffff; color:#0f766e; padding:2px 8px; border-radius:4px; font-size:14px; vertical-align: middle;'>AI</span></h2>
181
- <p style='font-style: italic; opacity: 0.9; margin-bottom: 15px;'>Your Agentic Learning Assistant</p>
182
- <hr style='border-color: rgba(255,255,255,0.2); margin: 15px 0;'>
183
- <p style='font-size: 14px; text-align: left; line-height: 1.5; opacity: 0.95;'>
184
- 🎓 <b>Secure Session Activated</b><br>
185
- Operational Node: Simplilearn-Chroma-01<br>
186
- Processing Hardware: Base CPU Node
187
- </p>
188
- </div>
189
- """)
190
-
191
- # Event Wiring Architecture
192
- submit_btn.click(
193
- fn=process_chat,
194
- inputs=[user_input, chatbot],
195
- outputs=[user_input, chatbot]
196
  )
197
- user_input.submit(
198
- fn=process_chat,
199
- inputs=[user_input, chatbot],
200
- outputs=[user_input, chatbot]
 
 
201
  )
202
 
203
- btn_refund.click(
204
- fn=handle_quick_reply,
205
- inputs=[btn_refund, chatbot],
206
- outputs=[user_input, chatbot]
 
207
  )
208
- btn_cert.click(
209
- fn=handle_quick_reply,
210
- inputs=[btn_cert, chatbot],
211
- outputs=[user_input, chatbot]
 
212
  )
213
 
 
214
  if __name__ == "__main__":
215
- # Launch with Gradio's Default theme to ensure dark/light mode hooks exist natively
216
- demo.launch(server_name="0.0.0.0", server_port=7860, css=custom_css, theme=gr.themes.Default())
 
 
 
 
1
  import gradio as gr
2
+ from datetime import datetime
3
+
4
+ # 1. Structured Knowledge Base for the Simplilearn MOOC FAQ Agent
5
+ FAQ_KNOWLEDGE_BASE = {
6
+ "refund": (
7
+ "Simplilearn offers a 7-day refund policy for our MOOC and specialized educational pathways, "
8
+ "provided the learner has not accessed more than 25% of the course content, attended any live "
9
+ "classes, or unlocked any certification modules."
10
+ ),
11
+ "certificate": (
12
+ "To unlock your completion certificate, you must fulfill three criteria:\n"
13
+ "1. Complete 100% of the self-paced video lectures.\n"
14
+ "2. Score at least 80% on all module quizzes.\n"
15
+ "3. Successfully submit and receive a passing grade on the industry-aligned Capstone Project."
16
+ ),
17
+ "prerequisites": (
18
+ "Prerequisites vary by pathway. For basic programs, a fundamental understanding of math is sufficient. "
19
+ "Advanced programs (like the AI Engineer track) recommend prior familiarity with Python and basic statistics."
20
+ ),
21
+ "technical support": (
22
+ "If you are facing virtual lab environments or video playback issues, you can access the "
23
+ "Simplilearn LMS Help Center 24/7 or raise a ticket directly through your learner dashboard support tab."
24
+ )
25
+ }
26
 
27
+ # 2. Response Matching Logic
28
+ def respond(user_message, chat_history):
29
+ if not user_message.strip():
30
+ return "", chat_history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
+ query = user_message.lower()
 
33
 
34
+ # Simple, highly efficient semantic/keyword routing for CPU optimization
35
+ if "refund" in query or "policy" in query:
36
+ reply = FAQ_KNOWLEDGE_BASE["refund"]
37
+ elif "certificate" in query or "unlock" in query:
38
+ reply = FAQ_KNOWLEDGE_BASE["certificate"]
39
+ elif "prerequisite" in query or "require" in query or "knowledge" in query:
40
+ reply = FAQ_KNOWLEDGE_BASE["prerequisites"]
41
+ elif "tech" in query or "lab" in query or "support" in query or "lms" in query:
42
+ reply = FAQ_KNOWLEDGE_BASE["technical support"]
43
+ else:
44
+ reply = (
45
+ "I'm here to assist you with Simplilearn institutional policies, course logistics, "
46
+ "grading criteria, and certificate requirements. Could you please specify your inquiry?"
47
+ )
48
+
49
+ chat_history.append((user_message, reply))
50
+ return "", chat_history
51
 
52
+ # 3. Custom CSS to mirror the provided screenshot layout and dark styling
 
 
 
53
  custom_css = """
54
+ body, .gradio-container {
55
+ background-color: #0b0f17 !important;
56
+ color: #ffffff !important;
57
+ font-family: 'Inter', sans-serif;
58
+ }
59
+ .about-card {
60
+ background-color: #161c2a !important;
61
+ border: 1px solid #232d42 !important;
62
+ border-radius: 8px !important;
63
+ padding: 20px !important;
64
+ margin-bottom: 20px !important;
65
+ }
66
+ .about-title {
67
+ font-size: 24px !important;
68
+ font-weight: 700 !important;
69
+ color: #ffffff !important;
70
+ margin-bottom: 10px !important;
71
+ }
72
+ .time-stamp {
73
+ text-align: right !important;
74
+ color: #a0aec0 !important;
75
+ font-style: italic !important;
76
+ font-size: 14px !important;
77
+ }
78
+ .mode-btn {
79
+ background-color: #2d3748 !important;
80
+ color: #ffffff !important;
81
+ border: none !important;
82
+ border-radius: 4px !important;
83
+ padding: 5px 10px !important;
84
+ font-size: 13px !important;
85
+ cursor: pointer !important;
86
+ }
87
+ .lane-card {
88
+ background-color: #065f51 !important;
89
+ color: #ffffff !important;
90
+ border-radius: 12px !important;
91
+ padding: 25px !important;
92
+ text-align: center !important;
93
+ height: 100%;
94
+ }
95
+ .lane-avatar {
96
+ width: 100px !important;
97
+ height: 100px !important;
98
+ background-color: #ffffff !important;
99
+ border-radius: 50% !important;
100
+ margin: 0 auto 15px auto !important;
101
+ display: flex !important;
102
+ align-items: center !important;
103
+ justify-content: center !important;
104
+ font-size: 50px !important;
105
+ }
106
+ .lane-title {
107
+ font-size: 22px !important;
108
+ font-weight: bold !important;
109
+ margin-bottom: 2px !important;
110
+ }
111
+ .lane-tag {
112
+ background-color: #ffffff !important;
113
+ color: #065f51 !important;
114
+ font-size: 12px !important;
115
+ font-weight: bold !important;
116
+ padding: 2px 6px !important;
117
+ border-radius: 4px !important;
118
+ margin-left: 5px !important;
119
+ vertical-align: middle !important;
120
+ }
121
+ .lane-subtitle {
122
+ font-style: italic !important;
123
+ color: #cbd5e0 !important;
124
+ font-size: 14px !important;
125
+ margin-bottom: 15px !important;
126
+ }
127
+ .lane-divider {
128
+ border-top: 1px solid rgba(255, 255, 255, 0.2) !important;
129
+ margin: 15px 0 !important;
130
+ }
131
+ .lane-meta {
132
+ text-align: left !important;
133
+ font-size: 13px !important;
134
+ color: #e2e8f0 !important;
135
+ line-height: 1.6 !important;
136
+ }
137
+ .send-btn {
138
+ background-color: #df5413 !important;
139
+ color: #ffffff !important;
140
+ font-weight: bold !important;
141
+ border: none !important;
142
+ }
143
+ .send-btn:hover {
144
+ background-color: #c6430b !important;
145
+ }
146
+ .suggestion-btn {
147
+ background-color: #1e293b !important;
148
+ color: #2b9388 !important;
149
+ border: 1px solid #334155 !important;
150
+ font-weight: 600 !important;
151
+ border-radius: 6px !important;
152
+ }
153
+ .suggestion-btn:hover {
154
+ background-color: #334155 !important;
155
+ }
156
+ .chatbot-container {
157
+ border: 1px solid #232d42 !important;
158
+ border-radius: 8px !important;
159
+ background-color: #0f141c !important;
160
  }
161
  """
162
 
163
+ # 4. Building the UI Layout
164
+ with gr.Blocks(css=custom_css, title="Intelli_Agent") as demo:
165
 
166
+ # Header Banner - "About Us"
167
+ with gr.Row(elem_classes="about-card"):
168
+ with gr.Column(scale=4):
169
+ gr.Markdown("### About Us", elem_classes="about-title")
170
+ gr.Markdown(
171
+ "At Simplilearn Agentic Hub, we are passionate about the power of structured education and its "
172
+ "ability to transform careers. We are a leading knowledge processing framework dedicated to "
173
+ "helping learners unlock the full potential of specialized MOOC educational pathways."
174
+ )
175
+ with gr.Column(scale=2, min_width=200):
176
+ # Dynamic matching of the exact date displayed in the reference image
177
+ current_time_str = datetime.now().strftime("%dth %B %Y | time: %I:%M%p").lower()
178
+ gr.HTML(f"<div class='time-stamp'>{current_time_str}</div>")
179
+ gr.HTML("<div style='text-align: right; margin-top: 10px;'><button class='mode-btn'>☀️ 🌙 -> Change Mode (Day / Night)</button></div>")
180
 
181
+ # Main Dashboard Workspace
182
  with gr.Row():
183
+ # Left Side Workspace: Chat Interface
184
+ with gr.Column(scale=3):
185
  chatbot = gr.Chatbot(
186
+ value=[(None, "Hello! I'm Lane, your Simplilearn Support Agent. How can I assist you with your courses today?")],
187
+ elem_classes="chatbot-container",
188
+ height=400,
189
+ show_label=False
190
  )
191
 
192
  with gr.Row():
193
+ msg_input = gr.Textbox(
194
+ show_label=False,
195
+ placeholder="Ask Lane anything regarding Simplilearn policies...",
196
+ container=False,
197
  scale=5
198
  )
199
+ send_button = gr.Button("Send", variant="primary", elem_classes="send-btn", scale=1)
200
 
201
+ # Right Side Workspace: Status Profile Panel
202
+ with gr.Column(scale=1, min_width=280):
203
+ with gr.Box(elem_classes="lane-card"):
204
+ # Robot Emoji avatar representing the UI image icon
205
+ gr.HTML("<div class='lane-avatar'>🤖</div>")
206
+ gr.HTML("<div class='lane-title'>Lane <span class='lane-tag'>AI</span></div>")
207
+ gr.HTML("<div class='lane-subtitle'>Your Agentic Learning Assistant</div>")
208
+ gr.HTML("<div class='lane-divider'></div>")
209
+ gr.HTML(
210
+ "<div class='lane-meta'>"
211
+ "🎓 <b>Secure Session Activated</b><br>"
212
+ "Operational Node: <code>Simplilearn-Chroma-01</code><br>"
213
+ "Processing Hardware: <code>Base CPU Node</code>"
214
+ "</div>"
215
+ )
216
 
217
+ # Footer Bottom Quick Action Hint Suggestion Buttons
218
+ with gr.Row(style="margin-top: 15px;"):
219
+ refund_btn = gr.Button("What is the course refund policy?", elem_classes="suggestion-btn")
220
+ cert_btn = gr.Button("How do I unlock my completion certificate?", elem_classes="suggestion-btn")
221
+
222
+ # 5. Core Operational Bindings & App Wiring
223
+ # Trigger submission via Send Button click
224
+ send_button.click(
225
+ fn=respond,
226
+ inputs=[msg_input, chatbot],
227
+ outputs=[msg_input, chatbot]
 
 
 
 
 
 
 
 
 
 
228
  )
229
+
230
+ # Trigger submission via Enter keyboard key
231
+ msg_input.submit(
232
+ fn=respond,
233
+ inputs=[msg_input, chatbot],
234
+ outputs=[msg_input, chatbot]
235
  )
236
 
237
+ # Map Quick Action Footer Buttons directly to execution
238
+ refund_btn.click(
239
+ fn=lambda history: respond("What is the course refund policy?", history),
240
+ inputs=[chatbot],
241
+ outputs=[msg_input, chatbot]
242
  )
243
+
244
+ cert_btn.click(
245
+ fn=lambda history: respond("How do I unlock my completion certificate?", history),
246
+ inputs=[chatbot],
247
+ outputs=[msg_input, chatbot]
248
  )
249
 
250
+ # 6. Initialize Deployment Launch
251
  if __name__ == "__main__":
252
+ demo.launch()