|
| 1 | +# coding:utf-8 |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License" |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +import argparse |
| 15 | +import ast |
| 16 | +import os |
| 17 | +import math |
| 18 | +import six |
| 19 | +import time |
| 20 | +from pathlib import Path |
| 21 | + |
| 22 | +from paddle.fluid.core import PaddleTensor, AnalysisConfig, create_paddle_predictor |
| 23 | +from paddlehub.module.module import runnable, serving, moduleinfo |
| 24 | +from paddlehub.io.parser import txt_parser |
| 25 | +from paddlehub.compat.module.nlp_module import DataFormatError |
| 26 | +import numpy as np |
| 27 | +import paddle |
| 28 | +import paddlehub as hub |
| 29 | + |
| 30 | +@moduleinfo( |
| 31 | + name="Rumor_prediction", |
| 32 | + version="1.0.0", |
| 33 | + type="nlp/semantic_model", |
| 34 | + summary= |
| 35 | + "Is the input text prediction a rumor", |
| 36 | + author="彭兆帅,郑博培", |
| 37 | + author_email="1084667371@qq.com,2733821739@qq.com") |
| 38 | +class Rumorprediction(hub.Module): |
| 39 | + def _initialize(self): |
| 40 | + """ |
| 41 | + Initialize with the necessary elements |
| 42 | + """ |
| 43 | + # 加载模型路径 |
| 44 | + self.default_pretrained_model_path = os.path.join(self.directory, "infer_model") |
| 45 | + |
| 46 | + def Rumor(self, texts, use_gpu=False): |
| 47 | + """ |
| 48 | + Get the input and program of the infer model |
| 49 | +
|
| 50 | + Args: |
| 51 | + image (list(numpy.ndarray)): images data, shape of each is [H, W, C], the color space is BGR. |
| 52 | + use_gpu(bool): Weather to use gpu |
| 53 | + """ |
| 54 | + # 获取数据 |
| 55 | + def get_data(sentence): |
| 56 | + # 读取数据字典 |
| 57 | + with open(self.directory + '/dict.txt', 'r', encoding='utf-8') as f_data: |
| 58 | + dict_txt = eval(f_data.readlines()[0]) |
| 59 | + dict_txt = dict(dict_txt) |
| 60 | + # 把字符串数据转换成列表数据 |
| 61 | + keys = dict_txt.keys() |
| 62 | + data = [] |
| 63 | + for s in sentence: |
| 64 | + # 判断是否存在未知字符 |
| 65 | + if not s in keys: |
| 66 | + s = '<unk>' |
| 67 | + data.append(int(dict_txt[s])) |
| 68 | + return data |
| 69 | + data = [] |
| 70 | + for text in texts: |
| 71 | + text = get_data(text) |
| 72 | + data.append(text) |
| 73 | + base_shape = [[len(c) for c in data]] |
| 74 | + paddle.enable_static() |
| 75 | + place = paddle.CUDAPlace(0) if use_gpu else paddle.CPUPlace() |
| 76 | + exe = paddle.static.Executor(place) |
| 77 | + exe.run(paddle.static.default_startup_program()) |
| 78 | + [infer_program, feeded_var_names, target_var] = paddle.fluid.io.load_inference_model(dirname=self.default_pretrained_model_path, executor=exe) |
| 79 | + # 生成预测数据 |
| 80 | + tensor_words = paddle.fluid.create_lod_tensor(data, base_shape, place) |
| 81 | + # 执行预测 |
| 82 | + result = exe.run(program=infer_program, |
| 83 | + feed={feeded_var_names[0]: tensor_words}, |
| 84 | + fetch_list=target_var) |
| 85 | + # 分类名称 |
| 86 | + names = [ '谣言', '非谣言'] |
| 87 | + |
| 88 | + |
| 89 | + results = [] |
| 90 | + |
| 91 | + # 获取结果概率最大的label |
| 92 | + for i in range(len(data)): |
| 93 | + content = texts[i] |
| 94 | + lab = np.argsort(result)[0][i][-1] |
| 95 | + |
| 96 | + alltext = { |
| 97 | + 'content': content, |
| 98 | + 'prediction': names[lab], |
| 99 | + 'probability': result[0][i][lab] |
| 100 | + } |
| 101 | + alltext = [alltext] |
| 102 | + results = results + alltext |
| 103 | + |
| 104 | + return results |
| 105 | + |
| 106 | + |
| 107 | + def add_module_config_arg(self): |
| 108 | + """ |
| 109 | + Add the command config options |
| 110 | + """ |
| 111 | + self.arg_config_group.add_argument( |
| 112 | + '--use_gpu', |
| 113 | + type=ast.literal_eval, |
| 114 | + default=False, |
| 115 | + help="whether use GPU for prediction") |
| 116 | + |
| 117 | + def add_module_input_arg(self): |
| 118 | + """ |
| 119 | + Add the command input options |
| 120 | + """ |
| 121 | + self.arg_input_group.add_argument( |
| 122 | + '--input_text', |
| 123 | + type=str, |
| 124 | + default=None, |
| 125 | + help="input_text is str") |
| 126 | + @runnable |
| 127 | + def run_cmd(self, argvs): |
| 128 | + """ |
| 129 | + Run as a command |
| 130 | + """ |
| 131 | + self.parser = argparse.ArgumentParser( |
| 132 | + description='Run the %s module.' % self.name, |
| 133 | + prog='hub run %s' % self.name, |
| 134 | + usage='%(prog)s', |
| 135 | + add_help=True) |
| 136 | + |
| 137 | + self.arg_input_group = self.parser.add_argument_group( |
| 138 | + title="Input options", description="Input data. Required") |
| 139 | + self.arg_config_group = self.parser.add_argument_group( |
| 140 | + title="Config options", |
| 141 | + description= |
| 142 | + "Run configuration for controlling module behavior, optional.") |
| 143 | + |
| 144 | + self.add_module_config_arg() |
| 145 | + self.add_module_input_arg() |
| 146 | + |
| 147 | + args = self.parser.parse_args(argvs) |
| 148 | + input_text = [args.input_text] |
| 149 | + results = self.Rumor( |
| 150 | + texts=input_text, use_gpu=args.use_gpu) |
| 151 | + |
| 152 | + return results |
0 commit comments