JDFPalladium commited on
Commit ·
1f6fbde
1
Parent(s): 67a5126
initial commit
Browse files- .gitignore +3 -0
- Makefile +3 -0
- app.py +225 -0
- requirements.txt +6 -0
.gitignore
CHANGED
|
@@ -172,3 +172,6 @@ cython_debug/
|
|
| 172 |
|
| 173 |
# PyPI configuration file
|
| 174 |
.pypirc
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
# PyPI configuration file
|
| 174 |
.pypirc
|
| 175 |
+
|
| 176 |
+
# Large Files
|
| 177 |
+
arv_metadata/
|
Makefile
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
install:
|
| 2 |
+
pip install --upgrade pip &&\
|
| 3 |
+
pip install -r requirements.txt
|
app.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#%% md
|
| 2 |
+
# ## Nuru HIV Informational Chatbot
|
| 3 |
+
#%%
|
| 4 |
+
# Import libraries
|
| 5 |
+
import os
|
| 6 |
+
import logging
|
| 7 |
+
import re
|
| 8 |
+
from langdetect import detect
|
| 9 |
+
from lingua import Language, LanguageDetectorBuilder
|
| 10 |
+
import gradio as gr
|
| 11 |
+
from openai import OpenAI as OpenAIOG
|
| 12 |
+
from llama_index.llms.openai import OpenAI
|
| 13 |
+
from llama_index.core import StorageContext, load_index_from_storage
|
| 14 |
+
from deep_translator import GoogleTranslator
|
| 15 |
+
from dotenv import load_dotenv
|
| 16 |
+
|
| 17 |
+
# Load environment variables from .env file
|
| 18 |
+
load_dotenv()
|
| 19 |
+
|
| 20 |
+
# Set OpenAI API Key (Ensure this is set in the environment)
|
| 21 |
+
# load_dotenv("config.env")
|
| 22 |
+
os.environ.get("OPENAI_API_KEY")
|
| 23 |
+
|
| 24 |
+
# Initialize OpenAI clients
|
| 25 |
+
llm = OpenAI(temperature=0.0, model="gpt-4o")
|
| 26 |
+
client = OpenAIOG()
|
| 27 |
+
|
| 28 |
+
# Load index for retrieval
|
| 29 |
+
storage_context = StorageContext.from_defaults(persist_dir="arv_metadata")
|
| 30 |
+
index = load_index_from_storage(storage_context)
|
| 31 |
+
retriever = index.as_retriever(similarity_top_k=5)
|
| 32 |
+
|
| 33 |
+
# Define keyword lists
|
| 34 |
+
acknowledgment_keywords_sw = ["sawa", "ndiyo", "naam", "hakika", "asante", "nimeelewa", "nimekupata", "ni kweli", "kwa hakika", "nimesikia", "ahsante"]
|
| 35 |
+
acknowledgment_keywords_en = ["thanks", "thank you", "thx", "ok", "okay", "great", "got it", "appreciate", "good", "makes sense"]
|
| 36 |
+
follow_up_keywords = ["but", "also", "and", "what", "how", "why", "when", "is", "?", "lakini", "pia", "na", "nini", "vipi", "kwanini", "wakati"]
|
| 37 |
+
greeting_keywords_sw = ["sasa", "niaje", "habari", "mambo", "jambo", "shikamoo", "marahaba", "hujambo", "hamjambo", "salama", "vipi"]
|
| 38 |
+
greeting_keywords_en = ["hi", "hello", "hey", "how's it", "what's up", "yo", "howdy"]
|
| 39 |
+
#%%
|
| 40 |
+
# Define helper functions
|
| 41 |
+
|
| 42 |
+
def contains_exact_word_or_phrase(text, keywords):
|
| 43 |
+
"""Check if the given text contains any exact keyword from the list."""
|
| 44 |
+
text = text.lower()
|
| 45 |
+
return any(re.search(r'\b' + re.escape(keyword) + r'\b', text) for keyword in keywords)
|
| 46 |
+
|
| 47 |
+
def contains_greeting_sw(text):
|
| 48 |
+
return contains_exact_word_or_phrase(text, greeting_keywords_sw)
|
| 49 |
+
|
| 50 |
+
def contains_greeting_en(text):
|
| 51 |
+
return contains_exact_word_or_phrase(text, greeting_keywords_en)
|
| 52 |
+
|
| 53 |
+
def contains_acknowledgment_sw(text):
|
| 54 |
+
return contains_exact_word_or_phrase(text, acknowledgment_keywords_sw)
|
| 55 |
+
|
| 56 |
+
def contains_acknowledgment_en(text):
|
| 57 |
+
return contains_exact_word_or_phrase(text, acknowledgment_keywords_en)
|
| 58 |
+
|
| 59 |
+
def contains_follow_up(text):
|
| 60 |
+
return contains_exact_word_or_phrase(text, follow_up_keywords)
|
| 61 |
+
|
| 62 |
+
def detect_language(text):
|
| 63 |
+
"""Detect language of a given text using Lingua for short texts and langdetect for longer ones."""
|
| 64 |
+
if len(text.split()) < 5:
|
| 65 |
+
languages = [Language.ENGLISH, Language.SWAHILI]
|
| 66 |
+
detector = LanguageDetectorBuilder.from_languages(*languages).build()
|
| 67 |
+
detected_language = detector.detect_language_of(text)
|
| 68 |
+
return "sw" if detected_language == Language.SWAHILI else "en"
|
| 69 |
+
try:
|
| 70 |
+
return detect(text)
|
| 71 |
+
except Exception as e:
|
| 72 |
+
logging.warning(f"Language detection error: {e}")
|
| 73 |
+
return "unknown"
|
| 74 |
+
#%%
|
| 75 |
+
# Define Gradio function
|
| 76 |
+
def nishauri(question, conversation_history: list[str]):
|
| 77 |
+
|
| 78 |
+
"""Process user query, detect language, handle greetings, acknowledgments, and retrieve relevant information."""
|
| 79 |
+
context = " ".join([item["user"] + " " + item["chatbot"] for item in conversation_history])
|
| 80 |
+
|
| 81 |
+
# Process greetings and acknowledgments
|
| 82 |
+
for lang, contains_greeting, contains_acknowledgment in [("en", contains_greeting_en, contains_acknowledgment_en), ("sw", contains_greeting_sw, contains_acknowledgment_sw)]:
|
| 83 |
+
if contains_greeting(question) and not contains_follow_up(question):
|
| 84 |
+
prompt = f"The user said: {question}. Respond accordingly in {lang}."
|
| 85 |
+
elif contains_acknowledgment(question) and not contains_follow_up(question):
|
| 86 |
+
prompt = f"The user acknowledged: {question}. Respond accordingly in {lang}."
|
| 87 |
+
else:
|
| 88 |
+
continue
|
| 89 |
+
completion = client.chat.completions.create(
|
| 90 |
+
model="gpt-4o",
|
| 91 |
+
messages=[{"role": "user", "content": prompt}]
|
| 92 |
+
)
|
| 93 |
+
reply_to_user = completion.choices[0].message.content
|
| 94 |
+
conversation_history.append({"user": question, "chatbot": reply_to_user})
|
| 95 |
+
source1return = ""
|
| 96 |
+
source2return = ""
|
| 97 |
+
source3return = ""
|
| 98 |
+
source4return = ""
|
| 99 |
+
source5return = ""
|
| 100 |
+
return reply_to_user, source1return, source2return, source3return, source4return, source5return, conversation_history
|
| 101 |
+
|
| 102 |
+
# Detect language and translate if needed
|
| 103 |
+
lang_question = detect_language(question)
|
| 104 |
+
if lang_question == "sw":
|
| 105 |
+
question = GoogleTranslator(source='sw', target='en').translate(question)
|
| 106 |
+
|
| 107 |
+
# Retrieve relevant sources
|
| 108 |
+
sources = retriever.retrieve(question)
|
| 109 |
+
retrieved_text = "\n\n".join([f"Source {i+1}: {source.text}" for i, source in enumerate(sources[:5])])
|
| 110 |
+
|
| 111 |
+
source1return = ("File Name: " +
|
| 112 |
+
sources[0].metadata["file_name"] +
|
| 113 |
+
"\nPage Number: " +
|
| 114 |
+
sources[0].metadata["page_label"] +
|
| 115 |
+
"\n Source Text: " +
|
| 116 |
+
sources[0].text)
|
| 117 |
+
|
| 118 |
+
source2return = ("File Name: " +
|
| 119 |
+
sources[1].metadata["file_name"] +
|
| 120 |
+
"\nPage Number: " +
|
| 121 |
+
sources[1].metadata["page_label"] +
|
| 122 |
+
"\n Source Text: " +
|
| 123 |
+
sources[1].text)
|
| 124 |
+
|
| 125 |
+
source3return = ("File Name: " +
|
| 126 |
+
sources[2].metadata["file_name"] +
|
| 127 |
+
"\nPage Number: " +
|
| 128 |
+
sources[2].metadata["page_label"] +
|
| 129 |
+
"\n Source Text: " +
|
| 130 |
+
sources[2].text)
|
| 131 |
+
|
| 132 |
+
source4return = ("File Name: " +
|
| 133 |
+
sources[3].metadata["file_name"] +
|
| 134 |
+
"\nPage Number: " +
|
| 135 |
+
sources[3].metadata["page_label"] +
|
| 136 |
+
"\n Source Text: " +
|
| 137 |
+
sources[3].text)
|
| 138 |
+
|
| 139 |
+
source5return = ("File Name: " +
|
| 140 |
+
sources[4].metadata["file_name"] +
|
| 141 |
+
"\nPage Number: " +
|
| 142 |
+
sources[4].metadata["page_label"] +
|
| 143 |
+
"\n Source Text: " +
|
| 144 |
+
sources[4].text)
|
| 145 |
+
|
| 146 |
+
# Combine into new user question - conversation history, new question, retrieved sources
|
| 147 |
+
question_final = (
|
| 148 |
+
f"The user asked the following question: \"{question}\"\n\n"
|
| 149 |
+
f"Use only the content below to answer the question:\n\n{retrieved_text}\n\n"
|
| 150 |
+
"Guidelines:\n"
|
| 151 |
+
"- Only answer the question that was asked.\n"
|
| 152 |
+
"- Do not change the subject or include unrelated information.\n"
|
| 153 |
+
"- If the question is not about HIV, say that you can only answer HIV-related questions.\n"
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
# Set LLM instructions. If user consented, add user parameters, otherwise proceed without
|
| 157 |
+
system_prompt = (
|
| 158 |
+
"You are a helpful assistant who only answers questions about HIV.\n"
|
| 159 |
+
"- Only answers questions about HIV (Human Immunodeficiency Virus). Recognize that users may type 'HIV' with any capitalization (e.g., HIV, hiv, Hiv, etc.) or make minor typos (e.g., hvi, hiv/aids). Use your best judgment to understand when a user intends to refer to HIV. Politely correct any significant misunderstandings, but otherwise proceed to answer normally.\n"
|
| 160 |
+
"- Do not answer questions about other topics (e.g., malaria or tuberculosis).\n"
|
| 161 |
+
"- If a question is unrelated to HIV, politely respond that you can only answer HIV-related questions.\n\n"
|
| 162 |
+
|
| 163 |
+
"The person asking the question is living with HIV.\n"
|
| 164 |
+
"- Do not suggest they get tested for HIV or take post-exposure prophylaxis (PEP).\n"
|
| 165 |
+
"- You may mention that their partners might benefit from testing or PEP, if relevant.\n"
|
| 166 |
+
"- Do not mention in your response that the person is living with HIV.\n"
|
| 167 |
+
"- Only suggest things relevant to someone who already has HIV.\n\n"
|
| 168 |
+
"- Keep the answer under 50 words.\n"
|
| 169 |
+
"- The user may user lowercase or slang for HIV or related terms.\n"
|
| 170 |
+
"- Use simple, easy-to-understand language. Avoid medical jargon.\n"
|
| 171 |
+
|
| 172 |
+
"Use the following authoritative information about viral loads:\n"
|
| 173 |
+
"- A high or non-suppressed viral load is above 200 copies/ml.\n"
|
| 174 |
+
"- A viral load above 1000 copies/ml suggests treatment failure.\n"
|
| 175 |
+
"- A suppressed viral load is one below 200 copies/ml.\n\n"
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
# Start with context
|
| 179 |
+
messages = [{"role": "system", "content": system_prompt}]
|
| 180 |
+
|
| 181 |
+
# Add conversation history
|
| 182 |
+
for turn in conversation_history:
|
| 183 |
+
messages.append({"role": "user", "content": turn["user"]})
|
| 184 |
+
messages.append({"role": "assistant", "content": turn["chatbot"]})
|
| 185 |
+
|
| 186 |
+
# Finally, add the current question
|
| 187 |
+
messages.append({"role": "user", "content": question_final})
|
| 188 |
+
|
| 189 |
+
# Generate response
|
| 190 |
+
completion = client.chat.completions.create(
|
| 191 |
+
model="gpt-4o",
|
| 192 |
+
messages=messages
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
# Collect response
|
| 196 |
+
reply_to_user = completion.choices[0].message.content
|
| 197 |
+
|
| 198 |
+
# add question and reply to conversation history
|
| 199 |
+
conversation_history.append({"user": question, "chatbot": reply_to_user})
|
| 200 |
+
|
| 201 |
+
# If initial question was in swahili, translate response to swahili
|
| 202 |
+
if lang_question=="sw":
|
| 203 |
+
reply_to_user = GoogleTranslator(source='auto', target='sw').translate(reply_to_user)
|
| 204 |
+
|
| 205 |
+
# return system_prompt, conversation_history
|
| 206 |
+
return reply_to_user, source1return, source2return, source3return, source4return, source5return, conversation_history
|
| 207 |
+
|
| 208 |
+
#%%
|
| 209 |
+
demo = gr.Interface(
|
| 210 |
+
title = "Nuru Chatbot Demo",
|
| 211 |
+
description="Enter a question and see the processed outputs in collapsible boxes.",
|
| 212 |
+
fn=nishauri,
|
| 213 |
+
inputs=["text", gr.State(value=[])],
|
| 214 |
+
outputs=[
|
| 215 |
+
gr.Textbox(label = "Nuru Response", type = "text"),
|
| 216 |
+
gr.Textbox(label = "Source 1", max_lines = 10, autoscroll = False, type = "text"),
|
| 217 |
+
gr.Textbox(label = "Source 2", max_lines = 10, autoscroll = False, type = "text"),
|
| 218 |
+
gr.Textbox(label = "Source 3", max_lines = 10, autoscroll = False, type = "text"),
|
| 219 |
+
gr.Textbox(label = "Source 4", max_lines = 10, autoscroll = False, type = "text"),
|
| 220 |
+
gr.Textbox(label = "Source 5", max_lines = 10, autoscroll = False, type = "text"),
|
| 221 |
+
gr.State()
|
| 222 |
+
],
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==4.44.1
|
| 2 |
+
llama_index==0.10.51
|
| 3 |
+
langdetect==1.0.9
|
| 4 |
+
deep-translator==1.11.4
|
| 5 |
+
lingua-language-detector==2.0.2
|
| 6 |
+
dotenv==0.9.9
|