PrathameshRaut commited on
Commit
da3b1af
·
verified ·
1 Parent(s): 5e9c8ca

Update chatbot.py

Browse files
Files changed (1) hide show
  1. chatbot.py +18 -41
chatbot.py CHANGED
@@ -1,7 +1,6 @@
1
  import os
2
  import pandas as pd
3
  import requests
4
- # import PyPDF2 # ❌ PDF no longer needed
5
  from sentence_transformers import SentenceTransformer
6
  from pinecone import Pinecone
7
  from openai import OpenAI
@@ -11,9 +10,6 @@ import re
11
  PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")
12
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
13
 
14
- if not PINECONE_API_KEY or not OPENAI_API_KEY:
15
- raise RuntimeError("❌ API keys not loaded. Check .env file")
16
-
17
  # ================= CONSTANTS =================
18
  SERVICES_INDEX_NAME = "aaple-sarkar-services"
19
  BASICS_INDEX_NAME = "aaplesarkarbasics"
@@ -22,15 +18,14 @@ BASE_DIR = os.path.dirname(__file__)
22
  DATA_DIR = os.path.join(BASE_DIR, "data")
23
 
24
  # ================= INIT =================
25
- pc = Pinecone(api_key=PINECONE_API_KEY)
26
- client = OpenAI(api_key=OPENAI_API_KEY)
27
  embedder = SentenceTransformer("all-MiniLM-L6-v2")
28
 
29
- services_index = pc.Index(SERVICES_INDEX_NAME)
30
- basics_index = pc.Index(BASICS_INDEX_NAME)
31
 
32
  # ================= LOAD DATA =================
33
-
34
  EXCEL_URL = "https://huggingface.co/datasets/PrathameshRaut/aaple-sarkar-data/resolve/main/Untitled%20spreadsheet-2.xlsx"
35
  LOCAL_EXCEL_PATH = os.path.join(DATA_DIR, "services.xlsx")
36
 
@@ -47,26 +42,6 @@ excel_df = pd.read_excel(
47
  sheet_name="Copy of Notified services (1212"
48
  )
49
 
50
-
51
- # ================= PDF REMOVED =================
52
- # PDF knowledge base is already embedded & stored in Pinecone
53
- # Hence no need to load, parse, or pass PDF text again
54
-
55
- # kb_pdf_path = os.path.join(
56
- # DATA_DIR,
57
- # "/Users/prathameshraut/Desktop/Code/updated/backend/data/chatbot_knowledge_base.pdf"
58
- # )
59
-
60
- # def extract_pdf_text(path):
61
- # text = ""
62
- # with open(path, "rb") as f:
63
- # reader = PyPDF2.PdfReader(f)
64
- # for page in reader.pages:
65
- # text += (page.extract_text() or "") + "\n"
66
- # return text
67
-
68
- # kb_text = extract_pdf_text(kb_pdf_path)[:3000]
69
-
70
  # ================= SEARCH =================
71
  def is_small_talk(text: str) -> bool:
72
  text = text.strip().lower()
@@ -74,8 +49,12 @@ def is_small_talk(text: str) -> bool:
74
  r"(hi|hello|hey|hii|hai|namaste|thanks|thank you|ok|okay|yes|no|namaskar|good morning|good afternoon|good evening|good night|how are you?|how are you|how are you.|who are you?|introduce yourself|introduce)",
75
  text
76
  ))
77
-
 
78
  def search_services(query, min_score=0.75):
 
 
 
79
  emb = embedder.encode([query])[0].tolist()
80
  res = services_index.query(
81
  vector=emb,
@@ -88,13 +67,15 @@ def search_services(query, min_score=0.75):
88
 
89
  match = res.matches[0]
90
  if match.score < min_score:
91
- return None # ⛔ STOP RANDOM SERVICE MATCHING
92
 
93
  return match.metadata["text"]
94
 
95
 
96
-
97
  def search_basics(query):
 
 
 
98
  emb = embedder.encode([query])[0].tolist()
99
  res = basics_index.query(
100
  vector=emb,
@@ -122,28 +103,28 @@ def get_service_info(dept, service):
122
  # ================= RESPONSE =================
123
  def generate_response(user_query, language="en"):
124
 
 
 
 
 
125
  # ================= SMALL TALK SHORT-CIRCUIT =================
126
  if is_small_talk(user_query):
127
  prompt = f"""
128
  You are Aaple Sarkar Services Chatbot (Maharashtra Government) named "Aapla Sahayak".
129
-
130
  Rules:
131
  - Respond politely, briefly, and naturally using some 1-2 emojis, also while greeting say Namaskar.
132
  - Respond with RAW, valid, render-ready HTML only.
133
  - Do not use markdown.
134
  - Do not add explanations outside HTML.
135
-
136
  User Query:
137
  {user_query}
138
  """
139
-
140
  response = client.chat.completions.create(
141
  model="gpt-4o-mini",
142
  messages=[{"role": "system", "content": prompt}],
143
  temperature=0.3,
144
  max_tokens=150,
145
  )
146
-
147
  return response.choices[0].message.content
148
 
149
  # ================= RAG PIPELINE =================
@@ -184,17 +165,13 @@ User Query:
184
  # ================= MAIN PROMPT =================
185
  prompt = f"""
186
  You are Aaple Sarkar Services Chatbot (Maharashtra Government).
187
-
188
  Rules:
189
  - Respond with RAW, valid, render-ready HTML only; do not use markdown, do not wrap the response in ``` or ```html, do not add explanations/comments/text outside HTML, do not add leading or trailing whitespace, and ensure the response starts directly with <html> or the first HTML tag.
190
  - If the user message is a generic, short, or social message (such as greetings, acknowledgements, or fillers), you must respond appropriately with a polite, natural, and context-independent reply.
191
-
192
  User Query:
193
  {user_query}
194
-
195
  Available Knowledge:
196
  {context}
197
-
198
  Provide complete guidance including:
199
  - Eligibility
200
  - Documents required
@@ -211,4 +188,4 @@ Provide complete guidance including:
211
  max_tokens=800,
212
  )
213
 
214
- return response.choices[0].message.content
 
1
  import os
2
  import pandas as pd
3
  import requests
 
4
  from sentence_transformers import SentenceTransformer
5
  from pinecone import Pinecone
6
  from openai import OpenAI
 
10
  PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")
11
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
12
 
 
 
 
13
  # ================= CONSTANTS =================
14
  SERVICES_INDEX_NAME = "aaple-sarkar-services"
15
  BASICS_INDEX_NAME = "aaplesarkarbasics"
 
18
  DATA_DIR = os.path.join(BASE_DIR, "data")
19
 
20
  # ================= INIT =================
21
+ pc = Pinecone(api_key=PINECONE_API_KEY) if PINECONE_API_KEY else None
22
+ client = OpenAI(api_key=OPENAI_API_KEY) if OPENAI_API_KEY else None
23
  embedder = SentenceTransformer("all-MiniLM-L6-v2")
24
 
25
+ services_index = pc.Index(SERVICES_INDEX_NAME) if pc else None
26
+ basics_index = pc.Index(BASICS_INDEX_NAME) if pc else None
27
 
28
  # ================= LOAD DATA =================
 
29
  EXCEL_URL = "https://huggingface.co/datasets/PrathameshRaut/aaple-sarkar-data/resolve/main/Untitled%20spreadsheet-2.xlsx"
30
  LOCAL_EXCEL_PATH = os.path.join(DATA_DIR, "services.xlsx")
31
 
 
42
  sheet_name="Copy of Notified services (1212"
43
  )
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  # ================= SEARCH =================
46
  def is_small_talk(text: str) -> bool:
47
  text = text.strip().lower()
 
49
  r"(hi|hello|hey|hii|hai|namaste|thanks|thank you|ok|okay|yes|no|namaskar|good morning|good afternoon|good evening|good night|how are you?|how are you|how are you.|who are you?|introduce yourself|introduce)",
50
  text
51
  ))
52
+
53
+
54
  def search_services(query, min_score=0.75):
55
+ if not services_index:
56
+ return None
57
+
58
  emb = embedder.encode([query])[0].tolist()
59
  res = services_index.query(
60
  vector=emb,
 
67
 
68
  match = res.matches[0]
69
  if match.score < min_score:
70
+ return None
71
 
72
  return match.metadata["text"]
73
 
74
 
 
75
  def search_basics(query):
76
+ if not basics_index:
77
+ return ""
78
+
79
  emb = embedder.encode([query])[0].tolist()
80
  res = basics_index.query(
81
  vector=emb,
 
103
  # ================= RESPONSE =================
104
  def generate_response(user_query, language="en"):
105
 
106
+ # ================= GUARD =================
107
+ if not client or not pc:
108
+ return "<p>❌ Server misconfiguration: API keys are missing. Please contact the administrator.</p>"
109
+
110
  # ================= SMALL TALK SHORT-CIRCUIT =================
111
  if is_small_talk(user_query):
112
  prompt = f"""
113
  You are Aaple Sarkar Services Chatbot (Maharashtra Government) named "Aapla Sahayak".
 
114
  Rules:
115
  - Respond politely, briefly, and naturally using some 1-2 emojis, also while greeting say Namaskar.
116
  - Respond with RAW, valid, render-ready HTML only.
117
  - Do not use markdown.
118
  - Do not add explanations outside HTML.
 
119
  User Query:
120
  {user_query}
121
  """
 
122
  response = client.chat.completions.create(
123
  model="gpt-4o-mini",
124
  messages=[{"role": "system", "content": prompt}],
125
  temperature=0.3,
126
  max_tokens=150,
127
  )
 
128
  return response.choices[0].message.content
129
 
130
  # ================= RAG PIPELINE =================
 
165
  # ================= MAIN PROMPT =================
166
  prompt = f"""
167
  You are Aaple Sarkar Services Chatbot (Maharashtra Government).
 
168
  Rules:
169
  - Respond with RAW, valid, render-ready HTML only; do not use markdown, do not wrap the response in ``` or ```html, do not add explanations/comments/text outside HTML, do not add leading or trailing whitespace, and ensure the response starts directly with <html> or the first HTML tag.
170
  - If the user message is a generic, short, or social message (such as greetings, acknowledgements, or fillers), you must respond appropriately with a polite, natural, and context-independent reply.
 
171
  User Query:
172
  {user_query}
 
173
  Available Knowledge:
174
  {context}
 
175
  Provide complete guidance including:
176
  - Eligibility
177
  - Documents required
 
188
  max_tokens=800,
189
  )
190
 
191
+ return response.choices[0].message.content