Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,207 +1,176 @@
|
|
| 1 |
import os
|
| 2 |
import datetime
|
| 3 |
-
|
| 4 |
import gradio as gr
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
|
|
|
|
|
|
|
| 8 |
from langchain_huggingface import HuggingFaceEmbeddings, HuggingFaceEndpoint
|
| 9 |
-
from langchain_core.prompts import
|
| 10 |
from langchain_core.runnables import RunnablePassthrough
|
| 11 |
from langchain_core.output_parsers import StrOutputParser
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
|
| 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 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
metadatas=metadatas,
|
| 51 |
-
ids=ids
|
| 52 |
-
)
|
| 53 |
-
retriever = vector_store.as_retriever(search_kwargs={"k": 2})
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
| 58 |
max_new_tokens=256,
|
| 59 |
-
|
|
|
|
|
|
|
| 60 |
)
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
Helpful Answer:"""
|
| 72 |
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
|
|
|
| 75 |
def format_docs(docs):
|
| 76 |
return "\n\n".join(doc.page_content for doc in docs)
|
| 77 |
|
|
|
|
| 78 |
rag_chain = (
|
| 79 |
-
{
|
| 80 |
-
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
| 82 |
| StrOutputParser()
|
| 83 |
)
|
| 84 |
|
| 85 |
-
# -
|
| 86 |
-
|
| 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 |
-
#
|
| 102 |
-
|
| 103 |
except Exception as e:
|
| 104 |
-
|
| 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 |
-
#
|
|
|
|
|
|
|
| 111 |
return "", history
|
| 112 |
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
| 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 |
-
.
|
| 123 |
-
.
|
| 124 |
-
.
|
| 125 |
-
.
|
| 126 |
-
.sidebar-panel { background-color: #004d40
|
| 127 |
-
.
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
-
#
|
| 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=
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
| 154 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
|
|
|
| 156 |
with gr.Row():
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
scale=5
|
| 161 |
-
)
|
| 162 |
-
submit_btn = gr.Button("Send", variant="primary", scale=1)
|
| 163 |
-
|
| 164 |
with gr.Row():
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 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 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 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(
|
|
|
|
| 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())
|