Spaces:
Running
Running
Ahmad Ammari
commited on
Commit
·
d59f8dc
1
Parent(s):
fab07ce
p4 early warning signs q8a demo app on hf spaces
Browse files
notebooks/zero-shot-classification-pbsp-q8a-azure-gpt35-eval-demo-hf.ipynb
ADDED
@@ -0,0 +1,507 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"id": "f56cc5ad",
|
6 |
+
"metadata": {},
|
7 |
+
"source": [
|
8 |
+
"# NDIS Project - PBSP Scoring - Quality Marker Q8a - Early Warning Signs"
|
9 |
+
]
|
10 |
+
},
|
11 |
+
{
|
12 |
+
"cell_type": "code",
|
13 |
+
"execution_count": null,
|
14 |
+
"id": "a8d844ea",
|
15 |
+
"metadata": {
|
16 |
+
"hide_input": false
|
17 |
+
},
|
18 |
+
"outputs": [],
|
19 |
+
"source": [
|
20 |
+
"import os\n",
|
21 |
+
"from ipywidgets import interact\n",
|
22 |
+
"import ipywidgets as widgets\n",
|
23 |
+
"from IPython.display import display, clear_output, Javascript, HTML\n",
|
24 |
+
"import matplotlib.pyplot as plt\n",
|
25 |
+
"import matplotlib.ticker as mtick\n",
|
26 |
+
"import json\n",
|
27 |
+
"import spacy\n",
|
28 |
+
"from spacy import displacy\n",
|
29 |
+
"import nltk\n",
|
30 |
+
"from nltk import sent_tokenize\n",
|
31 |
+
"from sklearn.feature_extraction import text\n",
|
32 |
+
"from pprint import pprint\n",
|
33 |
+
"import re\n",
|
34 |
+
"from sentence_transformers import SentenceTransformer, util\n",
|
35 |
+
"import pandas as pd\n",
|
36 |
+
"import argilla as rg\n",
|
37 |
+
"from argilla.metrics.text_classification import f1\n",
|
38 |
+
"from setfit import SetFitModel\n",
|
39 |
+
"import joblib\n",
|
40 |
+
"import random\n",
|
41 |
+
"from typing import Dict\n",
|
42 |
+
"import warnings\n",
|
43 |
+
"warnings.filterwarnings('ignore')\n",
|
44 |
+
"%matplotlib inline\n",
|
45 |
+
"from tqdm import tqdm\n",
|
46 |
+
"import time\n",
|
47 |
+
"for i in tqdm(range(15), disable=True):\n",
|
48 |
+
" time.sleep(1)"
|
49 |
+
]
|
50 |
+
},
|
51 |
+
{
|
52 |
+
"cell_type": "code",
|
53 |
+
"execution_count": null,
|
54 |
+
"id": "96b83a1d",
|
55 |
+
"metadata": {},
|
56 |
+
"outputs": [],
|
57 |
+
"source": [
|
58 |
+
"#initializations\n",
|
59 |
+
"model_name = \"setfit-zero-shot-classification-pbsp-q8a-azure-gpt35\"\n",
|
60 |
+
"model = SetFitModel.from_pretrained(f\"aammari/{model_name}\")\n",
|
61 |
+
"\n",
|
62 |
+
"# download nltk 'punkt' if not available\n",
|
63 |
+
"try:\n",
|
64 |
+
" nltk.data.find('tokenizers/punkt')\n",
|
65 |
+
"except LookupError:\n",
|
66 |
+
" nltk.download('punkt')\n",
|
67 |
+
"\n",
|
68 |
+
"# download nltk 'averaged_perceptron_tagger' if not available\n",
|
69 |
+
"try:\n",
|
70 |
+
" nltk.data.find('taggers/averaged_perceptron_tagger')\n",
|
71 |
+
"except LookupError:\n",
|
72 |
+
" nltk.download('averaged_perceptron_tagger')\n",
|
73 |
+
" \n",
|
74 |
+
"#argilla\n",
|
75 |
+
"rg.init(\n",
|
76 |
+
" api_url=os.environ[\"ARGILLA_API_URL\"],\n",
|
77 |
+
" api_key=os.environ[\"ARGILLA_API_KEY\"]\n",
|
78 |
+
")"
|
79 |
+
]
|
80 |
+
},
|
81 |
+
{
|
82 |
+
"cell_type": "code",
|
83 |
+
"execution_count": null,
|
84 |
+
"id": "72c2c6f9",
|
85 |
+
"metadata": {
|
86 |
+
"hide_input": false
|
87 |
+
},
|
88 |
+
"outputs": [],
|
89 |
+
"source": [
|
90 |
+
"#Text Preprocessing\n",
|
91 |
+
"try:\n",
|
92 |
+
" nlp = spacy.load('en_core_web_sm')\n",
|
93 |
+
"except OSError:\n",
|
94 |
+
" spacy.cli.download('en_core_web_sm')\n",
|
95 |
+
" nlp = spacy.load('en_core_web_sm')\n",
|
96 |
+
"sw_lst = text.ENGLISH_STOP_WORDS\n",
|
97 |
+
"def preprocess(onto_lst):\n",
|
98 |
+
" cleaned_onto_lst = []\n",
|
99 |
+
" pattern = re.compile(r'^[a-z ]*$')\n",
|
100 |
+
" for document in onto_lst:\n",
|
101 |
+
" text = []\n",
|
102 |
+
" doc = nlp(document)\n",
|
103 |
+
" person_tokens = []\n",
|
104 |
+
" for w in doc:\n",
|
105 |
+
" if w.ent_type_ == 'PERSON':\n",
|
106 |
+
" person_tokens.append(w.lemma_)\n",
|
107 |
+
" for w in doc:\n",
|
108 |
+
" if not w.is_stop and not w.is_punct and not w.like_num and not len(w.text.strip()) == 0 and not w.lemma_ in person_tokens:\n",
|
109 |
+
" text.append(w.lemma_.lower())\n",
|
110 |
+
" texts = [t for t in text if len(t) > 1 and pattern.search(t) is not None and t not in sw_lst]\n",
|
111 |
+
" cleaned_onto_lst.append(\" \".join(texts))\n",
|
112 |
+
" return cleaned_onto_lst"
|
113 |
+
]
|
114 |
+
},
|
115 |
+
{
|
116 |
+
"cell_type": "code",
|
117 |
+
"execution_count": null,
|
118 |
+
"id": "40070313",
|
119 |
+
"metadata": {},
|
120 |
+
"outputs": [],
|
121 |
+
"source": [
|
122 |
+
"#sentence extraction\n",
|
123 |
+
"def extract_sentences(nltk_query):\n",
|
124 |
+
" sentences = sent_tokenize(nltk_query)\n",
|
125 |
+
" return sentences"
|
126 |
+
]
|
127 |
+
},
|
128 |
+
{
|
129 |
+
"cell_type": "code",
|
130 |
+
"execution_count": null,
|
131 |
+
"id": "1550437b",
|
132 |
+
"metadata": {},
|
133 |
+
"outputs": [],
|
134 |
+
"source": [
|
135 |
+
"#query and get predicted topic\n",
|
136 |
+
"\n",
|
137 |
+
"def get_topic(sentences):\n",
|
138 |
+
" preds = list(model(sentences))\n",
|
139 |
+
" return preds\n",
|
140 |
+
"def get_topic_scores(sentences):\n",
|
141 |
+
" preds = model.predict_proba(sentences)\n",
|
142 |
+
" preds = [max(list(x)) for x in preds]\n",
|
143 |
+
" return preds"
|
144 |
+
]
|
145 |
+
},
|
146 |
+
{
|
147 |
+
"cell_type": "code",
|
148 |
+
"execution_count": null,
|
149 |
+
"id": "e99e5afc",
|
150 |
+
"metadata": {},
|
151 |
+
"outputs": [],
|
152 |
+
"source": [
|
153 |
+
"def convert_df(result_df):\n",
|
154 |
+
" new_df = pd.DataFrame(columns=['text', 'prediction'])\n",
|
155 |
+
" new_df['text'] = result_df['Answer']\n",
|
156 |
+
" new_df['prediction'] = result_df.apply(lambda row: [[row['Topic'], row['Score']]], axis=1)\n",
|
157 |
+
" return new_df"
|
158 |
+
]
|
159 |
+
},
|
160 |
+
{
|
161 |
+
"cell_type": "code",
|
162 |
+
"execution_count": null,
|
163 |
+
"id": "cd6f85fe",
|
164 |
+
"metadata": {},
|
165 |
+
"outputs": [],
|
166 |
+
"source": [
|
167 |
+
"def custom_f1(data: Dict[str, float], title: str):\n",
|
168 |
+
" from plotly.subplots import make_subplots\n",
|
169 |
+
" import plotly.colors\n",
|
170 |
+
" import random\n",
|
171 |
+
"\n",
|
172 |
+
" fig = make_subplots(\n",
|
173 |
+
" rows=2,\n",
|
174 |
+
" cols=1,\n",
|
175 |
+
" subplot_titles=[ \"Overall Model Score\", \"Model Score By Category\", ],\n",
|
176 |
+
" )\n",
|
177 |
+
"\n",
|
178 |
+
" x = ['precision', 'recall', 'f1']\n",
|
179 |
+
" macro_data = [v for k, v in data.items() if \"macro\" in k]\n",
|
180 |
+
" fig.add_bar(\n",
|
181 |
+
" x=x,\n",
|
182 |
+
" y=macro_data,\n",
|
183 |
+
" row=1,\n",
|
184 |
+
" col=1,\n",
|
185 |
+
" )\n",
|
186 |
+
" per_label = {\n",
|
187 |
+
" k: v\n",
|
188 |
+
" for k, v in data.items()\n",
|
189 |
+
" if all(key not in k for key in [\"macro\", \"micro\", \"support\"])\n",
|
190 |
+
" }\n",
|
191 |
+
"\n",
|
192 |
+
" num_labels = int(len(per_label.keys())/3)\n",
|
193 |
+
" fixed_colors = [str(color) for color in plotly.colors.qualitative.Plotly]\n",
|
194 |
+
" colors = random.sample(fixed_colors, num_labels)\n",
|
195 |
+
"\n",
|
196 |
+
" fig.add_bar(\n",
|
197 |
+
" x=[k for k, v in per_label.items()],\n",
|
198 |
+
" y=[v for k, v in per_label.items()],\n",
|
199 |
+
" row=2,\n",
|
200 |
+
" col=1,\n",
|
201 |
+
" marker_color=[colors[int(i/3)] for i in range(0, len(per_label.keys()))]\n",
|
202 |
+
" )\n",
|
203 |
+
" fig.update_layout(showlegend=False, title_text=title)\n",
|
204 |
+
"\n",
|
205 |
+
" return fig"
|
206 |
+
]
|
207 |
+
},
|
208 |
+
{
|
209 |
+
"cell_type": "code",
|
210 |
+
"execution_count": null,
|
211 |
+
"id": "e28f99b4",
|
212 |
+
"metadata": {},
|
213 |
+
"outputs": [],
|
214 |
+
"source": [
|
215 |
+
"def get_null_class_df(sentences, result_df):\n",
|
216 |
+
" sents = result_df['Answer'].tolist()\n",
|
217 |
+
" null_sents = [x for x in sentences if x not in sents]\n",
|
218 |
+
" topics = ['NONE'] * len(null_sents)\n",
|
219 |
+
" scores = [0.90] * len(null_sents)\n",
|
220 |
+
" null_df = pd.DataFrame({'Answer': null_sents, 'Topic': topics, 'Score': scores})\n",
|
221 |
+
" return null_df"
|
222 |
+
]
|
223 |
+
},
|
224 |
+
{
|
225 |
+
"cell_type": "code",
|
226 |
+
"execution_count": null,
|
227 |
+
"id": "02fda761",
|
228 |
+
"metadata": {},
|
229 |
+
"outputs": [],
|
230 |
+
"source": [
|
231 |
+
"# format output\n",
|
232 |
+
"ind_topic_dict = {\n",
|
233 |
+
" 0: 'NONE',\n",
|
234 |
+
" 1: 'EARLY WARNING'\n",
|
235 |
+
" }\n",
|
236 |
+
"\n",
|
237 |
+
"topic_color_dict = {\n",
|
238 |
+
" 'NONE': '#FFB6C1',\n",
|
239 |
+
" 'EARLY WARNING': '#90EE90'\n",
|
240 |
+
" }\n",
|
241 |
+
"\n",
|
242 |
+
"def color(df, color):\n",
|
243 |
+
" return df.style.format({'Score': '{:,.2%}'.format}).bar(subset=['Score'], color=color)\n",
|
244 |
+
"\n",
|
245 |
+
"def annotate_query(highlights, query, topics):\n",
|
246 |
+
" ents = []\n",
|
247 |
+
" for h, t in zip(highlights, topics):\n",
|
248 |
+
" ent_dict = {}\n",
|
249 |
+
" for match in re.finditer(h, query):\n",
|
250 |
+
" ent_dict = {\"start\": match.start(), \"end\": match.end(), \"label\": t}\n",
|
251 |
+
" break\n",
|
252 |
+
" if len(ent_dict.keys()) > 0:\n",
|
253 |
+
" ents.append(ent_dict)\n",
|
254 |
+
" return ents"
|
255 |
+
]
|
256 |
+
},
|
257 |
+
{
|
258 |
+
"cell_type": "code",
|
259 |
+
"execution_count": null,
|
260 |
+
"id": "905eaf2a",
|
261 |
+
"metadata": {},
|
262 |
+
"outputs": [],
|
263 |
+
"source": [
|
264 |
+
"def path_to_image_html(path):\n",
|
265 |
+
" return '<img src=\"'+ path + '\" width=\"30\" height=\"15\" />'\n",
|
266 |
+
"\n",
|
267 |
+
"final_passing = 0.0\n",
|
268 |
+
"def display_final_df(agg_df):\n",
|
269 |
+
" tags = []\n",
|
270 |
+
" crits = [\n",
|
271 |
+
" 'EARLY WARNING'\n",
|
272 |
+
" ]\n",
|
273 |
+
" orig_crits = crits\n",
|
274 |
+
" crits = [x for x in crits if x in agg_df.index.tolist()]\n",
|
275 |
+
" bools = [agg_df.loc[crit, 'Final_Score'] > final_passing for crit in crits]\n",
|
276 |
+
" paths = ['./thumbs_up.png' if x else './thumbs_down.png' for x in bools]\n",
|
277 |
+
" df = pd.DataFrame({'Life Event': crits, 'USED': paths})\n",
|
278 |
+
" rem_crits = [x for x in orig_crits if x not in crits]\n",
|
279 |
+
" if len(rem_crits) > 0:\n",
|
280 |
+
" df2 = pd.DataFrame({'Life Event': rem_crits, 'USED': ['./thumbs_down.png'] * len(rem_crits)})\n",
|
281 |
+
" df = pd.concat([df, df2])\n",
|
282 |
+
" df = df.set_index('Life Event')\n",
|
283 |
+
" pd.set_option('display.max_colwidth', None)\n",
|
284 |
+
" display(HTML('<div style=\"text-align: center;\">' + df.to_html(classes=[\"align-center\"], index=True, escape=False ,formatters=dict(USED=path_to_image_html)) + '</div>'))\n",
|
285 |
+
" "
|
286 |
+
]
|
287 |
+
},
|
288 |
+
{
|
289 |
+
"cell_type": "markdown",
|
290 |
+
"id": "2c6e9fe7",
|
291 |
+
"metadata": {},
|
292 |
+
"source": [
|
293 |
+
"### Question:\n",
|
294 |
+
"\n",
|
295 |
+
"#### Please outline the strategies that will be implemented to de-escalate the focus person’s target behaviour(s). \n",
|
296 |
+
"##### This section should focus on: Strategies to address early warning signs.\n",
|
297 |
+
"\n",
|
298 |
+
"### Quality Marker Q8a:\n",
|
299 |
+
"\n",
|
300 |
+
"#### A set of early warning signs for the target behaviour(s) are identified for the purposes of de-escalation"
|
301 |
+
]
|
302 |
+
},
|
303 |
+
{
|
304 |
+
"cell_type": "code",
|
305 |
+
"execution_count": null,
|
306 |
+
"id": "76dd8cab",
|
307 |
+
"metadata": {
|
308 |
+
"scrolled": false
|
309 |
+
},
|
310 |
+
"outputs": [],
|
311 |
+
"source": [
|
312 |
+
"#demo with Voila\n",
|
313 |
+
"\n",
|
314 |
+
"bhvr_label = widgets.Label(value='Please type your answer:')\n",
|
315 |
+
"bhvr_text_input = widgets.Textarea(\n",
|
316 |
+
" value='',\n",
|
317 |
+
" placeholder='Type your answer',\n",
|
318 |
+
" description='',\n",
|
319 |
+
" disabled=False,\n",
|
320 |
+
" layout={'height': '300px', 'width': '90%'}\n",
|
321 |
+
")\n",
|
322 |
+
"\n",
|
323 |
+
"bhvr_nlp_btn = widgets.Button(\n",
|
324 |
+
" description='Score Answer',\n",
|
325 |
+
" disabled=False,\n",
|
326 |
+
" button_style='success', # 'success', 'info', 'warning', 'danger' or ''\n",
|
327 |
+
" tooltip='Score Answer',\n",
|
328 |
+
" icon='check',\n",
|
329 |
+
" layout={'height': '70px', 'width': '250px'}\n",
|
330 |
+
")\n",
|
331 |
+
"bhvr_agr_btn = widgets.Button(\n",
|
332 |
+
" description='Validate Data',\n",
|
333 |
+
" disabled=False,\n",
|
334 |
+
" button_style='success', # 'success', 'info', 'warning', 'danger' or ''\n",
|
335 |
+
" tooltip='Validate Data',\n",
|
336 |
+
" icon='check',\n",
|
337 |
+
" layout={'height': '70px', 'width': '250px'}\n",
|
338 |
+
")\n",
|
339 |
+
"bhvr_eval_btn = widgets.Button(\n",
|
340 |
+
" description='Evaluate Model',\n",
|
341 |
+
" disabled=False,\n",
|
342 |
+
" button_style='success', # 'success', 'info', 'warning', 'danger' or ''\n",
|
343 |
+
" tooltip='Evaluate Model',\n",
|
344 |
+
" icon='check',\n",
|
345 |
+
" layout={'height': '70px', 'width': '250px'}\n",
|
346 |
+
")\n",
|
347 |
+
"btn_box = widgets.HBox([bhvr_nlp_btn, bhvr_agr_btn, bhvr_eval_btn], \n",
|
348 |
+
" layout={'width': '100%', 'height': '160%'})\n",
|
349 |
+
"bhvr_outt = widgets.Output()\n",
|
350 |
+
"bhvr_outt.layout.height = '100%'\n",
|
351 |
+
"bhvr_outt.layout.width = '100%'\n",
|
352 |
+
"bhvr_box = widgets.VBox([bhvr_text_input, btn_box, bhvr_outt], \n",
|
353 |
+
" layout={'width': '100%', 'height': '160%'})\n",
|
354 |
+
"dataset_rg_name = 'pbsp-page4-q8a-argilla-ds'\n",
|
355 |
+
"agrilla_df = None\n",
|
356 |
+
"annotated = False\n",
|
357 |
+
"def on_bhvr_button_next(b):\n",
|
358 |
+
" global agrilla_df\n",
|
359 |
+
" with bhvr_outt:\n",
|
360 |
+
" clear_output()\n",
|
361 |
+
" query = bhvr_text_input.value\n",
|
362 |
+
" fake_query = 'This is just a fake query to avoid ValueError'\n",
|
363 |
+
" sentences = extract_sentences(query)\n",
|
364 |
+
" cl_sentences = preprocess(sentences)\n",
|
365 |
+
" topic_inds = get_topic([query, fake_query])\n",
|
366 |
+
" topics = [ind_topic_dict[i] for i in topic_inds]\n",
|
367 |
+
" scores = get_topic_scores([query, fake_query])\n",
|
368 |
+
" result_df = pd.DataFrame({'Answer': [query, fake_query], 'Topic': topics, 'Score': scores})\n",
|
369 |
+
" sub_result_df = result_df[result_df['Topic'] != 'NONE']\n",
|
370 |
+
" sub_2_result_df = get_null_class_df([query, fake_query], sub_result_df)\n",
|
371 |
+
" highlights = []\n",
|
372 |
+
" if len(sub_result_df) > 0:\n",
|
373 |
+
" highlights = sub_result_df['Answer'].tolist()\n",
|
374 |
+
" highlight_topics = sub_result_df['Topic'].tolist() \n",
|
375 |
+
" ents = annotate_query(highlights, query, highlight_topics)\n",
|
376 |
+
" colors = {}\n",
|
377 |
+
" for ent, ht in zip(ents, highlight_topics):\n",
|
378 |
+
" colors[ent['label']] = topic_color_dict[ht]\n",
|
379 |
+
"\n",
|
380 |
+
" ex = [{\"text\": query,\n",
|
381 |
+
" \"ents\": ents,\n",
|
382 |
+
" \"title\": None}]\n",
|
383 |
+
" title = \"Warning Sign Highlights\"\n",
|
384 |
+
" display(HTML(f'<center><h1>{title}</h1></center>'))\n",
|
385 |
+
" html = displacy.render(ex, style=\"ent\", manual=True, jupyter=True, options={'colors': colors})\n",
|
386 |
+
" display(HTML(html))\n",
|
387 |
+
" title = \"Warning Sign Classifications\"\n",
|
388 |
+
" display(HTML(f'<center><h1>{title}</h1></center>'))\n",
|
389 |
+
" for top in topic_color_dict.keys():\n",
|
390 |
+
" top_result_df = sub_result_df[sub_result_df['Topic'] == top]\n",
|
391 |
+
" if len(top_result_df) > 0:\n",
|
392 |
+
" top_result_df = top_result_df.sort_values(by='Score', ascending=False).reset_index(drop=True)\n",
|
393 |
+
" top_result_df = top_result_df.set_index('Answer')\n",
|
394 |
+
" top_result_df = top_result_df[['Score']]\n",
|
395 |
+
" display(HTML(\n",
|
396 |
+
" f'<left><h2 style=\"text-decoration: underline; text-decoration-color:{topic_color_dict[top]};\">{top}</h2></left>'))\n",
|
397 |
+
" display(color(top_result_df, topic_color_dict[top]))\n",
|
398 |
+
" \n",
|
399 |
+
" agg_df = sub_result_df.groupby('Topic')['Score'].sum()\n",
|
400 |
+
" agg_df = agg_df.to_frame()\n",
|
401 |
+
" agg_df.index.name = 'Topic'\n",
|
402 |
+
" agg_df.columns = ['Total Score']\n",
|
403 |
+
" agg_df = agg_df.assign(\n",
|
404 |
+
" Final_Score=lambda x: x['Total Score'] / x['Total Score'].sum() * 100.00\n",
|
405 |
+
" )\n",
|
406 |
+
" agg_df = agg_df.sort_values(by='Final_Score', ascending=False)\n",
|
407 |
+
" agg_df['Topic'] = agg_df.index\n",
|
408 |
+
" rem_topics= [x for x in list(topic_color_dict.keys()) if not x in agg_df.Topic.tolist()]\n",
|
409 |
+
" if len(rem_topics) > 0:\n",
|
410 |
+
" rem_agg_df = pd.DataFrame({'Topic': rem_topics, 'Final_Score': 0.0, 'Total Score': 0.0})\n",
|
411 |
+
" agg_df = pd.concat([agg_df, rem_agg_df])\n",
|
412 |
+
" title = \"Final Scores\"\n",
|
413 |
+
" display(HTML(f'<left><h1>{title}</h1></left>'))\n",
|
414 |
+
" display_final_df(agg_df)\n",
|
415 |
+
" if len(sub_2_result_df) > 0:\n",
|
416 |
+
" sub_result_df = pd.concat([sub_result_df, sub_2_result_df]).reset_index(drop=True)\n",
|
417 |
+
" agrilla_df = sub_result_df.copy()\n",
|
418 |
+
" else:\n",
|
419 |
+
" print(query)\n",
|
420 |
+
"\n",
|
421 |
+
"def on_agr_button_next(b):\n",
|
422 |
+
" global agrilla_df, annotated\n",
|
423 |
+
" with bhvr_outt:\n",
|
424 |
+
" clear_output()\n",
|
425 |
+
" if agrilla_df is not None:\n",
|
426 |
+
" # convert the dataframe to the structure accepted by argilla\n",
|
427 |
+
" converted_df = convert_df(agrilla_df)\n",
|
428 |
+
" # convert pandas dataframe to DatasetForTextClassification\n",
|
429 |
+
" dataset_rg = rg.DatasetForTextClassification.from_pandas(converted_df)\n",
|
430 |
+
" # delete the old DatasetForTextClassification from the Argilla web app if exists\n",
|
431 |
+
" rg.delete(dataset_rg_name, workspace=\"admin\")\n",
|
432 |
+
" # load the new DatasetForTextClassification into the Argilla web app\n",
|
433 |
+
" rg.log(dataset_rg, name=dataset_rg_name, workspace=\"admin\")\n",
|
434 |
+
" # Make sure all classes are present for annotation\n",
|
435 |
+
" rg_settings = rg.TextClassificationSettings(label_schema=list(topic_color_dict.keys()))\n",
|
436 |
+
" rg.configure_dataset(name=dataset_rg_name, workspace=\"admin\", settings=rg_settings)\n",
|
437 |
+
" annotated = True\n",
|
438 |
+
" else:\n",
|
439 |
+
" display(Markdown(\"<h2 style='color:red; text-align:center;'>Please score the answer first!</h2>\"))\n",
|
440 |
+
" \n",
|
441 |
+
"def on_eval_button_next(b):\n",
|
442 |
+
" global annotated\n",
|
443 |
+
" with bhvr_outt:\n",
|
444 |
+
" clear_output()\n",
|
445 |
+
" if annotated:\n",
|
446 |
+
" data = dict(f1(dataset_rg_name))['data']\n",
|
447 |
+
" display(custom_f1(data, \"Model Evaluation Results\"))\n",
|
448 |
+
" else:\n",
|
449 |
+
" display(Markdown(\"<h2 style='color:red; text-align:center;'>Please score the answer and validate the data first!</h2>\"))\n",
|
450 |
+
"\n",
|
451 |
+
"bhvr_nlp_btn.on_click(on_bhvr_button_next)\n",
|
452 |
+
"bhvr_agr_btn.on_click(on_agr_button_next)\n",
|
453 |
+
"bhvr_eval_btn.on_click(on_eval_button_next)\n",
|
454 |
+
"\n",
|
455 |
+
"display(bhvr_label, bhvr_box)"
|
456 |
+
]
|
457 |
+
},
|
458 |
+
{
|
459 |
+
"cell_type": "code",
|
460 |
+
"execution_count": null,
|
461 |
+
"id": "ed551eba",
|
462 |
+
"metadata": {},
|
463 |
+
"outputs": [],
|
464 |
+
"source": []
|
465 |
+
}
|
466 |
+
],
|
467 |
+
"metadata": {
|
468 |
+
"hide_input": false,
|
469 |
+
"kernelspec": {
|
470 |
+
"display_name": "Python 3.9 (Argilla)",
|
471 |
+
"language": "python",
|
472 |
+
"name": "argilla"
|
473 |
+
},
|
474 |
+
"language_info": {
|
475 |
+
"codemirror_mode": {
|
476 |
+
"name": "ipython",
|
477 |
+
"version": 3
|
478 |
+
},
|
479 |
+
"file_extension": ".py",
|
480 |
+
"mimetype": "text/x-python",
|
481 |
+
"name": "python",
|
482 |
+
"nbconvert_exporter": "python",
|
483 |
+
"pygments_lexer": "ipython3",
|
484 |
+
"version": "3.9.16"
|
485 |
+
},
|
486 |
+
"toc": {
|
487 |
+
"base_numbering": 1,
|
488 |
+
"nav_menu": {},
|
489 |
+
"number_sections": false,
|
490 |
+
"sideBar": true,
|
491 |
+
"skip_h1_title": true,
|
492 |
+
"title_cell": "Table of Contents",
|
493 |
+
"title_sidebar": "Contents",
|
494 |
+
"toc_cell": false,
|
495 |
+
"toc_position": {
|
496 |
+
"height": "calc(100% - 180px)",
|
497 |
+
"left": "10px",
|
498 |
+
"top": "150px",
|
499 |
+
"width": "258.097px"
|
500 |
+
},
|
501 |
+
"toc_section_display": true,
|
502 |
+
"toc_window_display": false
|
503 |
+
}
|
504 |
+
},
|
505 |
+
"nbformat": 4,
|
506 |
+
"nbformat_minor": 5
|
507 |
+
}
|