Zenne commited on
Commit
b80864a
1 Parent(s): 9172d67

Create app.py

Browse files

chatbot that can ingest multiple files and chat

Files changed (1) hide show
  1. app.py +67 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from llama_index import SimpleDirectoryReader, GPTVectorStoreIndex
3
+ import os
4
+ import shutil
5
+
6
+
7
+ def save_file(files):
8
+ directory_name = 'tmp_docs'
9
+
10
+ # Remove existing files in the directory
11
+ if os.path.exists(directory_name):
12
+ for filename in os.listdir(directory_name):
13
+ file_path = os.path.join(directory_name, filename)
14
+ try:
15
+ if os.path.isfile(file_path):
16
+ os.remove(file_path)
17
+ except Exception as e:
18
+ print(f"Error: {e}")
19
+
20
+ # Save the new file with original filename
21
+ if files is not None:
22
+ for file in files:
23
+ file_name = file.name
24
+ file_path = os.path.join(directory_name, file_name)
25
+ with open(file_path, 'wb') as f:
26
+ shutil.copyfileobj(file, f)
27
+
28
+
29
+ def ingest(docs_dir):
30
+ documents = SimpleDirectoryReader(docs_dir).load_data()
31
+ index = GPTVectorStoreIndex.from_documents(documents)
32
+ return index
33
+
34
+
35
+ def get_answer(index, message):
36
+ response = query(index, message)
37
+ return [('Chatbot', ''.join(response.response))]
38
+
39
+
40
+ def query(index, query_text):
41
+ query_engine = index.as_query_engine()
42
+ response = query_engine.query(query_text)
43
+ return response
44
+
45
+
46
+ # Initialize chatbot history
47
+ chatbot = []
48
+
49
+ # Display file upload component
50
+ files = st.file_uploader('Upload Files', accept_multiple_files=True)
51
+ if files is not None:
52
+ save_file(files)
53
+
54
+
55
+ index = ingest('tmp_docs')
56
+
57
+ # Display message input component
58
+ message = st.text_input('Enter message')
59
+
60
+ # If message is entered, ingest documents and get chatbot response
61
+ if message:
62
+ chatbot.append(('You', message))
63
+ chatbot += get_answer(index, message)
64
+
65
+ # Display chat history
66
+ st.text_area('Chatbot:', value='\n'.join(
67
+ [f'{x[0]}: {x[1]}' for x in chatbot]), height=250)