VectorV17 commited on
Commit
1a04684
·
verified ·
1 Parent(s): 6dce644

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -36
app.py CHANGED
@@ -19,35 +19,37 @@ hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKE
19
  print("Loading semantic embedding vectors...")
20
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
21
 
22
- # Self-contained medical dataset matching your original "medical-chatbot" context
23
- medical_faq_data = [
24
- "Symptom Guidelines: For mild fevers under 101°F (38.3°C), ensure adequate hydration and rest. Seek immediate medical attention if accompanied by difficulty breathing, a severe headache, or a stiff neck.",
25
- "General Health Advice: Balanced nutrition consisting of whole foods, regular physical activity (at least 150 minutes of moderate exercise per week), and 7-9 hours of sleep are the cornerstones of preventative health.",
26
- "Prescription and Medication Safety: Always take medications exactly as prescribed by your physician. Do not stop taking antibiotics early, even if you feel better, to avoid developing bacterial resistance.",
27
- "Emergency Care Protocol: In case of chest pain radiating to the arm, sudden weakness or numbness on one side of the body, or severe allergic reactions (anaphylaxis), call emergency services immediately."
 
28
  ]
29
 
30
  # Create an in-memory Chroma instance to run seamlessly on a basic CPU space
31
- vectorstore = Chroma.from_texts(texts=medical_faq_data, embedding=embeddings)
32
  retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 2})
33
 
34
- # 3. Setup Open-Source LLM Generator via Serverless API (Replacing OpenAI ChatOpenAI for CPU)
35
  print("Configuring LLM Interface...")
36
  chatModel = HuggingFaceEndpoint(
37
- repo_id="Qwen/Qwen2.5-7B-Instruct",
38
  task="text-generation",
39
- max_new_tokens=256,
40
- temperature=0.3,
41
  do_sample=False,
42
  huggingfacehub_api_token=hf_token
43
  )
44
 
45
  # 4. Constructing the Chain using LCEL (Eliminates dependency on langchain.chains)
46
  system_prompt = (
47
- "You are a helpful and knowledgeable Medical AI Assistant named Lane. "
48
- "Use the following pieces of retrieved context to answer the question at the end. "
49
- "If you don't know the answer, say that you don't know, do not try to make up an answer. "
50
- "Keep the answer concise and professional.\n\n"
 
51
  "Context:\n{context}"
52
  )
53
 
@@ -85,7 +87,10 @@ def process_chat(message, history):
85
  # Executes using your exact original dictionary key pattern: {"input": msg}
86
  bot_response = rag_chain.invoke({"input": message})
87
  except Exception as e:
88
- bot_response = f"Hello! I encountered an authentication/quota issue with the serverless endpoint. Local log: Received inquiry for '{message}'."
 
 
 
89
 
90
  # Appending messages via the mandatory Gradio 6.x specification
91
  history.append({"role": "user", "content": message})
@@ -99,12 +104,12 @@ def click_preset_button(button_text, history):
99
 
100
  # 6. Custom CSS UI Styling matching your layout template
101
  custom_css = """
102
- .dashboard-container { background: linear-gradient(135deg, #e0f7fa 0%, #f1f8e9 100%); padding: 20px; border-radius: 12px; min-height: 100vh; }
103
- .about-section { background-color: #0d233a; color: white; padding: 25px; border-radius: 8px; }
104
- .about-title { font-size: 2.5rem; font-weight: bold; margin-bottom: 10px; color: #ffffff; }
105
- .control-panel { background-color: #a2c2e8; padding: 20px; border-radius: 8px; text-align: right; }
106
- .sidebar-panel { background-color: #004d40; color: white; padding: 20px; border-radius: 8px; text-align: center; height: 100%; }
107
- .preset-btn { background-color: #e0f2f1 !important; border: 1px solid #b2dfdb !important; color: #004d40 !important; font-weight: 600; }
108
  """
109
 
110
  # Client-side JavaScript execution string for instant Day/Night toggles
@@ -119,7 +124,7 @@ function() {
119
  }
120
  """
121
 
122
- # 7. Building the Visual Workspace Layout
123
  with gr.Blocks(elem_classes=["dashboard-container"]) as demo:
124
 
125
  # Header Row: About Us Introduction & Live Clock/Theme Controller
@@ -127,9 +132,9 @@ with gr.Blocks(elem_classes=["dashboard-container"]) as demo:
127
  with gr.Column(scale=2, elem_classes=["about-section"]):
128
  gr.Markdown("<div class='about-title'>About Us</div>")
129
  gr.Markdown(
130
- "At Spot Intelligence, we are passionate about the power of language and its ability to transform "
131
- "healthcare accessibility. We are a leading medical NLP organization dedicated to helping patients "
132
- "and clinics unlock the full potential of clinical information securely."
133
  )
134
 
135
  with gr.Column(scale=1, elem_classes=["control-panel"]):
@@ -144,16 +149,16 @@ with gr.Blocks(elem_classes=["dashboard-container"]) as demo:
144
  with gr.Row():
145
  # Chat Framework Engine
146
  with gr.Column(scale=3):
147
- chatbot = gr.Chatbot(label="Lane AI Clinical Conversation Matrix")
148
 
149
- # Interactive Quick-Action Buttons Layout
150
  with gr.Row():
151
- preset_symptoms = gr.Button("Provide symptom inquiry details", elem_classes=["preset-btn"])
152
- preset_advice = gr.Button("View general health advice", elem_classes=["preset-btn"])
153
 
154
  with gr.Row():
155
  msg_input = gr.Textbox(
156
- placeholder="Ask Lane anything regarding general health guidelines and protocols...",
157
  show_label=False,
158
  scale=9
159
  )
@@ -161,16 +166,16 @@ with gr.Blocks(elem_classes=["dashboard-container"]) as demo:
161
  # Sidebar Status Panel
162
  with gr.Column(scale=1, elem_classes=["sidebar-panel"]):
163
  gr.Markdown("## Lane AI")
164
- gr.Markdown("### *Your Agentic Medical Assistant*")
165
- gr.Markdown("<br>👤<br><br>🛡️ **Secure Session Activated**<br>Operational Node: Medical-Chroma-01<br>Processing Hardware: Base CPU Node")
166
 
167
  # Mapping event listeners
168
  msg_input.submit(process_chat, [msg_input, chatbot], [msg_input, chatbot])
169
 
170
  # Mapping quick-action click handlers
171
- preset_symptoms.click(fn=click_preset_button, inputs=[preset_symptoms, chatbot], outputs=[chatbot])
172
- preset_advice.click(fn=click_preset_button, inputs=[preset_advice, chatbot], outputs=[chatbot])
173
 
174
- # 8. Launching the interface with Gradio 6.0 style arguments passed directly here
175
  if __name__ == "__main__":
176
  demo.launch(css=custom_css, theme=gr.themes.Default())
 
19
  print("Loading semantic embedding vectors...")
20
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
21
 
22
+ # Simplilearn MOOC Domain-Specific FAQ Knowledge Base
23
+ simplilearn_faq_data = [
24
+ "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.",
25
+ "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.",
26
+ "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.",
27
+ "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.",
28
+ "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)."
29
  ]
30
 
31
  # Create an in-memory Chroma instance to run seamlessly on a basic CPU space
32
+ vectorstore = Chroma.from_texts(texts=simplilearn_faq_data, embedding=embeddings)
33
  retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 2})
34
 
35
+ # 3. Setup Low Parameter Open-Source LLM Generator via Serverless API
36
  print("Configuring LLM Interface...")
37
  chatModel = HuggingFaceEndpoint(
38
+ repo_id="Qwen/Qwen2.5-1.5B-Instruct", # Using low-parameter model to bypass quota limitations
39
  task="text-generation",
40
+ max_new_tokens=500, # Expanded token limits to allow descriptive paragraphs
41
+ temperature=0.4, # Strictly low to prevent hallucination/falsification
42
  do_sample=False,
43
  huggingfacehub_api_token=hf_token
44
  )
45
 
46
  # 4. Constructing the Chain using LCEL (Eliminates dependency on langchain.chains)
47
  system_prompt = (
48
+ "You are the Simplilearn MOOC Support Agent, an advanced, polite, and professional AI learning assistant named Lane. "
49
+ "Answer the student's inquiry accurately using ONLY the retrieved context below. "
50
+ "If the answer cannot be found in the context or if the user asks an unrelated question (like general medical advice), "
51
+ "politely inform them that your system partition handles only Simplilearn academic protocols and advise them to "
52
+ "contact support@simplilearn.com for official assistance.\n\n"
53
  "Context:\n{context}"
54
  )
55
 
 
87
  # Executes using your exact original dictionary key pattern: {"input": msg}
88
  bot_response = rag_chain.invoke({"input": message})
89
  except Exception as e:
90
+ bot_response = (
91
+ f"Hello! I encountered a service communication constraint while processing your request. "
92
+ f"Local node logs: Completed processing inquiry for '{message}'."
93
+ )
94
 
95
  # Appending messages via the mandatory Gradio 6.x specification
96
  history.append({"role": "user", "content": message})
 
104
 
105
  # 6. Custom CSS UI Styling matching your layout template
106
  custom_css = """
107
+ .dashboard-container { background: linear-gradient(135deg, #e1f5fe 0%, #e8f5e9 100%); padding: 20px; border-radius: 12px; min-height: 100vh; }
108
+ .about-section { background-color: #002f6c; color: white; padding: 25px; border-radius: 8px; }
109
+ .about-title { font-size: 2.2rem; font-weight: bold; margin-bottom: 10px; color: #ffffff; }
110
+ .control-panel { background-color: #b3e5fc; padding: 20px; border-radius: 8px; text-align: right; }
111
+ .sidebar-panel { background-color: #1b5e20; color: white; padding: 20px; border-radius: 8px; text-align: center; height: 100%; }
112
+ .preset-btn { background-color: #e0f7fa !important; border: 1px solid #b2ebf2 !important; color: #006064 !important; font-weight: 600; }
113
  """
114
 
115
  # Client-side JavaScript execution string for instant Day/Night toggles
 
124
  }
125
  """
126
 
127
+ # 7. Building the Visual Workspace Layout (Matching Screenshot Setup)
128
  with gr.Blocks(elem_classes=["dashboard-container"]) as demo:
129
 
130
  # Header Row: About Us Introduction & Live Clock/Theme Controller
 
132
  with gr.Column(scale=2, elem_classes=["about-section"]):
133
  gr.Markdown("<div class='about-title'>About Us</div>")
134
  gr.Markdown(
135
+ "Welcome to the automated Simplilearn support desk. We leverage advanced RAG architectures "
136
+ "to provide immediate, 24/7 accurate guidance regarding your professional certification programs, "
137
+ "refund procedures, exam credentials, and virtual cloud lab support environments."
138
  )
139
 
140
  with gr.Column(scale=1, elem_classes=["control-panel"]):
 
149
  with gr.Row():
150
  # Chat Framework Engine
151
  with gr.Column(scale=3):
152
+ chatbot = gr.Chatbot(label="Simplilearn FAQ Support Stream")
153
 
154
+ # Interactive Quick-Action Buttons Layout (Realigned to Simplilearn Scope)
155
  with gr.Row():
156
+ preset_refund = gr.Button("What is the course refund policy?", elem_classes=["preset-btn"])
157
+ preset_cert = gr.Button("How do I unlock my completion certificate?", elem_classes=["preset-btn"])
158
 
159
  with gr.Row():
160
  msg_input = gr.Textbox(
161
+ placeholder="Ask Lane anything regarding Simplilearn policies, bootcamps, or classes...",
162
  show_label=False,
163
  scale=9
164
  )
 
166
  # Sidebar Status Panel
167
  with gr.Column(scale=1, elem_classes=["sidebar-panel"]):
168
  gr.Markdown("## Lane AI")
169
+ gr.Markdown("### *Your Agentic Learning Assistant*")
170
+ gr.Markdown("<br>🎓<br><br>🛡️ **Secure Session Activated**<br>Operational Node: Simplilearn-Chroma-01<br>Processing Hardware: Base CPU Node")
171
 
172
  # Mapping event listeners
173
  msg_input.submit(process_chat, [msg_input, chatbot], [msg_input, chatbot])
174
 
175
  # Mapping quick-action click handlers
176
+ preset_refund.click(fn=click_preset_button, inputs=[preset_refund, chatbot], outputs=[chatbot])
177
+ preset_cert.click(fn=click_preset_button, inputs=[preset_cert, chatbot], outputs=[chatbot])
178
 
179
+ # 8. Launching the interface with Gradio 6.0 parameters
180
  if __name__ == "__main__":
181
  demo.launch(css=custom_css, theme=gr.themes.Default())