predict.py 15.5 KB
Newer Older
yuguo-Jack's avatar
yuguo-Jack committed
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
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import copy
import json
import os
import re
from collections import defaultdict
from functools import partial

import paddle
from datasets import Dataset, load_dataset
from paddle import inference
from seqeval.metrics.sequence_labeling import get_entities

from paddlenlp.data import DataCollatorForTokenClassification, DataCollatorWithPadding
from paddlenlp.transformers import SkepTokenizer


def load_dict(dict_path):
    with open(dict_path, "r", encoding="utf-8") as f:
        words = [word.strip() for word in f.readlines()]
        word2id = dict(zip(words, range(len(words))))
        id2word = dict((v, k) for k, v in word2id.items())

        return word2id, id2word


def read_test_file(data_path):
    with open(data_path, "r", encoding="utf-8") as f:
        for line in f.readlines():
            line = line.strip().replace(" ", "")
            yield {"text": line}


def decoding(text, tag_seq):
    assert len(text) == len(tag_seq), f"text len: {len(text)}, tag_seq len: {len(tag_seq)}"

    puncs = list(",.?;!,。?;!")
    splits = [idx for idx in range(len(text)) if text[idx] in puncs]

    prev = 0
    sub_texts, sub_tag_seqs = [], []
    for i, split in enumerate(splits):
        sub_tag_seqs.append(tag_seq[prev:split])
        sub_texts.append(text[prev:split])
        prev = split
    sub_tag_seqs.append(tag_seq[prev:])
    sub_texts.append((text[prev:]))

    ents_list = []
    for sub_text, sub_tag_seq in zip(sub_texts, sub_tag_seqs):
        ents = get_entities(sub_tag_seq, suffix=False)
        ents_list.append((sub_text, ents))

    aps = []
    no_a_words = []
    for sub_tag_seq, ent_list in ents_list:
        sub_aps = []
        sub_no_a_words = []
        for ent in ent_list:
            ent_name, start, end = ent
            if ent_name == "Aspect":
                aspect = sub_tag_seq[start : end + 1]
                sub_aps.append([aspect])
                if len(sub_no_a_words) > 0:
                    sub_aps[-1].extend(sub_no_a_words)
                    sub_no_a_words.clear()
            else:
                ent_name == "Opinion"
                opinion = sub_tag_seq[start : end + 1]
                if len(sub_aps) > 0:
                    sub_aps[-1].append(opinion)
                else:
                    sub_no_a_words.append(opinion)

        if sub_aps:
            aps.extend(sub_aps)
            if len(no_a_words) > 0:
                aps[-1].extend(no_a_words)
                no_a_words.clear()
        elif sub_no_a_words:
            if len(aps) > 0:
                aps[-1].extend(sub_no_a_words)
            else:
                no_a_words.extend(sub_no_a_words)

    if no_a_words:
        no_a_words.insert(0, "None")
        aps.append(no_a_words)

    return aps


def convert_example_to_feature_ext(example, tokenizer, label2id, max_seq_len=512, is_test=False):
    example = example["text"].rstrip().split("\t")
    text = list(example[0])
    if not is_test:
        label = example[1].split(" ")
        assert len(text) == len(label)
        new_text = []
        new_label = []
        for text_ch, label_ch in zip(text, label):
            if text_ch.strip():
                new_text.append(text_ch)
                new_label.append(label_ch)
        new_label = (
            [label2id["O"]] + [label2id[label_term] for label_term in new_label][: (max_seq_len - 2)] + [label2id["O"]]
        )
        encoded_inputs = tokenizer(new_text, is_split_into_words="token", max_seq_len=max_seq_len, return_length=True)
        encoded_inputs["labels"] = new_label
        assert len(encoded_inputs["input_ids"]) == len(
            new_label
        ), f"input_ids: {len(encoded_inputs['input_ids'])}, label: {len(new_label)}"
    else:
        new_text = [text_ch for text_ch in text if text_ch.strip()]
        encoded_inputs = tokenizer(new_text, is_split_into_words="token", max_seq_len=max_seq_len, return_length=True)

    return encoded_inputs


def convert_example_to_feature_cls(example, tokenizer, label2id, max_seq_len=512, is_test=False):
    example = example["text"].rstrip().split("\t")
    if not is_test:
        label = int(example[0])
        aspect_text = example[1]
        text = example[2]
        encoded_inputs = tokenizer(aspect_text, text_pair=text, max_seq_len=max_seq_len, return_length=True)
        encoded_inputs["label"] = label
    else:
        aspect_text = example[0]
        text = example[1]
        encoded_inputs = tokenizer(aspect_text, text_pair=text, max_seq_len=max_seq_len, return_length=True)

    return encoded_inputs


def remove_blanks(example):
    example["text"] = re.sub(" +", "", example["text"])
    return example


class Predictor(object):
    def __init__(self, args):
        self.args = args
        self.ext_predictor, self.ext_input_handles, self.ext_output_hanle = self.create_predictor(args.ext_model_path)
        print(f"ext_model_path: {args.ext_model_path}, {self.ext_predictor}")
        self.cls_predictor, self.cls_input_handles, self.cls_output_hanle = self.create_predictor(args.cls_model_path)
        self.ext_label2id, self.ext_id2label = load_dict(args.ext_label_path)
        self.cls_label2id, self.cls_id2label = load_dict(args.cls_label_path)
        self.tokenizer = SkepTokenizer.from_pretrained(args.base_model_name)

    def create_predictor(self, model_path):
        model_file = model_path + ".pdmodel"
        params_file = model_path + ".pdiparams"
        if not os.path.exists(model_file):
            raise ValueError("not find model file path {}".format(model_file))
        if not os.path.exists(params_file):
            raise ValueError("not find params file path {}".format(params_file))
        config = paddle.inference.Config(model_file, params_file)

        if self.args.device == "gpu":
            # set GPU configs accordingly
            # such as initialize the gpu memory, enable tensorrt
            config.enable_use_gpu(100, 0)
            precision_map = {
                "fp16": inference.PrecisionType.Half,
                "fp32": inference.PrecisionType.Float32,
                "int8": inference.PrecisionType.Int8,
            }
            precision_mode = precision_map[args.precision]

            if args.use_tensorrt:
                config.enable_tensorrt_engine(
                    max_batch_size=self.args.batch_size, min_subgraph_size=30, precision_mode=precision_mode
                )
        elif self.args.device == "cpu":
            # set CPU configs accordingly,
            # such as enable_mkldnn, set_cpu_math_library_num_threads
            config.disable_gpu()
            if args.enable_mkldnn:
                # cache 10 different shapes for mkldnn to avoid memory leak
                config.set_mkldnn_cache_capacity(10)
                config.enable_mkldnn()
            config.set_cpu_math_library_num_threads(args.cpu_threads)
        elif self.args.device == "xpu":
            # set XPU configs accordingly
            config.enable_xpu(100)

        config.switch_use_feed_fetch_ops(False)
        predictor = paddle.inference.create_predictor(config)
        input_handles = [predictor.get_input_handle(name) for name in predictor.get_input_names()]
        output_handle = predictor.get_output_handle(predictor.get_output_names()[0])

        return predictor, input_handles, output_handle

    def predict_ext(self, args):
        datasets = load_dataset("text", data_files={"test": args.test_path})
        datasets["test"] = datasets["test"].map(remove_blanks)
        trans_func = partial(
            convert_example_to_feature_ext,
            tokenizer=self.tokenizer,
            label2id=self.ext_label2id,
            max_seq_len=args.ext_max_seq_len,
            is_test=True,
        )
        test_ds = copy.copy(datasets["test"]).map(trans_func, batched=False, remove_columns=["text"])
        data_collator = DataCollatorForTokenClassification(self.tokenizer, label_pad_token_id=self.ext_label2id["O"])
        test_batch_sampler = paddle.io.BatchSampler(test_ds, batch_size=args.batch_size, shuffle=False)
        test_loader = paddle.io.DataLoader(test_ds, batch_sampler=test_batch_sampler, collate_fn=data_collator)

        results = []
        for bid, batch_data in enumerate(test_loader):
            input_ids, token_type_ids, seq_lens = (
                batch_data["input_ids"],
                batch_data["token_type_ids"],
                batch_data["seq_len"],
            )
            self.ext_input_handles[0].copy_from_cpu(input_ids.numpy())
            self.ext_input_handles[1].copy_from_cpu(token_type_ids.numpy())
            self.ext_predictor.run()
            logits = self.ext_output_hanle.copy_to_cpu()

            predictions = logits.argmax(axis=2)
            for eid, (seq_len, prediction) in enumerate(zip(seq_lens, predictions)):
                idx = bid * args.batch_size + eid
                tag_seq = [self.ext_id2label[idx] for idx in prediction[:seq_len][1:-1]]
                text = datasets["test"][idx]["text"]
                aps = decoding(text[: args.ext_max_seq_len - 2], tag_seq)
                for aid, ap in enumerate(aps):
                    aspect, opinions = ap[0], list(set(ap[1:]))
                    aspect_text = self._concate_aspect_and_opinion(text, aspect, opinions)
                    results.append(
                        {
                            "id": str(idx) + "_" + str(aid),
                            "aspect": aspect,
                            "opinions": opinions,
                            "text": text,
                            "aspect_text": aspect_text,
                        }
                    )

        return results

    def predict_cls(self, args, ext_results):
        text_list = []
        for result in ext_results:
            example = result["aspect_text"] + "\t" + result["text"]
            text_list.append(example)
        ext_results = {"text": text_list}

        dataset = Dataset.from_dict(ext_results)
        trans_func = partial(
            convert_example_to_feature_cls,
            tokenizer=self.tokenizer,
            label2id=self.cls_label2id,
            max_seq_len=args.cls_max_seq_len,
            is_test=True,
        )

        test_ds = dataset.map(trans_func, batched=False, remove_columns=["text"])
        data_collator = DataCollatorWithPadding(self.tokenizer, padding=True)
        test_batch_sampler = paddle.io.BatchSampler(test_ds, batch_size=args.batch_size, shuffle=False)
        test_loader = paddle.io.DataLoader(test_ds, batch_sampler=test_batch_sampler, collate_fn=data_collator)

        results = []
        for batch_data in test_loader:
            input_ids, token_type_ids = batch_data["input_ids"], batch_data["token_type_ids"]
            self.cls_input_handles[0].copy_from_cpu(input_ids.numpy())
            self.cls_input_handles[1].copy_from_cpu(token_type_ids.numpy())
            self.cls_predictor.run()
            logits = self.cls_output_hanle.copy_to_cpu()

            predictions = logits.argmax(axis=1).tolist()
            results.extend(predictions)

        return results

    def post_process(self, args, ext_results, cls_results):
        assert len(ext_results) == len(cls_results)

        collect_dict = defaultdict(list)
        for ext_result, cls_result in zip(ext_results, cls_results):
            ext_result["sentiment_polarity"] = self.cls_id2label[cls_result]
            eid, _ = ext_result["id"].split("_")
            collect_dict[eid].append(ext_result)

        sentiment_results = []
        for eid in collect_dict.keys():
            sentiment_result = {}
            ap_list = []
            for idx, single_ap in enumerate(collect_dict[eid]):
                if idx == 0:
                    sentiment_result["text"] = single_ap["text"]
                ap_list.append(
                    {
                        "aspect": single_ap["aspect"],
                        "opinions": single_ap["opinions"],
                        "sentiment_polarity": single_ap["sentiment_polarity"],
                    }
                )
            sentiment_result["ap_list"] = ap_list
            sentiment_results.append(sentiment_result)

        with open(args.save_path, "w", encoding="utf-8") as f:
            for sentiment_result in sentiment_results:
                f.write(json.dumps(sentiment_result, ensure_ascii=False) + "\n")
        print(f"sentiment analysis results has been saved to path: {args.save_path}")

    def predict(self, args):
        ext_results = self.predict_ext(args)
        cls_results = self.predict_cls(args, ext_results)
        self.post_process(args, ext_results, cls_results)

    def _concate_aspect_and_opinion(self, text, aspect, opinion_words):
        aspect_text = ""
        for opinion_word in opinion_words:
            if text.find(aspect) <= text.find(opinion_word):
                aspect_text += aspect + opinion_word + ","
            else:
                aspect_text += opinion_word + aspect + ","
        aspect_text = aspect_text[:-1]

        return aspect_text


if __name__ == "__main__":
    # yapf: disable
    parser = argparse.ArgumentParser()
    parser.add_argument("--base_model_name", default='skep_ernie_1.0_large_ch', type=str, help="Base model name, SKEP used by default", )
    parser.add_argument("--ext_model_path", type=str, default=None, help="The path of extraction model path that you want to load.")
    parser.add_argument("--cls_model_path", type=str, default=None, help="The path of classification model path that you want to load.")
    parser.add_argument("--ext_label_path", type=str, default=None, help="The path of extraction label dict.")
    parser.add_argument("--cls_label_path", type=str, default=None, help="The path of classification label dict.")
    parser.add_argument('--test_path', type=str, default=None, help="The path of test set that you want to predict.")
    parser.add_argument('--save_path', type=str, required=True, default=None, help="The saving path of predict results.")
    parser.add_argument("--batch_size", type=int, default=16, help="Batch size per GPU/CPU for training.")
    parser.add_argument("--ext_max_seq_len", type=int, default=512, help="The maximum total input sequence length after tokenization for extraction model.")
    parser.add_argument("--cls_max_seq_len", type=int, default=512, help="The maximum total input sequence length after tokenization for classification model.")
    parser.add_argument("--use_tensorrt", action='store_true', help="Whether to use inference engin TensorRT.")
    parser.add_argument("--precision", default="fp32", type=str, choices=["fp32", "fp16", "int8"], help='The tensorrt precision.')
    parser.add_argument("--device", default="gpu", choices=["gpu", "cpu", "xpu"], help="Device selected for inference.")
    parser.add_argument('--cpu_threads', default=10, type=int, help='Number of threads to predict when using cpu.')
    parser.add_argument('--enable_mkldnn', default=False, type=eval, choices=[True, False], help='Enable to use mkldnn to speed up when using cpu.')
    args = parser.parse_args()
    # yapf: enbale

    predictor = Predictor(args)
    predictor.predict(args)