├── requirements.txt
├── .streamlit
└── config.toml
├── images
├── logo.png
├── HFlogo.png
└── SF_logo_icon.png
├── dashboard_utils
├── .DS_Store
├── __pycache__
│ ├── gui.cpython-310.pyc
│ └── gui.cpython-37.pyc
└── gui.py
├── README.md
├── LICENSE
└── streamlit_app.py
/requirements.txt:
--------------------------------------------------------------------------------
1 | streamlit
2 | streamlit-tags
3 |
--------------------------------------------------------------------------------
/.streamlit/config.toml:
--------------------------------------------------------------------------------
1 | [theme]
2 | base="light"
3 | primaryColor="#29B4E8"
--------------------------------------------------------------------------------
/images/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/streamlit/example-app-zero-shot-text-classifier/HEAD/images/logo.png
--------------------------------------------------------------------------------
/images/HFlogo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/streamlit/example-app-zero-shot-text-classifier/HEAD/images/HFlogo.png
--------------------------------------------------------------------------------
/dashboard_utils/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/streamlit/example-app-zero-shot-text-classifier/HEAD/dashboard_utils/.DS_Store
--------------------------------------------------------------------------------
/images/SF_logo_icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/streamlit/example-app-zero-shot-text-classifier/HEAD/images/SF_logo_icon.png
--------------------------------------------------------------------------------
/dashboard_utils/__pycache__/gui.cpython-310.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/streamlit/example-app-zero-shot-text-classifier/HEAD/dashboard_utils/__pycache__/gui.cpython-310.pyc
--------------------------------------------------------------------------------
/dashboard_utils/__pycache__/gui.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/streamlit/example-app-zero-shot-text-classifier/HEAD/dashboard_utils/__pycache__/gui.cpython-37.pyc
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # 🤗 Zero-shot Text Classifier
3 |
4 | [](https://zero-shot-text-classifier.streamlitapp.com/)
5 |
6 | Classify keyphrases fast and on-the-fly with this mighty app. No ML training needed! Create classifying labels, paste your keyphrases, and you're off! 🚀
7 |
8 | You can set these labels anything, e.g.:
9 | - `Positive`, `Negative` and `Neutral` for sentiment analysis
10 | - `Angry`, `Happy`, `Emotional` for emotion analysis
11 | - `Navigational`, `Transactional`, Informational for intent classification purposes
12 | - Your product range (`Bags`, `Shoes`, `Boots` etc.)
13 |
14 | You decide!
15 |
16 | ### About the app
17 |
18 | - App created by [Datachaz](https://twitter.com/DataChaz) using 🎈[Streamlit](https://streamlit.io/) and [HuggingFace](https://huggingface.co/inference-api)'s [Distilbart-mnli-12-3](https://huggingface.co/valhalla/distilbart-mnli-12-3) model.
19 | - Deployed on [Streamlit Cloud](https://streamlit.io/cloud) ☁️
20 |
21 |
22 |
23 |
24 | ### Questions? Comments?
25 |
26 | Please ask in the [Streamlit community](https://discuss.streamlit.io).
27 |
--------------------------------------------------------------------------------
/dashboard_utils/gui.py:
--------------------------------------------------------------------------------
1 | import streamlit as st
2 |
3 | # Import for keyboard shortcuts
4 | import streamlit.components.v1 as components
5 |
6 | def load_keyboard_class():
7 | """This class enables to render some elements as if they were .
8 | Without this class, currently looks the same as in Streamlit.
9 | Usage:
10 | load_keyboard_class()
11 | st.write(' Press here ', unsafe_allow_html=True)
12 | """
13 | st.write(
14 | """""",
29 | unsafe_allow_html=True,
30 | )
31 |
32 |
33 |
34 |
35 | def keyboard_to_url(
36 | key: str = None,
37 | key_code: int = None,
38 | url: str = None,
39 | ):
40 | """Map a keyboard key to open a new tab with a given URL.
41 | Args:
42 | key (str, optional): Key to trigger (example 'k'). Defaults to None.
43 | key_code (int, optional): If key doesn't work, try hard-coding the key_code instead. Defaults to None.
44 | url (str, optional): Opens the input URL in new tab. Defaults to None.
45 | """
46 |
47 | assert not (
48 | key and key_code
49 | ), """You can not provide key and key_code.
50 | Either give key and we'll try to find its associated key_code. Or directly
51 | provide the key_code."""
52 |
53 | assert (key or key_code) and url, """You must provide key or key_code, and a URL"""
54 |
55 | if key:
56 | key_code_js_row = f"const keyCode = '{key}'.toUpperCase().charCodeAt(0);"
57 | if key_code:
58 | key_code_js_row = f"const keyCode = {key_code};"
59 |
60 | components.html(
61 | f"""
62 |
79 | """,
80 | height=0,
81 | width=0,
82 | )
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/streamlit_app.py:
--------------------------------------------------------------------------------
1 | ############ 1. IMPORTING LIBRARIES ############
2 |
3 | # Import streamlit, requests for API calls, and pandas and numpy for data manipulation
4 |
5 | import streamlit as st
6 | import requests
7 | import pandas as pd
8 | import numpy as np
9 | from streamlit_tags import st_tags # to add labels on the fly!
10 |
11 |
12 | ############ 2. SETTING UP THE PAGE LAYOUT AND TITLE ############
13 |
14 | # `st.set_page_config` is used to display the default layout width, the title of the app, and the emoticon in the browser tab.
15 |
16 | st.set_page_config(
17 | layout="centered", page_title="Zero-Shot Text Classifier", page_icon="❄️"
18 | )
19 |
20 | ############ CREATE THE LOGO AND HEADING ############
21 |
22 | # We create a set of columns to display the logo and the heading next to each other.
23 |
24 |
25 | c1, c2 = st.columns([0.32, 2])
26 |
27 | # The snowflake logo will be displayed in the first column, on the left.
28 |
29 | with c1:
30 |
31 | st.image(
32 | "images/logo.png",
33 | width=85,
34 | )
35 |
36 |
37 | # The heading will be on the right.
38 |
39 | with c2:
40 |
41 | st.caption("")
42 | st.title("Zero-Shot Text Classifier")
43 |
44 |
45 | # We need to set up session state via st.session_state so that app interactions don't reset the app.
46 |
47 | if not "valid_inputs_received" in st.session_state:
48 | st.session_state["valid_inputs_received"] = False
49 |
50 |
51 | ############ SIDEBAR CONTENT ############
52 |
53 | st.sidebar.write("")
54 |
55 | # For elements to be displayed in the sidebar, we need to add the sidebar element in the widget.
56 |
57 | # We create a text input field for users to enter their API key.
58 |
59 | API_KEY = st.sidebar.text_input(
60 | "Enter your HuggingFace API key",
61 | help="Once you created you HuggingFace account, you can get your free API token in your settings page: https://huggingface.co/settings/tokens",
62 | type="password",
63 | )
64 |
65 | # Adding the HuggingFace API inference URL.
66 | API_URL = "https://api-inference.huggingface.co/models/valhalla/distilbart-mnli-12-3"
67 |
68 | # Now, let's create a Python dictionary to store the API headers.
69 | headers = {"Authorization": f"Bearer {API_KEY}"}
70 |
71 |
72 | st.sidebar.markdown("---")
73 |
74 |
75 | # Let's add some info about the app to the sidebar.
76 |
77 | st.sidebar.write(
78 | """
79 |
80 | App created by [Charly Wargnier](https://twitter.com/DataChaz) using [Streamlit](https://streamlit.io/)🎈 and [HuggingFace](https://huggingface.co/inference-api)'s [Distilbart-mnli-12-3](https://huggingface.co/valhalla/distilbart-mnli-12-3) model.
81 |
82 | """
83 | )
84 |
85 |
86 | ############ TABBED NAVIGATION ############
87 |
88 | # First, we're going to create a tabbed navigation for the app via st.tabs()
89 | # tabInfo displays info about the app.
90 | # tabMain displays the main app.
91 |
92 | MainTab, InfoTab = st.tabs(["Main", "Info"])
93 |
94 | with InfoTab:
95 |
96 | st.subheader("What is Streamlit?")
97 | st.markdown(
98 | "[Streamlit](https://streamlit.io) is a Python library that allows the creation of interactive, data-driven web applications in Python."
99 | )
100 |
101 | st.subheader("Resources")
102 | st.markdown(
103 | """
104 | - [Streamlit Documentation](https://docs.streamlit.io/)
105 | - [Cheat sheet](https://docs.streamlit.io/library/cheatsheet)
106 | - [Book](https://www.amazon.com/dp/180056550X) (Getting Started with Streamlit for Data Science)
107 | """
108 | )
109 |
110 | st.subheader("Deploy")
111 | st.markdown(
112 | "You can quickly deploy Streamlit apps using [Streamlit Community Cloud](https://streamlit.io/cloud) in just a few clicks."
113 | )
114 |
115 |
116 | with MainTab:
117 |
118 | # Then, we create a intro text for the app, which we wrap in a st.markdown() widget.
119 |
120 | st.write("")
121 | st.markdown(
122 | """
123 |
124 | Classify keyphrases on the fly with this mighty app. No training needed!
125 |
126 | """
127 | )
128 |
129 | st.write("")
130 |
131 | # Now, we create a form via `st.form` to collect the user inputs.
132 |
133 | # All widget values will be sent to Streamlit in batch.
134 | # It makes the app faster!
135 |
136 | with st.form(key="my_form"):
137 |
138 | ############ ST TAGS ############
139 |
140 | # We initialize the st_tags component with default "labels"
141 |
142 | # Here, we want to classify the text into one of the following user intents:
143 | # Transactional
144 | # Informational
145 | # Navigational
146 |
147 | labels_from_st_tags = st_tags(
148 | value=["Transactional", "Informational", "Navigational"],
149 | maxtags=3,
150 | suggestions=["Transactional", "Informational", "Navigational"],
151 | label="",
152 | )
153 |
154 | # The block of code below is to display some text samples to classify.
155 | # This can of course be replaced with your own text samples.
156 |
157 | # MAX_KEY_PHRASES is a variable that controls the number of phrases that can be pasted:
158 | # The default in this app is 50 phrases. This can be changed to any number you like.
159 |
160 | MAX_KEY_PHRASES = 50
161 |
162 | new_line = "\n"
163 |
164 | pre_defined_keyphrases = [
165 | "I want to buy something",
166 | "We have a question about a product",
167 | "I want a refund through the Google Play store",
168 | "Can I have a discount, please",
169 | "Can I have the link to the product page?",
170 | ]
171 |
172 | # Python list comprehension to create a string from the list of keyphrases.
173 | keyphrases_string = f"{new_line.join(map(str, pre_defined_keyphrases))}"
174 |
175 | # The block of code below displays a text area
176 | # So users can paste their phrases to classify
177 |
178 | text = st.text_area(
179 | # Instructions
180 | "Enter keyphrases to classify",
181 | # 'sample' variable that contains our keyphrases.
182 | keyphrases_string,
183 | # The height
184 | height=200,
185 | # The tooltip displayed when the user hovers over the text area.
186 | help="At least two keyphrases for the classifier to work, one per line, "
187 | + str(MAX_KEY_PHRASES)
188 | + " keyphrases max in 'unlocked mode'. You can tweak 'MAX_KEY_PHRASES' in the code to change this",
189 | key="1",
190 | )
191 |
192 | # The block of code below:
193 |
194 | # 1. Converts the data st.text_area into a Python list.
195 | # 2. It also removes duplicates and empty lines.
196 | # 3. Raises an error if the user has entered more lines than in MAX_KEY_PHRASES.
197 |
198 | text = text.split("\n") # Converts the pasted text to a Python list
199 | linesList = [] # Creates an empty list
200 | for x in text:
201 | linesList.append(x) # Adds each line to the list
202 | linesList = list(dict.fromkeys(linesList)) # Removes dupes
203 | linesList = list(filter(None, linesList)) # Removes empty lines
204 |
205 | if len(linesList) > MAX_KEY_PHRASES:
206 | st.info(
207 | f"❄️ Note that only the first "
208 | + str(MAX_KEY_PHRASES)
209 | + " keyphrases will be reviewed to preserve performance. Fork the repo and tweak 'MAX_KEY_PHRASES' in the code to increase that limit."
210 | )
211 |
212 | linesList = linesList[:MAX_KEY_PHRASES]
213 |
214 | submit_button = st.form_submit_button(label="Submit")
215 |
216 | ############ CONDITIONAL STATEMENTS ############
217 |
218 | # Now, let us add conditional statements to check if users have entered valid inputs.
219 | # E.g. If the user has pressed the 'submit button without text, without labels, and with only one label etc.
220 | # The app will display a warning message.
221 |
222 | if not submit_button and not st.session_state.valid_inputs_received:
223 | st.stop()
224 |
225 | elif submit_button and not text:
226 | st.warning("❄️ There is no keyphrases to classify")
227 | st.session_state.valid_inputs_received = False
228 | st.stop()
229 |
230 | elif submit_button and not labels_from_st_tags:
231 | st.warning("❄️ You have not added any labels, please add some! ")
232 | st.session_state.valid_inputs_received = False
233 | st.stop()
234 |
235 | elif submit_button and len(labels_from_st_tags) == 1:
236 | st.warning("❄️ Please make sure to add at least two labels for classification")
237 | st.session_state.valid_inputs_received = False
238 | st.stop()
239 |
240 | elif submit_button or st.session_state.valid_inputs_received:
241 |
242 | if submit_button:
243 |
244 | # The block of code below if for our session state.
245 | # This is used to store the user's inputs so that they can be used later in the app.
246 |
247 | st.session_state.valid_inputs_received = True
248 |
249 | ############ MAKING THE API CALL ############
250 |
251 | # First, we create a Python function to construct the API call.
252 |
253 | def query(payload):
254 | response = requests.post(API_URL, headers=headers, json=payload)
255 | return response.json()
256 |
257 | # The function will send an HTTP POST request to the API endpoint.
258 | # This function has one argument: the payload
259 | # The payload is the data we want to send to HugggingFace when we make an API request
260 |
261 | # We create a list to store the outputs of the API call
262 |
263 | list_for_api_output = []
264 |
265 | # We create a 'for loop' that iterates through each keyphrase
266 | # An API call will be made every time, for each keyphrase
267 |
268 | # The payload is composed of:
269 | # 1. the keyphrase
270 | # 2. the labels
271 | # 3. the 'wait_for_model' parameter set to "True", to avoid timeouts!
272 |
273 | for row in linesList:
274 | api_json_output = query(
275 | {
276 | "inputs": row,
277 | "parameters": {"candidate_labels": labels_from_st_tags},
278 | "options": {"wait_for_model": True},
279 | }
280 | )
281 |
282 | # Let's have a look at the output of the API call
283 | # st.write(api_json_output)
284 |
285 | # All the results are appended to the empty list we created earlier
286 | list_for_api_output.append(api_json_output)
287 |
288 | # then we'll convert the list to a dataframe
289 | df = pd.DataFrame.from_dict(list_for_api_output)
290 |
291 | st.success("✅ Done!")
292 |
293 | st.caption("")
294 | st.markdown("### Check the results!")
295 | st.caption("")
296 |
297 | # st.write(df)
298 |
299 | ############ DATA WRANGLING ON THE RESULTS ############
300 | # Various data wrangling to get the data in the right format!
301 |
302 | # List comprehension to convert the score from decimals to percentages
303 | f = [[f"{x:.2%}" for x in row] for row in df["scores"]]
304 |
305 | # Join the classification scores to the dataframe
306 | df["classification scores"] = f
307 |
308 | # Rename the column 'sequence' to 'keyphrase'
309 | df.rename(columns={"sequence": "keyphrase"}, inplace=True)
310 |
311 | # The API returns a list of all labels sorted by score. We only want the top label.
312 |
313 | # For that, we need to select the first element in the 'labels' and 'classification scores' lists
314 | df["label"] = df["labels"].str[0]
315 | df["accuracy"] = df["classification scores"].str[0]
316 |
317 | # Drop the columns we don't need
318 | df.drop(["scores", "labels", "classification scores"], inplace=True, axis=1)
319 |
320 | # st.write(df)
321 |
322 | # We need to change the index. Index starts at 0, so we make it start at 1
323 | df.index = np.arange(1, len(df) + 1)
324 |
325 | # Display the dataframe
326 | st.write(df)
327 |
328 | cs, c1 = st.columns([2, 2])
329 |
330 |
331 |
332 |
333 | # The code below is for the download button
334 | # Cache the conversion to prevent computation on every rerun
335 |
336 | with cs:
337 |
338 | @st.experimental_memo
339 | def convert_df(df):
340 | return df.to_csv().encode("utf-8")
341 |
342 | csv = convert_df(df)
343 |
344 | st.caption("")
345 |
346 | st.download_button(
347 | label="Download results",
348 | data=csv,
349 | file_name="classification_results.csv",
350 | mime="text/csv",
351 | )
352 |
353 |
354 |
--------------------------------------------------------------------------------