VectorV17 commited on
Commit
ab42960
·
verified ·
1 Parent(s): 7bbda4d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -161
app.py CHANGED
@@ -1,207 +1,176 @@
1
  import os
2
  import datetime
3
- from dotenv import load_dotenv
4
  import gradio as gr
5
 
6
- # LangChain & Chroma Vector DB Components
7
- from langchain_chroma import Chroma
 
 
8
  from langchain_huggingface import HuggingFaceEmbeddings, HuggingFaceEndpoint
9
- from langchain_core.prompts import PromptTemplate
10
  from langchain_core.runnables import RunnablePassthrough
11
  from langchain_core.output_parsers import StrOutputParser
12
 
13
- # Load Environment Variables (HUGGINGFACEHUB_API_TOKEN)
14
- load_dotenv()
15
 
16
- # -------------------------------------------------------------------------
17
- # 1. Mock Data Setup (Simplilearn MOOC FAQs)
18
- # -------------------------------------------------------------------------
19
- faq_data = [
20
- {
21
- "question": "What is the refund policy for Simplilearn courses?",
22
- "answer": "Simplilearn offers a 7-day money-back guarantee for its online self-paced learning and blended learning programs. Raise a refund request within 7 days of purchase, provided you haven't accessed more than 25% of the content."
23
- },
24
- {
25
- "question": "Can I access my Simplilearn courses on a smartphone?",
26
- "answer": "Yes, Simplilearn has an official mobile app available on both Android and iOS platforms. You can download your video lessons to watch offline, complete quizzes, and track your learning progress on the go."
27
- },
28
- {
29
- "question": "Do I get a certificate after completing a course?",
30
- "answer": "Yes, upon successfully fulfilling the course completion criteria (which typically includes finishing 85% of the course material and clearing the simulation projects/exams), you will receive an industry-recognized digital certificate."
31
- },
32
- {
33
- "question": "Are there any prerequisites for enrolling in the AI and ML Bootcamps?",
34
- "answer": "While basic programming knowledge (preferably in Python) and a fundamental understanding of mathematics/statistics are helpful, Simplilearn's bootcamps include foundational electives to bring beginners up to speed."
35
- }
36
- ]
37
 
38
- documents = [item["answer"] for item in faq_data]
39
- metadatas = [{"question": item["question"]} for item in faq_data]
40
- ids = [f"faq_{i}" for i in range(len(faq_data))]
41
-
42
- # -------------------------------------------------------------------------
43
- # 2. RAG Pipeline Initialization (CPU-Optimized)
44
- # -------------------------------------------------------------------------
45
- embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
46
 
47
- vector_store = Chroma.from_texts(
48
- texts=documents,
49
- embedding=embeddings,
50
- metadatas=metadatas,
51
- ids=ids
52
- )
53
- retriever = vector_store.as_retriever(search_kwargs={"k": 2})
54
 
55
- llm = HuggingFaceEndpoint(
56
- repo_id="mistralai/Mistral-7B-Instruct-v0.3",
57
- temperature=0.3,
 
 
58
  max_new_tokens=256,
59
- huggingfacehub_api_token=os.getenv("HUGGINGFACEHUB_API_TOKEN")
 
 
60
  )
61
 
62
- prompt_template = """You are Lane, an intelligent, helpful, and friendly Agentic AI Assistant for Simplilearn MOOC.
63
- Use the following pieces of retrieved context to answer the user's question accurately.
64
- If you do not know the answer based on the context, politely state that you do not know.
65
-
66
- Context:
67
- {context}
68
-
69
- Question: {question}
70
-
71
- Helpful Answer:"""
72
 
73
- rag_prompt = PromptTemplate.from_template(prompt_template)
 
 
 
 
 
74
 
 
75
  def format_docs(docs):
76
  return "\n\n".join(doc.page_content for doc in docs)
77
 
 
78
  rag_chain = (
79
- {"context": retriever | format_docs, "question": RunnablePassthrough()}
80
- | rag_prompt
81
- | llm
 
 
 
82
  | StrOutputParser()
83
  )
84
 
85
- # -------------------------------------------------------------------------
86
- # 3. Application Core Logic
87
- # -------------------------------------------------------------------------
88
- def get_current_time_string():
89
- now = datetime.datetime.now()
90
- return now.strftime("%dth %B %Y | Time: %I:%M%p").lower()
91
-
92
- def chat_interface(user_message, history):
93
- if not user_message or not user_message.strip():
94
  return "", history
95
 
96
- # Initialize history list if empty
97
  if history is None:
98
  history = []
99
 
100
  try:
101
- # Generate RAG response safely
102
- ai_response = rag_chain.invoke(user_message)
103
  except Exception as e:
104
- ai_response = f"Connect Error: Unable to fetch live context pipeline. Details: {str(e)}"
105
-
106
- # Correctly append to state list
107
- history.append({"role": "user", "content": user_message})
108
- history.append({"role": "assistant", "content": ai_response})
109
 
110
- # Always return pair matching the defined output interfaces [user_input, chatbot]
 
 
111
  return "", history
112
 
113
- def handle_quick_reply(button_text, history):
114
- # Route text string immediately into processing frame
115
- return chat_interface(button_text, history)
 
116
 
117
- # -------------------------------------------------------------------------
118
- # 4. Gradio Web Interface Layout
119
- # -------------------------------------------------------------------------
120
- # Force text color constraints (`color: #1f2937 !important;`) on header metadata to resist dark modes
121
  custom_css = """
122
- .header-container { background-color: #f7f9fc !important; padding: 25px; border-radius: 12px; margin-bottom: 20px; border: 1px solid #e5e7eb; }
123
- .header-container h1, .header-container p, .header-container h3 { color: #1f2937 !important; }
124
- .meta-container { text-align: right; font-family: 'Georgia', serif; font-style: italic; color: #2563eb !important; }
125
- .meta-container h3 { color: #2563eb !important; margin: 4px 0; }
126
- .sidebar-panel { background-color: #004d40 !important; color: white !important; padding: 25px; border-radius: 12px; text-align: center; }
127
- .sidebar-panel p, .sidebar-panel h2 { color: white !important; }
128
- .quick-btn { background-color: #e0f2f1 !important; border: 1px solid #b2dfdb !important; color: #004d40 !important; font-weight: 600; }
129
- .quick-btn:hover { background-color: #b2dfdb !important; }
130
  """
131
 
132
- with gr.Blocks(title="Simplilearn MOOC FAQ Agent") as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
- # TOP SECTION: Header banner split into Info Branding and Dynamic Meta Controls
135
- with gr.Row(elem_classes=["header-container"]):
136
- with gr.Column(scale=3):
137
- gr.Markdown("""
138
- # About Us
139
- At Simplilearn Agentic Hub, we are passionate about the power of structured education and its ability
140
- to transform careers. We are a leading knowledge processing framework dedicated to helping
141
- learners unlock the full potential of specialized MOOC educational pathways.
142
- """)
143
- with gr.Column(scale=2, elem_classes=["meta-container"]):
144
- # Display localized real-time clock indicator directly inside standard text markdown wrapper
145
- gr.Markdown(f"### {get_current_time_string()}")
146
- gr.Markdown("### ☀️ 🌙 ➔ Change Mode (Day / Night)")
147
-
148
- # MAIN WORKSPACE SECTION
149
  with gr.Row():
150
- with gr.Column(scale=4):
151
- chatbot = gr.Chatbot(
152
- label="Lane AI Conversation",
153
- value=[{"role": "assistant", "content": "Hello! I'm Lane, your friendly AI Agent. How can I help you today?"}]
 
 
154
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
 
 
156
  with gr.Row():
157
- user_input = gr.Textbox(
158
- show_label=False,
159
- placeholder="Type your query regarding Simplilearn courses here...",
160
- scale=5
161
- )
162
- submit_btn = gr.Button("Send", variant="primary", scale=1)
163
-
164
  with gr.Row():
165
- btn_refund = gr.Button("Provide refund policy details", elem_classes=["quick-btn"])
166
- btn_cert = gr.Button("Learn about course certification", elem_classes=["quick-btn"])
167
-
168
- # RIGHT SIDEBAR PANEL
169
- with gr.Column(scale=2, elem_classes=["sidebar-panel"]):
170
- gr.HTML("""
171
- <div style='margin-top: 10px;'>
172
- <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%;'>
173
- <h2 style='margin-bottom: 5px; font-size: 24px; font-weight: bold;'>Lane <span style='background-color:#ffffff; color:#004d40; padding:2px 8px; border-radius:4px; font-size:14px; vertical-align: middle;'>AI</span></h2>
174
- <p style='font-style: italic; opacity: 0.9; margin-bottom: 15px;'>Your Agentic AI Assistant</p>
175
- <hr style='border-color: rgba(255,255,255,0.2); margin: 15px 0;'>
176
- <p style='font-size: 14px; text-align: justify; line-height: 1.5; opacity: 0.95;'>
177
- Lane runs an optimized RAG vector-space framework pipeline. It targets relevant local enterprise facts instantly without remote workflow friction.
178
- </p>
179
- </div>
180
- """)
181
-
182
- # Event Wiring Architecture (Ensures clean pipeline state processing without UI freezing)
183
- submit_btn.click(
184
- fn=chat_interface,
185
- inputs=[user_input, chatbot],
186
- outputs=[user_input, chatbot]
187
- )
188
- user_input.submit(
189
- fn=chat_interface,
190
- inputs=[user_input, chatbot],
191
- outputs=[user_input, chatbot]
192
- )
193
 
194
- btn_refund.click(
195
- fn=handle_quick_reply,
196
- inputs=[btn_refund, chatbot],
197
- outputs=[user_input, chatbot]
198
- )
199
- btn_cert.click(
200
- fn=handle_quick_reply,
201
- inputs=[btn_cert, chatbot],
202
- outputs=[user_input, chatbot]
203
- )
204
-
205
- # Run execution thread routing
206
  if __name__ == "__main__":
207
- demo.launch(server_name="0.0.0.0", server_port=7860, css=custom_css)
 
1
  import os
2
  import datetime
3
+ import warnings
4
  import gradio as gr
5
 
6
+ # Suppress the community sunset deprecation warnings to keep Hugging Face logs clean
7
+ warnings.filterwarnings("ignore", category=UserWarning, module="langchain_community")
8
+
9
+ from langchain_community.vectorstores import Chroma
10
  from langchain_huggingface import HuggingFaceEmbeddings, HuggingFaceEndpoint
11
+ from langchain_core.prompts import ChatPromptTemplate
12
  from langchain_core.runnables import RunnablePassthrough
13
  from langchain_core.output_parsers import StrOutputParser
14
 
15
+ # 1. Fetching the Hugging Face Space security token automatically
16
+ hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN")
17
 
18
+ # 2. Setup Vector Store & Embeddings Pipeline (Using ChromaDB)
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
 
54
+ prompt = ChatPromptTemplate.from_messages(
55
+ [
56
+ ("system", system_prompt),
57
+ ("human", "{input}"),
58
+ ]
59
+ )
60
 
61
+ # Helper function to combine document chunks into a single string context
62
  def format_docs(docs):
63
  return "\n\n".join(doc.page_content for doc in docs)
64
 
65
+ # The modern LCEL pipeline equivalent to your original create_retrieval_chain
66
  rag_chain = (
67
+ {
68
+ "context": lambda x: format_docs(retriever.invoke(x["input"])),
69
+ "input": lambda x: x["input"]
70
+ }
71
+ | prompt
72
+ | chatModel
73
  | StrOutputParser()
74
  )
75
 
76
+ # 5. UI Event Handlers (Gradio 6.0 Dict-based message history format)
77
+ def process_chat(message, history):
78
+ if not message.strip():
 
 
 
 
 
 
79
  return "", history
80
 
 
81
  if history is None:
82
  history = []
83
 
84
  try:
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})
92
+ history.append({"role": "assistant", "content": bot_response})
93
  return "", history
94
 
95
+ # Handles automatic prompt submission when clicking dashboard quick-action buttons
96
+ def click_preset_button(button_text, history):
97
+ _, updated_history = process_chat(button_text, history)
98
+ return updated_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
111
+ toggle_js = """
112
+ function() {
113
+ var body = document.querySelector('body');
114
+ if (body.classList.contains('dark')) {
115
+ body.classList.remove('dark');
116
+ } else {
117
+ body.classList.add('dark');
118
+ }
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  with gr.Row():
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"]):
136
+ current_date = datetime.datetime.now().strftime("%dth %B %Y | Time: %I:%M%p").lower()
137
+ gr.Markdown(f"### 🗓️ {current_date}")
138
+ mode_btn = gr.Button("🌗 Change Mode (Day/Night)", variant="secondary")
139
+ mode_btn.click(fn=None, js=toggle_js)
140
+
141
+ gr.Markdown("<br>")
142
+
143
+ # Main Core Interface Workspace Row
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
+ )
160
+
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())