varun1011 commited on
Commit
37b8064
Β·
verified Β·
1 Parent(s): 1db6476

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -62
app.py CHANGED
@@ -1,62 +1,111 @@
1
- import streamlit as st
2
- from pathlib import Path
3
- from data_preprocessing import process_docs
4
- from rag import create_rag_chain
5
- import time
6
-
7
- def response_generator(prompt,chain):
8
- response = chain.invoke(prompt)
9
- for word in response.split():
10
- yield word + " "
11
- time.sleep(0.05)
12
-
13
-
14
-
15
- # Set up the file uploader
16
- # uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
17
-
18
- # Specify the directory to save files
19
- save_directory = "docs"
20
- save_path="docs/file.pdf"
21
-
22
-
23
-
24
-
25
-
26
- st.title("πŸ“ InsureAgent")
27
- with st.sidebar:
28
- uploaded_file = st.file_uploader("Upload a document", type=("pdf"))
29
- if uploaded_file is not None:
30
- with open(save_path, "wb") as f:
31
- f.write(uploaded_file.getbuffer())
32
- st.success(f"File saved successfully: {save_path}")
33
- retriever=process_docs(save_path)
34
- chain,chain_with_sources=create_rag_chain(retriever)
35
-
36
- # Initialize chat history
37
- if "messages" not in st.session_state:
38
- st.session_state.messages = []
39
- for message in st.session_state.messages:
40
- with st.chat_message(message["role"]):
41
- st.markdown(message["content"])
42
- # Streamed response emulator
43
-
44
- if prompt := st.chat_input("What is up?"):
45
- # Add user message to chat history
46
- st.session_state.messages.append({"role": "user", "content": prompt})
47
- # Display user message in chat message container
48
- with st.chat_message("user"):
49
- st.markdown(prompt)
50
-
51
- # Display assistant response in chat message container
52
- with st.chat_message("assistant"):
53
- response = st.write_stream(response_generator(prompt,chain))
54
- # Add assistant response to chat history
55
- st.session_state.messages.append({"role": "assistant", "content": response})
56
-
57
-
58
-
59
-
60
-
61
-
62
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from pathlib import Path
3
+ from data_preprocessing import process_docs
4
+ from rag import create_rag_chain
5
+ import time
6
+ import pandas as pd
7
+ import os
8
+ from datetime import datetime
9
+
10
+ # Feedback storage setup
11
+ FEEDBACK_FILE = "feedback.csv"
12
+ if not os.path.exists(FEEDBACK_FILE):
13
+ pd.DataFrame(columns=["timestamp", "query", "response", "rating"]).to_csv(FEEDBACK_FILE, index=False)
14
+
15
+ def save_feedback(query, response, rating):
16
+ feedback = {
17
+ "timestamp": datetime.now().isoformat(),
18
+ "query": query,
19
+ "response": response,
20
+ "rating": rating
21
+ }
22
+ pd.DataFrame([feedback]).to_csv(FEEDBACK_FILE, mode="a", header=False, index=False)
23
+
24
+ def response_generator(prompt, chain):
25
+ response = chain.invoke(prompt)
26
+ for word in response.split():
27
+ yield word + " "
28
+ time.sleep(0.05)
29
+
30
+ # File handling setup
31
+ save_directory = "docs"
32
+ save_path = "docs/file.pdf"
33
+ Path(save_directory).mkdir(parents=True, exist_ok=True)
34
+
35
+ st.title("πŸ“ InsureAgent")
36
+
37
+ with st.sidebar:
38
+ uploaded_file = st.file_uploader("Upload a document", type=("pdf"))
39
+ if uploaded_file is not None:
40
+ with open(save_path, "wb") as f:
41
+ f.write(uploaded_file.getbuffer())
42
+ st.success(f"File saved successfully: {save_path}")
43
+
44
+ # Show feedback data toggle
45
+ show_feedback = st.checkbox("Show feedback data")
46
+
47
+ # Process documents
48
+ retriever = process_docs(save_path)
49
+ chain, chain_with_sources = create_rag_chain(retriever)
50
+
51
+ # Initialize chat history
52
+ if "messages" not in st.session_state:
53
+ st.session_state.messages = []
54
+
55
+ # Display chat messages
56
+ for idx, message in enumerate(st.session_state.messages):
57
+ with st.chat_message(message["role"]):
58
+ st.markdown(message["content"])
59
+
60
+ # Add rating buttons for assistant messages
61
+ if message["role"] == "assistant":
62
+ if "rating" not in message:
63
+ col1, col2 = st.columns(2)
64
+ with col1:
65
+ if st.button("πŸ‘ Good", key=f"good_{idx}"):
66
+ message["rating"] = "good"
67
+ query = st.session_state.messages[idx-1]["content"]
68
+ save_feedback(query, message["content"], "good")
69
+ st.rerun()
70
+ with col2:
71
+ if st.button("πŸ‘Ž Bad", key=f"bad_{idx}"):
72
+ message["rating"] = "bad"
73
+ query = st.session_state.messages[idx-1]["content"]
74
+ save_feedback(query, message["content"], "bad")
75
+ st.rerun()
76
+ else:
77
+ st.write(f"Rated: {message['rating'].capitalize()}")
78
+
79
+ # Show feedback data in sidebar if enabled
80
+ if show_feedback:
81
+ st.sidebar.subheader("User Feedback")
82
+ try:
83
+ feedback_df = pd.read_csv(FEEDBACK_FILE)
84
+ st.sidebar.dataframe(feedback_df)
85
+
86
+ # Download button for feedback data
87
+ csv = feedback_df.to_csv(index=False).encode('utf-8')
88
+ st.sidebar.download_button(
89
+ label="Download feedback as CSV",
90
+ data=csv,
91
+ file_name="feedback_data.csv",
92
+ mime="text/csv"
93
+ )
94
+ except FileNotFoundError:
95
+ st.sidebar.warning("No feedback data yet")
96
+
97
+ # Chat input and processing
98
+ if prompt := st.chat_input("Ask about your insurance document:"):
99
+ # Add user message to chat history
100
+ st.session_state.messages.append({"role": "user", "content": prompt})
101
+
102
+ # Display user message
103
+ with st.chat_message("user"):
104
+ st.markdown(prompt)
105
+
106
+ # Generate and display assistant response
107
+ with st.chat_message("assistant"):
108
+ response = st.write_stream(response_generator(prompt, chain))
109
+
110
+ # Add assistant response to chat history
111
+ st.session_state.messages.append({"role": "assistant", "content": response})