Spaces:
Build error
Build error
mobius.dev commited on
Commit ·
8940edd
1
Parent(s): 6a6a33a
nice done
Browse files- .gitignore +1 -0
- talk_sheet.py +180 -127
.gitignore
CHANGED
|
@@ -183,3 +183,4 @@ Talk-Sheet/share/jupyter/nbextensions/pydeck/index.js
|
|
| 183 |
Talk-Sheet/pyvenv.cfg
|
| 184 |
Talk-Sheet/Include/site/python3.10/greenlet/greenlet.h
|
| 185 |
Talk-Sheet/etc/jupyter/nbconfig/notebook.d/pydeck.json
|
|
|
|
|
|
| 183 |
Talk-Sheet/pyvenv.cfg
|
| 184 |
Talk-Sheet/Include/site/python3.10/greenlet/greenlet.h
|
| 185 |
Talk-Sheet/etc/jupyter/nbconfig/notebook.d/pydeck.json
|
| 186 |
+
poto-associations-sample.csv.pkl
|
talk_sheet.py
CHANGED
|
@@ -1,159 +1,212 @@
|
|
| 1 |
-
from fastapi import Query
|
| 2 |
-
import streamlit as st
|
| 3 |
-
import pandas as pd
|
| 4 |
-
import os
|
| 5 |
-
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
|
| 8 |
-
from streamlit_chat import message
|
| 9 |
|
| 10 |
-
from langchain.chat_models import ChatOpenAI
|
| 11 |
-
from langchain.vectorstores import Chroma
|
| 12 |
-
from langchain.prompts import PromptTemplate
|
| 13 |
-
from langchain.document_loaders.csv_loader import CSVLoader
|
| 14 |
-
from langchain.text_splitter import CharacterTextSplitter
|
| 15 |
from langchain.embeddings.openai import OpenAIEmbeddings
|
| 16 |
-
from langchain.
|
| 17 |
-
from langchain.
|
| 18 |
-
from sympy import use
|
| 19 |
-
import tiktoken
|
| 20 |
-
from langchain.chains import ConversationChain
|
| 21 |
-
from langchain.memory import ChatMessageHistory
|
| 22 |
-
from langchain.memory import ConversationBufferMemory
|
| 23 |
from langchain.chains.question_answering import load_qa_chain
|
| 24 |
-
|
| 25 |
-
from langchain.chains import ConversationChain
|
| 26 |
-
from langchain.chains.conversation.memory import ConversationEntityMemory
|
| 27 |
-
from langchain.chains.conversation.prompt import ENTITY_MEMORY_CONVERSATION_TEMPLATE
|
| 28 |
-
from langchain.llms import OpenAI
|
| 29 |
-
from langchain.chains import ChatVectorDBChain
|
| 30 |
from langchain.chains import ConversationalRetrievalChain
|
| 31 |
-
|
| 32 |
-
from langchain.
|
| 33 |
-
from langchain.chains.conversation.memory import ConversationSummaryMemory
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
|
|
|
| 36 |
|
|
|
|
| 37 |
|
| 38 |
-
#
|
|
|
|
| 39 |
st.set_page_config(layout="wide", page_icon="contents\logo_site.png", page_title="Talk-Sheet")
|
| 40 |
|
| 41 |
st.markdown(
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
#
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
)
|
| 60 |
-
else:
|
| 61 |
-
# Upload CSV file
|
| 62 |
-
uploaded_file = st.sidebar.file_uploader(label=" ",label_visibility='hidden', type=["csv"])
|
| 63 |
-
if uploaded_file is not None:
|
| 64 |
-
# Show uploaded CSV file
|
| 65 |
-
def show_user_file(uploaded_file):
|
| 66 |
-
file_container = st.expander("Votre fichier CSV :")
|
| 67 |
-
shows = pd.read_csv(uploaded_file)
|
| 68 |
-
uploaded_file.seek(0)
|
| 69 |
-
file_container.write(shows)
|
| 70 |
-
|
| 71 |
-
show_user_file(uploaded_file)
|
| 72 |
-
|
| 73 |
-
else :
|
| 74 |
-
st.sidebar.info(
|
| 75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
"👆 Upload a .csv file to get started, "
|
| 77 |
"example : [fishfry-locations.csv](https://drive.google.com/file/d/18i7tN2CqrmoouaSqm3hDfAk17hmWx94e/view?usp=sharing)"
|
| 78 |
-
|
| 79 |
|
| 80 |
-
if uploaded_file:
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
-
file_path_user=os.path.join('contents\dataset', uploaded_file.name)
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
embeddings = OpenAIEmbeddings()
|
| 106 |
-
|
| 107 |
-
vectorstore = Chroma.from_documents(documents, embeddings)
|
| 108 |
|
| 109 |
-
# return ConversationRetrievalChain that answers user questions based on a given document store
|
| 110 |
-
chain = ConversationalRetrievalChain.from_llm(ChatOpenAI(temperature=0, model_name=MODEL),
|
| 111 |
-
retriever=vectorstore.as_retriever(search_type="similarity", search_kwargs={"k":2})
|
| 112 |
-
)
|
| 113 |
-
|
| 114 |
-
# Chatbot UI function
|
| 115 |
-
if 'generated' not in st.session_state:
|
| 116 |
-
st.session_state['generated'] = []
|
| 117 |
-
|
| 118 |
-
if 'past' not in st.session_state:
|
| 119 |
-
st.session_state['past'] = []
|
| 120 |
-
|
| 121 |
-
def generate_response(query):
|
| 122 |
-
chat_history = []
|
| 123 |
-
|
| 124 |
-
result = chain({'chat_history': {}, 'question': query})
|
| 125 |
-
chat_history = []
|
| 126 |
-
query = query
|
| 127 |
-
result = chain({"question": query, "chat_history": chat_history})
|
| 128 |
-
response = result["answer"]
|
| 129 |
-
print(f"Type of response: {type(response)}, response: {response}")
|
| 130 |
-
return response
|
| 131 |
-
|
| 132 |
-
def get_text():
|
| 133 |
-
input_text = st.text_input("##### Let's Talk ! 👇: ", key="input", placeholder="Your AI assistant here! Ask me anything ...")
|
| 134 |
-
return input_text
|
| 135 |
|
| 136 |
-
user_input = get_text()
|
| 137 |
|
| 138 |
-
if
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
-
st.session_state
|
| 142 |
-
|
| 143 |
|
| 144 |
-
|
| 145 |
-
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
message(st.session_state['past'][i], is_user=True, key=str(i) + '_user')
|
| 150 |
-
except Exception as e:
|
| 151 |
-
st.error(f"Error: {str(e)}")
|
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from langchain.embeddings.openai import OpenAIEmbeddings
|
| 3 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 4 |
+
from langchain.vectorstores import FAISS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
from langchain.chains.question_answering import load_qa_chain
|
| 6 |
+
from langchain.chat_models import ChatOpenAI
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
from langchain.chains import ConversationalRetrievalChain
|
| 8 |
+
import pickle
|
| 9 |
+
from langchain.document_loaders.csv_loader import CSVLoader
|
|
|
|
| 10 |
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from dotenv import load_dotenv
|
| 13 |
+
import os
|
| 14 |
+
import streamlit as st
|
| 15 |
+
from streamlit_chat import message
|
| 16 |
+
from langchain.text_splitter import CharacterTextSplitter
|
| 17 |
+
import tempfile
|
| 18 |
+
import pandas as pd
|
| 19 |
+
from langchain.prompts import PromptTemplate
|
| 20 |
|
| 21 |
+
import asyncio
|
| 22 |
|
| 23 |
+
|
| 24 |
|
| 25 |
+
# vectors = getDocEmbeds("gpt4.pdf")
|
| 26 |
+
# qa = ChatVectorDBChain.from_llm(ChatOpenAI(model_name="gpt-3.5-turbo"), vectors, return_source_documents=True)
|
| 27 |
st.set_page_config(layout="wide", page_icon="contents\logo_site.png", page_title="Talk-Sheet")
|
| 28 |
|
| 29 |
st.markdown(
|
| 30 |
+
"<h1 style='text-align: center;'>Talk-Sheet, Talk with your sheet-data ! 💬</h1>",
|
| 31 |
+
unsafe_allow_html=True)
|
| 32 |
+
|
| 33 |
+
user_api_key = st.sidebar.text_input(
|
| 34 |
+
label="#### Your OpenAI API key 👇",
|
| 35 |
+
placeholder="Paste your openAI API key, sk-",
|
| 36 |
+
type="password")
|
| 37 |
+
|
| 38 |
+
async def main():
|
| 39 |
+
|
| 40 |
+
if user_api_key == "":
|
| 41 |
+
st.markdown(
|
| 42 |
+
"<div style='text-align: center;'><h4>Enter your OpenAI API key to start chatting 😉</h4></div>",
|
| 43 |
+
unsafe_allow_html=True
|
| 44 |
+
)
|
| 45 |
+
else:
|
| 46 |
+
os.environ["OPENAI_API_KEY"] = user_api_key
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
uploaded_file = st.sidebar.file_uploader("", type="csv", label_visibility="hidden")
|
| 49 |
+
if uploaded_file:
|
| 50 |
+
# Show uploaded CSV file
|
| 51 |
+
def show_user_file(uploaded_file):
|
| 52 |
+
file_container = st.expander("Votre fichier CSV :")
|
| 53 |
+
shows = pd.read_csv(uploaded_file)
|
| 54 |
+
uploaded_file.seek(0)
|
| 55 |
+
file_container.write(shows)
|
| 56 |
+
show_user_file(uploaded_file)
|
| 57 |
+
else :
|
| 58 |
+
st.sidebar.info(
|
| 59 |
"👆 Upload a .csv file to get started, "
|
| 60 |
"example : [fishfry-locations.csv](https://drive.google.com/file/d/18i7tN2CqrmoouaSqm3hDfAk17hmWx94e/view?usp=sharing)"
|
| 61 |
+
)
|
| 62 |
|
|
|
|
| 63 |
|
| 64 |
+
if uploaded_file :
|
| 65 |
+
async def storeDocEmbeds(file, filename):
|
| 66 |
+
with tempfile.NamedTemporaryFile(mode="wb", delete=False) as tmp_file:
|
| 67 |
+
tmp_file.write(file)
|
| 68 |
+
tmp_file_path = tmp_file.name
|
| 69 |
+
|
| 70 |
+
loader = CSVLoader(file_path=tmp_file_path, encoding="utf-8")
|
| 71 |
+
data = loader.load()
|
| 72 |
+
|
| 73 |
+
splitter = CharacterTextSplitter(separator="\n",chunk_size=1500, chunk_overlap=0)
|
| 74 |
+
chunks = splitter.split_documents(data)
|
| 75 |
+
|
| 76 |
+
embeddings = OpenAIEmbeddings()
|
| 77 |
+
vectors = FAISS.from_documents(chunks, embeddings)
|
| 78 |
+
os.remove(tmp_file_path)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
with open(filename + ".pkl", "wb") as f:
|
| 82 |
+
pickle.dump(vectors, f)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
async def getDocEmbeds(file, filename):
|
| 86 |
+
|
| 87 |
+
if not os.path.isfile(filename + ".pkl"):
|
| 88 |
+
await storeDocEmbeds(file, filename)
|
| 89 |
+
|
| 90 |
+
with open(filename + ".pkl", "rb") as f:
|
| 91 |
+
global vectores
|
| 92 |
+
vectors = pickle.load(f)
|
| 93 |
+
|
| 94 |
+
return vectors
|
| 95 |
|
|
|
|
| 96 |
|
| 97 |
+
async def conversational_chat(query):
|
| 98 |
+
result = qa({"question": query, "chat_history": st.session_state['history']})
|
| 99 |
+
st.session_state['history'].append((query, result["answer"]))
|
| 100 |
+
print("Log: ")
|
| 101 |
+
print(st.session_state['history'])
|
| 102 |
+
return result["answer"]
|
| 103 |
+
|
| 104 |
+
prompt_template = (
|
| 105 |
+
"You are Talk-Sheet, a user-friendly chatbot designed to assist users by engaging in conversations based on data from CSV or Excel files. "
|
| 106 |
+
"Your knowledge comes from:"
|
| 107 |
+
|
| 108 |
+
"{context}"
|
| 109 |
+
|
| 110 |
+
"Help users by providing relevant information from the data in their files. Answer their questions accurately and concisely. "
|
| 111 |
+
"If the user's specific issue or need cannot be addressed with the available data, "
|
| 112 |
+
"empathize with their situation and suggest that they may need to seek assistance elsewhere. "
|
| 113 |
+
"Always maintain a friendly and helpful tone. "
|
| 114 |
+
"If you don't know the answer to a question, truthfully say you don't know."
|
| 115 |
+
"answers the user's question in the same language as the user"
|
| 116 |
+
|
| 117 |
+
"Human: {question} "
|
| 118 |
+
|
| 119 |
+
"Talk-Sheet: "
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
PROMPT = PromptTemplate(template=prompt_template, input_variables=["context","question"])
|
| 123 |
|
| 124 |
+
# Set up sidebar with various options
|
| 125 |
+
with st.sidebar.expander("🛠️ setting", expanded=False):
|
| 126 |
+
# Option to preview memory store
|
| 127 |
+
if st.button("Reset Chat"):
|
| 128 |
+
st.session_state['reset_chat'] = True
|
| 129 |
|
| 130 |
+
MODEL = st.selectbox(label='Model', options=['gpt-3.5-turbo','gpt-4'])
|
| 131 |
+
|
| 132 |
+
#llm = ChatOpenAI(model_name="gpt-3.5-turbo")
|
| 133 |
+
#chain = load_qa_chain(llm, chain_type="stuff")
|
| 134 |
|
| 135 |
|
| 136 |
+
if 'history' not in st.session_state:
|
| 137 |
+
st.session_state['history'] = []
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
if 'ready' not in st.session_state:
|
| 141 |
+
st.session_state['ready'] = False
|
| 142 |
+
|
| 143 |
+
if 'reset_chat' not in st.session_state:
|
| 144 |
+
st.session_state['reset_chat'] = False
|
| 145 |
|
|
|
|
|
|
|
|
|
|
| 146 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
|
|
|
| 148 |
|
| 149 |
+
if uploaded_file is not None:
|
| 150 |
+
|
| 151 |
+
with st.spinner("Processing..."):
|
| 152 |
+
# Add your code here that needs to be executed
|
| 153 |
+
uploaded_file.seek(0)
|
| 154 |
+
file = uploaded_file.read()
|
| 155 |
+
# pdf = PyPDF2.PdfFileReader()
|
| 156 |
+
vectors = await getDocEmbeds(file, uploaded_file.name)
|
| 157 |
+
qa = ConversationalRetrievalChain.from_llm(ChatOpenAI(model_name=MODEL), retriever=vectors.as_retriever(), qa_prompt=PROMPT,return_source_documents=False)
|
| 158 |
+
|
| 159 |
+
st.session_state['ready'] = True
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
if st.session_state['ready']:
|
| 163 |
+
|
| 164 |
+
# Le reste du code existant
|
| 165 |
|
| 166 |
+
if 'generated' not in st.session_state:
|
| 167 |
+
st.session_state['generated'] = ["Welcome! You can now ask any questions regarding " + uploaded_file.name]
|
| 168 |
|
| 169 |
+
if 'past' not in st.session_state:
|
| 170 |
+
st.session_state['past'] = ["Hey!"]
|
| 171 |
|
| 172 |
+
# container for chat history
|
| 173 |
+
response_container = st.container()
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
+
|
| 178 |
+
# container for text box
|
| 179 |
+
container = st.container()
|
| 180 |
+
|
| 181 |
+
with container:
|
| 182 |
+
with st.form(key='my_form', clear_on_submit=True):
|
| 183 |
+
user_input = st.text_input("Query:", placeholder="e.g: Summarize the paper in a few sentences", key='input')
|
| 184 |
+
submit_button = st.form_submit_button(label='Send')
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
if st.session_state['reset_chat']:
|
| 188 |
+
st.session_state['history'] = []
|
| 189 |
+
st.session_state['past'] = ["Hey!"]
|
| 190 |
+
st.session_state['generated'] = ["Welcome! You can now ask any questions regarding " + uploaded_file.name]
|
| 191 |
+
response_container.empty()
|
| 192 |
+
st.session_state['reset_chat'] = False
|
| 193 |
+
|
| 194 |
+
if submit_button and user_input:
|
| 195 |
+
output = await conversational_chat(user_input)
|
| 196 |
+
st.session_state['past'].append(user_input)
|
| 197 |
+
st.session_state['generated'].append(output)
|
| 198 |
+
|
| 199 |
+
if st.session_state['generated']:
|
| 200 |
+
with response_container:
|
| 201 |
+
for i in range(len(st.session_state['generated'])):
|
| 202 |
+
message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="big-smile")
|
| 203 |
+
message(st.session_state["generated"][i], key=str(i), avatar_style="thumbs")
|
| 204 |
+
|
| 205 |
+
# About section
|
| 206 |
+
about = st.sidebar.expander("About Talk-Sheet 🤖")
|
| 207 |
+
about.write("#### Talk-Sheet is a user-friendly chatbot designed to assist users by engaging in conversations based on data from CSV or excel files. 📄")
|
| 208 |
+
about.write("#### Ideal for various purposes and users, Talk-Sheet provides a simple yet effective way to interact with your sheet-data. 🌐")
|
| 209 |
+
about.write("#### Powered by [Langchain]('https://github.com/hwchase17/langchain'), [OpenAI]('https://platform.openai.com/docs/models/gpt-3-5') and [Streamlit]('https://github.com/streamlit/streamlit') Talk-Sheet offers a seamless and personalized experience. ⚡")
|
| 210 |
+
|
| 211 |
+
if __name__ == "__main__":
|
| 212 |
+
asyncio.run(main())
|