lrenzoha commited on
Commit
1f73fce
1 Parent(s): 562820b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ os.environ['OPENAI_API_KEY'] = st.text_input(
47
+ "Enter your OpenAI API key", type="password")
48
+
49
+ if os.environ['OPENAI_API_KEY']:
50
+ # Initialize chatbot history
51
+ chatbot = []
52
+
53
+ # Display file upload component
54
+ files = st.file_uploader('Upload Files', accept_multiple_files=True)
55
+ if files is not None:
56
+ save_file(files)
57
+
58
+ index = ingest('tmp_docs')
59
+
60
+ # Display message input component
61
+ message = st.text_input('Enter message')
62
+
63
+ # If message is entered, ingest documents and get chatbot response
64
+ if message:
65
+ chatbot.append(('You', message))
66
+ chatbot += get_answer(index, message)
67
+
68
+ # Display chat history
69
+ st.text_area('Chatbot:', value='\n'.join(
70
+ [f'{x[0]}: {x[1]}' for x in chatbot]), height=250)