YoniFriedman commited on
Commit
3f6a465
·
verified ·
1 Parent(s): e99586b

updating app.py

Browse files
Files changed (1) hide show
  1. app.py +139 -181
app.py CHANGED
@@ -1,222 +1,180 @@
 
 
 
 
1
  import os
2
- os.environ["OPENAI_API_KEY"]
3
-
4
- from llama_index.llms.openai import OpenAI
5
- from llama_index.core.schema import MetadataMode
6
- import openai
7
- from openai import OpenAI as OpenAIOG
8
  import logging
9
  import sys
10
- llm = OpenAI(temperature=0.0, model="gpt-3.5-turbo")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  client = OpenAIOG()
12
 
13
- from langdetect import detect
14
- from langdetect import DetectorFactory
15
  DetectorFactory.seed = 0
16
- from deep_translator import GoogleTranslator
17
- from lingua import Language, LanguageDetectorBuilder
18
 
19
- # Load index
20
- from llama_index.core import VectorStoreIndex
21
- from llama_index.core import StorageContext
22
- from llama_index.core import load_index_from_storage
23
  storage_context = StorageContext.from_defaults(persist_dir="arv_metadata")
24
  index = load_index_from_storage(storage_context)
25
- query_engine = index.as_query_engine(similarity_top_k=3, llm=llm)
26
- retriever = index.as_retriever(similarity_top_k = 3)
27
-
28
- import gradio as gr
29
 
30
- import re
31
- import json
32
- from datetime import datetime
33
-
34
- acknowledgment_keywords_sw = ["sawa", "ndiyo", "naam", "hakika", "asante", "nimeelewa", "nimekupata", "ni kweli",
35
- "kwa hakika", "nimesikia"]
36
  acknowledgment_keywords_en = ["thanks", "thank you", "thx", "ok", "okay", "great", "got it", "appreciate", "good", "makes sense"]
37
- follow_up_keywords = ["but", "also", "and", "what", "how", "why", "when", "is", "?",
38
- "lakini", "pia", "na", "nini", "vipi", "kwanini", "wakati"]
39
  greeting_keywords_sw = ["sasa", "niaje", "habari", "mambo", "jambo", "shikamoo", "marahaba", "hujambo", "hamjambo", "salama", "vipi"]
40
  greeting_keywords_en = ["hi", "hello", "hey", "how's it", "what's up", "yo", "howdy"]
 
 
41
 
42
  def contains_exact_word_or_phrase(text, keywords):
 
43
  text = text.lower()
44
- for keyword in keywords:
45
- if re.search(r'\b' + re.escape(keyword) + r'\b', text):
46
- return True
47
- return False
48
 
49
- def contains_greeting_sw(question):
50
- # Check if the question contains acknowledgment keywords
51
- return contains_exact_word_or_phrase(question, greeting_keywords_sw)
52
 
53
- def contains_greeting_en(question):
54
- # Check if the question contains acknowledgment keywords
55
- return contains_exact_word_or_phrase(question, greeting_keywords_en)
56
 
57
- def contains_acknowledgment_sw(question):
58
- # Check if the question contains acknowledgment keywords
59
- return contains_exact_word_or_phrase(question, acknowledgment_keywords_sw)
60
 
61
- def contains_acknowledgment_en(question):
62
- # Check if the question contains acknowledgment keywords
63
- return contains_exact_word_or_phrase(question, acknowledgment_keywords_en)
64
 
65
- def contains_follow_up(question):
66
- # Check if the question contains follow-up indicators
67
- return contains_exact_word_or_phrase(question, follow_up_keywords)
68
 
69
  def convert_to_date(date_str):
70
- return datetime.strptime(date_str, "%Y%m%d")
71
-
72
- def detect_language(question):
73
- # Check if the text has less than 5 words
74
- if len(question.split()) < 5:
75
- languages = [Language.ENGLISH, Language.SWAHILI] # Add more languages as needed
 
 
 
 
76
  detector = LanguageDetectorBuilder.from_languages(*languages).build()
77
- detected_language = detector.detect_language_of(question)
78
- # Return language code for consistency
79
- if detected_language == Language.SWAHILI:
80
- return "sw"
81
- elif detected_language == Language.ENGLISH:
82
- return "en"
83
- else:
84
- try:
85
- lang_detect = detect(question)
86
- return lang_detect
87
- except Exception as e:
88
- print(f"Error with langdetect: {e}")
89
- return "unknown"
90
-
91
- def nishauri(question: str, conversation_history: list[str]):
92
-
93
- # Get conversation history
94
- context = " ".join([item["user"] + " " + item["chatbot"] for item in conversation_history])
95
-
96
- ## Process greeting
97
- # greet_response = process_greeting_response(question)
98
- if contains_greeting_en(question) and not contains_follow_up(question):
99
- greeting = (
100
- f" The user previously asked and answered the following: {context}. "
101
- f" The user just provided the following greeting: {question}. "
102
- "Please respond accordingly in English."
103
- )
104
- completion = client.chat.completions.create(
105
- model="gpt-4o",
106
- messages=[
107
- {"role": "user", "content": greeting}
108
- ]
109
- )
110
- reply_to_user = completion.choices[0].message.content
111
- conversation_history.append({"user": question, "chatbot": reply_to_user})
112
- return reply_to_user, conversation_history
113
-
114
- if contains_greeting_sw(question) and not contains_follow_up(question):
115
- greeting = (
116
- f" The user previously asked and answered the following: {context}. "
117
- f" The user just provided the following greeting: {question}. "
118
- "Please respond accordingly in Swahili."
119
- )
120
- completion = client.chat.completions.create(
121
- model="gpt-4o",
122
- messages=[
123
- {"role": "user", "content": greeting}
124
- ]
125
- )
126
- reply_to_user = completion.choices[0].message.content
127
- conversation_history.append({"user": question, "chatbot": reply_to_user})
128
- return reply_to_user, conversation_history
129
 
130
- ## Process acknowledgment
131
- if contains_acknowledgment_en(question) and not contains_follow_up(question):
132
- acknowledgment = (
133
- f" The user previously asked and answered the following: {context}. "
134
- f" The user just provided the following acknowledgement: {question}. "
135
- "Please respond accordingly in English."
136
- )
137
- completion = client.chat.completions.create(
138
- model="gpt-4o",
139
- messages=[
140
- {"role": "user", "content": acknowledgment}
141
- ]
142
- )
143
- reply_to_user = completion.choices[0].message.content
144
- conversation_history.append({"user": question, "chatbot": reply_to_user})
145
- return reply_to_user, conversation_history
146
-
147
- if contains_acknowledgment_sw(question) and not contains_follow_up(question):
148
- acknowledgment = (
149
- f" The user previously asked and answered the following: {context}. "
150
- f" The user just provided the following acknowledgment: {question}. "
151
- "Please respond accordingly in Swahili."
152
- )
153
- completion = client.chat.completions.create(
154
- model="gpt-4o",
155
- messages=[
156
- {"role": "user", "content": acknowledgment}
157
- ]
158
- )
159
- reply_to_user = completion.choices[0].message.content
160
- conversation_history.append({"user": question, "chatbot": reply_to_user})
161
- return reply_to_user, conversation_history
162
-
163
- ## If not greeting or acknowledgement, then proceed with RAG
164
-
165
- ## Detect language of question - if Swahili, translate to English
166
  lang_question = detect_language(question)
167
- if lang_question=="sw":
168
  question = GoogleTranslator(source='sw', target='en').translate(question)
169
-
170
- # Now, retrieve relevant sources
171
  sources = retriever.retrieve(question)
172
- source0 = sources[0].text
173
- source1 = sources[1].text
174
- source2 = sources[2].text
175
-
176
- background = ("The person who asked the question is a person living with HIV."
177
- " They are asking questions about HIV. Do not talk about anything that is not related to HIV. "
178
- " Recognize that they already have HIV and do not suggest that they have to get tested"
179
- " for HIV or take post-exposure prophylaxis, as that is not relevant, though their partners perhaps should."
180
- " Do not suggest anything that is not relevant to someone who already has HIV."
181
- " Do not mention in the response that the person is living with HIV."
182
- " The following information about viral loads is authoritative for any question about viral loads:"
183
- # " Under 50 copies/ml is low detectable level,"
184
- # " 50 - 199 copies/ml is low level viremia, 200 - 999 is high level viremia, and "
185
- # " 1000 and above is suspected treatment failure."
186
- " A high viral load or non-suppressed viral load is any viral load above 200 copies/ml."
187
- " A viral load above 1000 copies/ml suggests treatment failure."
188
- " A suppressed viral load is one below 200 copies / ml.")
189
 
 
190
  question_final = (
191
- f" The user previously asked and answered the following: {context}. "
192
- f" The user just asked the following question: {question}."
193
- f" Please use the following content to generate a response: {source0} {source1} {source2}."
194
- f" Please consider the following background information when generating a response: {background}."
195
- " Keep answers brief and limited to the question that was asked."
196
- " If they share a greeting, just greet them in return and ask if they have a question."
197
- " Do not change the subject or address anything the user didn't directly ask about."
198
- " If they respond with an acknowledgement, simply thank them."
199
- " Do not discuss anything other than HIV. If they ask a question that is not about HIV, respond that"
200
- " you are only able to discuss HIV."
201
- " Keep the response to under 50 words and use simple language. The person asking the question does not know technical terms."
202
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  completion = client.chat.completions.create(
205
- model="gpt-4o",
206
- messages=[
207
- {"role": "user", "content": question_final}
208
- ]
209
  )
210
 
 
211
  reply_to_user = completion.choices[0].message.content
212
-
 
 
 
 
213
  if lang_question=="sw":
214
- reply_to_user = GoogleTranslator(source='auto', target='sw').translate(reply_to_user)
215
-
216
- conversation_history.append({"user": question, "chatbot": reply_to_user})
217
 
218
- return reply_to_user, conversation_history
 
219
 
 
220
  demo = gr.Interface(
221
  title = "Nishauri Chatbot Demo",
222
  fn=nishauri,
@@ -224,4 +182,4 @@ demo = gr.Interface(
224
  outputs=["text", gr.State()],
225
  )
226
 
227
- demo.launch()
 
1
+ #%% md
2
+ # ## Nuru HIV Informational Chatbot
3
+ #%%
4
+ # Import libraries
5
  import os
6
+ from dotenv import load_dotenv
 
 
 
 
 
7
  import logging
8
  import sys
9
+ import re
10
+ import json
11
+ from datetime import datetime
12
+ from langdetect import detect, DetectorFactory
13
+ from deep_translator import GoogleTranslator
14
+ from lingua import Language, LanguageDetectorBuilder
15
+ import gradio as gr
16
+ from openai import OpenAI as OpenAIOG
17
+ from llama_index.llms.openai import OpenAI
18
+ from llama_index.core import VectorStoreIndex, StorageContext, load_index_from_storage
19
+ from deep_translator import GoogleTranslator
20
+
21
+ # Set OpenAI API Key (Ensure this is set in the environment)
22
+ # load_dotenv("config.env")
23
+ os.environ.get("OPENAI_API_KEY")
24
+
25
+ # Initialize OpenAI clients
26
+ llm = OpenAI(temperature=0.0, model="gpt-4o")
27
  client = OpenAIOG()
28
 
29
+ # Set seed for language detection consistency
 
30
  DetectorFactory.seed = 0
 
 
31
 
32
+ # Load index for retrieval
 
 
 
33
  storage_context = StorageContext.from_defaults(persist_dir="arv_metadata")
34
  index = load_index_from_storage(storage_context)
35
+ retriever = index.as_retriever(similarity_top_k=3)
 
 
 
36
 
37
+ # Define keyword lists
38
+ acknowledgment_keywords_sw = ["sawa", "ndiyo", "naam", "hakika", "asante", "nimeelewa", "nimekupata", "ni kweli", "kwa hakika", "nimesikia", "ahsante"]
 
 
 
 
39
  acknowledgment_keywords_en = ["thanks", "thank you", "thx", "ok", "okay", "great", "got it", "appreciate", "good", "makes sense"]
40
+ follow_up_keywords = ["but", "also", "and", "what", "how", "why", "when", "is", "?", "lakini", "pia", "na", "nini", "vipi", "kwanini", "wakati"]
 
41
  greeting_keywords_sw = ["sasa", "niaje", "habari", "mambo", "jambo", "shikamoo", "marahaba", "hujambo", "hamjambo", "salama", "vipi"]
42
  greeting_keywords_en = ["hi", "hello", "hey", "how's it", "what's up", "yo", "howdy"]
43
+ #%%
44
+ # Define helper functions
45
 
46
  def contains_exact_word_or_phrase(text, keywords):
47
+ """Check if the given text contains any exact keyword from the list."""
48
  text = text.lower()
49
+ return any(re.search(r'\b' + re.escape(keyword) + r'\b', text) for keyword in keywords)
 
 
 
50
 
51
+ def contains_greeting_sw(text):
52
+ return contains_exact_word_or_phrase(text, greeting_keywords_sw)
 
53
 
54
+ def contains_greeting_en(text):
55
+ return contains_exact_word_or_phrase(text, greeting_keywords_en)
 
56
 
57
+ def contains_acknowledgment_sw(text):
58
+ return contains_exact_word_or_phrase(text, acknowledgment_keywords_sw)
 
59
 
60
+ def contains_acknowledgment_en(text):
61
+ return contains_exact_word_or_phrase(text, acknowledgment_keywords_en)
 
62
 
63
+ def contains_follow_up(text):
64
+ return contains_exact_word_or_phrase(text, follow_up_keywords)
 
65
 
66
  def convert_to_date(date_str):
67
+ """Convert date string in YYYYMMDD format to YYYY-MM-DD."""
68
+ try:
69
+ return datetime.strptime(date_str, "%Y%m%d").strftime("%Y-%m-%d")
70
+ except ValueError:
71
+ return "Unknown Date"
72
+
73
+ def detect_language(text):
74
+ """Detect language of a given text using Lingua for short texts and langdetect for longer ones."""
75
+ if len(text.split()) < 5:
76
+ languages = [Language.ENGLISH, Language.SWAHILI]
77
  detector = LanguageDetectorBuilder.from_languages(*languages).build()
78
+ detected_language = detector.detect_language_of(text)
79
+ return "sw" if detected_language == Language.SWAHILI else "en"
80
+ try:
81
+ return detect(text)
82
+ except Exception as e:
83
+ logging.warning(f"Language detection error: {e}")
84
+ return "unknown"
85
+ #%%
86
+ # Define Gradio function
87
+ def nishauri(user_params: str, conversation_history: list[str]):
88
+
89
+ """Process user query, detect language, handle greetings, acknowledgments, and retrieve relevant information."""
90
+ context = " ".join([item["user"] + " " + item["chatbot"] for item in conversation_history])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
+ # Process greetings and acknowledgments
93
+ for lang, contains_greeting, contains_acknowledgment in [("en", contains_greeting_en, contains_acknowledgment_en), ("sw", contains_greeting_sw, contains_acknowledgment_sw)]:
94
+ if contains_greeting(question) and not contains_follow_up(question):
95
+ prompt = f"The user said: {question}. Respond accordingly in {lang}."
96
+ elif contains_acknowledgment(question) and not contains_follow_up(question):
97
+ prompt = f"The user acknowledged: {question}. Respond accordingly in {lang}."
98
+ else:
99
+ continue
100
+ completion = client.chat.completions.create(
101
+ model="gpt-4o",
102
+ messages=[{"role": "user", "content": prompt}]
103
+ )
104
+ reply_to_user = completion.choices[0].message.content
105
+ conversation_history.append({"user": question, "chatbot": reply_to_user})
106
+ return reply_to_user, conversation_history
107
+
108
+ # Detect language and translate if needed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  lang_question = detect_language(question)
110
+ if lang_question == "sw":
111
  question = GoogleTranslator(source='sw', target='en').translate(question)
112
+
113
+ # Retrieve relevant sources
114
  sources = retriever.retrieve(question)
115
+ retrieved_text = "\n\n".join([f"Source {i+1}: {source.text}" for i, source in enumerate(sources[:3])])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
+ # Combine into new user question - conversation history, new question, retrieved sources
118
  question_final = (
119
+ f"The user asked the following question: \"{question}\"\n\n"
120
+ f"Use only the content below to answer the question:\n\n{retrieved_text}\n\n"
121
+ "Guidelines:\n"
122
+ "- Only answer the question that was asked.\n"
123
+ "- Do not change the subject or include unrelated information.\n"
124
+ "- Only discuss HIV. If the question is not about HIV, say that you can only answer HIV-related questions.\n"
 
 
 
 
 
125
  )
126
+
127
+ # Set LLM instructions. If user consented, add user parameters, otherwise proceed without
128
+ system_prompt = (
129
+ "You are a helpful assistant who only answers questions about HIV.\n"
130
+ "- Do not answer questions about other topics (e.g., malaria or tuberculosis).\n"
131
+ "- If a question is unrelated to HIV, politely respond that you can only answer HIV-related questions.\n\n"
132
+
133
+ "The person asking the question is living with HIV.\n"
134
+ "- Do not suggest they get tested for HIV or take post-exposure prophylaxis (PEP).\n"
135
+ "- You may mention that their partners might benefit from testing or PEP, if relevant.\n"
136
+ "- Do not mention in your response that the person is living with HIV.\n"
137
+ "- Only suggest things relevant to someone who already has HIV.\n\n"
138
+ "- Keep the answer under 50 words.\n"
139
+ "- Use simple, easy-to-understand language. Avoid medical jargon.\n"
140
 
141
+ "Use the following authoritative information about viral loads:\n"
142
+ "- A high or non-suppressed viral load is above 200 copies/ml.\n"
143
+ "- A viral load above 1000 copies/ml suggests treatment failure.\n"
144
+ "- A suppressed viral load is one below 200 copies/ml.\n\n"
145
+ )
146
+
147
+ # Start with context
148
+ messages = [{"role": "system", "content": system_prompt}]
149
+
150
+ # Add conversation history
151
+ for turn in conversation_history:
152
+ messages.append({"role": "user", "content": turn["user"]})
153
+ messages.append({"role": "assistant", "content": turn["chatbot"]})
154
+
155
+ # Finally, add the current question
156
+ messages.append({"role": "user", "content": question_final})
157
+
158
+ # Generate response
159
  completion = client.chat.completions.create(
160
+ model="gpt-4o",
161
+ messages=messages
 
 
162
  )
163
 
164
+ # Collect response
165
  reply_to_user = completion.choices[0].message.content
166
+
167
+ # add question and reply to conversation history
168
+ conversation_history.append({"user": question, "chatbot": reply_to_user})
169
+
170
+ # If initial question was in swahili, translate response to swahili
171
  if lang_question=="sw":
172
+ reply_to_user = GoogleTranslator(source='auto', target='sw').translate(reply_to_user)
 
 
173
 
174
+ # return system_prompt, conversation_history
175
+ return reply_to_user, conversation_history
176
 
177
+ #%%
178
  demo = gr.Interface(
179
  title = "Nishauri Chatbot Demo",
180
  fn=nishauri,
 
182
  outputs=["text", gr.State()],
183
  )
184
 
185
+ demo.launch()