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/pretrained/dep.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-29 02:55
from hanlp_common.constant import HANLP_URL
CTB5_BIAFFINE_DEP_ZH = HANLP_URL + 'dep/biaffine_ctb5_20191229_025833.zip'
'Biaffine LSTM model (:cite:`dozat:17a`) trained on CTB5.'
CTB7_BIAFFINE_DEP_ZH = HANLP_URL + 'dep/biaffine_ctb7_20200109_022431.zip'
'... | 24 | 1,319 |
HanLP | hanlp/layers/cnn_encoder.py | .py | from typing import Optional, Tuple
import torch
from torch.nn import Conv1d, Linear
class CnnEncoder(torch.nn.Module):
"""
A `CnnEncoder` is a combination of multiple convolution layers and max pooling layers. As a
[`Seq2VecEncoder`](./seq2vec_encoder.md), the input to this module is of shape `(batch_si... | 119 | 5,711 |
HanLP | hanlp/layers/feed_forward.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-07-06 14:37
from typing import Union, List
from hanlp.layers import feedforward
from hanlp.common.structure import ConfigTracker
class FeedForward(feedforward.FeedForward, ConfigTracker):
def __init__(self, input_dim: int, num_layers: int, hidden_dims: Union[... | 16 | 571 |
HanLP | hanlp/layers/time_distributed.py | .py | """
A wrapper that unrolls the second (time) dimension of a tensor
into the first (batch) dimension, applies some other `Module`,
and then rolls the time dimension back up.
"""
from typing import List
import torch
class TimeDistributed(torch.nn.Module):
"""
Given an input shaped like `(batch_size, time_ste... | 73 | 2,549 |
HanLP | hanlp/layers/dropout.py | .py | # -*- coding:utf-8 -*-
# Date: 2020-06-05 17:47
from typing import List
import torch
import torch.nn as nn
class WordDropout(nn.Module):
def __init__(self, p: float, oov_token: int, exclude_tokens: List[int] = None) -> None:
super().__init__()
self.oov_token = oov_token
self.p = p
... | 160 | 5,436 |
HanLP | hanlp/layers/feedforward.py | .py | """
A feed-forward neural network.
"""
from typing import List, Union
import torch
from hanlp.utils.torch_util import activation_from_name
class FeedForward(torch.nn.Module):
"""
This `Module` is a feed-forward neural network, just a sequence of `Linear` layers with
activation functions in between.
... | 108 | 4,141 |
HanLP | hanlp/layers/weight_normalization.py | .py | # Copyright 2019 The TensorFlow 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 applica... | 225 | 7,778 |
HanLP | hanlp/layers/scalar_mix.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... | 157 | 7,080 |
HanLP | hanlp/layers/embeddings/fast_text_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-10-29 13:14
import os
import sys
import numpy as np
import tensorflow as tf
from tensorflow.python.keras.utils import tf_utils
from hanlp_common.constant import PAD
from hanlp.utils.io_util import get_resource, stdout_redirected
from hanlp.utils.log_util import log... | 105 | 3,925 |
HanLP | hanlp/layers/embeddings/contextual_word_embedding.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-07-05 13:50
from typing import Optional, Union, List, Any, Dict, Tuple
import torch
from torch import nn
from hanlp_common.configurable import AutoConfigurable
from hanlp.layers.embeddings.embedding import Embedding
from hanlp.layers.scalar_mix import ScalarMixWith... | 188 | 9,795 |
HanLP | hanlp/layers/embeddings/concat_embedding.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-20 17:08
import tensorflow as tf
from hanlp.utils.tf_util import hanlp_register, copy_mask
@hanlp_register
class ConcatEmbedding(tf.keras.layers.Layer):
def __init__(self, *embeddings, trainable=True, name=None, dtype=None, dynamic=False, **kwargs):
... | 61 | 2,064 |
HanLP | hanlp/layers/embeddings/util.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-09 15:45
from typing import Union
import torch
from torch import nn
from hanlp.common.vocab import Vocab
from hanlp.utils.init_util import embedding_uniform
from hanlp.utils.torch_util import load_word2vec, load_word2vec_as_vocab_tensor
def index_word2vec_with... | 111 | 4,121 |
HanLP | hanlp/layers/embeddings/util_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-09 15:46
from typing import Union
import tensorflow as tf
from hanlp.common.transform_tf import Transform
from hanlp.common.vocab_tf import VocabTF
from hanlp.layers.embeddings.char_cnn_tf import CharCNNEmbeddingTF
from hanlp.layers.embeddings.char_rnn_tf import... | 89 | 4,214 |
HanLP | hanlp/layers/embeddings/word2vec.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-09 13:38
import logging
import math
import os.path
from typing import Optional, Callable, Union, List, Dict
import torch
from hanlp_common.configurable import AutoConfigurable
from hanlp_common.constant import HANLP_VERBOSE
from hanlp_trie.trie import Trie
from t... | 356 | 15,031 |
HanLP | hanlp/layers/embeddings/word2vec_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-08-24 21:49
import os
from typing import Tuple, Union, List
import numpy as np
import tensorflow as tf
from tensorflow.python.ops import math_ops
from hanlp.common.vocab_tf import VocabTF
from hanlp.utils.io_util import get_resource
from hanlp.utils.torch_util impo... | 198 | 8,343 |
HanLP | hanlp/layers/embeddings/char_rnn_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-20 17:02
import tensorflow as tf
from hanlp.common.vocab_tf import VocabTF
from hanlp.utils.tf_util import hanlp_register
@hanlp_register
class CharRNNEmbeddingTF(tf.keras.layers.Layer):
def __init__(self, word_vocab: VocabTF, char_vocab: VocabTF,
... | 62 | 2,837 |
HanLP | hanlp/layers/embeddings/contextual_string_embedding.py | .py | # Most codes of this file is adopted from flair, which is licenced under:
#
# The MIT License (MIT)
#
# Flair is licensed under the following MIT License (MIT) Copyright © 2018 Zalando SE, https://tech.zalando.com
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associ... | 217 | 8,591 |
HanLP | hanlp/layers/embeddings/char_cnn.py | .py | # Adopted from https://github.com/allenai/allennlp under Apache Licence 2.0.
# Changed the packaging and created a subclass CharCNNEmbedding
from typing import Union, Tuple, Optional, Callable
import torch
from torch import nn
from hanlp.layers.cnn_encoder import CnnEncoder
from hanlp.layers.time_distributed import Ti... | 148 | 7,434 |
HanLP | hanlp/layers/embeddings/contextual_string_embedding_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-19 03:24
from typing import List
import tensorflow as tf
import numpy as np
from hanlp.components.rnn_language_model_tf import RNNLanguageModel
from hanlp_common.constant import PAD
from hanlp.utils.io_util import get_resource
from hanlp.utils.tf_util import copy... | 136 | 4,988 |
HanLP | hanlp/layers/embeddings/char_rnn.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-02 23:49
from typing import Optional, Callable, Union
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence
from hanlp_common.configurable import AutoConfigurable
from hanlp.common.transform import VocabDict, ToChar
from hanlp.co... | 110 | 4,000 |
HanLP | hanlp/layers/embeddings/char_cnn_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-20 21:15
from functools import reduce
import tensorflow as tf
from hanlp.common.vocab_tf import VocabTF
from hanlp.utils.tf_util import hanlp_register
@hanlp_register
class CharCNNEmbeddingTF(tf.keras.layers.Layer):
def __init__(self, word_vocab: VocabTF, ... | 104 | 3,603 |
HanLP | hanlp/layers/embeddings/embedding.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-02 13:04
from abc import ABC, abstractmethod
from typing import Callable, List, Optional, Iterable
import torch
from torch import nn
from torch.nn import Module
from hanlp_common.configurable import AutoConfigurable
from hanlp.common.transform import TransformLi... | 134 | 3,986 |
HanLP | hanlp/layers/embeddings/fast_text.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-27 15:06
import logging
import os
import sys
from typing import Optional, Callable
import fasttext
import torch
from torch import nn
from torch.nn.utils.rnn import pad_sequence
from hanlp_common.configurable import AutoConfigurable
from torch.utils.data import D... | 168 | 5,697 |
HanLP | hanlp/layers/crf/crf_layer_tf.py | .py | # ******************************************************************************
# Copyright 2017-2018 Intel Corporation
#
# 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.apa... | 166 | 7,242 |
HanLP | hanlp/layers/crf/crf_tf.py | .py | # Copyright 2019 The TensorFlow 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 applica... | 521 | 19,677 |
HanLP | hanlp/layers/crf/crf.py | .py | # Copied from https://github.com/kmkurn/pytorch-crf
# Copyright 2017 Kemal Kurniawan <kemal@kkurniawan.com>
#
# 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 wi... | 354 | 15,514 |
HanLP | hanlp/layers/transformers/pt_imports.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-09 11:25
import os
import warnings
from hanlp.layers.transformers.resource import get_tokenizer_mirror, get_model_mirror
if os.environ.get('TOKENIZERS_PARALLELISM', None) is None:
os.environ["TOKENIZERS_PARALLELISM"] = "false"
from transformers import BertTo... | 70 | 3,352 |
HanLP | hanlp/layers/transformers/utils.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-15 21:22
from collections import defaultdict
from typing import Tuple, Union
import torch
from torch.nn import functional as F
from hanlp.components.parsers.ud import udify_util as util
from hanlp.layers.transformers.pt_imports import PreTrainedModel
def trans... | 370 | 17,183 |
HanLP | hanlp/layers/transformers/utils_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-29 15:32
import tensorflow as tf
from hanlp.optimizers.adamw import create_optimizer
from hanlp.utils.log_util import logger
def config_is(config, model='bert'):
return model in type(config).__name__.lower()
def convert_examples_to_features(
words,... | 192 | 7,861 |
HanLP | hanlp/layers/transformers/__init__.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-29 15:17
# mute transformers
import logging
logging.getLogger('transformers.file_utils').setLevel(logging.ERROR)
logging.getLogger('transformers.filelock').setLevel(logging.ERROR)
logging.getLogger('transformers.tokenization_utils').setLevel(logging.ERROR)
loggin... | 14 | 623 |
HanLP | hanlp/layers/transformers/loader_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-01-04 06:05
import tensorflow as tf
from transformers import TFAutoModel
from hanlp.layers.transformers.pt_imports import AutoTokenizer_, AutoModel_
def build_transformer(transformer, max_seq_length, num_labels, tagging=True, tokenizer_only=False):
tokenizer =... | 25 | 1,214 |
HanLP | hanlp/layers/transformers/encoder.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-22 21:06
import warnings
from typing import Union, Dict, Any, Sequence, Tuple, Optional
import torch
from torch import nn
from hanlp.layers.dropout import WordDropout
from hanlp.layers.scalar_mix import ScalarMixWithDropout, ScalarMixWithDropoutBuilder
from hanlp... | 130 | 6,264 |
HanLP | hanlp/layers/transformers/resource.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2021-05-20 12:43
from hanlp.utils.io_util import get_resource
from hanlp_common.constant import HANLP_URL
tokenizer_mirrors = {
'hfl/chinese-electra-180g-base-discriminator': HANLP_URL + 'transformers/electra_zh_base_20210706_125233.zip',
'hfl/chinese-electra-180... | 39 | 1,865 |
HanLP | hanlp/layers/transformers/tf_imports.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-08 21:57
from transformers import BertTokenizer, BertConfig, PretrainedConfig, TFAutoModel, \
AutoConfig, AutoTokenizer, PreTrainedTokenizer, TFPreTrainedModel, TFAlbertModel, TFAutoModelWithLMHead, \
BertTokenizerFast, TFAlbertForMaskedLM, AlbertConfig, T... | 7 | 331 |
HanLP | hanlp/layers/transformers/relative_transformer.py | .py | # A modified version of the implementation from the following paper:
# TENER: Adapting Transformer Encoder for Named Entity Recognition
# Hang Yan, Bocao Deng, Xiaonan Li, Xipeng Qiu
import math
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from hanlp.common.structure import ConfigTracker
... | 330 | 11,347 |
HanLP | hanlp/optimizers/adamw/__init__.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-11-11 18:44
import tensorflow as tf
from hanlp.optimizers.adamw.optimization import WarmUp, AdamWeightDecay
# from hanlp.optimization.adamw.optimizers_v2 import AdamW
# from hanlp.optimization.adamw.utils import get_weight_decays
# def create_optimizer(model, ini... | 72 | 2,484 |
HanLP | hanlp/optimizers/adamw/optimization.py | .py | # Copyright 2019 The TensorFlow 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 applica... | 241 | 8,702 |
HanLP | hanlp/losses/sparse_categorical_crossentropy.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-20 01:29
import tensorflow as tf
from hanlp.utils.tf_util import hanlp_register
@hanlp_register
class SparseCategoricalCrossentropyOverNonzeroWeights(object):
def __init__(self) -> None:
super().__init__()
self.__name__ = type(self).__name_... | 64 | 2,395 |
HanLP | hanlp/datasets/sts/stsb.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2021-05-20 16:25
from typing import Union, List, Callable
from hanlp.common.dataset import TransformableDataset
from hanlp.utils.io_util import read_cells
STS_B_TRAIN = 'http://ixa2.si.ehu.es/stswiki/images/4/48/Stsbenchmark.tar.gz#sts-train.csv'
STS_B_DEV = 'http://ixa... | 37 | 1,412 |
HanLP | hanlp/datasets/classification/sentiment.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-30 21:03
_ERNIE_TASK_DATA = 'https://ernie.bj.bcebos.com/task_data_zh.tgz#'
CHNSENTICORP_ERNIE_TRAIN = _ERNIE_TASK_DATA + 'chnsenticorp/train.tsv'
CHNSENTICORP_ERNIE_DEV = _ERNIE_TASK_DATA + 'chnsenticorp/dev.tsv'
CHNSENTICORP_ERNIE_TEST = _ERNIE_TASK_DATA + 'chn... | 9 | 340 |
HanLP | hanlp/datasets/coref/loaders/conll12coref.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-07-04 15:33
import collections
import os
from typing import Union, List, Callable, DefaultDict, Tuple, Optional, Iterator
from hanlp.datasets.srl.loaders.ontonotes_loader import Ontonotes as _Ontonotes, OntonotesSentence, \
make_coref_instance
from hanlp.common... | 89 | 3,517 |
HanLP | hanlp/datasets/lu/glue.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-11-10 11:47
from hanlp.common.dataset import TableDataset
STANFORD_SENTIMENT_TREEBANK_2_TRAIN = 'http://file.hankcs.com/corpus/SST2.zip#train.tsv'
STANFORD_SENTIMENT_TREEBANK_2_DEV = 'http://file.hankcs.com/corpus/SST2.zip#dev.tsv'
STANFORD_SENTIMENT_TREEBANK_2_TEST... | 26 | 835 |
HanLP | hanlp/datasets/eos/eos.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-07-26 18:12
import itertools
from collections import Counter
from typing import Union, List, Callable
from hanlp.common.dataset import TransformableDataset
from hanlp.utils.io_util import TimingFileIterator
from hanlp.utils.log_util import cprint
from hanlp.utils.st... | 102 | 3,939 |
HanLP | hanlp/datasets/eos/loaders/nn_eos.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-24 22:51
_SETIMES2_EN_HR_SENTENCES_HOME = 'https://schweter.eu/cloud/nn_eos/SETIMES2.en-hr.sentences.tar.xz'
SETIMES2_EN_HR_HR_SENTENCES_TRAIN = _SETIMES2_EN_HR_SENTENCES_HOME + '#SETIMES2.en-hr.hr.sentences.train'
'''Training set of SETimes corpus.'''
SETIMES2_EN... | 18 | 1,233 |
HanLP | hanlp/datasets/srl/loaders/ontonotes_loader.py | .py | from typing import DefaultDict, List, Optional, Iterator, Set, Tuple, Dict
from collections import defaultdict
import codecs
import os
import logging
from hanlp.utils.span_util import TypedSpan, enumerate_spans
from phrasetree.tree import Tree
logger = logging.getLogger(__name__)
class OntonotesSentence:
"""
... | 615 | 27,116 |
HanLP | hanlp/datasets/srl/loaders/conll2012.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-22 19:15
import glob
import json
import os
from typing import Union, List, Callable
from hanlp.utils.span_util import enumerate_spans
from hanlp.common.dataset import TransformableDataset
from hanlp.common.transform import NamedTransform
from hanlp.utils.io_util... | 228 | 8,505 |
HanLP | hanlp/datasets/srl/ontonotes5/_utils.py | .py | #!/usr/bin/env python
import codecs
import collections
import glob
import json
import os
import re
import sys
from pprint import pprint
from typing import List, Dict, Union
from hanlp_common.io import eprint, save_json
from hanlp.common.transform import NormalizeToken
from hanlp.datasets.parsing.loaders._ctb_utils im... | 678 | 25,088 |
HanLP | hanlp/datasets/srl/ontonotes5/__init__.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-11-26 16:07
ONTONOTES5_HOME = 'https://catalog.ldc.upenn.edu/LDC2013T19/LDC2013T19.tgz#/ontonotes-release-5.0/data/'
CONLL12_HOME = ONTONOTES5_HOME + '../conll-2012/'
| 6 | 220 |
HanLP | hanlp/datasets/srl/ontonotes5/chinese.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-11-26 16:07
import os
from urllib.error import HTTPError
import shutil
from hanlp.datasets.srl.ontonotes5 import ONTONOTES5_HOME, CONLL12_HOME
from hanlp.datasets.srl.ontonotes5._utils import make_gold_conll, make_ontonotes_language_jsonlines, \
batch_make_ner_t... | 107 | 6,212 |
HanLP | hanlp/datasets/srl/ontonotes5/english.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-25 18:48
from urllib.error import HTTPError
from hanlp.datasets.srl.ontonotes5 import ONTONOTES5_HOME, CONLL12_HOME
from hanlp.datasets.srl.ontonotes5._utils import make_gold_conll, make_ontonotes_language_jsonlines, \
batch_make_ner_tsv_if_necessary, batch... | 92 | 5,237 |
HanLP | hanlp/datasets/pos/ctb5.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-28 22:51
_CTB5_POS_HOME = 'http://file.hankcs.com/corpus/ctb5.1-pos.zip'
CTB5_POS_TRAIN = f'{_CTB5_POS_HOME}#train.tsv'
'''PoS training set for CTB5.'''
CTB5_POS_DEV = f'{_CTB5_POS_HOME}#dev.tsv'
'''PoS dev set for CTB5.'''
CTB5_POS_TEST = f'{_CTB5_POS_HOME}#tes... | 13 | 356 |
HanLP | hanlp/datasets/tokenization/ctb6.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-28 22:19
_CTB6_CWS_HOME = 'http://file.hankcs.com/corpus/ctb6_cws.zip'
CTB6_CWS_TRAIN = _CTB6_CWS_HOME + '#train.txt'
'''CTB6 training set.'''
CTB6_CWS_DEV = _CTB6_CWS_HOME + '#dev.txt'
'''CTB6 dev set.'''
CTB6_CWS_TEST = _CTB6_CWS_HOME + '#test.txt'
'''CTB6 tes... | 13 | 330 |
HanLP | hanlp/datasets/tokenization/loaders/chunking_dataset.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-03 18:50
from typing import Union, List, Callable
from hanlp.common.dataset import TransformableDataset
from hanlp.utils.io_util import get_resource
from hanlp.utils.span_util import bmes_of
from hanlp.utils.string_util import ispunct
class ChunkingDataset(Tran... | 49 | 2,065 |
HanLP | hanlp/datasets/tokenization/loaders/txt.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-01 12:35
from typing import Union, List, Callable
from hanlp.common.dataset import TransformableDataset
from hanlp.utils.io_util import TimingFileIterator
from hanlp.utils.span_util import words_to_bmes, words_to_bi
from hanlp.utils.string_util import split_long_... | 130 | 5,643 |
HanLP | hanlp/datasets/tokenization/loaders/multi_criteria_cws/mcws_dataset.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-10-21 19:11
import os
from typing import Union, List, Callable, Dict, Iterable
from hanlp.datasets.tokenization.loaders.txt import TextTokenizingDataset
from hanlp.utils.io_util import get_resource
class MultiCriteriaTextTokenizingDataset(TextTokenizingDataset):
... | 99 | 3,860 |
HanLP | hanlp/datasets/tokenization/loaders/multi_criteria_cws/__init__.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-11 20:35
_HOME = 'https://github.com/hankcs/multi-criteria-cws/archive/naive-mix.zip#data/raw/'
CNC_TRAIN_ALL = _HOME + 'cnc/train-all.txt'
CNC_TRAIN = _HOME + 'cnc/train.txt'
CNC_DEV = _HOME + 'cnc/dev.txt'
CNC_TEST = _HOME + 'cnc/test.txt'
CTB_TRAIN_ALL = _HO... | 36 | 1,027 |
HanLP | hanlp/datasets/tokenization/sighan2005/pku.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-21 15:42
from hanlp.datasets.tokenization.sighan2005 import SIGHAN2005, make
SIGHAN2005_PKU_DICT = SIGHAN2005 + "#" + "gold/pku_training_words.utf8"
'''Dictionary built on trainings set.'''
SIGHAN2005_PKU_TRAIN_ALL = SIGHAN2005 + "#" + "training/pku_training.utf8... | 20 | 813 |
HanLP | hanlp/datasets/tokenization/sighan2005/__init__.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-21 15:42
import os
from hanlp.utils.io_util import get_resource, split_file
from hanlp.utils.log_util import logger
SIGHAN2005 = 'http://sighan.cs.uchicago.edu/bakeoff2005/data/icwb2-data.zip'
def make(train):
root = get_resource(SIGHAN2005)
train = os... | 23 | 862 |
HanLP | hanlp/datasets/tokenization/sighan2005/as_.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-21 15:42
from hanlp.datasets.tokenization.sighan2005 import SIGHAN2005, make
SIGHAN2005_AS_DICT = SIGHAN2005 + "#" + "gold/as_training_words.utf8"
'''Dictionary built on trainings set.'''
SIGHAN2005_AS_TRAIN_ALL = SIGHAN2005 + "#" + "training/as_training.utf8"
''... | 20 | 806 |
HanLP | hanlp/datasets/tokenization/sighan2005/msr.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-21 15:42
from hanlp.datasets.tokenization.sighan2005 import SIGHAN2005, make
SIGHAN2005_MSR_DICT = SIGHAN2005 + "#" + "gold/msr_training_words.utf8"
'''Dictionary built on trainings set.'''
SIGHAN2005_MSR_TRAIN_ALL = SIGHAN2005 + "#" + "training/msr_training.utf8... | 20 | 813 |
HanLP | hanlp/datasets/tokenization/sighan2005/cityu.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-21 15:42
from hanlp.datasets.tokenization.sighan2005 import SIGHAN2005, make
SIGHAN2005_CITYU_DICT = SIGHAN2005 + "#" + "gold/cityu_training_words.utf8"
'''Dictionary built on trainings set.'''
SIGHAN2005_CITYU_TRAIN_ALL = SIGHAN2005 + "#" + "training/cityu_train... | 20 | 839 |
HanLP | hanlp/datasets/ner/weibo.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-03 23:33
from hanlp.common.dataset import TransformableDataset
from hanlp.utils.io_util import get_resource, generate_words_tags_from_tsv
_WEIBO_NER_HOME = 'https://github.com/hltcoe/golden-horse/archive/master.zip#data/'
WEIBO_NER_TRAIN = _WEIBO_NER_HOME + 'we... | 16 | 584 |
HanLP | hanlp/datasets/ner/msra.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-28 23:13
_MSRA_NER_HOME = 'http://file.hankcs.com/corpus/msra_ner.zip'
_MSRA_NER_TOKEN_LEVEL_HOME = 'http://file.hankcs.com/corpus/msra_ner_token_level.zip'
MSRA_NER_CHAR_LEVEL_TRAIN = f'{_MSRA_NER_HOME}#train.tsv'
'''Training set of MSRA (:cite:`levow-2006-thir... | 35 | 2,270 |
HanLP | hanlp/datasets/ner/conll03.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-06 15:31
CONLL03_EN_TRAIN = 'https://file.hankcs.com/corpus/conll03_en_iobes.zip#eng.train.tsv'
'''Training set of CoNLL03 (:cite:`tjong-kim-sang-de-meulder-2003-introduction`)'''
CONLL03_EN_DEV = 'https://file.hankcs.com/corpus/conll03_en_iobes.zip#eng.dev.tsv'... | 12 | 565 |
HanLP | hanlp/datasets/ner/resume.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-08 12:10
from hanlp.common.dataset import TransformableDataset
from hanlp.utils.io_util import get_resource, generate_words_tags_from_tsv
_RESUME_NER_HOME = 'https://github.com/jiesutd/LatticeLSTM/archive/master.zip#'
RESUME_NER_TRAIN = _RESUME_NER_HOME + 'Resu... | 17 | 593 |
HanLP | hanlp/datasets/ner/loaders/tsv.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-24 23:09
from typing import Union, List, Callable
from hanlp.common.dataset import TransformableDataset
from hanlp.utils.io_util import get_resource, generate_words_tags_from_tsv
from hanlp.utils.string_util import split_long_sentence_into
class TSVTaggingDatas... | 87 | 3,588 |
HanLP | hanlp/datasets/ner/loaders/json_ner.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-07-21 16:26
import json
import os
from typing import Union, List, Callable, Dict
from hanlp_common.constant import NULL
import hanlp.utils.span_util
from hanlp.common.dataset import TransformableDataset
from hanlp.utils.io_util import TimingFileIterator, read_tsv_a... | 156 | 5,821 |
HanLP | hanlp/datasets/parsing/ptb.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-02-17 15:46
_PTB_HOME = 'https://github.com/KhalilMrini/LAL-Parser/archive/master.zip#data/'
PTB_TRAIN = _PTB_HOME + '02-21.10way.clean'
'''Training set of PTB without empty categories. PoS tags are automatically predicted using 10-fold
jackknifing (:cite:`collins... | 49 | 1,791 |
HanLP | hanlp/datasets/parsing/amr.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-18 17:47
from collections import defaultdict
from copy import copy
from typing import List
import numpy as np
import torch
from hanlp_common.constant import CLS
from hanlp.common.dataset import TransformableDataset, PadSequenceDataLoader
from hanlp.common.trans... | 391 | 16,531 |
HanLP | hanlp/datasets/parsing/ctb7.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-28 18:44
from hanlp.datasets.parsing.ctb5 import _CTB_HOME
_CTB7_HOME = _CTB_HOME + 'BPNN/data/ctb7/'
CTB7_DEP_TRAIN = _CTB7_HOME + 'train.conll'
'''Training set for ctb7 dependency parsing.'''
CTB7_DEP_DEV = _CTB7_HOME + 'dev.conll'
'''Dev set for ctb7 dependen... | 14 | 421 |
HanLP | hanlp/datasets/parsing/pmt1.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2022-02-15 04:14
import os.path
from hanlp.utils.io_util import get_resource
from hanlp.utils.log_util import cprint
from hanlp_common.conll import CoNLLSentence, CoNLLWord
_HOME = 'https://github.com/qiulikun/PKUMultiviewTreebank/archive/refs/heads/master.zip'
PTM_V1_R... | 59 | 2,232 |
HanLP | hanlp/datasets/parsing/semeval15.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-07-28 14:40
# from hanlp.datasets.parsing.conll_dataset import CoNLLParsingDataset
#
#
# class SemEval15Dataset(CoNLLParsingDataset):
# def load_file(self, filepath: str):
# pass
import warnings
from hanlp_common.constant import ROOT, PAD
from hanlp_comm... | 62 | 2,165 |
HanLP | hanlp/datasets/parsing/ctb5.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-28 18:44
from hanlp_common.constant import HANLP_URL
_CTB_HOME = HANLP_URL + 'embeddings/SUDA-LA-CIP_20200109_021624.zip#'
_CTB5_DEP_HOME = _CTB_HOME + 'BPNN/data/ctb5/'
CTB5_DEP_TRAIN = _CTB5_DEP_HOME + 'train.conll'
'''Training set for ctb5 dependency parsing... | 18 | 554 |
HanLP | hanlp/datasets/parsing/ctb8.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-10-14 20:54
from hanlp.datasets.parsing.loaders._ctb_utils import make_ctb
_CTB8_HOME = 'https://wakespace.lib.wfu.edu/bitstream/handle/10339/39379/LDC2013T21.tgz#data/'
CTB8_CWS_TRAIN = _CTB8_HOME + 'tasks/cws/train.txt'
'''Training set for ctb8 Chinese word segm... | 45 | 2,001 |
HanLP | hanlp/datasets/parsing/ctb9.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-10-14 20:54
from urllib.error import HTTPError
from hanlp.datasets.parsing.loaders._ctb_utils import make_ctb
from hanlp.utils.io_util import get_resource, path_from_url
_CTB9_HOME = 'https://catalog.ldc.upenn.edu/LDC2016T13/ctb9.0_LDC2016T13.tgz#data/'
CTB9_CWS_T... | 56 | 2,422 |
HanLP | hanlp/datasets/parsing/semeval16.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-28 00:51
from hanlp_common.conll import CoNLLSentence
import os
from hanlp.utils.io_util import get_resource, merge_files
from hanlp_common.io import eprint
_SEMEVAL2016_HOME = 'https://github.com/HIT-SCIR/SemEval-2016/archive/master.zip'
SEMEVAL2016_NEWS_TRAIN... | 65 | 2,969 |
HanLP | hanlp/datasets/parsing/ud/__init__.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-07 21:45
import os
import shutil
from hanlp.components.parsers.ud.udify_util import get_ud_treebank_files
from hanlp.utils.io_util import get_resource
from hanlp.utils.log_util import flash
def concat_treebanks(home, version):
ud_home = get_resource(home)
... | 31 | 1,130 |
HanLP | hanlp/datasets/parsing/ud/ud27m.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-21 20:39
import os
from hanlp.datasets.parsing.ud import concat_treebanks
from hanlp.datasets.parsing.ud.ud27 import _UD_27_HOME
_UD_27_MULTILINGUAL_HOME = concat_treebanks(_UD_27_HOME, '2.7')
UD_27_MULTILINGUAL_TRAIN = os.path.join(_UD_27_MULTILINGUAL_HOME, 'tr... | 16 | 719 |
HanLP | hanlp/datasets/parsing/ud/ud23m.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-21 20:39
import os
from hanlp.datasets.parsing.ud import concat_treebanks
from .ud23 import _UD_23_HOME
_UD_23_MULTILINGUAL_HOME = concat_treebanks(_UD_23_HOME, '2.3')
UD_23_MULTILINGUAL_TRAIN = os.path.join(_UD_23_MULTILINGUAL_HOME, 'train.conllu')
UD_23_MULTIL... | 13 | 466 |
HanLP | hanlp/datasets/parsing/ud/ud210m.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-21 20:39
import os
from hanlp.datasets.parsing.ud import concat_treebanks
from hanlp.datasets.parsing.ud.ud210 import _UD_210_HOME
_UD_210_MULTILINGUAL_HOME = concat_treebanks(_UD_210_HOME, '2.10')
UD_210_MULTILINGUAL_TRAIN = os.path.join(_UD_210_MULTILINGUAL_HO... | 16 | 733 |
HanLP | hanlp/datasets/parsing/ud/ud210.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-07 21:03
import glob
import os
from hanlp.utils.io_util import uncompress, get_resource
_UD_210_URL = "https://lindat.mff.cuni.cz/repository/xmlui/handle/11234/1-4758/allzip"
_UD_210_HOME = _UD_210_URL + '#ud-treebanks-v2.10/'
_path = get_resource(_UD_210_URL)
i... | 1,020 | 61,702 |
HanLP | hanlp/datasets/parsing/ud/ud27.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-07 21:03
import glob
import os
from hanlp.utils.io_util import uncompress, get_resource
_UD_27_URL = "https://lindat.mff.cuni.cz/repository/xmlui/handle/11234/1-3424/allzip"
_UD_27_HOME = _UD_27_URL + '#ud-treebanks-v2.7/'
_path = get_resource(_UD_27_URL)
if os.... | 856 | 49,930 |
HanLP | hanlp/datasets/parsing/ud/ud23.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-21 20:26
_UD_23_HOME = "https://lindat.mff.cuni.cz/repository/xmlui/bitstream/handle/11234/1-2895/ud-treebanks-v2.3.tgz?sequence=1&isAllowed=y"
_UD_24_HOME = "https://lindat.mff.cuni.cz/repository/xmlui/bitstream/handle/11234/1-2988/ud-treebanks-v2.4.tgz?sequence... | 342 | 26,967 |
HanLP | hanlp/datasets/parsing/loaders/constituency_dataset.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-11-28 19:27
from typing import List
from phrasetree.tree import Tree
from hanlp_common.constant import EOS, BOS
from hanlp.common.dataset import TransformableDataset
class ConstituencyDataset(TransformableDataset):
def load_file(self, filepath: str):
... | 212 | 7,321 |
HanLP | hanlp/datasets/parsing/loaders/conll_dataset.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-08 16:10
from typing import Union, List, Callable, Dict
from hanlp_common.constant import ROOT, EOS, BOS
from hanlp.common.dataset import TransformableDataset
from hanlp.components.parsers.conll import read_conll
from hanlp.utils.io_util import TimingFileIterator... | 107 | 3,931 |
HanLP | hanlp/datasets/parsing/loaders/_ctb_utils.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-11-25 16:14
import os
import shutil
import sys
from collections import defaultdict
from os import listdir
from os.path import join, isfile
from typing import List
from phrasetree.tree import Tree
from hanlp.components.parsers.conll import read_conll
from hanlp.util... | 321 | 11,603 |
HanLP | hanlp/datasets/qa/hotpotqa.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-03-20 19:46
from enum import Enum, auto
import torch
import ujson
from torch.nn.utils.rnn import pad_sequence
from hanlp.common.dataset import TransformableDataset
from hanlp_common.util import merge_list_of_dict
HOTPOT_QA_TRAIN = 'http://curtis.ml.cmu.edu/dataset... | 195 | 6,170 |
HanLP | hanlp/datasets/lm/__init__.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-05 21:41
_PTB_HOME = 'http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz#'
PTB_TOKEN_TRAIN = _PTB_HOME + 'data/ptb.train.txt'
PTB_TOKEN_DEV = _PTB_HOME + 'data/ptb.valid.txt'
PTB_TOKEN_TEST = _PTB_HOME + 'data/ptb.test.txt'
PTB_CHAR_TRAIN = _PTB_HOME + ... | 13 | 452 |
HanLP | hanlp/datasets/lm/loaders/lm_dataset.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-05 21:42
import os
from typing import Union, Callable, List
import hanlp_common.io
import torch
from hanlp.common.dataset import TransformSequentialDataset
from hanlp.common.transform import ToChar, WhitespaceTokenizer, AppendEOS, FieldToIndex
from hanlp.common.... | 143 | 5,025 |
HanLP | hanlp/transform/conll_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-08 15:30
from abc import abstractmethod
from collections import Counter
from typing import Union, Tuple, Iterable, Any, Generator
import numpy as np
import tensorflow as tf
from transformers import PreTrainedTokenizer, PretrainedConfig
from hanlp_common.constant... | 815 | 39,426 |
HanLP | hanlp/transform/transformer_tokenizer.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-03 16:23
import warnings
from typing import Union, Optional
from hanlp_common.constant import BOS, EOS
from hanlp_common.structure import SerializableDict
from hanlp.layers.transformers.pt_imports import PreTrainedTokenizer, PretrainedConfig, AutoTokenizer_
from ... | 717 | 37,066 |
HanLP | hanlp/transform/tacred_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-03-14 17:06
from typing import Union, Tuple
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_common.io import load_json
from hanlp_common... | 107 | 4,510 |
HanLP | hanlp/transform/glue_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-08 16:34
from hanlp_common.structure import SerializableDict
from hanlp.datasets.glu.glue import STANFORD_SENTIMENT_TREEBANK_2_TRAIN, MICROSOFT_RESEARCH_PARAPHRASE_CORPUS_DEV
from hanlp.transform.table_tf import TableTransform
class StanfordSentimentTreebank2Tra... | 44 | 1,461 |
HanLP | hanlp/transform/tsv_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-06-13 21:15
import functools
from abc import ABC
from typing import Tuple, Union, Optional, Iterable, List
import tensorflow as tf
from hanlp_common.structure import SerializableDict
from hanlp.common.transform_tf import Transform
from hanlp.common.vocab_tf import... | 152 | 5,960 |
HanLP | hanlp/transform/txt_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-10-24 15:07
import functools
from abc import ABC
from typing import Tuple, Union, List, Iterable
import tensorflow as tf
from hanlp.common.transform_tf import Transform
from hanlp.common.vocab_tf import VocabTF
from hanlp.utils.io_util import get_resource
from hanl... | 202 | 8,326 |
HanLP | hanlp/transform/table_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-11-10 21:00
from abc import ABC
from typing import Tuple, Union
import numpy as np
import tensorflow as tf
from hanlp_common.structure import SerializableDict
from hanlp.common.transform_tf import Transform
from hanlp_common.constant import PAD
from hanlp.common.voc... | 90 | 3,961 |
HanLP | hanlp/transform/text_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-04 11:46
from typing import Union, Tuple, Iterable, Any
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.metrics.chunking.sequence_lab... | 101 | 3,605 |
HanLP | hanlp/metrics/mtl.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-03 00:16
from hanlp.metrics.metric import Metric
class MetricDict(Metric, dict):
_COLORS = ["magenta", "cyan", "green", "yellow"]
@property
def score(self):
return sum(float(x) for x in self.values()) / len(self)
def __call__(self, pred... | 46 | 1,389 |
HanLP | hanlp/metrics/metric.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-03 11:35
from abc import ABC, abstractmethod
class Metric(ABC):
def __lt__(self, other):
return self.score < other
def __le__(self, other):
return self.score <= other
def __eq__(self, other):
return self.score == other
... | 45 | 834 |
HanLP | hanlp/metrics/spearman_correlation.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2021-05-23 16:12
import torch
from hanlp.metrics.metric import Metric
def _get_ranks(x: torch.Tensor) -> torch.Tensor:
argsort = x.argsort()
ranks = torch.zeros_like(argsort, device=x.device)
ranks[argsort] = torch.arange(len(x), device=x.device)
return... | 87 | 2,885 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.