Maria Tsilimos commited on
Commit
a71b275
·
unverified ·
1 Parent(s): 3f5cc9c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +217 -0
app.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+
4
+ import pandas as pd
5
+ import plotly.express as px
6
+
7
+ from cryptography.fernet import Fernet
8
+ import time
9
+
10
+ import io
11
+ from transformers import pipeline
12
+ from streamlit_extras.stylable_container import stylable_container
13
+ import json
14
+
15
+
16
+
17
+ from io import StringIO
18
+
19
+
20
+ # sidebar
21
+ with st.sidebar:
22
+ with stylable_container(
23
+ key="test_button",
24
+ css_styles="""
25
+ button {
26
+ background-color: yellow;
27
+ border: 1px solid black;
28
+ padding: 5px;
29
+ color: black;
30
+ }
31
+ """,
32
+ ):
33
+ st.button("DEMO APP")
34
+
35
+
36
+ expander = st.expander("**Important notes on the Google Sheet Table Question Answering (QA) App**")
37
+ expander.write('''
38
+
39
+ **Supported File Formats**
40
+ This app works with public URLs of Google Sheets. Google Sheets must not exceed 3,000 rows.
41
+
42
+
43
+ **How to Use**
44
+ Paste the public URL of your Google Sheet. Press the 'Fetch Data' button, then type your question into the text area provided and click the 'Retrieve your answer' button. Always press the 'Fetch Data' button before typing a question.
45
+
46
+
47
+ **Usage Limits**
48
+ You can ask up to 5 questions.
49
+
50
+
51
+ **Subscription Management**
52
+ This demo app offers a one-day subscription, expiring after 24 hours. If you are interested in building your own Table Question Answering (QA) Web App, we invite you to explore our NLP Web App Store on our website. You can select your desired features, place your order, and we will deliver your custom app in five business days. If you wish to delete your Account with us, please contact us at [email protected]
53
+
54
+
55
+ **Authorization**
56
+ For security purposes, your authorization access expires hourly. To restore access, click the "Request Authorization" button.
57
+
58
+
59
+ **Customization**
60
+ To change the app's background color to white or black, click the three-dot menu on the right-hand side of your app, go to Settings and then Choose app theme, colors and fonts.
61
+
62
+
63
+ **File Handling and Errors**
64
+ The app may display an error message if your file has errors.
65
+ For any errors or inquiries, please contact us at [email protected]
66
+
67
+
68
+ ''')
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+ if 'fernet_key' not in st.session_state:
84
+ st.session_state.fernet_key = Fernet.generate_key()
85
+
86
+ key = st.session_state.fernet_key
87
+
88
+
89
+ # function for generating and validating fernet key
90
+ def generate_fernet_token(key, data):
91
+ fernet = Fernet(key)
92
+ token = fernet.encrypt(data.encode())
93
+ return token
94
+
95
+ def validate_fernet_token(key, token, ttl_seconds):
96
+
97
+ fernet = Fernet(key)
98
+ try:
99
+ decrypted_data = fernet.decrypt(token, ttl=ttl_seconds).decode()
100
+ return decrypted_data, None
101
+ except Exception as e:
102
+ return None, f"Expired token: {e}"
103
+
104
+ if 'question_attempts' not in st.session_state:
105
+ st.session_state['question_attempts'] = 0
106
+
107
+ max_attempts = 5
108
+
109
+
110
+ def clear_text():
111
+ st.session_state["url"] = ""
112
+
113
+
114
+
115
+ # --- UI elements ---
116
+ st.subheader("Google Sheet Question Answering (QA)", divider = "green")
117
+
118
+ url = st.text_input("Enter Google Sheet URL:", key="url")
119
+ st.button("Clear URL", on_click=clear_text)
120
+
121
+
122
+
123
+ # --- Data fetching and processing ---
124
+
125
+
126
+
127
+ if st.button("Fetch Data"):
128
+ if url:
129
+ try:
130
+ spreadsheet_key = url.split('/d/')[1].split('/')[0]
131
+ csv_url = f'https://docs.google.com/spreadsheets/d/{spreadsheet_key}/export?format=csv'
132
+ df = pd.read_csv(csv_url, na_filter=False)
133
+
134
+
135
+
136
+ st.dataframe(df)
137
+ st.write("_number of rows_", df.shape[0])
138
+ st.write("_number of columns_", df.shape[1])
139
+ st.session_state.df = df # Store DataFrame in session state
140
+
141
+ if df.shape[0] > 3000: # Check row count inside try block
142
+ st.warning ("Google Sheets must not exceed 3,000 rows.")
143
+ st.stop()
144
+
145
+
146
+ except Exception as e:
147
+ st.error(f"Error fetching data: {e}")
148
+ else:
149
+ st.warning("Please enter a Google Sheet URL.")
150
+
151
+ st.divider()
152
+
153
+ # Authorization and question answering
154
+
155
+
156
+
157
+ if 'fernet_token' not in st.session_state:
158
+ if 'df' in st.session_state:
159
+ df = st.session_state.df
160
+ st.session_state.fernet_token = generate_fernet_token(key, df.to_json())
161
+ else:
162
+ st.stop()
163
+
164
+ decrypted_data_streamlit, error_streamlit = validate_fernet_token(key, st.session_state.fernet_token, ttl_seconds=3600)
165
+
166
+ if error_streamlit:
167
+ st.warning("Please press Request Authorization.")
168
+ if st.button("Request Authorization"):
169
+ if 'df' in st.session_state:
170
+ df = st.session_state.df
171
+ st.session_state.fernet_token = generate_fernet_token(key, df.to_json())
172
+ st.success("Authorization granted")
173
+ decrypted_data_streamlit, error_streamlit = validate_fernet_token(key, st.session_state.fernet_token, ttl_seconds=3600)
174
+ if error_streamlit:
175
+ st.error(f"Your authorization has expired: {error_streamlit}")
176
+ st.stop()
177
+ if error_streamlit:
178
+ st.error("Please paste the public URL of your Google Sheet.")
179
+ st.stop()
180
+ else:
181
+ try:
182
+ df = pd.read_json(decrypted_data_streamlit)
183
+ except Exception as e:
184
+ st.error(f"Error decoding data: {e}")
185
+ st.stop()
186
+ else:
187
+ st.error(f"Your authorization has expired: {error_streamlit}")
188
+ st.stop()
189
+
190
+
191
+
192
+
193
+ def clear_question():
194
+ st.session_state["question"] = ""
195
+
196
+ question = st.text_input("Type your question here:", key="question")
197
+ st.button("Clear question", on_click=clear_question)
198
+
199
+
200
+ if 'df' in st.session_state: # Check if DataFrame is in session state
201
+ df = st.session_state.df # Retrieve DataFrame from session state
202
+ if st.button("Retrieve your answer"):
203
+ if st.session_state.question_attempts < max_attempts:
204
+ try:
205
+ tqa = pipeline(task="table-question-answering", model="microsoft/tapex-large-finetuned-wtq")
206
+ answer = tqa(table=df, query=question)['answer']
207
+ st.write(f"Answer: {answer}")
208
+ st.session_state.question_attempts += 1
209
+ except Exception as e:
210
+ st.error(f"Error retrieving answer: {e}")
211
+ else:
212
+ st.error("Maximum question attempts reached.")
213
+ else:
214
+ st.warning("Please fetch data first.")
215
+
216
+ st.divider()
217
+ st.write(f"Number of times you asked a question: {st.session_state['question_attempts']}/{max_attempts}")