repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
HanLP | hanlp/metrics/f1.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-07-10 14:55
from abc import ABC
from hanlp.metrics.metric import Metric
class F1(Metric, ABC):
def __init__(self, nb_pred=0, nb_true=0, nb_correct=0) -> None:
super().__init__()
self.nb_correct = nb_correct
self.nb_pred = nb_pred
... | 65 | 1,561 |
HanLP | hanlp/metrics/accuracy.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-12 17:56
from typing import Optional, Iterable
import torch
from hanlp.metrics.metric import Metric
class CategoricalAccuracy(Metric):
"""
Categorical Top-K accuracy. Assumes integer labels, with
each item to be classified having a single correct c... | 228 | 9,609 |
HanLP | hanlp/metrics/chunking/chunking_f1.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-11 22:14
import io
from collections import defaultdict
from typing import List, Set, Tuple, Dict
from hanlp.metrics.chunking.conlleval import calculate_metrics, DetailedF1, metrics
from hanlp.metrics.chunking.sequence_labeling import get_entities
from hanlp.metri... | 139 | 5,354 |
HanLP | hanlp/metrics/chunking/chunking_f1_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-29 23:09
from abc import ABC, abstractmethod
import tensorflow as tf
from hanlp.common.vocab_tf import VocabTF
class ChunkingF1_TF(tf.keras.metrics.Metric, ABC):
def __init__(self, tag_vocab: VocabTF, from_logits=True, name='f1', dtype=None, **kwargs):
... | 66 | 2,490 |
HanLP | hanlp/metrics/chunking/bmes_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-09-14 21:55
from hanlp.common.vocab_tf import VocabTF
from hanlp.metrics.chunking.chunking_f1_tf import ChunkingF1_TF
from hanlp.metrics.chunking.sequence_labeling import get_entities
class BMES_F1_TF(ChunkingF1_TF):
def __init__(self, tag_vocab: VocabTF, fro... | 48 | 1,578 |
HanLP | hanlp/metrics/chunking/sequence_labeling.py | .py | # MIT License
#
# Copyright (c) 2018 chakki
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publi... | 405 | 14,144 |
HanLP | hanlp/metrics/chunking/iobes_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-09-14 21:55
from hanlp.common.vocab_tf import VocabTF
from hanlp.metrics.chunking.conlleval import SpanF1
from hanlp.metrics.chunking.chunking_f1_tf import ChunkingF1_TF
class IOBES_F1_TF(ChunkingF1_TF):
def __init__(self, tag_vocab: VocabTF, from_logits=True... | 29 | 984 |
HanLP | hanlp/metrics/chunking/binary_chunking_f1.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-02 14:27
from collections import defaultdict
from typing import List, Union
import torch
from hanlp.metrics.f1 import F1
class BinaryChunkingF1(F1):
def __call__(self, pred_tags: torch.LongTensor, gold_tags: torch.LongTensor, lens: List[int] = None):
... | 34 | 1,223 |
HanLP | hanlp/metrics/chunking/conlleval.py | .py | #!/usr/bin/env python
# Python version of the evaluation script from CoNLL'00-
# Intentional differences:
# - accept any space as delimiter by default
# - optional file argument (default STDIN)
# - option to set boundary (-b argument)
# - LaTeX output (-l argument) not supported
# - raw tags (-r argument) not support... | 345 | 11,543 |
HanLP | hanlp/metrics/srl/srlconll.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-07-16 18:44
import os
from hanlp.utils.io_util import get_resource, get_exitcode_stdout_stderr, run_cmd
def official_conll_05_evaluate(pred_path, gold_path):
script_root = get_resource('http://www.lsi.upc.edu/~srlconll/srlconll-1.1.tgz')
lib_path = f'{scri... | 40 | 1,701 |
HanLP | hanlp/metrics/parsing/labeled_f1.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-27 21:42
from hanlp.metrics.metric import Metric
class LabeledF1(Metric):
def __init__(self):
super(LabeledF1, self).__init__()
self.sum_gold_arcs_wo_punc = 0.0
self.sum_pred_arcs_wo_punc = 0.0
self.correct_arcs_wo_punc = 0... | 104 | 2,727 |
HanLP | hanlp/metrics/parsing/labeled_f1_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-27 21:42
import tensorflow as tf
class LabeledF1TF(object):
def __init__(self):
super(LabeledF1TF, self).__init__()
self.sum_gold_arcs_wo_punc = 0.0
self.sum_pred_arcs_wo_punc = 0.0
self.correct_arcs_wo_punc = 0.0
se... | 104 | 2,854 |
HanLP | hanlp/metrics/parsing/conllx_eval.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-03-08 22:35
import tempfile
from hanlp.utils.io_util import get_resource, get_exitcode_stdout_stderr
CONLLX_EVAL = get_resource(
'https://github.com/elikip/bist-parser/archive/master.zip' + '#bmstparser/src/utils/eval.pl')
def evaluate(gold_file, pred_file):
... | 68 | 2,417 |
HanLP | hanlp/metrics/parsing/span.py | .py | # MIT License
#
# Copyright (c) 2020 Yu Zhang
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, pub... | 104 | 3,222 |
HanLP | hanlp/metrics/parsing/semdep_eval.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2017 Timothy Dozat
#
# 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 ... | 138 | 5,188 |
HanLP | hanlp/metrics/parsing/labeled_score.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-27 00:49
import tensorflow as tf
class LabeledScore(object):
def __init__(self, eps=1e-5):
super(LabeledScore, self).__init__()
self.eps = eps
self.total = 0.0
self.correct_arcs = 0.0
self.correct_rels = 0.0
de... | 60 | 1,457 |
HanLP | hanlp/metrics/parsing/attachmentscore.py | .py | # MIT License
#
# Copyright (c) 2020 Yu Zhang
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, pub... | 76 | 2,433 |
HanLP | hanlp/metrics/amr/smatch_eval.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-24 12:47
import os
import warnings
from typing import Union
from hanlp.metrics.f1 import F1_
from hanlp.metrics.mtl import MetricDict
from hanlp.utils.io_util import get_resource, run_cmd, pushd
from hanlp.utils.log_util import flash
_SMATCH_SCRIPT = 'https://gi... | 102 | 3,591 |
HanLP | hanlp/utils/torch_util.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-09 15:52
import os
import random
import time
from typing import List, Union, Dict, Tuple
import numpy as np
import torch
from pynvml import nvmlDeviceGetHandleByIndex, nvmlDeviceGetMemoryInfo, nvmlInit, nvmlShutdown, nvmlDeviceGetCount
from torch import nn
from t... | 296 | 9,585 |
HanLP | hanlp/utils/span_util.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-12 20:34
import warnings
from typing import Dict, List, Tuple, Callable, Set, Optional
def generate_words_per_line(file_path):
with open(file_path, encoding='utf-8') as src:
for line in src:
cells = line.strip().split()
if not... | 729 | 26,998 |
HanLP | hanlp/utils/io_util.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-08-26 15:02
import contextlib
import glob
import gzip
import json
import logging
import os
import platform
import random
import shlex
import shutil
import sys
import tarfile
import tempfile
import urllib
import zipfile
from contextlib import contextmanager
from pathl... | 720 | 25,526 |
HanLP | hanlp/utils/rules.py | .py | import re
_SEPARATOR = r'@'
_RE_SENTENCE = re.compile(r'(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)', re.UNICODE)
_AB_SENIOR = re.compile(r'([A-Z][a-z]{1,2}\.)\s(\w)', re.UNICODE)
_AB_ACRONYM = re.compile(r'(\.[a-zA-Z]\.)\s(\w)', re.UNICODE)
_UNDO_AB_SENIOR = re.compile(r'([A-Z][a-z]{1,2}\.)' + _SEPARATOR + r'(\w)', re.UN... | 41 | 1,475 |
HanLP | hanlp/utils/log_util.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-08-24 22:12
import datetime
import io
import logging
import os
import sys
from logging import LogRecord
import termcolor
from hanlp_common.constant import IPYTHON
class ColoredFormatter(logging.Formatter):
def __init__(self, fmt=None, datefmt=None, style='%',... | 183 | 5,512 |
HanLP | hanlp/utils/__init__.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-08-24 22:12
from . import rules
def ls_resource_in_module(root) -> dict:
res = dict()
for k, v in root.__dict__.items():
if k.startswith('_') or v == root:
continue
if isinstance(v, str):
if v.startswith('http') and n... | 20 | 639 |
HanLP | hanlp/utils/init_util.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-27 13:25
import math
import torch
from torch import nn
import functools
def embedding_uniform(tensor:torch.Tensor, seed=233):
gen = torch.Generator().manual_seed(seed)
with torch.no_grad():
fan_out = tensor.size(-1)
bound = math.sqrt(3.0... | 17 | 393 |
HanLP | hanlp/utils/string_util.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-08-25 00:19
import unicodedata
from typing import List, Dict, Tuple
def format_scores(results: Dict[str, float]) -> str:
return ' - '.join(f'{k}: {v:.4f}' for (k, v) in results.items())
def ispunct(token):
return all(unicodedata.category(char).startswith(... | 118 | 3,786 |
HanLP | hanlp/utils/component_util.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-31 19:24
import os
from hanlp_common.constant import HANLP_VERBOSE
from hanlp_common.io import load_json, eprint, save_json
from hanlp_common.reflection import object_from_classpath, str_to_type
from hanlp import pretrained
from hanlp import version
from hanlp.com... | 196 | 10,525 |
HanLP | hanlp/utils/tf_util.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-08-27 01:27
import json
import logging
import os
import random
from typing import List
import numpy as np
from hanlp_common.constant import PAD
def set_gpu(idx=0):
"""Restrict TensorFlow to only use the GPU of idx
Args:
idx: (Default value = 0)
... | 222 | 5,648 |
HanLP | hanlp/utils/time_util.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-08-27 00:01
import datetime
import logging
import sys
import time
from typing import Union
from hanlp.utils.log_util import ErasablePrinter, color_format, color_format_len
def human_time_delta(days, hours, minutes, seconds, delimiter=' ') -> str:
units = local... | 247 | 6,719 |
HanLP | hanlp/utils/lang/__init__.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-01-09 18:46
__doc__ = '''
This package holds misc utils for specific languages.
'''
| 8 | 138 |
HanLP | hanlp/utils/lang/en/english_tokenizer.py | .py | #!/usr/bin/env python
"""
Regex-based word tokenizers.
Note that small/full/half-width character variants are *not* covered.
If a text were to contains such characters, normalize it first.
A modified version of https://github.com/fnl/segtok
- dropped dependency on regex
- dropped web_tokenize
- supported concat word
... | 325 | 13,792 |
HanLP | hanlp/utils/lang/ja/bert_tok.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2021-05-13 13:24
from typing import Union, Optional
from transformers import BertTokenizerFast, TensorType, BatchEncoding, BertJapaneseTokenizer as _BertJapaneseTokenizer
from transformers.file_utils import PaddingStrategy
from transformers.tokenization_utils_base import... | 82 | 4,281 |
HanLP | hanlp/utils/lang/zh/localization.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-05 02:09
task = {
'dep': '依存句法树',
'token': '单词',
'pos': '词性',
'ner': '命名实体',
'srl': '语义角色'
}
pos = {
'VA': '表语形容词', 'VC': '系动词', 'VE': '动词有无', 'VV': '其他动词', 'NR': '专有名词', 'NT': '时间名词', 'NN': '其他名词',
'LC': '方位词', 'PN': '代词', 'DT': '限定词... | 36 | 2,318 |
HanLP | hanlp/utils/lang/zh/char_table.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-01-09 19:07
from typing import List
from hanlp.utils.io_util import get_resource
from hanlp_common.io import load_json
HANLP_CHAR_TABLE_TXT = 'https://file.hankcs.com/corpus/char_table.zip#CharTable.txt'
HANLP_CHAR_TABLE_JSON = 'https://file.hankcs.com/corpus/char_... | 54 | 1,350 |
HanLP | hanlp/utils/file_read_backwards/__init__.py | .py | # -*- coding: utf-8 -*-
from .file_read_backwards import FileReadBackwards # noqa: F401
__author__ = """Robin Robin"""
__email__ = 'robinsquare42@gmail.com'
__version__ = '2.0.0'
| 8 | 182 |
HanLP | hanlp/utils/file_read_backwards/buffer_work_space.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""BufferWorkSpace module."""
import os
new_lines = ["\r\n", "\n", "\r"]
new_lines_bytes = [n.encode("ascii") for n in new_lines] # we only support encodings that's backward compat with ascii
class BufferWorkSpace:
"""It is a helper module for FileReadBackwards."... | 203 | 6,248 |
HanLP | hanlp/utils/file_read_backwards/file_read_backwards.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""FileReadBackwards module."""
import io
import os
from .buffer_work_space import BufferWorkSpace
supported_encodings = ["utf-8", "ascii", "latin-1"] # any encodings that are backward compatible with ascii should work
class FileReadBackwards:
"""Class definitio... | 147 | 4,148 |
HanLP | hanlp/callbacks/fine_csv_logger.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-05 02:12
import copy
from io import TextIOWrapper
from typing import List
import numpy as np
import tensorflow as tf
class StreamTableFormatter(object):
def __init__(self) -> None:
super().__init__()
self.col_widths = None
def format_r... | 72 | 2,613 |
HanLP | hanlp/common/transform.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-03 14:44
import logging
import os
from abc import ABC, abstractmethod
from typing import Tuple, Union, List
from hanlp_common.constant import EOS, PAD
from hanlp_common.structure import SerializableDict
from hanlp_common.configurable import Configurable
from hanl... | 539 | 15,420 |
HanLP | hanlp/common/structure.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-08-26 14:58
from typing import Dict
from hanlp_common.configurable import Configurable
from hanlp_common.reflection import classpath_of
from hanlp_common.structure import SerializableDict
class ConfigTracker(Configurable):
def __init__(self, locals_: Dict, ex... | 70 | 2,454 |
HanLP | hanlp/common/keras_component.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-08-26 14:45
import logging
import math
import os
import sys
from abc import ABC, abstractmethod
from typing import Optional, List, Any, Dict
import numpy as np
import tensorflow as tf
import hanlp.utils
from hanlp_common.io import save_json, load_json
from hanlp.ca... | 520 | 25,197 |
HanLP | hanlp/common/transform_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-10-27 14:22
import inspect
from abc import ABC, abstractmethod
from typing import Generator, Tuple, Union, Iterable, Any
import tensorflow as tf
from hanlp_common.structure import SerializableDict
from hanlp.common.vocab_tf import VocabTF
from hanlp.utils.io_util i... | 311 | 11,225 |
HanLP | hanlp/common/vocab.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-06-13 22:42
from collections import Counter
from typing import List, Dict, Union, Iterable
from hanlp_common.constant import UNK, PAD
from hanlp_common.structure import Serializable
from hanlp_common.reflection import classpath_of
class Vocab(Serializable):
de... | 507 | 16,012 |
HanLP | hanlp/common/dataset.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-09 20:27
import math
import os
import random
import tempfile
import warnings
from abc import ABC, abstractmethod
from copy import copy
from logging import Logger
from typing import Union, List, Callable, Iterable, Dict, Any
import torch
import torch.multiprocessi... | 841 | 34,211 |
HanLP | hanlp/common/component.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-08-26 14:45
import inspect
from abc import ABC, abstractmethod
from typing import Any
from hanlp_common.configurable import Configurable
class Component(Configurable, ABC):
@abstractmethod
def predict(self, *args, **kwargs):
"""Predict on data. Thi... | 37 | 1,004 |
HanLP | hanlp/common/vocab_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-06-13 22:42
from typing import List, Dict, Union, Iterable
from hanlp_common.structure import Serializable
from hanlp_common.constant import PAD, UNK
import tensorflow as tf
from tensorflow.python.ops.lookup_ops import index_table_from_tensor
class VocabTF(Seriali... | 271 | 8,615 |
HanLP | hanlp/common/torch_component.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-08 21:20
import logging
import os
import re
import time
from abc import ABC, abstractmethod
from typing import Optional, Dict, List, Union, Callable
import torch
from torch import nn
from torch.utils.data import DataLoader
import hanlp
from hanlp.common.componen... | 643 | 26,624 |
HanLP | hanlp/components/pipeline.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-31 00:22
import types
from typing import Callable, Union, Iterable, Any
from hanlp.components.lambda_wrapper import LambdaComponent
from hanlp.common.component import Component
from hanlp_common.document import Document
from hanlp.utils.component_util import load_... | 180 | 6,522 |
HanLP | hanlp/components/lambda_wrapper.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-31 18:36
from typing import Callable, Any
from hanlp.common.component import Component
from hanlp_common.reflection import classpath_of, object_from_classpath, str_to_type
class LambdaComponent(Component):
def __init__(self, function: Callable) -> None:
... | 30 | 946 |
HanLP | hanlp/components/rnn_language_model_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-04 17:28
from typing import List, Union
import tensorflow as tf
from hanlp.common.keras_component import KerasComponent
from hanlp.transform.text_tf import TextTransform
class RNNLanguageModel(KerasComponent):
def __init__(self, transform: TextTransform =... | 85 | 3,573 |
HanLP | hanlp/components/lemmatizer.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-08 18:35
from typing import List
from hanlp.common.transform import TransformList
from hanlp.components.parsers.ud.lemma_edit import gen_lemma_rule, apply_lemma_rule
from hanlp.components.taggers.transformers.transformer_tagger import TransformerTagger
def add_... | 43 | 1,588 |
HanLP | hanlp/components/classifiers/transformer_classifier_hf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2023-02-17 17:54
import logging
from typing import List, Union, Callable
import torch
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, PreTrainedTokenizer, AutoTokenizer
from hanlp.common.dataset import TableDataset, P... | 126 | 4,984 |
HanLP | hanlp/components/classifiers/fasttext_classifier.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2022-09-28 13:31
import os
import sys
from typing import List, Union
import fasttext
from fasttext.FastText import _FastText
import hanlp
from hanlp.common.component import Component
from hanlp.utils.io_util import get_resource, stdout_redirected
from hanlp_common.io im... | 96 | 3,161 |
HanLP | hanlp/components/classifiers/transformer_classifier.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-08 16:31
import logging
from abc import ABC
from typing import Callable, Union
from typing import List
import torch
from torch import nn
from torch.utils.data import DataLoader
from hanlp_common.constant import IDX
from hanlp.common.dataset import TableDataset, ... | 384 | 17,237 |
HanLP | hanlp/components/classifiers/transformer_classifier_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-11-10 13:19
import math
from typing import Union, Tuple, Any, Iterable
import tensorflow as tf
from hanlp.common.keras_component import KerasComponent
from hanlp_common.structure import SerializableDict
from hanlp.layers.transformers.loader_tf import build_transform... | 194 | 9,668 |
HanLP | hanlp/components/classifiers/transformer_regression_hf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2023-02-17 17:54
import logging
from typing import List, Union, Callable
import torch
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, PreTrainedTokenizer, AutoTokenizer
from hanlp.common.dataset import TableDataset, P... | 100 | 3,949 |
HanLP | hanlp/components/taggers/tagger_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-10-25 21:49
import logging
from abc import ABC
import tensorflow as tf
from hanlp.common.keras_component import KerasComponent
from hanlp.layers.crf.crf_layer_tf import CRF, CRFLoss, CRFWrapper
from hanlp.metrics.chunking.iobes_tf import IOBES_F1_TF
class TaggerC... | 39 | 1,617 |
HanLP | hanlp/components/taggers/rnn_tagger_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-09-14 20:30
from typing import Union, List
import tensorflow as tf
from hanlp.common.transform_tf import Transform
from hanlp.components.taggers.tagger_tf import TaggerComponent
from hanlp.transform.tsv_tf import TSVTaggingTransform
from hanlp.common.vocab_tf impor... | 90 | 4,190 |
HanLP | hanlp/components/taggers/util.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-01 00:31
from typing import List, Tuple
from hanlp.utils.span_util import allowed_transitions
def guess_tagging_scheme(labels: List[str]) -> str:
tagset = set(y.split('-')[0] for y in labels)
for scheme in "BIO", "BIOUL", "BMES", 'IOBES':
if tags... | 23 | 710 |
HanLP | hanlp/components/taggers/rnn_tagger.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-20 13:12
import logging
import torch
from torch import nn
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.data import DataLoader
from hanlp.common.dataset import PadSequenceDataLoader, SortingSampler, TransformableDataset
from hanlp_commo... | 196 | 8,415 |
HanLP | hanlp/components/taggers/tagger.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-11 12:19
import logging
import warnings
from abc import ABC, abstractmethod
from typing import List, TextIO, Any, Union, Dict, Tuple, Sequence
import torch
from torch import optim, nn
from torch.utils.data import DataLoader
from hanlp_common.constant import IDX
... | 232 | 10,084 |
HanLP | hanlp/components/taggers/cnn_tagger_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-10-31 13:52
from abc import ABC
from typing import Union, Tuple, Any, List, Iterable
import tensorflow as tf
from hanlp.components.taggers.tagger_tf import TaggerComponent
from hanlp.transform.tsv_tf import TSVTaggingTransform
from hanlp.common.vocab_tf import Voca... | 126 | 4,928 |
HanLP | hanlp/components/taggers/ngram_conv/ngram_conv_tagger.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-10-25 00:04
from typing import Union, Optional, Tuple, Any, Iterable, List
import tensorflow as tf
from hanlp_common.structure import SerializableDict
from hanlp.components.taggers.tagger_tf import TaggerComponent
from hanlp.transform.tsv_tf import TSVTaggingTrans... | 178 | 8,043 |
HanLP | hanlp/components/taggers/rnn/rnntaggingmodel.py | .py | # MIT License
#
# Copyright (c) 2020 Yu Zhang
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, pub... | 101 | 3,411 |
HanLP | hanlp/components/taggers/transformers/metrics_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-30 16:33
import tensorflow as tf
class Accuracy(tf.keras.metrics.SparseCategoricalAccuracy):
def __init__(self, name='sparse_categorical_accuracy', dtype=None, mask_value=0):
super().__init__(name, dtype)
self.mask_value = mask_value
de... | 16 | 507 |
HanLP | hanlp/components/taggers/transformers/transformer_tagger_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-29 13:55
import math
import tensorflow as tf
from hanlp.common.transform_tf import Transform
from hanlp.components.taggers.tagger_tf import TaggerComponent
from hanlp.components.taggers.transformers.transformer_transform_tf import TransformerTransform
from hanlp... | 95 | 4,176 |
HanLP | hanlp/components/taggers/transformers/transformer_transform_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-29 15:14
from typing import Union, Tuple, List, Iterable
import tensorflow as tf
from hanlp_common.structure import SerializableDict
from hanlp.common.transform_tf import Transform
from hanlp.common.vocab_tf import VocabTF
from hanlp.layers.transformers.utils_tf... | 133 | 6,373 |
HanLP | hanlp/components/taggers/transformers/transformer_tagger.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-15 20:55
import logging
from typing import Union, List
import torch
from torch import nn
from torch.utils.data import DataLoader
from hanlp.common.dataset import PadSequenceDataLoader, SamplerBuilder, TransformableDataset
from hanlp.common.structure import Histo... | 295 | 12,934 |
HanLP | hanlp/components/sts/transformer_sts.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2021-05-20 17:03
import logging
from typing import Union, List
import torch
from torch.utils.data import DataLoader
from hanlp.common.structure import History
from hanlp.layers.transformers.pt_imports import AutoConfig_, AutoTokenizer_
from transformers import AutoModelFo... | 243 | 11,294 |
HanLP | hanlp/components/mtl/multi_task_learning.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-20 19:55
import functools
import itertools
import logging
import os
from collections import defaultdict
from copy import copy
from itertools import chain
from typing import Union, List, Callable, Dict, Optional, Any, Iterable, Tuple
import numpy as np
import torc... | 816 | 38,855 |
HanLP | hanlp/components/mtl/tasks/constituency.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-11-29 16:52
import logging
from typing import Dict, Any, List, Union, Iterable, Callable
import torch
from phrasetree.tree import Tree
from hanlp_common.constant import BOS, EOS
from hanlp_common.document import Document
from hanlp.components.parsers.biaffine.biaff... | 170 | 7,753 |
HanLP | hanlp/components/mtl/tasks/ud.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-17 21:54
import logging
from typing import Dict, Any, List, Union, Iterable, Callable
import torch
from torch.utils.data import DataLoader
from hanlp.common.dataset import SamplerBuilder, PadSequenceDataLoader
from hanlp_common.document import Document
from hanl... | 172 | 7,550 |
HanLP | hanlp/components/mtl/tasks/lem.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-09 16:37
import logging
from typing import Dict, Any, Union, Iterable, Callable, List
import torch
from hanlp.common.dataset import SamplerBuilder, PadSequenceDataLoader
from hanlp.common.transform import VocabDict
from hanlp.components.lemmatizer import Transfor... | 130 | 6,279 |
HanLP | hanlp/components/mtl/tasks/pos.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-10-19 18:56
import logging
from typing import Dict, Any, Union, Iterable, Callable, List, Tuple, Sequence
import torch
from torch.utils.data import DataLoader
from hanlp.common.dataset import SamplerBuilder, PadSequenceDataLoader
from hanlp.common.transform import ... | 166 | 7,924 |
HanLP | hanlp/components/mtl/tasks/amr.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-12 16:05
import logging
from typing import Dict, Any, List, Union, Iterable, Callable
import torch
from stog.data.dataset_readers.amr_parsing.amr import AMRGraph
from stog.data.dataset_readers.amr_parsing.node_utils import NodeUtilities
from stog.data.dataset_rea... | 175 | 8,216 |
HanLP | hanlp/components/mtl/tasks/dep_2nd.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-07 14:14
import logging
from typing import Dict, Any, Union, Iterable, Callable, List
import torch
from hanlp_common.util import merge_locals_kwargs
from torch.utils.data import DataLoader
import hanlp.utils.torch_util
from hanlp.common.dataset import SamplerBui... | 112 | 5,181 |
HanLP | hanlp/components/mtl/tasks/__init__.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-02 16:51
import logging
import os
import warnings
from abc import ABC, abstractmethod
from copy import copy
from typing import Callable, Dict, Any, Union, Iterable, List
import torch
from hanlp_common.util import merge_locals_kwargs
from torch.utils.data import D... | 289 | 11,578 |
HanLP | hanlp/components/mtl/tasks/sdp.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-13 21:39
import logging
from typing import Dict, Any, Union, Iterable, List
import torch
from torch.optim import Adam
from torch.optim.lr_scheduler import ExponentialLR
from torch.utils.data import DataLoader
from hanlp.common.dataset import SamplerBuilder, PadS... | 171 | 8,587 |
HanLP | hanlp/components/mtl/tasks/dep.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-13 21:39
import logging
from typing import Dict, Any, Union, Iterable, List
import torch
from torch.optim import Adam
from torch.optim.lr_scheduler import ExponentialLR
from torch.utils.data import DataLoader
from hanlp.common.dataset import SamplerBuilder, PadS... | 167 | 8,197 |
HanLP | hanlp/components/mtl/tasks/tok/tag_tok.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-11 16:35
import logging
from typing import Dict, Any, Union, Iterable, List, Set
import torch
from torch.utils.data import DataLoader
from hanlp.common.dataset import SamplerBuilder, PadSequenceDataLoader
from hanlp.common.transform import VocabDict, TransformLi... | 206 | 10,201 |
HanLP | hanlp/components/mtl/tasks/tok/reg_tok.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-02 16:51
import logging
from typing import Union, List, Dict, Any, Iterable, Tuple
import torch
from hanlp_common.util import merge_locals_kwargs
from torch import Tensor
from torch.utils.data import DataLoader
import hanlp.utils.torch_util
from hanlp.common.dat... | 110 | 5,225 |
HanLP | hanlp/components/mtl/tasks/srl/bio_srl.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-04 16:50
import logging
from typing import Dict, Any, List, Union, Iterable, Callable
import torch
from torch.utils.data import DataLoader
from hanlp.common.dataset import PadSequenceDataLoader, SamplerBuilder
from hanlp.common.transform import VocabDict
from ha... | 127 | 6,010 |
HanLP | hanlp/components/mtl/tasks/srl/rank_srl.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-05 15:43
import logging
from typing import Union, List, Dict, Any, Iterable, Callable
import torch
from torch.utils.data import DataLoader
from hanlp.common.dataset import SamplerBuilder, PadSequenceDataLoader
from hanlp.common.transform import VocabDict
from ha... | 122 | 6,609 |
HanLP | hanlp/components/mtl/tasks/ner/biaffine_ner.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-05 01:49
import logging
from copy import copy
from typing import Dict, Any, Union, Iterable, List
import torch
from torch.utils.data import DataLoader
from hanlp.common.dataset import SamplerBuilder, PadSequenceDataLoader
from hanlp.common.transform import Vocab... | 108 | 5,782 |
HanLP | hanlp/components/mtl/tasks/ner/tag_ner.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-03 14:35
import logging
from typing import Union, List, Dict, Any, Iterable, Callable, Set, Sequence
import torch
from hanlp_trie import DictInterface
from torch.utils.data import DataLoader
from hanlp.common.dataset import SamplerBuilder, PadSequenceDataLoader
... | 169 | 8,902 |
HanLP | hanlp/components/parsers/biaffine_parser_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-22 12:47
import logging
import math
import os
from typing import List
import numpy as np
import tensorflow as tf
from hanlp.components.parsers.parse_alg import unique_root, adjust_root_score, chu_liu_edmonds
from hanlp.layers.transformers.loader_tf import build_t... | 568 | 29,536 |
HanLP | hanlp/components/parsers/alg_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-26 19:49
# Ported from the PyTorch implementation https://github.com/zysite/biaffine-parser
from typing import List
import numpy as np
import tensorflow as tf
from collections import defaultdict
def nonzero(t: tf.Tensor) -> tf.Tensor:
return tf.where(t > 0)
... | 290 | 10,513 |
HanLP | hanlp/components/parsers/parse_alg.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-04-02 23:20
from collections import defaultdict
import hanlp.utils.span_util
from hanlp.components.parsers.chu_liu_edmonds import decode_mst
import numpy as np
class Tarjan:
"""Computes Tarjan's algorithm for finding strongly connected components (cycles) of a... | 313 | 10,912 |
HanLP | hanlp/components/parsers/chu_liu_edmonds.py | .py | # Adopted from https://github.com/allenai/allennlp under Apache Licence 2.0.
# Changed the packaging.
from typing import List, Set, Tuple, Dict
import numpy
def decode_mst(
energy: numpy.ndarray, length: int, has_labels: bool = True
) -> Tuple[numpy.ndarray, numpy.ndarray]:
"""Note: Counter to typical in... | 315 | 10,923 |
HanLP | hanlp/components/parsers/alg.py | .py | # MIT License
#
# Copyright (c) 2020 Yu Zhang
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, pub... | 762 | 29,627 |
HanLP | hanlp/components/parsers/conll.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-26 15:37
from typing import Union
from hanlp.utils.io_util import get_resource, TimingFileIterator
from hanlp.utils.log_util import logger
def collapse_enhanced_empty_nodes(sent: list):
collapsed = []
for cells in sent:
if isinstance(cells[0], f... | 74 | 2,534 |
HanLP | hanlp/components/parsers/ud/tag_decoder.py | .py | # This file is modified from udify, which is licensed under the MIT license:
# MIT License
#
# Copyright (c) 2019 Dan Kondratyuk
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without rest... | 137 | 5,766 |
HanLP | hanlp/components/parsers/ud/util.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-14 20:44
from hanlp_common.constant import ROOT
from hanlp.components.parsers.ud.lemma_edit import gen_lemma_rule
def generate_lemma_rule(sample: dict):
if 'LEMMA' in sample:
sample['lemma'] = [gen_lemma_rule(word, lemma) if lemma != "_" else "_" for... | 29 | 955 |
HanLP | hanlp/components/parsers/ud/ud_parser.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-14 20:34
import logging
from copy import deepcopy
from typing import Union, List, Callable
import torch
from torch.utils.data import DataLoader
from hanlp_common.constant import IDX
from hanlp.common.dataset import PadSequenceDataLoader, SortingSamplerBuilder
fr... | 347 | 15,674 |
HanLP | hanlp/components/parsers/ud/ud_model.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-15 14:21
from typing import Dict, Any
import torch
from hanlp.components.parsers.biaffine.biaffine_dep import BiaffineDependencyParser
from hanlp.components.parsers.biaffine.biaffine_model import BiaffineDecoder
from hanlp.components.parsers.ud.tag_decoder impo... | 140 | 5,198 |
HanLP | hanlp/components/parsers/ud/lemma_edit.py | .py | """
Utilities for processing lemmas
Adopted from UDPipe Future
https://github.com/CoNLL-UD-2018/UDPipe-Future
"""
def min_edit_script(source, target, allow_copy=False):
"""Finds the minimum edit script to transform the source to the target
Args:
source:
target:
allow_copy: (Default valu... | 136 | 4,317 |
HanLP | hanlp/components/parsers/ud/udify_util.py | .py | # This file is modified from udify and allennlp, which are licensed under the MIT license:
# MIT License
#
# Copyright (c) 2019 Dan Kondratyuk and allennlp
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# i... | 370 | 15,298 |
HanLP | hanlp/components/parsers/constituency/crf_constituency_parser.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-11-28 21:24
import logging
from typing import Union, List
import torch
from phrasetree.tree import Tree
from torch.utils.data import DataLoader
from hanlp_common.constant import BOS, EOS, IDX
from hanlp.common.dataset import TransformableDataset, SamplerBuilder, Pa... | 323 | 13,484 |
HanLP | hanlp/components/parsers/constituency/treecrf.py | .py | # -*- coding:utf-8 -*-
# Adopted from https://github.com/yzhangcs/parser
# MIT License
#
# Copyright (c) 2020 Yu Zhang
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, i... | 361 | 16,923 |
HanLP | hanlp/components/parsers/constituency/crf_constituency_model.py | .py | # -*- coding:utf-8 -*-
# Adopted from https://github.com/yzhangcs/parser
# MIT License
#
# Copyright (c) 2020 Yu Zhang
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, i... | 215 | 9,086 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.