|
| 1 | +# -*- coding:utf-8 -*- |
| 2 | +# Author: hankcs |
| 3 | +# Date: 2022-09-28 13:31 |
| 4 | +import os |
| 5 | +import sys |
| 6 | +from typing import List, Union |
| 7 | + |
| 8 | +import fasttext |
| 9 | +from fasttext.FastText import _FastText |
| 10 | + |
| 11 | +import hanlp |
| 12 | +from hanlp.common.component import Component |
| 13 | +from hanlp.utils.io_util import get_resource, stdout_redirected |
| 14 | +from hanlp_common.io import load_json |
| 15 | +from hanlp_common.reflection import classpath_of |
| 16 | +from hanlp_common.structure import SerializableDict |
| 17 | + |
| 18 | + |
| 19 | +class FastTextClassifier(Component): |
| 20 | + |
| 21 | + def __init__(self) -> None: |
| 22 | + super().__init__() |
| 23 | + self._model: _FastText = None |
| 24 | + self.config = SerializableDict({ |
| 25 | + 'classpath': classpath_of(self), |
| 26 | + 'hanlp_version': hanlp.__version__, |
| 27 | + }) |
| 28 | + |
| 29 | + def load(self, save_dir, model_path=None, **kwargs): |
| 30 | + config_path = os.path.join(save_dir, 'config.json') |
| 31 | + if os.path.isfile(config_path): |
| 32 | + self.config: dict = load_json(config_path) |
| 33 | + model_path = self.config.get('model_path', model_path) |
| 34 | + else: |
| 35 | + model_path = model_path or save_dir |
| 36 | + self.config['model_path'] = model_path |
| 37 | + filepath = get_resource(model_path) |
| 38 | + with stdout_redirected(to=os.devnull, stdout=sys.stderr): |
| 39 | + self._model = fasttext.load_model(filepath) |
| 40 | + |
| 41 | + def predict(self, text: Union[str, List[str]], topk=False, prob=False, max_len=None, **kwargs): |
| 42 | + """ |
| 43 | + Classify text. |
| 44 | +
|
| 45 | + Args: |
| 46 | + text: A document or a list of documents. |
| 47 | + topk: ``True`` or ``int`` to return the top-k labels. |
| 48 | + prob: Return also probabilities. |
| 49 | + max_len: Strip long document into ``max_len`` characters for faster prediction. |
| 50 | + **kwargs: Not used |
| 51 | +
|
| 52 | + Returns: |
| 53 | + Classification results. |
| 54 | + """ |
| 55 | + num_labels = len(self._model.get_labels()) |
| 56 | + flat = isinstance(text, str) |
| 57 | + if flat: |
| 58 | + text = [text] |
| 59 | + if not isinstance(topk, list): |
| 60 | + topk = [topk] * len(text) |
| 61 | + if not isinstance(prob, list): |
| 62 | + prob = [prob] * len(text) |
| 63 | + if max_len: |
| 64 | + text = [x[:max_len] for x in text] |
| 65 | + text = [x.replace('\n', ' ') for x in text] |
| 66 | + batch_labels, batch_probs = self._model.predict(text, k=num_labels) |
| 67 | + results = [] |
| 68 | + for labels, probs, k, p in zip(batch_labels, batch_probs, topk, prob): |
| 69 | + labels = [self._strip_prefix(x) for x in labels] |
| 70 | + if k is False: |
| 71 | + labels = labels[0] |
| 72 | + elif k is True: |
| 73 | + pass |
| 74 | + elif k: |
| 75 | + labels = labels[:k] |
| 76 | + if p: |
| 77 | + probs = probs.tolist() |
| 78 | + if k is False: |
| 79 | + result = labels, probs[0] |
| 80 | + else: |
| 81 | + result = dict(zip(labels, probs)) |
| 82 | + else: |
| 83 | + result = labels |
| 84 | + results.append(result) |
| 85 | + if flat: |
| 86 | + results = results[0] |
| 87 | + return results |
| 88 | + |
| 89 | + @property |
| 90 | + def labels(self): |
| 91 | + return [self._strip_prefix(x) for x in self._model.get_labels()] |
| 92 | + |
| 93 | + @staticmethod |
| 94 | + def _strip_prefix(label: str): |
| 95 | + return label[len('__label__'):] |
0 commit comments