File size: 13,255 Bytes
7d7d506
 
 
 
 
 
 
 
 
0181e0b
7d7de10
 
9cd92fc
 
7d7d506
 
 
 
 
7d7de10
7d7d506
0dd0180
9cd92fc
7d7d506
0181e0b
 
7d7d506
 
 
0181e0b
f1fde39
0181e0b
 
 
 
 
7d7d506
 
0181e0b
 
 
7d7d506
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0181e0b
 
 
7d7de10
0dd0180
7d7de10
 
 
 
 
 
 
 
 
 
 
 
0dd0180
7d7de10
7d7d506
 
7d7de10
 
 
0dd0180
 
 
7d7de10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dd0180
 
7d7de10
 
 
 
 
 
 
 
 
 
 
0dd0180
 
 
7d7de10
0dd0180
 
7d7de10
 
 
 
 
 
 
7d7d506
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cd92fc
 
7d7d506
0181e0b
7d7d506
 
 
9cd92fc
7d7d506
9cd92fc
7d7d506
 
0dd0180
0181e0b
 
7d7de10
 
 
 
 
0181e0b
0dd0180
0181e0b
0dd0180
7d7de10
 
7d7d506
 
0dd0180
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d7d506
0dd0180
 
 
 
28e88ea
7d7de10
0dd0180
 
 
 
 
 
 
 
 
7d7d506
 
0dd0180
 
7d7de10
0dd0180
 
 
7d7de10
 
 
0dd0180
7d7de10
 
0dd0180
7d7de10
 
 
0dd0180
 
 
 
 
7d7de10
 
 
0dd0180
 
 
 
 
 
 
 
 
 
 
 
 
7d7de10
0dd0180
 
 
 
 
 
7d7de10
0dd0180
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
# file: app.py
# time: 17:08 2023/3/6
# author: YANG, HENG <hy345@exeter.ac.uk> (杨恒)
# github: https://github.com/yangheng95
# huggingface: https://huggingface.co/yangheng
# google scholar: https://scholar.google.com/citations?user=NPq5a_0AAAAJ&hl=en
# Copyright (C) 2023. All Rights Reserved.

import random

import autocuda
import gradio as gr
import pandas as pd
from pyabsa import (
    download_all_available_datasets,
    TaskCodeOption,
    available_checkpoints,
)
from pyabsa import ABSAInstruction
from pyabsa.utils.data_utils.dataset_manager import detect_infer_dataset
import requests

download_all_available_datasets()


def get_atepc_example(dataset):
    task = TaskCodeOption.Aspect_Polarity_Classification
    dataset_file = detect_infer_dataset(atepc_dataset_items[dataset], task)

    for fname in dataset_file:
        lines = []
        if isinstance(fname, str):
            fname = [fname]

        for f in fname:
            print("loading: {}".format(f))
            fin = open(f, "r", encoding="utf-8")
            lines.extend(fin.readlines())
            fin.close()
        for i in range(len(lines)):
            lines[i] = (
                lines[i][: lines[i].find("$LABEL$")]
                .replace("[B-ASP]", "")
                .replace("[E-ASP]", "")
                .strip()
            )
        return sorted(set(lines), key=lines.index)


def get_aste_example(dataset):
    task = TaskCodeOption.Aspect_Sentiment_Triplet_Extraction
    dataset_file = detect_infer_dataset(aste_dataset_items[dataset], task)

    for fname in dataset_file:
        lines = []
        if isinstance(fname, str):
            fname = [fname]

        for f in fname:
            print("loading: {}".format(f))
            fin = open(f, "r", encoding="utf-8")
            lines.extend(fin.readlines())
            fin.close()
        return sorted(set(lines), key=lines.index)


def get_acos_example(dataset):
    task = "ACOS"
    dataset_file = detect_infer_dataset(acos_dataset_items[dataset], task)

    for fname in dataset_file:
        lines = []
        if isinstance(fname, str):
            fname = [fname]

        for f in fname:
            print("loading: {}".format(f))
            fin = open(f, "r", encoding="utf-8")
            lines.extend(fin.readlines())
            fin.close()
        lines = [line.split("####")[0] for line in lines]
        return sorted(set(lines), key=lines.index)


try:
    from pyabsa import AspectTermExtraction as ATEPC

    atepc_dataset_items = {
        dataset.name: dataset for dataset in ATEPC.ATEPCDatasetList()
    }
    atepc_dataset_dict = {
        dataset.name: get_atepc_example(dataset.name)
        for dataset in ATEPC.ATEPCDatasetList()
    }
    aspect_extractor = ATEPC.AspectExtractor(checkpoint="multilingual")
except Exception as e:
    print(e)
    atepc_dataset_items = {}
    atepc_dataset_dict = {}
    aspect_extractor = None

try:
    from pyabsa import AspectSentimentTripletExtraction as ASTE

    aste_dataset_items = {dataset.name: dataset for dataset in ASTE.ASTEDatasetList()}
    aste_dataset_dict = {
        dataset.name: get_aste_example(dataset.name)
        for dataset in ASTE.ASTEDatasetList()[:-1]
    }
    triplet_extractor = ASTE.AspectSentimentTripletExtractor(checkpoint="multilingual")
except Exception as e:
    print(e)
    aste_dataset_items = {}
    aste_dataset_dict = {}
    triplet_extractor = None

try:
    from pyabsa import ABSAInstruction

    acos_dataset_items = {
        dataset.name: dataset for dataset in ABSAInstruction.ACOSDatasetList()
    }
    acos_dataset_dict = {
        dataset.name: get_acos_example(dataset.name)
        for dataset in ABSAInstruction.ACOSDatasetList()
    }
    quadruple_extractor = ABSAInstruction.ABSAGenerator("multilingual")
except Exception as e:
    print(e)
    acos_dataset_items = {}
    acos_dataset_dict = {}
    quadruple_extractor = None


def perform_atepc_inference(text, dataset):
    if not text:
        text = atepc_dataset_dict[dataset][
            random.randint(0, len(atepc_dataset_dict[dataset]) - 1)
        ]

    result = aspect_extractor.predict(text, pred_sentiment=True)

    result = pd.DataFrame(
        {
            "aspect": result["aspect"],
            "sentiment": result["sentiment"],
            # 'probability': result[0]['probs'],
            "confidence": [round(x, 4) for x in result["confidence"]],
            "position": result["position"],
        }
    )
    return result, "{}".format(text)


def perform_aste_inference(text, dataset):
    if not text:
        text = aste_dataset_dict[dataset][
            random.randint(0, len(aste_dataset_dict[dataset]) - 1)
        ]

    result = triplet_extractor.predict(text)

    pred_triplets = pd.DataFrame(result["Triplets"])
    true_triplets = pd.DataFrame(result["True Triplets"])
    return pred_triplets, true_triplets, "{}".format(text.split("####")[0])


def perform_acos_inference(text, dataset):
    if not text:
        text = acos_dataset_dict[dataset][
            random.randint(0, len(acos_dataset_dict[dataset]) - 1)
        ]

    raw_output = quadruple_extractor.predict(text.split("####")[0], max_length=128)

    result = raw_output["Quadruples"]
    result = pd.DataFrame(result)
    return result, text


def run_demo(text, dataset, task):
    try:
        data = {
            "text": text,
            "dataset": dataset,
            "task": task,
        }
        response = requests.post("https://pyabsa.pagekite.me/api/inference", json=data)
        result = response.json()
        print(response.json())
        if task == "ATEPC":
            return (
                pd.DataFrame(
                    {
                        "aspect": result["aspect"],
                        "sentiment": result["sentiment"],
                        # 'probability': result[0]['probs'],
                        "confidence": [round(x, 4) for x in result["confidence"]],
                        "position": result["position"],
                    }
                ),
                result["text"],
            )
        elif task == "ASTE":
            return (
                        pd.DataFrame(result["pred_triplets"]),
                        pd.DataFrame(result["true_triplets"]),
                        result["text"],
                    )
        elif task == "ACOS":
            return pd.DataFrame(result["Quadruples"]), result["text"]

    except Exception as e:
        print(e)
        print("Failed to connect to the server, running locally...")
        return inference(text, dataset, task)


def inference(text, dataset, task):
    if task == "ATEPC":
        return perform_atepc_inference(text, dataset)
    elif task == "ASTE":
        return perform_aste_inference(text, dataset)
    elif task == "ACOS":
        return perform_acos_inference(text, dataset)
    else:
        raise Exception("No such task: {}".format(task))


if __name__ == "__main__":
    demo = gr.Blocks()

    with demo:
        with gr.Row():
            if quadruple_extractor:
                with gr.Row():
                    with gr.Column():
                        gr.Markdown(
                            "# <p align='center'> ABSA Quadruple Extraction (Experimental) </p>"
                        )

                        acos_input_sentence = gr.Textbox(
                            placeholder="Leave this box blank and choose a dataset will give you a random example...",
                            label="Example:",
                        )
                        acos_dataset_ids = gr.Radio(
                            choices=[
                                dataset.name
                                for dataset in ABSAInstruction.ACOSDatasetList()
                            ],
                            value="Laptop14",
                            label="Datasets",
                        )
                        acos_inference_button = gr.Button("Let's go!")

                        acos_output_text = gr.TextArea(label="Example:")
                        acos_output_pred_df = gr.DataFrame(label="Predicted Triplets:")

                        acos_inference_button.click(
                            fn=run_demo,
                            inputs=[
                                acos_input_sentence,
                                acos_dataset_ids,
                                gr.Text("ACOS", visible=False),
                            ],
                            outputs=[acos_output_pred_df, acos_output_text],
                        )
        with gr.Row():
            if triplet_extractor:
                with gr.Column():
                    gr.Markdown(
                        "# <p align='center'>Aspect Sentiment Triplet Extraction !</p>"
                    )

                    with gr.Row():
                        with gr.Column():
                            aste_input_sentence = gr.Textbox(
                                placeholder="Leave this box blank and choose a dataset will give you a random example...",
                                label="Example:",
                            )
                            gr.Markdown(
                                "You can find code and dataset at [ASTE examples](https://github.com/yangheng95/PyABSA/tree/v2/examples-v2/aspect_sentiment_triplet_extration)"
                            )
                            aste_dataset_ids = gr.Radio(
                                choices=[
                                    dataset.name
                                    for dataset in ASTE.ASTEDatasetList()[:-1]
                                ],
                                value="Restaurant14",
                                label="Datasets",
                            )
                            aste_inference_button = gr.Button("Let's go!")

                            aste_output_text = gr.TextArea(label="Example:")
                            aste_output_pred_df = gr.DataFrame(
                                label="Predicted Triplets:"
                            )
                            aste_output_true_df = gr.DataFrame(
                                label="Original Triplets:"
                            )

                            aste_inference_button.click(
                                fn=run_demo,
                                inputs=[
                                    aste_input_sentence,
                                    aste_dataset_ids,
                                    gr.Text("ASTE", visible=False),
                                ],
                                outputs=[
                                    aste_output_pred_df,
                                    aste_output_true_df,
                                    aste_output_text,
                                ],
                            )
            if aspect_extractor:
                with gr.Column():
                    gr.Markdown(
                        "# <p align='center'>Multilingual Aspect-based Sentiment Analysis !</p>"
                    )
                    with gr.Row():
                        with gr.Column():
                            atepc_input_sentence = gr.Textbox(
                                placeholder="Leave this box blank and choose a dataset will give you a random example...",
                                label="Example:",
                            )
                            gr.Markdown(
                                "You can find the datasets at [github.com/yangheng95/ABSADatasets](https://github.com/yangheng95/ABSADatasets/tree/v1.2/datasets/text_classification)"
                            )
                            atepc_dataset_ids = gr.Radio(
                                choices=[
                                    dataset.name
                                    for dataset in ATEPC.ATEPCDatasetList()[:-1]
                                ],
                                value="Laptop14",
                                label="Datasets",
                            )
                            atepc_inference_button = gr.Button("Let's go!")

                            atepc_output_text = gr.TextArea(label="Example:")
                            atepc_output_df = gr.DataFrame(label="Prediction Results:")

                            atepc_inference_button.click(
                                fn=run_demo,
                                inputs=[
                                    atepc_input_sentence,
                                    atepc_dataset_ids,
                                    gr.Text("ATEPC", visible=False),
                                ],
                                outputs=[atepc_output_df, atepc_output_text],
                            )

        gr.Markdown(
            """### GitHub Repo: [PyABSA V2](https://github.com/yangheng95/PyABSA)
            ### Author: [Heng Yang](https://github.com/yangheng95) (杨恒)
            [![Downloads](https://pepy.tech/badge/pyabsa)](https://pepy.tech/project/pyabsa) 
            [![Downloads](https://pepy.tech/badge/pyabsa/month)](https://pepy.tech/project/pyabsa)
            """
        )

    demo.launch()