DINESHDAS commited on
Commit
97b2c00
·
verified ·
1 Parent(s): 41e18c7

Upload 2 files

Browse files
Files changed (2) hide show
  1. app (1).py +146 -0
  2. psychiatrists_data.json +142 -0
app (1).py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"),
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
+ # Ensure default values if inputs are None
92
+ user_message = user_message or "" # Default empty string if None
93
+ country = country or "Other" # Default to "Other"
94
+ state = state or "" # Default empty string
95
+
96
+ if user_message.lower() == "exit":
97
+ return "Chatbot: Take care of yourself. Goodbye! ❤️"
98
+
99
+ # Generate chatbot response
100
+ response = qa_chain.run(user_message)
101
+
102
+ # Check for serious issues
103
+ if detect_serious_issue(user_message):
104
+ if country.lower() == "india":
105
+ doctors = get_psychiatrists_by_location(state)
106
+ if doctors:
107
+ doc_info = "\n".join([f"🏥 {doc['name']}\n📍 {doc['hospital']}\n🧠 {doc['specialization']}\n" for doc in doctors])
108
+ return f"Chatbot: {response}\n\n🔹 Your mental health is important. If you're struggling, please don't hesitate to seek help. Here are some top psychiatrists in {state} who can assist you:\n{doc_info}"
109
+ else:
110
+ return f"Chatbot: {response}\n\n⚠️ Sorry, no specific doctors found for {state}. Please visit a nearby hospital."
111
+ else:
112
+ return f"Chatbot: {response}\n\n⚠️ Currently, psychiatrist details are only available for India."
113
+
114
+ return f"Chatbot: {response}"
115
+
116
+ except Exception as e:
117
+ error_message = traceback.format_exc()
118
+ print("❌ ERROR DETECTED:\n", error_message)
119
+ return f"⚠️ Error in chatbot: {str(e)}"
120
+
121
+
122
+ custom_css = """
123
+ body {
124
+ background-color: #1e1e1e; /* Dark Grey */
125
+ color: white;
126
+ font-size: 18px;
127
+ }
128
+ h1 {
129
+ text-align: center;
130
+ color: #FFD700; /* Gold */
131
+ }
132
+ """
133
+
134
+ gr.Interface(
135
+ fn=chatbot_interface,
136
+ inputs=[
137
+ gr.Textbox(label="Enter your message"),
138
+ gr.Textbox(label="Country"),
139
+ gr.Textbox(label="State (if in India)")
140
+ ],
141
+ outputs=gr.Textbox(label="Output"),
142
+ title="Welcome to AI-Powered Chatbot Created by Sandeep",
143
+ theme="dark",
144
+ css=custom_css
145
+ ).launch(share=True)
146
+
psychiatrists_data.json ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "India": {
3
+ "Odisha": [
4
+ {
5
+ "name": "Dr. Pranab Kumar Dalai",
6
+ "city": "Bhubaneswar",
7
+ "hospital": "AIMS Bhubaneswar",
8
+ "contact": "+91 94370 12345",
9
+ "specialization": "Psychiatry, Depression, Anxiety"
10
+ },
11
+ {
12
+ "name": "Dr. Suchitra Panda",
13
+ "city": "Cuttack",
14
+ "hospital": "SCB Medical College",
15
+ "contact": "+91 98765 43210",
16
+ "specialization": "Mental Health, Schizophrenia"
17
+ },
18
+ {
19
+ "name": "Dr. Subhankar Mishra",
20
+ "city": "Sambalpur",
21
+ "hospital": "VIMSAR",
22
+ "contact": "+91 78945 67890",
23
+ "specialization": "Bipolar Disorder, Mood Disorders"
24
+ }
25
+ ],
26
+ "Delhi": [
27
+ {
28
+ "name": "Dr. Samir Parikh",
29
+ "city": "New Delhi",
30
+ "hospital": "Fortis Hospital",
31
+ "contact": "+91 99999 88888",
32
+ "specialization": "Depression, Anxiety, OCD"
33
+ },
34
+ {
35
+ "name": "Dr. Rajesh Sagar",
36
+ "city": "New Delhi",
37
+ "hospital": "AIIMS Delhi",
38
+ "contact": "+91 88888 77777",
39
+ "specialization": "Schizophrenia, PTSD"
40
+ },
41
+ {
42
+ "name": "Dr. Arvind Kumar",
43
+ "city": "New Delhi",
44
+ "hospital": "Max Healthcare",
45
+ "contact": "+91 77777 66666",
46
+ "specialization": "Child Psychiatry, ADHD"
47
+ }
48
+ ],
49
+ "Maharashtra": [
50
+ {
51
+ "name": "Dr. Harish Shetty",
52
+ "city": "Mumbai",
53
+ "hospital": "Dr. L H Hiranandani Hospital",
54
+ "contact": "+91 98765 43211",
55
+ "specialization": "Depression, Bipolar Disorder"
56
+ },
57
+ {
58
+ "name": "Dr. Avinash Desousa",
59
+ "city": "Mumbai",
60
+ "hospital": "Sion Hospital",
61
+ "contact": "+91 87654 32110",
62
+ "specialization": "Schizophrenia, Psychotherapy"
63
+ },
64
+ {
65
+ "name": "Dr. Yusuf Matcheswalla",
66
+ "city": "Mumbai",
67
+ "hospital": "Masina Hospital",
68
+ "contact": "+91 76543 21099",
69
+ "specialization": "Addiction, Mood Disorders"
70
+ }
71
+ ],
72
+ "Karnataka": [
73
+ {
74
+ "name": "Dr. B. N. Gangadhar",
75
+ "city": "Bangalore",
76
+ "hospital": "NIMHANS",
77
+ "contact": "+91 65432 10987",
78
+ "specialization": "Neuropsychiatry, Depression"
79
+ },
80
+ {
81
+ "name": "Dr. Prabha Chandra",
82
+ "city": "Bangalore",
83
+ "hospital": "Apollo Hospitals",
84
+ "contact": "+91 54321 09876",
85
+ "specialization": "Women's Mental Health, Anxiety"
86
+ },
87
+ {
88
+ "name": "Dr. Shyam Sundar",
89
+ "city": "Mysore",
90
+ "hospital": "JSS Hospital",
91
+ "contact": "+91 43210 98765",
92
+ "specialization": "PTSD, Schizophrenia"
93
+ }
94
+ ],
95
+ "Tamil Nadu": [
96
+ {
97
+ "name": "Dr. Thara Rangaswamy",
98
+ "city": "Chennai",
99
+ "hospital": "SCARF India",
100
+ "contact": "+91 32109 87654",
101
+ "specialization": "Schizophrenia, Bipolar Disorder"
102
+ },
103
+ {
104
+ "name": "Dr. Lakshmi Vijayakumar",
105
+ "city": "Chennai",
106
+ "hospital": "SNEHI Foundation",
107
+ "contact": "+91 21098 76543",
108
+ "specialization": "Suicide Prevention, Depression"
109
+ },
110
+ {
111
+ "name": "Dr. Ramesh Kumar",
112
+ "city": "Coimbatore",
113
+ "hospital": "PSG Hospitals",
114
+ "contact": "+91 10987 65432",
115
+ "specialization": "Addiction Psychiatry, Anxiety"
116
+ }
117
+ ],
118
+ "West Bengal": [
119
+ {
120
+ "name": "Dr. Kalyan B. Saha",
121
+ "city": "Kolkata",
122
+ "hospital": "Apollo Gleneagles",
123
+ "contact": "+91 87654 32109",
124
+ "specialization": "Child Psychiatry, ADHD"
125
+ },
126
+ {
127
+ "name": "Dr. Alok Das",
128
+ "city": "Kolkata",
129
+ "hospital": "CMRI Hospital",
130
+ "contact": "+91 76543 21098",
131
+ "specialization": "Geriatric Psychiatry, Dementia"
132
+ },
133
+ {
134
+ "name": "Dr. Partha Pratim",
135
+ "city": "Durgapur",
136
+ "hospital": "The Mission Hospital",
137
+ "contact": "+91 65432 10987",
138
+ "specialization": "Depression, Anxiety"
139
+ }
140
+ ]
141
+ }
142
+ }