chrisvnz commited on
Commit
fadca99
·
1 Parent(s): 7775da1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -0
app.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import pandas as pd
4
+ import streamlit as st
5
+ from llama_index import GPTVectorStoreIndex, SimpleDirectoryReader
6
+ from llama_index import download_loader
7
+ from matplotlib import pyplot as plt
8
+ from pandasai.llm.openai import OpenAI
9
+
10
+ documents_folder = "documents"
11
+
12
+ # Load PandasAI loader, Which is a wrapper over PandasAI library
13
+ PandasAIReader = download_loader("PandasAIReader")
14
+
15
+ st.title("Welcome to `ChatwithDocs`")
16
+ st.header(
17
+ "Interact with Documents such as `PDFs/CSV/Docs` using the power of LLMs\nPowered by `LlamaIndex🦙` \nCheckout the [GITHUB Repo Here](https://github.com/anoopshrma/Chat-with-Docs) and Leave a star⭐")
18
+
19
+
20
+ def get_csv_result(df, query):
21
+ reader = PandasAIReader(llm=csv_llm)
22
+ csv_response = reader.run_pandas_ai(
23
+ df,
24
+ query,
25
+ is_conversational_answer=False
26
+ )
27
+ return csv_response
28
+
29
+
30
+ def save_file(doc):
31
+ fn = os.path.basename(doc.name)
32
+ # check if documents_folder exists in the directory
33
+ if not os.path.exists(documents_folder):
34
+ # if documents_folder does not exist then making the directory
35
+ os.makedirs(documents_folder)
36
+ # open read and write the file into the server
37
+ open(documents_folder + '/' + fn, 'wb').write(doc.read())
38
+ # Check for the current filename, If new filename
39
+ # clear the previous cached vectors and update the filename
40
+ # with current name
41
+ if st.session_state.get('file_name'):
42
+ if st.session_state.file_name != fn:
43
+ st.cache_resource.clear()
44
+ st.session_state['file_name'] = fn
45
+ else:
46
+ st.session_state['file_name'] = fn
47
+
48
+ return fn
49
+
50
+
51
+ def remove_file(file_path):
52
+ # Remove the file from the Document folder once
53
+ # vectors are created
54
+ if os.path.isfile(documents_folder + '/' + file_path):
55
+ os.remove(documents_folder + '/' + file_path)
56
+
57
+
58
+ @st.cache_resource
59
+ def create_index():
60
+ # Create vectors for the file stored under Document folder.
61
+ # NOTE: You can create vectors for multiple files at once.
62
+ try:
63
+ documents = SimpleDirectoryReader(documents_folder).load_data()
64
+ index = GPTVectorStoreIndex.from_documents(documents)
65
+ return index
66
+ except Exception as e:
67
+ st.error("Failed to read documents")
68
+
69
+
70
+
71
+ def query_doc(vector_index, query):
72
+ # Applies Similarity Algo, Finds the nearest match and
73
+ # take the match and user query to OpenAI for rich response
74
+ query_engine = vector_index.as_query_engine()
75
+ response = query_engine.query(query)
76
+ return response
77
+
78
+
79
+ api_key = st.text_input("Enter your OpenAI API key here:", type="password")
80
+ if api_key:
81
+ os.environ['OPENAI_API_KEY'] = api_key
82
+ csv_llm = OpenAI(api_token=api_key)
83
+
84
+ tab1, tab2 = st.tabs(["CSV", "PDFs/Docs"])
85
+
86
+ with tab1:
87
+ st.write("Chat with CSV files using PandasAI loader with LlamaIndex")
88
+ input_csv = st.file_uploader("Upload your CSV file", type=['csv'])
89
+
90
+ if input_csv is not None:
91
+ st.info("CSV Uploaded Successfully")
92
+ df = pd.read_csv(input_csv)
93
+ st.dataframe(df, use_container_width=True)
94
+
95
+ st.divider()
96
+
97
+ input_text = st.text_area("Ask your query")
98
+
99
+ if input_text is not None:
100
+ if st.button("Send"):
101
+ st.info("Your query: " + input_text)
102
+ with st.spinner('Processing your query...'):
103
+ response = get_csv_result(df, input_text)
104
+ if plt.get_fignums():
105
+ st.pyplot(plt.gcf())
106
+ else:
107
+ st.success(response)
108
+
109
+ with tab2:
110
+ st.write("Chat with PDFs/Docs")
111
+ input_doc = st.file_uploader("Upload your Docs")
112
+
113
+ if input_doc is not None:
114
+ st.info("Doc Uploaded Successfully")
115
+ file_name = save_file(input_doc)
116
+ index = create_index()
117
+ remove_file(file_name)
118
+
119
+ st.divider()
120
+ input_text = st.text_area("Ask your question")
121
+
122
+ if input_text is not None:
123
+ if st.button("Ask"):
124
+ st.info("Your query: \n" + input_text)
125
+ with st.spinner("Processing your query.."):
126
+ response = query_doc(index, input_text)
127
+ print(response)
128
+
129
+ st.success(response)
130
+
131
+ st.divider()
132
+ # Shows the source documents context which
133
+ # has been used to prepare the response
134
+ st.write("Source Documents")
135
+ st.write(response.get_formatted_sources())