Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from langchain_groq import ChatGroq
|
| 5 |
+
from langchain.embeddings import HuggingFaceBgeEmbeddings
|
| 6 |
+
from langchain.vectorstores import Chroma
|
| 7 |
+
from langchain.chains import RetrievalQA
|
| 8 |
+
from langchain.prompts import PromptTemplate
|
| 9 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 10 |
+
from langchain.document_loaders import PyPDFLoader, DirectoryLoader
|
| 11 |
+
from transformers import pipeline
|
| 12 |
+
import traceback
|
| 13 |
+
|
| 14 |
+
# Load psychiatrist details from JSON file
|
| 15 |
+
def load_psychiatrists_data():
|
| 16 |
+
try:
|
| 17 |
+
json_path = "psychiatrists_data.json" # Adjusted for local use
|
| 18 |
+
with open(json_path, "r", encoding="utf-8") as file:
|
| 19 |
+
data = json.load(file)
|
| 20 |
+
return {key.strip().lower(): value for key, value in data.get("India", {}).items()}
|
| 21 |
+
except FileNotFoundError:
|
| 22 |
+
print("❌ Error: psychiatrists_data.json file not found.")
|
| 23 |
+
return {}
|
| 24 |
+
|
| 25 |
+
doc_data = load_psychiatrists_data()
|
| 26 |
+
|
| 27 |
+
# Initialize sentiment analysis model
|
| 28 |
+
sentiment_classifier = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
|
| 29 |
+
|
| 30 |
+
# Initialize LLM
|
| 31 |
+
def initialize_llm():
|
| 32 |
+
return ChatGroq(
|
| 33 |
+
temperature=0,
|
| 34 |
+
groq_api_key=os.getenv("GROQ_API_KEY"), # Use environment variable for security
|
| 35 |
+
model_name="llama-3.3-70b-versatile"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# Create or Load ChromaDB
|
| 39 |
+
def create_vector_db():
|
| 40 |
+
db_path = "./chroma_db"
|
| 41 |
+
|
| 42 |
+
if os.path.exists(db_path):
|
| 43 |
+
embeddings = HuggingFaceBgeEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 44 |
+
return Chroma(persist_directory=db_path, embedding_function=embeddings)
|
| 45 |
+
|
| 46 |
+
print("📄 Creating new ChromaDB...")
|
| 47 |
+
loader = DirectoryLoader("./data", glob="*.pdf", loader_cls=PyPDFLoader) # Adjusted path
|
| 48 |
+
documents = loader.load()
|
| 49 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
|
| 50 |
+
texts = text_splitter.split_documents(documents)
|
| 51 |
+
embeddings = HuggingFaceBgeEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 52 |
+
vector_db = Chroma.from_documents(texts, embeddings, persist_directory=db_path)
|
| 53 |
+
vector_db.persist()
|
| 54 |
+
return vector_db
|
| 55 |
+
|
| 56 |
+
# Setup QA Chain
|
| 57 |
+
def setup_qa_chain(vector_db, llm):
|
| 58 |
+
retriever = vector_db.as_retriever()
|
| 59 |
+
prompt_template = """You are a compassionate mental health chatbot. Respond thoughtfully to the following question:
|
| 60 |
+
{context}
|
| 61 |
+
User: {question}
|
| 62 |
+
Chatbot: """
|
| 63 |
+
|
| 64 |
+
PROMPT = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
|
| 65 |
+
|
| 66 |
+
return RetrievalQA.from_chain_type(
|
| 67 |
+
llm=llm,
|
| 68 |
+
chain_type="stuff",
|
| 69 |
+
retriever=retriever,
|
| 70 |
+
chain_type_kwargs={"prompt": PROMPT}
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
# Initialize LLM and QA Chain before using them
|
| 74 |
+
llm = initialize_llm()
|
| 75 |
+
vector_db = create_vector_db()
|
| 76 |
+
qa_chain = setup_qa_chain(vector_db, llm)
|
| 77 |
+
|
| 78 |
+
# Detect Serious Issues using Transformer Model
|
| 79 |
+
def detect_serious_issue(user_message):
|
| 80 |
+
result = sentiment_classifier(user_message)[0]
|
| 81 |
+
negative_sentiment = result["label"] == "NEGATIVE" and result["score"] > 0.7
|
| 82 |
+
return negative_sentiment
|
| 83 |
+
|
| 84 |
+
# Fetch Top Psychiatrists Based on Location
|
| 85 |
+
def get_psychiatrists_by_location(state):
|
| 86 |
+
state = state.strip().lower()
|
| 87 |
+
return doc_data.get(state, [])
|
| 88 |
+
|
| 89 |
+
def chatbot_interface(user_message, country, state):
|
| 90 |
+
try:
|
| 91 |
+
if user_message.lower() == "exit":
|
| 92 |
+
return "Chatbot: Take care of yourself. Goodbye! ❤️"
|
| 93 |
+
|
| 94 |
+
# Generate chatbot response
|
| 95 |
+
response = qa_chain.run(user_message)
|
| 96 |
+
|
| 97 |
+
# Check for serious issues
|
| 98 |
+
if detect_serious_issue(user_message):
|
| 99 |
+
if country.lower() == "india":
|
| 100 |
+
doctors = get_psychiatrists_by_location(state.lower())
|
| 101 |
+
if doctors:
|
| 102 |
+
doc_info = "\n".join([f"🏥 {doc['name']}\n📍 {doc['hospital']}\n📞 {doc['specialization']}" for doc in doctors])
|
| 103 |
+
return f"Chatbot: {response}\n\n🔹 Here are some psychiatrists in {state}:\n{doc_info}"
|
| 104 |
+
else:
|
| 105 |
+
return f"Chatbot: {response}\n\n⚠️ Sorry, no specific doctors found for {state}. Please visit a nearby hospital."
|
| 106 |
+
else:
|
| 107 |
+
return f"Chatbot: {response}\n\n⚠️ Currently, psychiatrist details are only available for India."
|
| 108 |
+
|
| 109 |
+
return f"Chatbot: {response}"
|
| 110 |
+
|
| 111 |
+
except Exception as e:
|
| 112 |
+
error_message = traceback.format_exc()
|
| 113 |
+
print("❌ ERROR DETECTED:\n", error_message)
|
| 114 |
+
return f"⚠️ Error in chatbot: {str(e)}"
|
| 115 |
+
|
| 116 |
+
gr.Interface(
|
| 117 |
+
fn=chatbot_interface,
|
| 118 |
+
inputs=[
|
| 119 |
+
gr.Textbox(label="Enter your message"),
|
| 120 |
+
gr.Dropdown(["India", "Other"], label="Country"),
|
| 121 |
+
gr.Textbox(label="State (if in India)")
|
| 122 |
+
],
|
| 123 |
+
outputs=gr.Textbox(label="Output"),
|
| 124 |
+
theme="soft"
|
| 125 |
+
).launch()
|