File size: 18,841 Bytes
4ba4a77
 
 
 
 
 
add688f
c297653
 
 
4ba4a77
de5ddcb
2c8d271
4ba4a77
 
 
 
 
 
 
2c8d271
 
4ba4a77
 
 
 
 
 
 
 
 
 
 
41ceeed
6335809
9768496
4ba4a77
6335809
 
 
 
 
 
 
 
4ba4a77
 
9768496
4ba4a77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40d4c45
4ba4a77
 
 
 
 
 
 
 
 
 
 
6e9f2fe
4ba4a77
6e9f2fe
4ba4a77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c297653
4ba4a77
 
 
 
 
906bdab
add688f
906bdab
4ba4a77
 
 
6e9f2fe
 
 
 
4ba4a77
 
 
 
 
 
 
 
 
 
 
40d4c45
6f191ac
40d4c45
 
6827860
6335809
 
 
 
 
 
 
 
 
 
4ba4a77
 
6e9f2fe
4ba4a77
cfd3e7b
4ba4a77
6e9f2fe
4ba4a77
 
 
 
cfd3e7b
6e9f2fe
cfd3e7b
 
6e9f2fe
4ba4a77
 
 
 
6e9f2fe
4ba4a77
cfd3e7b
 
4ba4a77
 
 
dc44695
6e9f2fe
4ba4a77
 
dc44695
6e9f2fe
4ba4a77
 
6e9f2fe
 
 
 
 
4ba4a77
 
 
 
6e9f2fe
 
 
4ba4a77
 
6e9f2fe
 
 
 
 
cfd3e7b
4ba4a77
 
 
dc44695
6e9f2fe
4ba4a77
 
6e9f2fe
 
4ba4a77
6e9f2fe
4ba4a77
 
 
 
6e9f2fe
 
 
4ba4a77
 
6e9f2fe
 
4ba4a77
6e9f2fe
 
4ba4a77
 
 
dc44695
6e9f2fe
4ba4a77
 
cf06e4b
 
 
 
 
 
4ba4a77
 
434c239
1002ef8
 
 
4ba4a77
6e9f2fe
 
cf06e4b
 
 
 
 
 
 
 
 
 
 
 
 
4ba4a77
cf06e4b
4ba4a77
 
 
 
c297653
4ba4a77
 
c297653
 
4ba4a77
 
 
 
c297653
e7af507
 
c297653
e7af507
 
 
 
 
 
c297653
5f09622
 
 
6f8b2b2
5f09622
6f8b2b2
8c73fbd
5f09622
 
 
 
 
 
 
 
 
8c73fbd
5f09622
cf3bdbb
5f09622
 
6335809
 
 
 
 
 
 
 
 
 
 
 
4ba4a77
 
6335809
 
 
 
 
 
 
 
 
 
 
4ba4a77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
906bdab
 
4ba4a77
 
 
 
6e9f2fe
 
 
 
4ba4a77
 
 
 
 
 
 
 
 
 
6e9f2fe
 
f2c0f86
4ba4a77
6e9f2fe
 
 
4ba4a77
 
 
906bdab
 
4ba4a77
906bdab
cf3bdbb
4ba4a77
906bdab
cf3bdbb
4ba4a77
 
 
 
 
cf3bdbb
4ba4a77
cf3bdbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ba4a77
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
import requests
import random
import time
import pandas as pd
import gradio as gr
import numpy as np
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from transformers import pipeline
import shap


def read1(lang, num_selected_former):
    if lang in ['en']:
        fname = 'data1_en.txt'
    else:
        fname = 'data1_nl_10.txt'
    with open(fname, encoding='utf-8') as f:
        content = f.readlines()
        index_selected = random.randint(0,len(content)/2-1)
        while index_selected == num_selected_former:
            index_selected = random.randint(0,len(content)/2-1)
        text = eval(content[index_selected*2])
        interpretation = eval(content[int(index_selected*2+1)])
        if lang == 'en': 
            min_len = 4
        else:
            min_len = 2
        tokens = [i[0] for i in interpretation]
        tokens = tokens[1:-1]
        while len(tokens) <= min_len or '\\' in text['text'] or '//' in text['text']:
            index_selected = random.randint(0,len(content)/2-1)
            text = eval(content[int(index_selected*2)])
        res_tmp = [(i, 0) for i in text['text'].split(' ')]
        res = {"original": text['text'], "interpretation": res_tmp}
        # res_empty = {"original": "", "interpretation": []}

        # res = []
        # res.append(("P", "+"))
        # res.append(("/", None))
        # res.append(("N", "-"))
        # res.append(("Review:", None))
        # for i in text['text'].split(' '):
        #     res.append((i, None))
        # res_empty = None
    # checkbox_update = gr.CheckboxGroup.update(choices=tokens, value=None)
    
    return res, lang, index_selected

def read1_written(lang):
    if lang in ['en']:
        fname = 'data1_en.txt'
    else:
        fname = 'data1_nl_10.txt'
    with open(fname, encoding='utf-8') as f:
        content = f.readlines()
        index_selected = random.randint(0,len(content)/2-1)
        text = eval(content[index_selected*2])
        if lang == 'en': 
            min_len = 4
        else:
            min_len = 2
        while (len(text['text'].split(' '))) <= min_len or '\\' in text['text'] or '//' in text['text']:
        # while (len(text['text'].split(' '))) <= min_len:
            index_selected = random.randint(0,len(content)/2-1)
            text = eval(content[int(index_selected*2)])
        # interpretation = [(i, 0) for i in text['text'].split(' ')]
        # res = {"original": text['text'], "interpretation": interpretation}
        # print(res)
    return text['text']
    
def func1(lang_selected, num_selected, human_predict, num1, num2, user_important):
    chatbot = []
    # num1: Human score; num2: AI score
    if lang_selected in ['en']:
        fname = 'data1_en.txt'
    else:
        fname = 'data1_nl_10.txt'
    with open(fname) as f:
        content = f.readlines()
        text = eval(content[int(num_selected*2)])
        interpretation = eval(content[int(num_selected*2+1)])
        if lang_selected in ['en']:
            golden_label = text['label'] * 2.5
        else:
            golden_label = text['label'] * 10

    '''
    # (START) API version -- quick
    
    API_URL = "https://api-inference.huggingface.co/models/nlptown/bert-base-multilingual-uncased-sentiment"
    # API_URL = "https://api-inference.huggingface.co/models/cmarkea/distilcamembert-base-sentiment"
    headers = {"Authorization": "Bearer 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"}

    response = requests.post(API_URL, headers=headers, json=text['text'])
    output = response.json()
    
    # result = dict()
    star2num = {
        "5 stars": 100,
        "4 stars": 75,
        "3 stars": 50,
        "2 stars": 25,
        "1 star": 0,
    }

    print(output)
    out = output[0][0]
    # (END) API version
    ''' 

    # (START) off-the-shelf version -- slow at the beginning
    # Load model directly

    tokenizer = AutoTokenizer.from_pretrained("nlptown/bert-base-multilingual-uncased-sentiment")
    model = AutoModelForSequenceClassification.from_pretrained("nlptown/bert-base-multilingual-uncased-sentiment")

    # Use a pipeline as a high-level helper

    device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
    print(device)
    classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer, device=device)
    output = classifier([text['text']])

    star2num = {
        "5 stars": 10,
        "4 stars": 7.5,
        "3 stars": 5,
        "2 stars": 2.5,
        "1 star": 0,
    }
    print(output)
    out = output[0]
    
    # (END) off-the-shelf version
    
    ai_predict = star2num[out['label']]
    # result[label] = out['score']

    user_select = "You focused on "
    flag_select = False
    if user_important == "":
        user_select += "nothing. Interesting! "
    else:
        user_select += "'" + user_important + "'. "
    # for i in range(len(user_marks)):
    #     if user_marks[i][1] != None and h1[i][0] not in ["P", "N"]:
    #         flag_select = True
    #         user_select += "'" + h1[i][0] + "'"
    #         if i == len(h1) - 1:
    #             user_select += ". "
    #         else:
    #             user_select += ", "
    # if not flag_select:
    #     user_select += "nothing. Interesting! "
    user_select += "Wanna see how the AI made the guess? Click here. ⬅️"
    if lang_selected in ['en']:
        # 0 1 2 3 4 5 6 7 8 9 10
        if ai_predict == golden_label:
            if abs(human_predict - golden_label) <= 2: # Both correct
                golden_label = int((human_predict + ai_predict) / 2)
                ai_predict = golden_label
                chatbot.append(("The correct answer is " + str(golden_label) + ". Congratulations! πŸŽ‰ Both of you get the correct answer!", user_select))
                num1 += 1
                num2 += 1
            else:
                golden_label += random.randint(-1, 1) * 0.5
                while golden_label > 10 or golden_label < 0:
                    golden_label += random.randint(-1, 1) * 0.5
                golden_label = int(golden_label)
                ai_predict = golden_label
                chatbot.append(("The correct answer is " + str(golden_label) + ". Sorry.. AI wins in this round.", user_select))
                num2 += 1
        else:
            if abs(human_predict - golden_label) < abs(ai_predict - golden_label):
                if abs(human_predict - golden_label) < 2:
                    golden_label = int((golden_label + human_predict) / 2)
                    ai_predict += random.randint(-1, 1) * 0.5
                    ai_predict = int(ai_predict)
                    chatbot.append(("The correct answer is " + str(golden_label) + ". Great! πŸŽ‰ You are closer to the answer and better than AI!", user_select))
                    num1 += 1
                else:
                    golden_label = int(golden_label)
                    ai_predict = int(ai_predict)
                    chatbot.append(("The correct answer is " + str(golden_label) + ". Both wrong... Maybe next time you'll win!", user_select))
            else:
                golden_label = int(golden_label)
                ai_predict = int(ai_predict)
                chatbot.append(("The correct answer is " + str(golden_label) + ". Sorry.. No one gets the correct answer. But nice try! πŸ˜‰", user_select))
    else:
        if golden_label == 10:
            if ai_predict > 5 and human_predict > 5:
                golden_label = int((human_predict + ai_predict)/2) + random.randint(-1, 1)
                while golden_label > 10:
                    golden_label = int((human_predict + ai_predict)/2) + random.randint(-1, 1)
                ai_predict = int((golden_label + ai_predict) / 2)
                chatbot.append(("The correct answer is " + str(golden_label) + ". Congratulations! πŸŽ‰ Both of you get the correct answer!", user_select))
                num1 += 1
                num2 += 1
            elif ai_predict > 5 and human_predict <= 5:
                golden_label -= random.randint(0, 3)
                ai_predict = 7 + random.randint(-1, 2)
                chatbot.append(("The correct answer is " + str(golden_label) + ". Sorry.. AI wins in this round.", user_select))
                num2 += 1
            elif ai_predict <= 5 and human_predict > 5:
                golden_label = human_predict + random.randint(-1, 1)
                while golden_label > 10:
                    golden_label = human_predict + random.randint(-1, 1)
                ai_predict = int(ai_predict)
                golden_label = int(golden_label)
                chatbot.append(("The correct answer is " + str(golden_label) + ". Great! πŸŽ‰ You are close to the answer and better than AI!", user_select))
                num1 += 1
            else:
                golden_label = int(golden_label)
                ai_predict = int(ai_predict)
                chatbot.append(("The correct answer is " + str(golden_label) + ". Sorry... No one gets the correct answer. But nice try! πŸ˜‰", user_select))
        else:
            if ai_predict < 5 and human_predict < 5:
                golden_label = int((human_predict + ai_predict)/2) + random.randint(-1, 1)
                while golden_label < 0:
                    golden_label = int((human_predict + ai_predict)/2) + random.randint(-1, 1)
                ai_predict = int((golden_label + ai_predict) / 2)
                chatbot.append(("The correct answer is " + str(golden_label) + ". Congratulations! πŸŽ‰ Both of you get the correct answer!", user_select))
                num1 += 1
                num2 += 1
            elif ai_predict < 5 and human_predict >= 5:
                golden_label += random.randint(0, 3)
                ai_predict = 3 + random.randint(-2, 1)
                chatbot.append(("The correct answer is " + str(golden_label) + ". Sorry.. AI wins in this round.", user_select))
                num2 += 1
            elif ai_predict >= 5 and human_predict < 5:
                golden_label = human_predict + random.randint(-1, 1)
                while golden_label < 0:
                    golden_label = human_predict + random.randint(-1, 1)
                ai_predict = int(ai_predict)
                chatbot.append(("The correct answer is " + str(golden_label) + ". Great! πŸŽ‰ You are close to the answer and better than AI!", user_select))
                num1 += 1
            else:
                golden_label = int(golden_label)
                ai_predict = int(ai_predict)
                chatbot.append(("The correct answer is " + str(golden_label) + ". Sorry... No one gets the correct answer. But nice try! πŸ˜‰", user_select))

    # data = pd.DataFrame(
    #     {
    #         "Role": ["AI πŸ€–", "HUMAN πŸ‘¨πŸ‘©"],
    #         "Scores": [num2, num1],
    #     }
    # )
    # scroe_human = ''' # Human: ''' + str(int(num1))
    # scroe_robot = ''' # Robot: ''' + str(int(num2))
    # tot_scores = ''' ### <p style="text-align: center;"> πŸ€– Machine &ensp; ''' + str(int(num2)) + ''' &ensp; VS &ensp; ''' + str(int(num1)) + ''' &ensp; Human πŸ‘¨πŸ‘© </p>'''

    tot_scores = ''' #### <p style="text-align: center;"> Today's Scores:</p>
                    #### <p style="text-align: center;"> πŸ€– Machine &ensp; <span style="color: red;">''' + str(int(num2)) + '''</span> &ensp; VS &ensp; <span style="color: red;">''' + str(int(num1)) + '''</span> &ensp; Human πŸ™‹ </p>'''
    
    # num_tmp = max(num1, num2)
    # y_lim_upper = (int((num_tmp + 3)/10)+1) * 10
    # figure = gr.BarPlot.update(
    #         data,
    #         x="Role",
    #         y="Scores",
    #         color="Role",
    #         vertical=False,
    #         y_lim=[0,y_lim_upper],
    #         color_legend_position='none', 
    #         height=250, 
    #         width=500,
    #         show_label=False,
    #         container=False,
    #     )
    # tooltip=["Role", "Scores"],
    return ai_predict, chatbot, num1, num2, tot_scores

def interpre1(lang_selected, num_selected):
    if lang_selected in ['en']:
        fname = 'data1_en.txt'
        tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased-finetuned-sst-2-english")
    else:
        fname = 'data1_nl_10.txt'
        tokenizer = AutoTokenizer.from_pretrained("DTAI-KULeuven/robbert-v2-dutch-sentiment")
        
    with open(fname) as f:
        content = f.readlines()
        text = eval(content[int(num_selected*2)])
        interpretation = eval(content[int(num_selected*2+1)])

    encodings = tokenizer(text['text'], return_offsets_mapping=True)

    print(encodings['offset_mapping'])
    is_subword = [False, False]
    for i in range(2, len(encodings['offset_mapping'])):
        if encodings['offset_mapping'][i][0] == encodings['offset_mapping'][i-1][1]:
            is_subword.append(True)
        else:
            is_subword.append(False)
    print(is_subword)
    interpretation_combined = []

    index_tmp = 0
    while index_tmp < (len(interpretation) - 1):
        if not is_subword[index_tmp+1]:
            interpretation_combined.append(interpretation[index_tmp])
            index_tmp += 1
        else:
            text_combined = interpretation[index_tmp][0]
            score_combinded = interpretation[index_tmp][1]
            length = 1
            while is_subword[index_tmp+length]:
                text_combined += interpretation[index_tmp+length][0]
                score_combinded += interpretation[index_tmp+length][1]
                length += 1
            interpretation_combined.append((text_combined, score_combinded/length))
            index_tmp += length

    interpretation_combined.append(('', 0.0))
    print(interpretation_combined)
    res = {"original": text['text'], "interpretation": interpretation_combined}
    # pos = []
    # neg = []
    # res = []
    # for i in interpretation:
    #     if i[1] > 0:
    #         pos.append(i[1])
    #     elif i[1] < 0:
    #         neg.append(i[1])
    #     else:
    #         continue
    # median_pos = np.median(pos)
    # median_neg = np.median(neg)


    # res.append(("P", "+"))
    # res.append(("/", None))
    # res.append(("N", "-"))
    # res.append(("Review:", None))
    # for i in interpretation:
    #     if i[1] > median_pos:
    #         res.append((i[0], "+"))
    #     elif i[1] < median_neg:
    #         res.append((i[0], "-"))
    #     else:
    #         res.append((i[0], None))
    return res
    
def func1_written(text_written, human_predict, lang_written):
    chatbot = []
    # num1: Human score; num2: AI score

    '''
    # (START) API version
    
    API_URL = "https://api-inference.huggingface.co/models/nlptown/bert-base-multilingual-uncased-sentiment"
    # API_URL = "https://api-inference.huggingface.co/models/cmarkea/distilcamembert-base-sentiment"
    headers = {"Authorization": "Bearer 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"}

    response = requests.post(API_URL, headers=headers, json=text_written)
    output = response.json()
    
    # result = dict()
    star2num = {
        "5 stars": 100,
        "4 stars": 75,
        "3 stars": 50,
        "2 stars": 25,
        "1 star": 0,
    }

    out = output[0][0]
    # (END) API version
    ''' 

    # (START) off-the-shelf version


    # tokenizer = AutoTokenizer.from_pretrained("nlptown/bert-base-multilingual-uncased-sentiment")
    # model = AutoModelForSequenceClassification.from_pretrained("nlptown/bert-base-multilingual-uncased-sentiment")

    device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
    classifier = pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment", device=device)
    
    output = classifier([text_written])

    star2num = {
        "5 stars": 10,
        "4 stars": 7.5,
        "3 stars": 5,
        "2 stars": 2.5,
        "1 star": 0,
    }
    print(output)
    out = output[0]
    # (END) off-the-shelf version

    
    ai_predict = star2num[out['label']]
    # result[label] = out['score']

    if abs(ai_predict - human_predict) <= 2:
        ai_predict = int(ai_predict)
        chatbot.append(("AI gives it a close score! πŸŽ‰", "⬅️ Feel free to try another one! This time let’s see if you can trick the AI into giving a wrong rating. ⬅️"))
    else:
        ai_predict += int(random.randint(-1, 1))
        while ai_predict > 10 or ai_predict < 0:
            ai_predict += int(random.randint(-1, 1))
        chatbot.append(("AI thinks in a different way from human. πŸ˜‰", "⬅️ Feel free to try another one! ⬅️"))

    # sentiment_classifier = pipeline("text-classification", return_all_scores=True)
    device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")

    if lang_written == "Dutch":
        sentiment_classifier = pipeline("text-classification", model='DTAI-KULeuven/robbert-v2-dutch-sentiment', return_all_scores=True, device=device)
        tokenizer = AutoTokenizer.from_pretrained("DTAI-KULeuven/robbert-v2-dutch-sentiment")
    else:
        sentiment_classifier = pipeline("text-classification", model='distilbert-base-uncased-finetuned-sst-2-english', return_all_scores=True, device=device)
        tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased-finetuned-sst-2-english")

    explainer = shap.Explainer(sentiment_classifier)

    shap_values = explainer([text_written])
    interpretation = list(zip(shap_values.data[0], shap_values.values[0, :, 1]))

    
    encodings = tokenizer(text_written, return_offsets_mapping=True)

    print(encodings['offset_mapping'])
    is_subword = [False, False]
    for i in range(2, len(encodings['offset_mapping'])):
        if encodings['offset_mapping'][i][0] == encodings['offset_mapping'][i-1][1]:
            is_subword.append(True)
        else:
            is_subword.append(False)
    print(is_subword)
    interpretation_combined = []

    index_tmp = 0
    while index_tmp < (len(interpretation) - 1):
        if not is_subword[index_tmp+1]:
            interpretation_combined.append(interpretation[index_tmp])
            index_tmp += 1
        else:
            text_combined = interpretation[index_tmp][0]
            score_combinded = interpretation[index_tmp][1]
            length = 1
            while is_subword[index_tmp+length]:
                text_combined += interpretation[index_tmp+length][0]
                score_combinded += interpretation[index_tmp+length][1]
                length += 1
            interpretation_combined.append((text_combined, score_combinded/length))
            index_tmp += length

    interpretation_combined.append(('', 0.0))
    print(interpretation_combined)

    res = {"original": text_written, "interpretation": interpretation_combined}
    print(res)

    return res, ai_predict, chatbot