JBHF commited on
Commit
9dbe2e4
1 Parent(s): 1c70265

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py (ChatPDF)
2
+
3
+ import os
4
+ import tempfile
5
+ import streamlit as st
6
+ from streamlit_chat import message
7
+ from rag import ChatPDF
8
+
9
+ st.set_page_config(page_title="ChatPDF")
10
+
11
+
12
+ def display_messages():
13
+ st.subheader("Chat")
14
+ for i, (msg, is_user) in enumerate(st.session_state["messages"]):
15
+ message(msg, is_user=is_user, key=str(i))
16
+ st.session_state["thinking_spinner"] = st.empty()
17
+
18
+
19
+ def process_input():
20
+ if st.session_state["user_input"] and len(st.session_state["user_input"].strip()) > 0:
21
+ user_text = st.session_state["user_input"].strip()
22
+ with st.session_state["thinking_spinner"], st.spinner(f"Thinking"):
23
+ agent_text = st.session_state["assistant"].ask(user_text)
24
+
25
+ st.session_state["messages"].append((user_text, True))
26
+ st.session_state["messages"].append((agent_text, False))
27
+
28
+
29
+ def read_and_save_file():
30
+ st.session_state["assistant"].clear()
31
+ st.session_state["messages"] = []
32
+ st.session_state["user_input"] = ""
33
+
34
+ for file in st.session_state["file_uploader"]:
35
+ with tempfile.NamedTemporaryFile(delete=False) as tf:
36
+ tf.write(file.getbuffer())
37
+ file_path = tf.name
38
+
39
+ with st.session_state["ingestion_spinner"], st.spinner(f"Ingesting {file.name}"):
40
+ st.session_state["assistant"].ingest(file_path)
41
+ os.remove(file_path)
42
+
43
+
44
+ def page():
45
+ if len(st.session_state) == 0:
46
+ st.session_state["messages"] = []
47
+ st.session_state["assistant"] = ChatPDF()
48
+
49
+ st.header("ChatPDF")
50
+
51
+ st.subheader("Upload a document")
52
+ st.file_uploader(
53
+ "Upload document",
54
+ type=["pdf"],
55
+ key="file_uploader",
56
+ on_change=read_and_save_file,
57
+ label_visibility="collapsed",
58
+ accept_multiple_files=True,
59
+ )
60
+
61
+ st.session_state["ingestion_spinner"] = st.empty()
62
+
63
+ display_messages()
64
+ st.text_input("Message", key="user_input", on_change=process_input)
65
+
66
+
67
+ if __name__ == "__main__":
68
+ page()