Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,57 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
-
import datetime
|
| 3 |
-
import warnings
|
| 4 |
-
import gradio as gr
|
| 5 |
|
| 6 |
-
|
| 7 |
-
warnings.filterwarnings("ignore", category=UserWarning, module="langchain_community")
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
#
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
embeddings =
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 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
|
| 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 Open-Source LLM via Hugging Face's OpenAI-Compatible API
|
| 36 |
-
print("Configuring LLM Interface...")
|
| 37 |
-
chatModel = ChatOpenAI(
|
| 38 |
-
model="Qwen/Qwen2.5-1.5B-Instruct",
|
| 39 |
-
# FIX: Pointing the URL directly to the model's dedicated instance to prevent connection drops
|
| 40 |
-
base_url="https://api-inference.huggingface.co/models/Qwen/Qwen2.5-1.5B-Instruct/v1/",
|
| 41 |
-
api_key=hf_token,
|
| 42 |
-
max_tokens=500,
|
| 43 |
-
temperature=0.3,
|
| 44 |
-
max_retries=2 # Adds a safety net if the connection flickers
|
| 45 |
)
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
)
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
prompt = ChatPromptTemplate.from_messages(
|
| 56 |
[
|
| 57 |
("system", system_prompt),
|
|
@@ -59,113 +56,31 @@ prompt = ChatPromptTemplate.from_messages(
|
|
| 59 |
]
|
| 60 |
)
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
"input": lambda x: x["input"]
|
| 70 |
-
}
|
| 71 |
-
| prompt
|
| 72 |
-
| chatModel
|
| 73 |
-
| StrOutputParser()
|
| 74 |
-
)
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
| 80 |
|
| 81 |
-
if history is None:
|
| 82 |
-
history = []
|
| 83 |
-
|
| 84 |
try:
|
| 85 |
-
#
|
| 86 |
-
|
|
|
|
|
|
|
| 87 |
|
| 88 |
except Exception as e:
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
f"`{str(e)}`\n\n"
|
| 93 |
-
f"**Note:** If the free inference API is 'waking up' the model, it can take about 30 seconds. Please try clicking the button again!"
|
| 94 |
-
)
|
| 95 |
-
|
| 96 |
-
# Appending messages via Gradio 6.x specification
|
| 97 |
-
history.append({"role": "user", "content": message})
|
| 98 |
-
history.append({"role": "assistant", "content": bot_response})
|
| 99 |
-
return "", history
|
| 100 |
-
|
| 101 |
-
def click_preset_button(button_text, history):
|
| 102 |
-
_, updated_history = process_chat(button_text, history)
|
| 103 |
-
return updated_history
|
| 104 |
-
|
| 105 |
-
# 6. Custom CSS UI Styling
|
| 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 |
-
toggle_js = """
|
| 116 |
-
function() {
|
| 117 |
-
var body = document.querySelector('body');
|
| 118 |
-
if (body.classList.contains('dark')) {
|
| 119 |
-
body.classList.remove('dark');
|
| 120 |
-
} else {
|
| 121 |
-
body.classList.add('dark');
|
| 122 |
-
}
|
| 123 |
-
}
|
| 124 |
-
"""
|
| 125 |
-
|
| 126 |
-
# 7. Building the Visual Workspace Layout
|
| 127 |
-
with gr.Blocks(elem_classes=["dashboard-container"]) as demo:
|
| 128 |
-
|
| 129 |
-
with gr.Row():
|
| 130 |
-
with gr.Column(scale=2, elem_classes=["about-section"]):
|
| 131 |
-
gr.Markdown("<div class='about-title'>About Us</div>")
|
| 132 |
-
gr.Markdown(
|
| 133 |
-
"Welcome to the automated Simplilearn support desk. We leverage advanced RAG architectures "
|
| 134 |
-
"to provide immediate, 24/7 accurate guidance regarding your professional certification programs, "
|
| 135 |
-
"refund procedures, exam credentials, and virtual cloud lab support environments."
|
| 136 |
-
)
|
| 137 |
-
|
| 138 |
-
with gr.Column(scale=1, elem_classes=["control-panel"]):
|
| 139 |
-
current_date = datetime.datetime.now().strftime("%dth %B %Y | Time: %I:%M%p").lower()
|
| 140 |
-
gr.Markdown(f"### 🗓️ {current_date}")
|
| 141 |
-
mode_btn = gr.Button("🌗 Change Mode (Day/Night)", variant="secondary")
|
| 142 |
-
mode_btn.click(fn=None, js=toggle_js)
|
| 143 |
-
|
| 144 |
-
gr.Markdown("<br>")
|
| 145 |
-
|
| 146 |
-
with gr.Row():
|
| 147 |
-
with gr.Column(scale=3):
|
| 148 |
-
chatbot = gr.Chatbot(label="Simplilearn FAQ Support Stream")
|
| 149 |
-
|
| 150 |
-
with gr.Row():
|
| 151 |
-
preset_refund = gr.Button("What is the course refund policy?", elem_classes=["preset-btn"])
|
| 152 |
-
preset_cert = gr.Button("How do I unlock my completion certificate?", elem_classes=["preset-btn"])
|
| 153 |
-
|
| 154 |
-
with gr.Row():
|
| 155 |
-
msg_input = gr.Textbox(
|
| 156 |
-
placeholder="Ask Lane anything regarding Simplilearn policies, bootcamps, or classes...",
|
| 157 |
-
show_label=False,
|
| 158 |
-
scale=9
|
| 159 |
-
)
|
| 160 |
-
|
| 161 |
-
with gr.Column(scale=1, elem_classes=["sidebar-panel"]):
|
| 162 |
-
gr.Markdown("## Lane AI")
|
| 163 |
-
gr.Markdown("### *Your Agentic Learning Assistant*")
|
| 164 |
-
gr.Markdown("<br>🎓<br><br>🛡️ **Secure Session Activated**<br>Operational Node: Simplilearn-Chroma-01<br>Processing Hardware: Base CPU Node")
|
| 165 |
|
| 166 |
-
msg_input.submit(process_chat, [msg_input, chatbot], [msg_input, chatbot])
|
| 167 |
-
preset_refund.click(fn=click_preset_button, inputs=[preset_refund, chatbot], outputs=[chatbot])
|
| 168 |
-
preset_cert.click(fn=click_preset_button, inputs=[preset_cert, chatbot], outputs=[chatbot])
|
| 169 |
|
| 170 |
-
if __name__ ==
|
| 171 |
-
|
|
|
|
| 1 |
+
from flask import Flask, render_template, jsonify, request
|
| 2 |
+
from src.helper import download_hugging_face_embeddings
|
| 3 |
+
from langchain_pinecone import PineconeVectorStore
|
| 4 |
+
# Native Hugging Face Chat Model imports
|
| 5 |
+
from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
|
| 6 |
+
from langchain.chains import create_retrieval_chain
|
| 7 |
+
from langchain.chains.combine_documents import create_stuff_documents_chain
|
| 8 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
from src.prompt import *
|
| 11 |
import os
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
app = Flask(__name__)
|
|
|
|
| 14 |
|
| 15 |
+
load_dotenv()
|
| 16 |
+
|
| 17 |
+
# Fetching environment credentials
|
| 18 |
+
PINECONE_API_KEY = os.environ.get('PINECONE_API_KEY')
|
| 19 |
+
HF_TOKEN = os.environ.get('HF_TOKEN') or os.environ.get('HUGGINGFACEHUB_API_TOKEN')
|
| 20 |
+
|
| 21 |
+
# Ensuring keys are accessible in the environment mapping
|
| 22 |
+
os.environ["PINECONE_API_KEY"] = PINECONE_API_KEY
|
| 23 |
+
os.environ["HUGGINGFACEHUB_API_TOKEN"] = HF_TOKEN
|
| 24 |
+
|
| 25 |
+
# 1. Initialize Embeddings and Vector Store
|
| 26 |
+
embeddings = download_hugging_face_embeddings()
|
| 27 |
+
|
| 28 |
+
index_name = "medical-chatbot"
|
| 29 |
+
docsearch = PineconeVectorStore.from_existing_index(
|
| 30 |
+
index_name=index_name,
|
| 31 |
+
embedding=embeddings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
)
|
| 33 |
|
| 34 |
+
retriever = docsearch.as_retriever(search_type="similarity", search_kwargs={"k": 3})
|
| 35 |
+
|
| 36 |
+
# 2. Configure Native Hugging Face LLM Client
|
| 37 |
+
# Setting task="conversational" satisfies the backend requirements perfectly.
|
| 38 |
+
print("Initializing Hugging Face conversational endpoint...")
|
| 39 |
+
llm = HuggingFaceEndpoint(
|
| 40 |
+
repo_id="Qwen/Qwen2.5-1.5B-Instruct",
|
| 41 |
+
task="conversational",
|
| 42 |
+
huggingfacehub_api_token=HF_TOKEN,
|
| 43 |
+
max_new_tokens=500,
|
| 44 |
+
temperature=0.3,
|
| 45 |
+
timeout=300 # Generous 5-minute timeout window to prevent connection cuts during server spin-ups
|
| 46 |
)
|
| 47 |
|
| 48 |
+
# Wrap the endpoint into a Chat Model interface to accept ChatPromptTemplates
|
| 49 |
+
chatModel = ChatHuggingFace(llm=llm)
|
| 50 |
+
|
| 51 |
+
# 3. Create the Prompt and RAG Chain
|
| 52 |
prompt = ChatPromptTemplate.from_messages(
|
| 53 |
[
|
| 54 |
("system", system_prompt),
|
|
|
|
| 56 |
]
|
| 57 |
)
|
| 58 |
|
| 59 |
+
question_answer_chain = create_stuff_documents_chain(chatModel, prompt)
|
| 60 |
+
rag_chain = create_retrieval_chain(retriever, question_answer_chain)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@app.route("/")
|
| 64 |
+
def index():
|
| 65 |
+
return render_template('chat.html')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
+
|
| 68 |
+
@app.route("/get", methods=["GET", "POST"])
|
| 69 |
+
def chat():
|
| 70 |
+
msg = request.form["msg"]
|
| 71 |
+
print(f"User Message: {msg}")
|
| 72 |
|
|
|
|
|
|
|
|
|
|
| 73 |
try:
|
| 74 |
+
# Invoke the complete RAG pipeline
|
| 75 |
+
response = rag_chain.invoke({"input": msg})
|
| 76 |
+
print("Response : ", response["answer"])
|
| 77 |
+
return str(response["answer"])
|
| 78 |
|
| 79 |
except Exception as e:
|
| 80 |
+
print(f"Execution Error: {str(e)}")
|
| 81 |
+
# Graceful UI response to catch any temporary server overloads
|
| 82 |
+
return "⚠️ The Hugging Face serverless hub is currently busy or spinning up the model instance. Please submit your message once more."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
+
if __name__ == '__main__':
|
| 86 |
+
app.run(host="0.0.0.0", port=8080, debug=True)
|