moukawil / app.py
JasperV13's picture
Update app.py
66fb1d2
from gradio_client import Client
from langchain.document_loaders.text import TextLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.schema import Document
from langchain.embeddings import HuggingFaceEmbeddings
from langchain import PromptTemplate
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
from langchain.callbacks.manager import CallbackManager
from langchain.vectorstores import FAISS
from langchain.chains import RetrievalQA
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationalRetrievalChain
from huggingface_hub import hf_hub_download
from langchain.llms import LlamaCpp
from langchain.chains import LLMChain
import time
import streamlit as st
class MyBot:
def __init__(self, text_file, model_id, model_basename):
self.text_file = text_file
self.model_id = model_id
self.model_basename = model_basename
self.loader = TextLoader(self.text_file)
self.pages = self.loader.load()
self.chunks_text = self.split_text(self.pages)
self.docs_text = [doc.page_content for doc in self.chunks_text]
self.embedding = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2')
self.VectorStore = FAISS.from_texts(self.docs_text, embedding=self.embedding)
self.model_path = self.download_model(self.model_id, self.model_basename)
self.callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])
self.llm = self.init_llm(self.model_path, self.callback_manager)
self.memory = ConversationBufferMemory(
memory_key="chat_history",
return_messages=True,
input_key='question',
output_key='answer'
)
self.qa = self.init_qa(self.llm, self.VectorStore, self.memory)
def split_text(self, documents):
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=150,
length_function=len,
add_start_index=True,
)
chunks = text_splitter.split_documents(documents)
return chunks
def download_model(self, model_id, model_basename):
model_path = hf_hub_download(
repo_id=model_id,
filename=model_basename,
resume_download=True,
)
print("model_path : ", model_path)
return model_path
def init_llm(self, model_path, callback_manager):
CONTEXT_WINDOW_SIZE = 1500
MAX_NEW_TOKENS = 2000
N_BATCH = 512
n_gpu_layers = 40
kwargs = {
"model_path": model_path,
"n_ctx": CONTEXT_WINDOW_SIZE,
"max_tokens": MAX_NEW_TOKENS,
"n_batch": N_BATCH,
"n_gpu_layers": n_gpu_layers,
"callback_manager": callback_manager,
"verbose":True,
}
llm = LlamaCpp(**kwargs)
return llm
def init_qa(self, llm, VectorStore, memory):
qa = ConversationalRetrievalChain.from_llm(
llm,
chain_type="stuff",
retriever=VectorStore.as_retriever(search_kwargs={"k": 5}),
memory=memory,
return_source_documents=True,
verbose=False,
)
return qa
def translate(self, text, source,target):
client = Client("https://facebook-seamless-m4t-v2-large.hf.space/--replicas/2bmbx/")
result = client.predict(
text,
source,
target,
api_name="/t2tt"
)
#---------------------------------------------------------
# Set page config
st.set_page_config(
page_title="πŸ€–πŸ’Ό πŸ‡²πŸ‡¦ Financial advisor is Here",
page_icon="πŸ€–",
layout="wide",
initial_sidebar_state="expanded",
)
# Set Streamlit theme
# Define the custom CSS
custom_css = """
<style>
body {
background-color: #FFE6C7;
}
h1 {
color: #454545;
}
h2 {
color: #FF6000;
}
h3 {
color: #FFA559;
}
</style>
"""
# Add the custom CSS to the app
st.markdown(custom_css, unsafe_allow_html=True)
# Replicate Credentials
with st.sidebar:
st.title('Mokawil.AI is Here πŸ€–πŸ’Ό')
st.markdown('πŸ€– An AI-powered advisor designed to assist founders (or anyone aspiring to start their own company) with various aspects of business in Morocco. This includes legal considerations, budget planning, strategies for success, and much more.')
selected_language = st.sidebar.selectbox("Select Language", ["English", "Darija"], index=0) # English is the default
# Store LLM generated responses
if "messages" not in st.session_state.keys():
st.session_state.messages = [{"role": "assistant", "content": "How may I assist you today?"}]
# Display or clear chat messages
for message in st.session_state.messages:
if message["role"] == "user" :
with st.chat_message(message["role"], avatar="user.png"):
st.write(message["content"])
else :
with st.chat_message(message["role"], avatar="logo.png"):
st.write(message["content"])
# Create an instance of LangChain
lc = MyBot("Data_blog.txt", "TheBloke/Mistral-7B-OpenOrca-GGUF", "mistral-7b-openorca.Q4_K_M.gguf")
# Use the instance methods in your Streamlit application
def clear_chat_history():
lc.memory.clear()
lc.qa = lc.init_qa(lc.llm, lc.VectorStore, lc.memory)
st.session_state.messages = [{"role": "assistant", "content": "How may I assist you today?"}]
def generate_llm_response(prompt_input):
res = lc.qa(f'''{prompt_input}''')
if selected_language == "Darija":
translated_response = lc.translate(res['answer'])
return translated_response
else:
return res['answer']
# User-provided prompt
if prompt := st.chat_input("Cities to start my buisiness in finance?"):
if selected_language == "Darija":
tprompt = translate(str(prompt),"Moroccan Arabic","English")
else:
tprompt = prompt
st.session_state.messages.append({"role": "user", "content": tprompt})
with st.chat_message("user", avatar="user.png"):
st.write(prompt)
# Generate a new response if last message is not from assistant
if st.session_state.messages[-1]["role"] != "assistant":
with st.chat_message("assistant", avatar="logo.png"):
with st.spinner("Thinking..."):
response = generate_llm_response(st.session_state.messages[-1]["content"])
placeholder = st.empty()
full_response = ''
for item in response:
full_response += item
placeholder.markdown(full_response)
time.sleep(0.05)
placeholder.markdown(full_response)
message = {"role": "assistant", "content": full_response}
st.session_state.messages.append(message)
# Example prompt
with st.sidebar :
st.title('Examples :')
def promptExample1():
prompt = "How can I start my company in Morocco?"
st.session_state.messages.append({"role": "user", "content": prompt})
# Example prompt
def promptExample2():
prompt = "What are some recommended cities for starting a business in the finance sector?"
st.session_state.messages.append({"role": "user", "content": prompt})
# Example prompt
def promptExample3():
prompt = "What is the estimated amount of money I need to start my company?"
st.session_state.messages.append({"role": "user", "content": prompt})
st.sidebar.button('How can I start my company in Morocco?', on_click=promptExample1)
st.sidebar.button('What are some recommended cities for starting a business in the finance sector?', on_click=promptExample2)
st.sidebar.button('What is the estimated amount of money I need to start my company?', on_click=promptExample3)
with st.sidebar:
st.title('Disclaimer ⚠️:')
st.markdown('may introduce false information')
st.markdown('consult with a preofessionel advisor for more specific problems')