nlpblogs commited on
Commit
83b9128
·
verified ·
1 Parent(s): 8ceebe5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -111
app.py CHANGED
@@ -8,148 +8,139 @@ import json
8
  import plotly.express as px
9
 
10
  st.subheader("AI CSV and XLSX Data Analyzer", divider="blue")
11
- st.link_button("by nlpblogs", "https://nlpblogs.com", type = "tertiary")
12
 
13
  expander = st.expander("**Important notes on the AI CSV and XLSX Data Analyzer**")
14
- expander.write('''
15
-
16
- **Supported File Formats:**
17
- This app accepts files in .csv and .xlsx formats.
18
-
19
- **How to Use:**
20
- Upload your file first. Select two different columns from your data to visualize in a Tree Map. Then, type your question into the text area provided and click the 'Retrieve your answer' button.
21
-
22
- **Tree Map:**
23
- Your uploaded data is presented in an interactive Tree Map for visual exploration. Click on any area within the map to access specific data insights.
24
-
25
- **Usage Limits:**
26
- You can ask up to 5 questions.
27
-
28
- **Subscription Management:**
29
- This app offers a one-day free trial, followed by a one-day subscription, expiring after 24 hours. If you are interested in building your own AI CSV and XLSX Data Analyzer, 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]
30
-
31
- **Customization:**
32
- 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.
33
-
34
- **File Handling and Errors:**
35
- (a) The app may provide an inaccurate answer if the information is missing from the relevant cell. (b) The app may display an error message if your file has errors, date values or float numbers (0.5, 1.2, 4.5 etc.).
36
-
37
- For any errors or inquiries, please contact us at [email protected]
38
-
39
- ''')
40
-
41
 
42
  with st.sidebar:
43
  container = st.container(border=True)
44
- container.write("**Question-Answering (QA)** is the task of retrieving the answer to a question from a given text (knowledge base), which is used as context.")
45
- st.subheader("Related NLP Web Apps", divider = "blue")
46
- st.link_button("AI Google Sheet Data Analyzer", "https://nlpblogs.com/shop/table-question-answering-qa/google-sheet-qa-demo-app/", type = "primary")
47
-
48
-
49
- if 'question_attempts' not in st.session_state:
50
- st.session_state['question_attempts'] = 0
51
-
 
 
 
 
52
  max_attempts = 5
53
-
54
  MAX_FILE_SIZE_KB = 10
55
  MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_KB * 1024
56
 
57
-
58
- upload_file = st.file_uploader("Upload your file. Accepted file formats include: .csv, .xlsx", type=['csv', 'xlsx'])
 
 
59
 
60
  if upload_file is not None:
61
  if upload_file.size > MAX_FILE_SIZE_BYTES:
62
  st.error(f"Error: The uploaded file is too large. Maximum allowed size is {MAX_FILE_SIZE_KB} KB.")
63
- upload_file = None # Clear the uploaded file to prevent further processing
64
  else:
65
  st.success("File uploaded successfully!")
66
-
67
-
68
-
69
-
70
-
71
-
72
-
73
- if upload_file is not None:
74
- file_extension = upload_file.name.split('.')[-1].lower()
75
- try:
76
- if file_extension == 'csv':
77
- df_original = pd.read_csv(upload_file, na_filter=False)
78
-
79
- elif file_extension == 'xlsx':
80
- df_original = pd.read_excel(upload_file, na_filter=False)
81
-
82
- else:
83
- st.warning("Unsupported file type.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  st.stop()
85
-
86
- if df_original.isnull().values.any():
87
- st.error("Error: The file contains missing values.")
 
 
 
 
 
88
  st.stop()
89
- else:
90
- st.session_state.df_original = df_original
91
-
92
- all_columns = df_original.columns.tolist()
93
- st.divider()
94
- st.write("Select two different columns from your data to visualize in a **Tree Map**. ")
95
-
96
- parent_column = st.selectbox("Select the parent column:", all_columns)
97
- value_column = st.selectbox("Select the value column:", all_columns)
98
-
99
- if parent_column and value_column:
100
- if parent_column == value_column:
101
- st.warning("Warning: You have selected the same column for both the parent and value column. Please select two different columns from your data.")
102
- else:
103
- df_treemap = df_original.copy()
104
- path_columns = [px.Constant("all"), parent_column, value_column]
105
- fig = px.treemap(df_treemap,
106
- path=path_columns)
107
- fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))
108
- st.subheader("Tree Map", divider="blue")
109
- st.plotly_chart(fig)
110
-
111
- st.subheader("Uploaded File", divider="blue")
112
- st.dataframe(df_original, key="uploaded_dataframe")
113
- st.write(f"_Number of rows_: {df_original.shape[0]}")
114
- st.write(f"_Number of columns_: {df_original.shape[1]}")
115
-
116
- except pd.errors.ParserError:
117
- st.error("Error: The CSV file is not readable or is incorrectly formatted.")
118
- st.stop()
119
- except UnicodeDecodeError:
120
- st.error("Error: The CSV file could not be decoded.")
121
- st.stop()
122
- except ValueError:
123
- st.error("Error: The Excel file is not readable or is incorrectly formatted.")
124
- st.stop()
125
- except Exception as e:
126
- st.error(f"An unexpected error occurred: {e}")
127
- st.stop()
128
 
129
  st.divider()
130
-
131
 
132
  def clear_question():
133
  st.session_state["question"] = ""
134
 
135
- question = st.text_input("Type your question here and then press **Retrieve your answer**:", key="question")
136
- st.button("Clear question", on_click=clear_question)
137
 
 
 
 
 
138
 
139
  if st.button("Retrieve your answer"):
140
- if st.session_state['question_attempts'] >= max_attempts:
141
  st.error(f"You have asked {max_attempts} questions. Maximum question attempts reached.")
142
  st.stop()
143
- st.session_state['question_attempts'] += 1
144
-
145
  with st.spinner("Wait for it...", show_time=True):
146
- time.sleep(5)
147
- if df_original is not None:
148
- tqa = pipeline(task="table-question-answering", model="microsoft/tapex-large-finetuned-wtq")
149
- st.write(tqa(table=df_original, query=question)['answer'])
 
 
 
 
 
 
 
 
 
 
 
150
 
151
  st.divider()
152
- st.write(f"Number of questions asked: {st.session_state['question_attempts']}/{max_attempts}")
 
 
153
 
154
 
155
 
 
8
  import plotly.express as px
9
 
10
  st.subheader("AI CSV and XLSX Data Analyzer", divider="blue")
11
+ st.link_button("by nlpblogs", "https://nlpblogs.com", type="tertiary")
12
 
13
  expander = st.expander("**Important notes on the AI CSV and XLSX Data Analyzer**")
14
+ expander.write(
15
+ """
16
+ **Supported File Formats:** This app accepts files in .csv and .xlsx formats.
17
+ **How to Use:** Upload your file first. Select two different columns from your data to visualize in a Tree Map. Then, type your question into the text area provided and click the 'Retrieve your answer' button.
18
+ **Tree Map:** Your uploaded data is presented in an interactive Tree Map for visual exploration. Click on any area within the map to access specific data insights.
19
+ **Usage Limits:** You can ask up to 5 questions.
20
+ **Subscription Management:** This app offers a one-day free trial, followed by a one-day subscription, expiring after 24 hours. If you are interested in building your own AI CSV and XLSX Data Analyzer, 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 info@nlpblogs.com
21
+ **Customization:** 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.
22
+ **File Handling and Errors:** (a) The app may provide an inaccurate answer if the information is missing from the relevant cell. (b) The app may display an error message if your file has errors, date values or float numbers (0.5, 1.2, 4.5 etc.).
23
+ For any errors or inquiries, please contact us at info@nlpblogs.com
24
+ """
25
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  with st.sidebar:
28
  container = st.container(border=True)
29
+ container.write(
30
+ "**Question-Answering (QA)** is the task of retrieving the answer to a question from a given text (knowledge base), which is used as context."
31
+ )
32
+ st.subheader("Related NLP Web Apps", divider="blue")
33
+ st.link_button(
34
+ "AI Google Sheet Data Analyzer",
35
+ "https://nlpblogs.com/shop/table-question-answering-qa/google-sheet-qa-demo-app/",
36
+ type="primary",
37
+ )
38
+
39
+ if "question_attempts" not in st.session_state:
40
+ st.session_state["question_attempts"] = 0
41
  max_attempts = 5
 
42
  MAX_FILE_SIZE_KB = 10
43
  MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_KB * 1024
44
 
45
+ upload_file = st.file_uploader(
46
+ f"Upload your file (max {MAX_FILE_SIZE_KB} KB). Accepted file formats include: .csv, .xlsx",
47
+ type=['csv', 'xlsx']
48
+ )
49
 
50
  if upload_file is not None:
51
  if upload_file.size > MAX_FILE_SIZE_BYTES:
52
  st.error(f"Error: The uploaded file is too large. Maximum allowed size is {MAX_FILE_SIZE_KB} KB.")
 
53
  else:
54
  st.success("File uploaded successfully!")
55
+ file_extension = upload_file.name.split('.')[-1].lower()
56
+ try:
57
+ if file_extension == 'csv':
58
+ df_original = pd.read_csv(upload_file, na_filter=False)
59
+ elif file_extension == 'xlsx':
60
+ df_original = pd.read_excel(upload_file, na_filter=False)
61
+ else:
62
+ st.warning("Unsupported file type.")
63
+ st.stop()
64
+
65
+ if df_original.isnull().values.any():
66
+ st.error("Error: The file contains missing values.")
67
+ st.stop()
68
+ else:
69
+ st.session_state.df_original = df_original
70
+
71
+ all_columns = df_original.columns.tolist()
72
+ st.divider()
73
+ st.write("Select two different columns from your data to visualize in a **Tree Map**. ")
74
+
75
+ parent_column = st.selectbox("Select the parent column:", all_columns)
76
+ value_column = st.selectbox("Select the value column:", all_columns)
77
+ if parent_column and value_column:
78
+ if parent_column == value_column:
79
+ st.warning("Warning: You have selected the same column for both the parent and value column. Please select two different columns from your data.")
80
+ else:
81
+ df_treemap = df_original.copy()
82
+ path_columns = [px.Constant("all"), parent_column, value_column]
83
+ fig = px.treemap(df_treemap, path=path_columns)
84
+ fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))
85
+ st.subheader("Tree Map", divider="blue")
86
+ st.plotly_chart(fig)
87
+ st.subheader("Uploaded File", divider="blue")
88
+ st.dataframe(df_original, key="uploaded_dataframe")
89
+ st.write(f"_Number of rows_: {df_original.shape[0]}")
90
+ st.write(f"_Number of columns_: {df_original.shape[1]}")
91
+
92
+ except pd.errors.ParserError:
93
+ st.error("Error: The CSV file is not readable or is incorrectly formatted.")
94
  st.stop()
95
+ except UnicodeDecodeError:
96
+ st.error("Error: The CSV file could not be decoded.")
97
+ st.stop()
98
+ except ValueError:
99
+ st.error("Error: The Excel file is not readable or is incorrectly formatted.")
100
+ st.stop()
101
+ except Exception as e:
102
+ st.error(f"An unexpected error occurred: {e}")
103
  st.stop()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
  st.divider()
106
+
107
 
108
  def clear_question():
109
  st.session_state["question"] = ""
110
 
 
 
111
 
112
+ question = st.text_input(
113
+ "Type your question here and then press **Retrieve your answer**:", key="question"
114
+ )
115
+ st.button("Clear question", on_click=clear_question)
116
 
117
  if st.button("Retrieve your answer"):
118
+ if st.session_state["question_attempts"] >= max_attempts:
119
  st.error(f"You have asked {max_attempts} questions. Maximum question attempts reached.")
120
  st.stop()
121
+ st.session_state["question_attempts"] += 1
122
+
123
  with st.spinner("Wait for it...", show_time=True):
124
+ time.sleep(5)
125
+
126
+ if "df_original" in st.session_state and st.session_state.df_original is not None:
127
+ tqa = pipeline(
128
+ task="table-question-answering",
129
+ model="microsoft/tapex-large-finetuned-wtq",
130
+ )
131
+ try:
132
+ answer = tqa(table=st.session_state.df_original, query=question)["answer"]
133
+ st.write(answer)
134
+ except Exception as e:
135
+ st.error(f"An error occurred during question answering: {e}")
136
+ st.error(f"Error details: {e}")
137
+ else:
138
+ st.warning("Please upload a file first to ask questions.")
139
 
140
  st.divider()
141
+ st.write(
142
+ f"Number of questions asked: {st.session_state['question_attempts']}/{max_attempts}"
143
+ )
144
 
145
 
146