sijieye commited on
Commit
4d17192
1 Parent(s): 3a47a19

Upload app files

Browse files
Files changed (4) hide show
  1. app.ipynb +483 -0
  2. app.py +396 -0
  3. best_model_fold2.h5 +3 -0
  4. requirements.txt +100 -0
app.ipynb ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "import numpy as np\n",
10
+ "import tensorflow as tf\n",
11
+ "import tensorflow_addons as tfa\n",
12
+ "from tensorflow.keras import layers\n",
13
+ "import transformers\n",
14
+ "import sentencepiece as spm\n",
15
+ "#show the version of the package imported with text instructions\\\n",
16
+ "print(\"Tensorflow version: \", tf.__version__)\n",
17
+ "print(\"Tensorflow Addons version: \", tfa.__version__)\n",
18
+ "print(\"Transformers version: \", transformers.__version__)\n",
19
+ "print(\"Sentencepiece version: \", spm.__version__)\n",
20
+ "print(\"Numpy version: \", np.__version__)"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": null,
26
+ "metadata": {},
27
+ "outputs": [],
28
+ "source": [
29
+ "class MeanPool(tf.keras.layers.Layer):\n",
30
+ " def call(self, inputs, mask=None):\n",
31
+ " broadcast_mask = tf.expand_dims(tf.cast(mask, \"float32\"), -1)\n",
32
+ " embedding_sum = tf.reduce_sum(inputs * broadcast_mask, axis=1)\n",
33
+ " mask_sum = tf.reduce_sum(broadcast_mask, axis=1)\n",
34
+ " mask_sum = tf.math.maximum(mask_sum, tf.constant([1e-9]))\n",
35
+ " return embedding_sum / mask_sum\n",
36
+ "class WeightsSumOne(tf.keras.constraints.Constraint):\n",
37
+ " def __call__(self, w):\n",
38
+ " return tf.nn.softmax(w, axis=0)"
39
+ ]
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "execution_count": null,
44
+ "metadata": {},
45
+ "outputs": [],
46
+ "source": [
47
+ "tokenizer = transformers.AutoTokenizer.from_pretrained(\"microsoft/deberta-v3-large\"\n",
48
+ ")\n",
49
+ "tokenizer.save_pretrained('./tokenizer/')\n",
50
+ "\n",
51
+ "cfg = transformers.AutoConfig.from_pretrained(\"microsoft/deberta-v3-large\", output_hidden_states=True)\n",
52
+ "cfg.hidden_dropout_prob = 0\n",
53
+ "cfg.attention_probs_dropout_prob = 0\n",
54
+ "cfg.save_pretrained('./tokenizer/')"
55
+ ]
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "execution_count": null,
60
+ "metadata": {},
61
+ "outputs": [],
62
+ "source": [
63
+ "def deberta_encode(texts, tokenizer=tokenizer):\n",
64
+ " input_ids = []\n",
65
+ " attention_mask = []\n",
66
+ " \n",
67
+ " for text in texts:\n",
68
+ " token = tokenizer(text, \n",
69
+ " add_special_tokens=True, \n",
70
+ " max_length=512, \n",
71
+ " return_attention_mask=True, \n",
72
+ " return_tensors=\"np\", \n",
73
+ " truncation=True, \n",
74
+ " padding='max_length')\n",
75
+ " input_ids.append(token['input_ids'][0])\n",
76
+ " attention_mask.append(token['attention_mask'][0])\n",
77
+ " \n",
78
+ " return np.array(input_ids, dtype=\"int32\"), np.array(attention_mask, dtype=\"int32\")"
79
+ ]
80
+ },
81
+ {
82
+ "cell_type": "code",
83
+ "execution_count": null,
84
+ "metadata": {},
85
+ "outputs": [],
86
+ "source": [
87
+ "MAX_LENGTH=512\n",
88
+ "BATCH_SIZE=8"
89
+ ]
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "execution_count": null,
94
+ "metadata": {},
95
+ "outputs": [],
96
+ "source": [
97
+ "def get_model():\n",
98
+ " input_ids = tf.keras.layers.Input(\n",
99
+ " shape=(MAX_LENGTH,), dtype=tf.int32, name=\"input_ids\"\n",
100
+ " )\n",
101
+ " \n",
102
+ " attention_masks = tf.keras.layers.Input(\n",
103
+ " shape=(MAX_LENGTH,), dtype=tf.int32, name=\"attention_masks\"\n",
104
+ " )\n",
105
+ " \n",
106
+ " deberta_model = transformers.TFAutoModel.from_pretrained(\"microsoft/deberta-v3-large\", config=cfg)\n",
107
+ " \n",
108
+ " \n",
109
+ " REINIT_LAYERS = 1\n",
110
+ " normal_initializer = tf.keras.initializers.GlorotUniform()\n",
111
+ " zeros_initializer = tf.keras.initializers.Zeros()\n",
112
+ " ones_initializer = tf.keras.initializers.Ones()\n",
113
+ "\n",
114
+ "# print(f'\\nRe-initializing encoder block:')\n",
115
+ " for encoder_block in deberta_model.deberta.encoder.layer[-REINIT_LAYERS:]:\n",
116
+ "# print(f'{encoder_block}')\n",
117
+ " for layer in encoder_block.submodules:\n",
118
+ " if isinstance(layer, tf.keras.layers.Dense):\n",
119
+ " layer.kernel.assign(normal_initializer(shape=layer.kernel.shape, dtype=layer.kernel.dtype))\n",
120
+ " if layer.bias is not None:\n",
121
+ " layer.bias.assign(zeros_initializer(shape=layer.bias.shape, dtype=layer.bias.dtype))\n",
122
+ "\n",
123
+ " elif isinstance(layer, tf.keras.layers.LayerNormalization):\n",
124
+ " layer.beta.assign(zeros_initializer(shape=layer.beta.shape, dtype=layer.beta.dtype))\n",
125
+ " layer.gamma.assign(ones_initializer(shape=layer.gamma.shape, dtype=layer.gamma.dtype))\n",
126
+ "\n",
127
+ " deberta_output = deberta_model.deberta(\n",
128
+ " input_ids, attention_mask=attention_masks\n",
129
+ " )\n",
130
+ " hidden_states = deberta_output.hidden_states\n",
131
+ " \n",
132
+ " #WeightedLayerPool + MeanPool of the last 4 hidden states\n",
133
+ " stack_meanpool = tf.stack(\n",
134
+ " [MeanPool()(hidden_s, mask=attention_masks) for hidden_s in hidden_states[-4:]], \n",
135
+ " axis=2)\n",
136
+ " \n",
137
+ " weighted_layer_pool = layers.Dense(1,\n",
138
+ " use_bias=False,\n",
139
+ " kernel_constraint=WeightsSumOne())(stack_meanpool)\n",
140
+ " \n",
141
+ " weighted_layer_pool = tf.squeeze(weighted_layer_pool, axis=-1)\n",
142
+ " output=layers.Dense(15,activation='linear')(weighted_layer_pool)\n",
143
+ " #x = layers.Dense(6, activation='linear')(x)\n",
144
+ " \n",
145
+ " #output = layers.Rescaling(scale=4.0, offset=1.0)(x)\n",
146
+ " model = tf.keras.Model(inputs=[input_ids, attention_masks], outputs=output)\n",
147
+ " \n",
148
+ " #Compile model with Layer-wise Learning Rate Decay\n",
149
+ " layer_list = [deberta_model.deberta.embeddings] + list(deberta_model.deberta.encoder.layer)\n",
150
+ " layer_list.reverse()\n",
151
+ " \n",
152
+ " INIT_LR = 1e-5\n",
153
+ " LLRDR = 0.9\n",
154
+ " LR_SCH_DECAY_STEPS = 1600\n",
155
+ " \n",
156
+ " lr_schedules = [tf.keras.optimizers.schedules.ExponentialDecay(\n",
157
+ " initial_learning_rate=INIT_LR * LLRDR ** i, \n",
158
+ " decay_steps=LR_SCH_DECAY_STEPS, \n",
159
+ " decay_rate=0.3) for i in range(len(layer_list))]\n",
160
+ " lr_schedule_head = tf.keras.optimizers.schedules.ExponentialDecay(\n",
161
+ " initial_learning_rate=1e-4, \n",
162
+ " decay_steps=LR_SCH_DECAY_STEPS, \n",
163
+ " decay_rate=0.3)\n",
164
+ " \n",
165
+ " optimizers = [tf.keras.optimizers.Adam(learning_rate=lr_sch) for lr_sch in lr_schedules]\n",
166
+ " \n",
167
+ " optimizers_and_layers = [(tf.keras.optimizers.Adam(learning_rate=lr_schedule_head), model.layers[-4:])] +\\\n",
168
+ " list(zip(optimizers, layer_list))\n",
169
+ " \n",
170
+ " optimizer = tfa.optimizers.MultiOptimizer(optimizers_and_layers)\n",
171
+ " \n",
172
+ " model.compile(optimizer=optimizer,\n",
173
+ " loss='mse',\n",
174
+ " metrics=[tf.keras.metrics.RootMeanSquaredError()],\n",
175
+ " )\n",
176
+ " return model"
177
+ ]
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "execution_count": null,
182
+ "metadata": {},
183
+ "outputs": [],
184
+ "source": [
185
+ "tf.keras.backend.clear_session()\n",
186
+ "model = get_model()\n",
187
+ "model.load_weights('./best_model_fold2.h5')"
188
+ ]
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "execution_count": null,
193
+ "metadata": {},
194
+ "outputs": [],
195
+ "source": []
196
+ },
197
+ {
198
+ "cell_type": "code",
199
+ "execution_count": null,
200
+ "metadata": {},
201
+ "outputs": [],
202
+ "source": [
203
+ "# map the integer labels to their original string representation\n",
204
+ "label_mapping = {\n",
205
+ " 0: 'Greeting',\n",
206
+ " 1: 'Curiosity',\n",
207
+ " 2: 'Interest',\n",
208
+ " 3: 'Obscene',\n",
209
+ " 4: 'Annoyed',\n",
210
+ " 5: 'Openness',\n",
211
+ " 6: 'Anxious',\n",
212
+ " 7: 'Acceptance',\n",
213
+ " 8: 'Uninterested',\n",
214
+ " 9: 'Informative',\n",
215
+ " 10: 'Accusatory',\n",
216
+ " 11: 'Denial',\n",
217
+ " 12: 'Confused',\n",
218
+ " 13: 'Disapproval',\n",
219
+ " 14: 'Remorse'\n",
220
+ "}\n",
221
+ "\n",
222
+ "#label_strings = [label_mapping[label] for label in labels]\n",
223
+ "\n",
224
+ "#print(label_strings)"
225
+ ]
226
+ },
227
+ {
228
+ "cell_type": "code",
229
+ "execution_count": null,
230
+ "metadata": {},
231
+ "outputs": [],
232
+ "source": [
233
+ "def inference(texts):\n",
234
+ " prediction = model.predict(deberta_encode([texts]))\n",
235
+ " labels = np.argmax(prediction, axis=1)\n",
236
+ " label_strings = [label_mapping[label] for label in labels]\n",
237
+ " return label_strings[0]"
238
+ ]
239
+ },
240
+ {
241
+ "cell_type": "markdown",
242
+ "metadata": {},
243
+ "source": [
244
+ "# GPT"
245
+ ]
246
+ },
247
+ {
248
+ "cell_type": "code",
249
+ "execution_count": null,
250
+ "metadata": {},
251
+ "outputs": [],
252
+ "source": [
253
+ "import openai\n",
254
+ "import os\n",
255
+ "import pandas as pd\n",
256
+ "import gradio as gr"
257
+ ]
258
+ },
259
+ {
260
+ "cell_type": "code",
261
+ "execution_count": null,
262
+ "metadata": {},
263
+ "outputs": [],
264
+ "source": [
265
+ "openai.organization = os.environ['org_id']\n",
266
+ "openai.api_key = os.environ['openai_api']\n",
267
+ "model_version = \"gpt-3.5-turbo\"\n",
268
+ "model_token_limit = 10\n",
269
+ "model_temperature = 0.1\n"
270
+ ]
271
+ },
272
+ {
273
+ "cell_type": "code",
274
+ "execution_count": null,
275
+ "metadata": {},
276
+ "outputs": [],
277
+ "source": [
278
+ "def generatePrompt () :\n",
279
+ " labels = [\"Openness\", \n",
280
+ " \"Anxious\",\n",
281
+ " \"Confused\",\n",
282
+ " \"Disapproval\",\n",
283
+ " \"Remorse\",\n",
284
+ " \"Uninterested\",\n",
285
+ " \"Accusatory\",\n",
286
+ " \"Annoyed\",\n",
287
+ " \"Interest\",\n",
288
+ " \"Curiosity\",\n",
289
+ " \"Acceptance\",\n",
290
+ " \"Obscene\",\n",
291
+ " \"Denial\",\n",
292
+ " \"Informative\",\n",
293
+ " \"Greeting\"]\n",
294
+ "\n",
295
+ " formatted_labels = ', '.join(labels[:-1]) + ', or ' + labels[-1] + '.'\n",
296
+ "\n",
297
+ " label_set = [\"Openness\", \"Anxious\", \"Confused\", \"Disapproval\", \"Remorse\", \"Accusatory\",\n",
298
+ " \"Denial\", \"Obscene\", \"Uninterested\", \"Annoyed\", \"Informative\", \"Greeting\",\n",
299
+ " \"Interest\", \"Curiosity\", \"Acceptance\"]\n",
300
+ "\n",
301
+ " formatted_labels = ', '.join(label_set[:-1]) + ', or ' + label_set[-1] + '.\\n'\n",
302
+ "\n",
303
+ " # The basic task to assign GPT (in natural language)\n",
304
+ " base_task = \"Classify the following text messages into one of the following categories using one word: \" + formatted_labels\n",
305
+ " base_task += \"Provide only a one word response. Use only the labels provided.\\n\"\n",
306
+ "\n",
307
+ " return base_task"
308
+ ]
309
+ },
310
+ {
311
+ "cell_type": "code",
312
+ "execution_count": null,
313
+ "metadata": {},
314
+ "outputs": [],
315
+ "source": [
316
+ "def predict(message):\n",
317
+ " \n",
318
+ " prompt = [{\"role\": \"user\", \"content\": generatePrompt () + \"Text: \"+ message}]\n",
319
+ " \n",
320
+ " response = openai.ChatCompletion.create(\n",
321
+ " model=model_version,\n",
322
+ " temperature=model_temperature,\n",
323
+ " max_tokens=model_token_limit,\n",
324
+ " messages=prompt\n",
325
+ " )\n",
326
+ " \n",
327
+ " return response[\"choices\"][0][\"message\"][\"content\"]"
328
+ ]
329
+ },
330
+ {
331
+ "cell_type": "markdown",
332
+ "metadata": {},
333
+ "source": [
334
+ "# Update"
335
+ ]
336
+ },
337
+ {
338
+ "cell_type": "code",
339
+ "execution_count": null,
340
+ "metadata": {},
341
+ "outputs": [],
342
+ "source": [
343
+ "model_version = \"gpt-3.5-turbo\"\n",
344
+ "model_token_limit = 2000\n",
345
+ "model_temperature = 0.1"
346
+ ]
347
+ },
348
+ {
349
+ "cell_type": "code",
350
+ "execution_count": null,
351
+ "metadata": {},
352
+ "outputs": [],
353
+ "source": [
354
+ "def revision(message):\n",
355
+ " base_prompt = \"Here is a conversation between a Caller and a Volunteer. The Volunteer is trying to be as non-accusatory as possible but also wants to get as much information about the caller as possible. What should the volunteer say next in this exchange? Proved 3 possible responses.\"\n",
356
+ "\n",
357
+ " prompt = [{\"role\": \"user\", \"content\": base_prompt + message}]\n",
358
+ " \n",
359
+ " response = openai.ChatCompletion.create(\n",
360
+ " model=model_version,\n",
361
+ " temperature=model_temperature,\n",
362
+ " max_tokens=model_token_limit,\n",
363
+ " messages=prompt\n",
364
+ " )\n",
365
+ "\n",
366
+ " return response[\"choices\"][0][\"message\"][\"content\"]"
367
+ ]
368
+ },
369
+ {
370
+ "cell_type": "code",
371
+ "execution_count": null,
372
+ "metadata": {},
373
+ "outputs": [],
374
+ "source": [
375
+ "import gradio as gr\n",
376
+ "\n",
377
+ "def combine(a):\n",
378
+ " return a + \"hello\"\n",
379
+ "\n",
380
+ "\n",
381
+ "\n",
382
+ "\n",
383
+ "with gr.Blocks() as demo:\n",
384
+ " gr.Markdown(\"## DeBERTa Sentiment Analysis\")\n",
385
+ " gr.Markdown(\"This is a custom DeBERTa model architecture for sentiment analysis with 15 labels: Openness, Anxiety, Confusion, Disapproval, Remorse, Accusation, Denial, Obscenity, Disinterest, Annoyance, Information, Greeting, Interest, Curiosity, or Acceptance.<br />Please enter your sentence(s) in the input box below and click the Submit button. The model will then process the input and provide the sentiment in one of the labels.<br/>The Test Example section below provides some input examples. Click on them and submit them to the model to see how it works.\")\n",
386
+ "\n",
387
+ " txt = gr.Textbox(label=\"Input\", lines=2)\n",
388
+ " txt_1 = gr.Textbox(value=\"\", label=\"Output\")\n",
389
+ " btn = gr.Button(value=\"Submit\")\n",
390
+ " btn.click(inference, inputs=txt, outputs= txt_1)\n",
391
+ "\n",
392
+ " demoExample = [\n",
393
+ " \"Hello, how are you?\",\n",
394
+ " \"I am so happy to be here!\",\n",
395
+ " \"i don't have time for u\"\n",
396
+ " ]\n",
397
+ "\n",
398
+ " gr.Markdown(\"## Text Examples\")\n",
399
+ " gr.Examples(\n",
400
+ " demoExample,\n",
401
+ " txt,\n",
402
+ " txt_1,\n",
403
+ " inference\n",
404
+ " )\n",
405
+ "\n",
406
+ "with gr.Blocks() as gptdemo:\n",
407
+ "\n",
408
+ " gr.Markdown(\"## GPT Sentiment Analysis\")\n",
409
+ " gr.Markdown(\"This a custom GPT model for sentiment analysis with 15 labels: Openness, Anxiety, Confusion, Disapproval, Remorse, Accusation, Denial, Obscenity, Disinterest, Annoyance, Information, Greeting, Interest, Curiosity, or Acceptance.<br />Please enter your sentence(s) in the input box below and click the Submit button. The model will then process the input and provide the sentiment in one of the labels.<br />The Test Example section below provides some input examples. Click on them and submit them to the model to see how it works.Please note that the input may be collected by service providers.\")\n",
410
+ " txt = gr.Textbox(label=\"Input\", lines=2)\n",
411
+ " txt_1 = gr.Textbox(value=\"\", label=\"Output\")\n",
412
+ " btn = gr.Button(value=\"Submit\")\n",
413
+ " btn.click(predict, inputs=txt, outputs= txt_1)\n",
414
+ "\n",
415
+ " gptExample = [\n",
416
+ " \"Hello, how are you?\",\n",
417
+ " \"Are you busy at the moment?\",\n",
418
+ " \"I'm doing real good\"\n",
419
+ " ]\n",
420
+ "\n",
421
+ " gr.Markdown(\"## Text Examples\")\n",
422
+ " gr.Examples(\n",
423
+ " gptExample,\n",
424
+ " txt,\n",
425
+ " txt_1,\n",
426
+ " predict\n",
427
+ " )\n",
428
+ "\n",
429
+ "\n",
430
+ "with gr.Blocks() as revisiondemo:\n",
431
+ " gr.Markdown(\"## Conversation Revision\")\n",
432
+ " gr.Markdown(\"This is a custom GPT model designed to generate possible response texts based on previous contexts. You can input a conversation between a caller and a volunteer, and the model will provide three possible responses based on the input. <br />The Test Example section below provides some input examples. Click on them and submit them to the model to see how it works. Please note that the input may be collected by service providers.\")\n",
433
+ " txt = gr.Textbox(label=\"Input\", lines=2)\n",
434
+ " txt_1 = gr.Textbox(value=\"\", label=\"Output\",lines=4)\n",
435
+ " btn = gr.Button(value=\"Submit\")\n",
436
+ " btn.click(revision, inputs=txt, outputs= txt_1)\n",
437
+ "\n",
438
+ " revisionExample = [\"Caller: sup\\nVolunteer: Hey, how's it going?\\nCaller: not very well, actually\\nVolunteer: What's the matter?\\nCaller: it's my wife, don't worry about it\"]\n",
439
+ "\n",
440
+ " with gr.Column():\n",
441
+ " gr.Markdown(\"## Text Examples\")\n",
442
+ " gr.Examples(\n",
443
+ " revisionExample,\n",
444
+ " [txt],\n",
445
+ " txt_1,\n",
446
+ " revision\n",
447
+ " )\n",
448
+ "\n",
449
+ "\n",
450
+ "\n",
451
+ "\n",
452
+ "gr.TabbedInterface([demo, gptdemo,revisiondemo], [\"Model\", \"GPT\",\"Text Revision\"]\n",
453
+ ").launch(inline=False)"
454
+ ]
455
+ }
456
+ ],
457
+ "metadata": {
458
+ "kernelspec": {
459
+ "display_name": "Python 3",
460
+ "language": "python",
461
+ "name": "python3"
462
+ },
463
+ "language_info": {
464
+ "codemirror_mode": {
465
+ "name": "ipython",
466
+ "version": 3
467
+ },
468
+ "file_extension": ".py",
469
+ "mimetype": "text/x-python",
470
+ "name": "python",
471
+ "nbconvert_exporter": "python",
472
+ "pygments_lexer": "ipython3",
473
+ "version": "3.10.9"
474
+ },
475
+ "vscode": {
476
+ "interpreter": {
477
+ "hash": "76d9096663e4677afe736ff46b3dcdaff586dfdb471519f50b872333a086db78"
478
+ }
479
+ }
480
+ },
481
+ "nbformat": 4,
482
+ "nbformat_minor": 2
483
+ }
app.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding: utf-8
3
+
4
+ # In[ ]:
5
+
6
+
7
+ import numpy as np
8
+ import tensorflow as tf
9
+ import tensorflow_addons as tfa
10
+ from tensorflow.keras import layers
11
+ import transformers
12
+ import sentencepiece as spm
13
+ #show the version of the package imported with text instructions\
14
+ print("Tensorflow version: ", tf.__version__)
15
+ print("Tensorflow Addons version: ", tfa.__version__)
16
+ print("Transformers version: ", transformers.__version__)
17
+ print("Sentencepiece version: ", spm.__version__)
18
+ print("Numpy version: ", np.__version__)
19
+
20
+
21
+ # In[ ]:
22
+
23
+
24
+ class MeanPool(tf.keras.layers.Layer):
25
+ def call(self, inputs, mask=None):
26
+ broadcast_mask = tf.expand_dims(tf.cast(mask, "float32"), -1)
27
+ embedding_sum = tf.reduce_sum(inputs * broadcast_mask, axis=1)
28
+ mask_sum = tf.reduce_sum(broadcast_mask, axis=1)
29
+ mask_sum = tf.math.maximum(mask_sum, tf.constant([1e-9]))
30
+ return embedding_sum / mask_sum
31
+ class WeightsSumOne(tf.keras.constraints.Constraint):
32
+ def __call__(self, w):
33
+ return tf.nn.softmax(w, axis=0)
34
+
35
+
36
+ # In[ ]:
37
+
38
+
39
+ tokenizer = transformers.AutoTokenizer.from_pretrained("microsoft/deberta-v3-large"
40
+ )
41
+ tokenizer.save_pretrained('./tokenizer/')
42
+
43
+ cfg = transformers.AutoConfig.from_pretrained("microsoft/deberta-v3-large", output_hidden_states=True)
44
+ cfg.hidden_dropout_prob = 0
45
+ cfg.attention_probs_dropout_prob = 0
46
+ cfg.save_pretrained('./tokenizer/')
47
+
48
+
49
+ # In[ ]:
50
+
51
+
52
+ def deberta_encode(texts, tokenizer=tokenizer):
53
+ input_ids = []
54
+ attention_mask = []
55
+
56
+ for text in texts:
57
+ token = tokenizer(text,
58
+ add_special_tokens=True,
59
+ max_length=512,
60
+ return_attention_mask=True,
61
+ return_tensors="np",
62
+ truncation=True,
63
+ padding='max_length')
64
+ input_ids.append(token['input_ids'][0])
65
+ attention_mask.append(token['attention_mask'][0])
66
+
67
+ return np.array(input_ids, dtype="int32"), np.array(attention_mask, dtype="int32")
68
+
69
+
70
+ # In[ ]:
71
+
72
+
73
+ MAX_LENGTH=512
74
+ BATCH_SIZE=8
75
+
76
+
77
+ # In[ ]:
78
+
79
+
80
+ def get_model():
81
+ input_ids = tf.keras.layers.Input(
82
+ shape=(MAX_LENGTH,), dtype=tf.int32, name="input_ids"
83
+ )
84
+
85
+ attention_masks = tf.keras.layers.Input(
86
+ shape=(MAX_LENGTH,), dtype=tf.int32, name="attention_masks"
87
+ )
88
+
89
+ deberta_model = transformers.TFAutoModel.from_pretrained("microsoft/deberta-v3-large", config=cfg)
90
+
91
+
92
+ REINIT_LAYERS = 1
93
+ normal_initializer = tf.keras.initializers.GlorotUniform()
94
+ zeros_initializer = tf.keras.initializers.Zeros()
95
+ ones_initializer = tf.keras.initializers.Ones()
96
+
97
+ # print(f'\nRe-initializing encoder block:')
98
+ for encoder_block in deberta_model.deberta.encoder.layer[-REINIT_LAYERS:]:
99
+ # print(f'{encoder_block}')
100
+ for layer in encoder_block.submodules:
101
+ if isinstance(layer, tf.keras.layers.Dense):
102
+ layer.kernel.assign(normal_initializer(shape=layer.kernel.shape, dtype=layer.kernel.dtype))
103
+ if layer.bias is not None:
104
+ layer.bias.assign(zeros_initializer(shape=layer.bias.shape, dtype=layer.bias.dtype))
105
+
106
+ elif isinstance(layer, tf.keras.layers.LayerNormalization):
107
+ layer.beta.assign(zeros_initializer(shape=layer.beta.shape, dtype=layer.beta.dtype))
108
+ layer.gamma.assign(ones_initializer(shape=layer.gamma.shape, dtype=layer.gamma.dtype))
109
+
110
+ deberta_output = deberta_model.deberta(
111
+ input_ids, attention_mask=attention_masks
112
+ )
113
+ hidden_states = deberta_output.hidden_states
114
+
115
+ #WeightedLayerPool + MeanPool of the last 4 hidden states
116
+ stack_meanpool = tf.stack(
117
+ [MeanPool()(hidden_s, mask=attention_masks) for hidden_s in hidden_states[-4:]],
118
+ axis=2)
119
+
120
+ weighted_layer_pool = layers.Dense(1,
121
+ use_bias=False,
122
+ kernel_constraint=WeightsSumOne())(stack_meanpool)
123
+
124
+ weighted_layer_pool = tf.squeeze(weighted_layer_pool, axis=-1)
125
+ output=layers.Dense(15,activation='linear')(weighted_layer_pool)
126
+ #x = layers.Dense(6, activation='linear')(x)
127
+
128
+ #output = layers.Rescaling(scale=4.0, offset=1.0)(x)
129
+ model = tf.keras.Model(inputs=[input_ids, attention_masks], outputs=output)
130
+
131
+ #Compile model with Layer-wise Learning Rate Decay
132
+ layer_list = [deberta_model.deberta.embeddings] + list(deberta_model.deberta.encoder.layer)
133
+ layer_list.reverse()
134
+
135
+ INIT_LR = 1e-5
136
+ LLRDR = 0.9
137
+ LR_SCH_DECAY_STEPS = 1600
138
+
139
+ lr_schedules = [tf.keras.optimizers.schedules.ExponentialDecay(
140
+ initial_learning_rate=INIT_LR * LLRDR ** i,
141
+ decay_steps=LR_SCH_DECAY_STEPS,
142
+ decay_rate=0.3) for i in range(len(layer_list))]
143
+ lr_schedule_head = tf.keras.optimizers.schedules.ExponentialDecay(
144
+ initial_learning_rate=1e-4,
145
+ decay_steps=LR_SCH_DECAY_STEPS,
146
+ decay_rate=0.3)
147
+
148
+ optimizers = [tf.keras.optimizers.Adam(learning_rate=lr_sch) for lr_sch in lr_schedules]
149
+
150
+ optimizers_and_layers = [(tf.keras.optimizers.Adam(learning_rate=lr_schedule_head), model.layers[-4:])] +\
151
+ list(zip(optimizers, layer_list))
152
+
153
+ optimizer = tfa.optimizers.MultiOptimizer(optimizers_and_layers)
154
+
155
+ model.compile(optimizer=optimizer,
156
+ loss='mse',
157
+ metrics=[tf.keras.metrics.RootMeanSquaredError()],
158
+ )
159
+ return model
160
+
161
+
162
+ # In[ ]:
163
+
164
+
165
+ tf.keras.backend.clear_session()
166
+ model = get_model()
167
+ model.load_weights('./best_model_fold2.h5')
168
+
169
+
170
+ # In[ ]:
171
+
172
+
173
+
174
+
175
+
176
+ # In[ ]:
177
+
178
+
179
+ # map the integer labels to their original string representation
180
+ label_mapping = {
181
+ 0: 'Greeting',
182
+ 1: 'Curiosity',
183
+ 2: 'Interest',
184
+ 3: 'Obscene',
185
+ 4: 'Annoyed',
186
+ 5: 'Openness',
187
+ 6: 'Anxious',
188
+ 7: 'Acceptance',
189
+ 8: 'Uninterested',
190
+ 9: 'Informative',
191
+ 10: 'Accusatory',
192
+ 11: 'Denial',
193
+ 12: 'Confused',
194
+ 13: 'Disapproval',
195
+ 14: 'Remorse'
196
+ }
197
+
198
+ #label_strings = [label_mapping[label] for label in labels]
199
+
200
+ #print(label_strings)
201
+
202
+
203
+ # In[ ]:
204
+
205
+
206
+ def inference(texts):
207
+ prediction = model.predict(deberta_encode([texts]))
208
+ labels = np.argmax(prediction, axis=1)
209
+ label_strings = [label_mapping[label] for label in labels]
210
+ return label_strings[0]
211
+
212
+
213
+ # # GPT
214
+
215
+ # In[ ]:
216
+
217
+
218
+ import openai
219
+ import os
220
+ import pandas as pd
221
+ import gradio as gr
222
+
223
+
224
+ # In[ ]:
225
+
226
+
227
+ openai.organization = os.environ['org_id']
228
+ openai.api_key = os.environ['openai_api']
229
+ model_version = "gpt-3.5-turbo"
230
+ model_token_limit = 10
231
+ model_temperature = 0.1
232
+
233
+
234
+ # In[ ]:
235
+
236
+
237
+ def generatePrompt () :
238
+ labels = ["Openness",
239
+ "Anxious",
240
+ "Confused",
241
+ "Disapproval",
242
+ "Remorse",
243
+ "Uninterested",
244
+ "Accusatory",
245
+ "Annoyed",
246
+ "Interest",
247
+ "Curiosity",
248
+ "Acceptance",
249
+ "Obscene",
250
+ "Denial",
251
+ "Informative",
252
+ "Greeting"]
253
+
254
+ formatted_labels = ', '.join(labels[:-1]) + ', or ' + labels[-1] + '.'
255
+
256
+ label_set = ["Openness", "Anxious", "Confused", "Disapproval", "Remorse", "Accusatory",
257
+ "Denial", "Obscene", "Uninterested", "Annoyed", "Informative", "Greeting",
258
+ "Interest", "Curiosity", "Acceptance"]
259
+
260
+ formatted_labels = ', '.join(label_set[:-1]) + ', or ' + label_set[-1] + '.\n'
261
+
262
+ # The basic task to assign GPT (in natural language)
263
+ base_task = "Classify the following text messages into one of the following categories using one word: " + formatted_labels
264
+ base_task += "Provide only a one word response. Use only the labels provided.\n"
265
+
266
+ return base_task
267
+
268
+
269
+ # In[ ]:
270
+
271
+
272
+ def predict(message):
273
+
274
+ prompt = [{"role": "user", "content": generatePrompt () + "Text: "+ message}]
275
+
276
+ response = openai.ChatCompletion.create(
277
+ model=model_version,
278
+ temperature=model_temperature,
279
+ max_tokens=model_token_limit,
280
+ messages=prompt
281
+ )
282
+
283
+ return response["choices"][0]["message"]["content"]
284
+
285
+
286
+ # # Update
287
+
288
+ # In[ ]:
289
+
290
+
291
+ model_version = "gpt-3.5-turbo"
292
+ model_token_limit = 2000
293
+ model_temperature = 0.1
294
+
295
+
296
+ # In[ ]:
297
+
298
+
299
+ def revision(message):
300
+ base_prompt = "Here is a conversation between a Caller and a Volunteer. The Volunteer is trying to be as non-accusatory as possible but also wants to get as much information about the caller as possible. What should the volunteer say next in this exchange? Proved 3 possible responses."
301
+
302
+ prompt = [{"role": "user", "content": base_prompt + message}]
303
+
304
+ response = openai.ChatCompletion.create(
305
+ model=model_version,
306
+ temperature=model_temperature,
307
+ max_tokens=model_token_limit,
308
+ messages=prompt
309
+ )
310
+
311
+ return response["choices"][0]["message"]["content"]
312
+
313
+
314
+ # In[ ]:
315
+
316
+
317
+ import gradio as gr
318
+
319
+ def combine(a):
320
+ return a + "hello"
321
+
322
+
323
+
324
+
325
+ with gr.Blocks() as demo:
326
+ gr.Markdown("## DeBERTa Sentiment Analysis")
327
+ gr.Markdown("This is a custom DeBERTa model architecture for sentiment analysis with 15 labels: Openness, Anxiety, Confusion, Disapproval, Remorse, Accusation, Denial, Obscenity, Disinterest, Annoyance, Information, Greeting, Interest, Curiosity, or Acceptance.<br />Please enter your sentence(s) in the input box below and click the Submit button. The model will then process the input and provide the sentiment in one of the labels.<br/>The Test Example section below provides some input examples. Click on them and submit them to the model to see how it works.")
328
+
329
+ txt = gr.Textbox(label="Input", lines=2)
330
+ txt_1 = gr.Textbox(value="", label="Output")
331
+ btn = gr.Button(value="Submit")
332
+ btn.click(inference, inputs=txt, outputs= txt_1)
333
+
334
+ demoExample = [
335
+ "Hello, how are you?",
336
+ "I am so happy to be here!",
337
+ "i don't have time for u"
338
+ ]
339
+
340
+ gr.Markdown("## Text Examples")
341
+ gr.Examples(
342
+ demoExample,
343
+ txt,
344
+ txt_1,
345
+ inference
346
+ )
347
+
348
+ with gr.Blocks() as gptdemo:
349
+
350
+ gr.Markdown("## GPT Sentiment Analysis")
351
+ gr.Markdown("This a custom GPT model for sentiment analysis with 15 labels: Openness, Anxiety, Confusion, Disapproval, Remorse, Accusation, Denial, Obscenity, Disinterest, Annoyance, Information, Greeting, Interest, Curiosity, or Acceptance.<br />Please enter your sentence(s) in the input box below and click the Submit button. The model will then process the input and provide the sentiment in one of the labels.<br />The Test Example section below provides some input examples. Click on them and submit them to the model to see how it works.Please note that the input may be collected by service providers.")
352
+ txt = gr.Textbox(label="Input", lines=2)
353
+ txt_1 = gr.Textbox(value="", label="Output")
354
+ btn = gr.Button(value="Submit")
355
+ btn.click(predict, inputs=txt, outputs= txt_1)
356
+
357
+ gptExample = [
358
+ "Hello, how are you?",
359
+ "Are you busy at the moment?",
360
+ "I'm doing real good"
361
+ ]
362
+
363
+ gr.Markdown("## Text Examples")
364
+ gr.Examples(
365
+ gptExample,
366
+ txt,
367
+ txt_1,
368
+ predict
369
+ )
370
+
371
+
372
+ with gr.Blocks() as revisiondemo:
373
+ gr.Markdown("## Conversation Revision")
374
+ gr.Markdown("This is a custom GPT model designed to generate possible response texts based on previous contexts. You can input a conversation between a caller and a volunteer, and the model will provide three possible responses based on the input. <br />The Test Example section below provides some input examples. Click on them and submit them to the model to see how it works. Please note that the input may be collected by service providers.")
375
+ txt = gr.Textbox(label="Input", lines=2)
376
+ txt_1 = gr.Textbox(value="", label="Output",lines=4)
377
+ btn = gr.Button(value="Submit")
378
+ btn.click(revision, inputs=txt, outputs= txt_1)
379
+
380
+ revisionExample = ["Caller: sup\nVolunteer: Hey, how's it going?\nCaller: not very well, actually\nVolunteer: What's the matter?\nCaller: it's my wife, don't worry about it"]
381
+
382
+ with gr.Column():
383
+ gr.Markdown("## Text Examples")
384
+ gr.Examples(
385
+ revisionExample,
386
+ [txt],
387
+ txt_1,
388
+ revision
389
+ )
390
+
391
+
392
+
393
+
394
+ gr.TabbedInterface([demo, gptdemo,revisiondemo], ["Model", "GPT","Text Revision"]
395
+ ).launch(inline=False)
396
+
best_model_fold2.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b766e08d25b38c595d5db04da5b602d71b3439956b5693d6665914183a614568
3
+ size 1736668216
requirements.txt ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ openai
2
+ absl-py==1.4.0
3
+ aiofiles==23.1.0
4
+ aiohttp==3.8.4
5
+ aiosignal==1.3.1
6
+ altair==4.2.2
7
+ anyio==3.6.2
8
+ astunparse==1.6.3
9
+ async-timeout==4.0.2
10
+ attrs==23.1.0
11
+ cachetools==5.3.0
12
+ charset-normalizer==3.1.0
13
+ click==8.1.3
14
+ contourpy==1.0.7
15
+ cycler==0.11.0
16
+ entrypoints==0.4
17
+ fastapi==0.95.1
18
+ ffmpy==0.3.0
19
+ filelock==3.10.7
20
+ flatbuffers==1.12
21
+ fonttools==4.39.3
22
+ frozenlist==1.3.3
23
+ fsspec==2023.4.0
24
+ gast==0.4.0
25
+ google-auth==2.17.1
26
+ google-auth-oauthlib==0.4.6
27
+ google-pasta==0.2.0
28
+ gradio==3.27.0
29
+ gradio-client==0.1.3
30
+ grpcio==1.53.0
31
+ h11==0.14.0
32
+ h5py==3.8.0
33
+ httpcore==0.17.0
34
+ httpx==0.24.0
35
+ huggingface-hub==0.13.3
36
+ idna==3.4
37
+ imbalanced-learn==0.10.1
38
+ jinja2==3.1.2
39
+ joblib==1.2.0
40
+ jsonschema==4.17.3
41
+ keras==2.9.0
42
+ keras-preprocessing==1.1.2
43
+ kiwisolver==1.4.4
44
+ libclang==16.0.0
45
+ linkify-it-py==2.0.0
46
+ markdown==3.4.3
47
+ markdown-it-py==2.2.0
48
+ markupsafe==2.1.2
49
+ matplotlib==3.7.1
50
+ mdit-py-plugins==0.3.3
51
+ mdurl==0.1.2
52
+ multidict==6.0.4
53
+ numpy==1.24.2
54
+ oauthlib==3.2.2
55
+ opt-einsum==3.3.0
56
+ orjson==3.8.10
57
+ pandas==2.0.0
58
+ pillow==9.5.0
59
+ protobuf==3.19.6
60
+ pyasn1==0.4.8
61
+ pyasn1-modules==0.2.8
62
+ pydantic==1.10.7
63
+ pydub==0.25.1
64
+ pyparsing==3.0.9
65
+ pyrsistent==0.19.3
66
+ python-multipart==0.0.6
67
+ pytz==2023.3
68
+ pyyaml==6.0
69
+ regex==2023.3.23
70
+ requests==2.28.2
71
+ requests-oauthlib==1.3.1
72
+ rsa==4.9
73
+ scikit-learn==1.2.2
74
+ scipy==1.10.1
75
+ semantic-version==2.10.0
76
+ sentencepiece==0.1.97
77
+ sniffio==1.3.0
78
+ starlette==0.26.1
79
+ tensorboard==2.9.1
80
+ tensorboard-data-server==0.6.1
81
+ tensorboard-plugin-wit==1.8.1
82
+ tensorflow==2.9.0
83
+ tensorflow-addons==0.19.0
84
+ tensorflow-estimator==2.9.0
85
+ tensorflow-io-gcs-filesystem==0.31.0
86
+ termcolor==2.2.0
87
+ threadpoolctl==3.1.0
88
+ tokenizers==0.13.2
89
+ toolz==0.12.0
90
+ tqdm==4.65.0
91
+ transformers==4.27.4
92
+ typeguard==3.0.2
93
+ tzdata==2023.3
94
+ uc-micro-py==1.0.1
95
+ urllib3==1.26.15
96
+ uvicorn==0.21.1
97
+ websockets==11.0.2
98
+ werkzeug==2.2.3
99
+ wrapt==1.15.0
100
+ yarl==1.8.2