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/components/parsers/biaffine_tf/model.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-26 23:04
import tensorflow as tf
from hanlp.layers.transformers.tf_imports import TFPreTrainedModel
from hanlp.components.parsers.biaffine_tf.layers import IndependentDropout, SharedDropout, Biaffine, MLP
class BiaffineModelTF(tf.keras.Model):
def __init__(... | 151 | 7,725 |
HanLP | hanlp/components/parsers/biaffine_tf/layers.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-26 23:05
# Ported from the PyTorch implementation https://github.com/zysite/biaffine-parser
import tensorflow as tf
from hanlp.utils.tf_util import tf_bernoulli
class Biaffine(tf.keras.layers.Layer):
def __init__(self, n_in, n_out=1, bias_x=True, bias_y=True... | 121 | 4,019 |
HanLP | hanlp/components/parsers/biaffine/biaffine_2nd_dep.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-06 13:57
import functools
from typing import Union, List, Any
import torch
from hanlp_common.constant import UNK
from hanlp.common.transform import TransformList
from hanlp.common.vocab import Vocab
from hanlp.components.parsers.biaffine.biaffine import Biaffine
... | 214 | 11,525 |
HanLP | hanlp/components/parsers/biaffine/variationalbilstm.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... | 232 | 9,708 |
HanLP | hanlp/components/parsers/biaffine/biaffine_model.py | .py | # -*- coding: utf-8 -*-
from typing import Any, Tuple
import torch
import torch.nn as nn
from torch.nn.utils.rnn import (pack_padded_sequence, pad_packed_sequence,
pad_sequence)
from hanlp.components.parsers.biaffine.biaffine import Biaffine
from hanlp.components.parsers.biaffine.mlp i... | 231 | 10,518 |
HanLP | hanlp/components/parsers/biaffine/biaffine_dep.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-08 20:51
import os
from collections import Counter
from typing import Union, Any, List
from hanlp.layers.transformers.pt_imports import PreTrainedTokenizer, AutoModel_, AutoTokenizer_
import torch
from hanlp.utils.torch_util import lengths_to_mask
from torch impo... | 576 | 26,753 |
HanLP | hanlp/components/parsers/biaffine/structual_attention.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-26 10:40
from typing import Union, List
import torch
import torch.nn.functional as F
from hanlp.utils.torch_util import lengths_to_mask
from torch import nn
from hanlp.common.torch_component import TorchComponent
from hanlp.components.parsers.biaffine.biaffine_d... | 235 | 10,453 |
HanLP | hanlp/components/parsers/biaffine/mlp.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... | 84 | 2,784 |
HanLP | hanlp/components/parsers/biaffine/biaffine_sdp.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-07-28 15:12
import functools
from collections import Counter
from typing import Union, List
import torch
from torch import nn
from hanlp_common.constant import UNK
from hanlp.common.transform import TransformList
from hanlp.components.parsers.biaffine.biaffine_dep ... | 204 | 8,750 |
HanLP | hanlp/components/parsers/biaffine/biaffine.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... | 99 | 3,526 |
HanLP | hanlp/components/eos/ngram.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-07-26 20:19
import logging
from collections import Counter
from typing import Union, List, Callable
import torch
from torch import nn, optim
from torch.nn import BCEWithLogitsLoss
from torch.utils.data import DataLoader
from hanlp.common.dataset import PadSequenceD... | 312 | 12,206 |
HanLP | hanlp/components/tokenizers/transformer.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-11 02:48
import functools
from typing import TextIO, Union, List, Dict, Any, Set
import torch
from hanlp.common.dataset import SamplerBuilder
from hanlp.common.transform import TransformList
from hanlp.components.taggers.transformers.transformer_tagger import Tra... | 300 | 14,815 |
HanLP | hanlp/components/tokenizers/tok_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-10-27 14:30
import logging
from typing import Union, Any, List, Tuple, Iterable
import tensorflow as tf
from hanlp.common.keras_component import KerasComponent
from hanlp.components.taggers.ngram_conv.ngram_conv_tagger import NgramTransform, NgramConvTaggerTF
from ... | 111 | 5,007 |
HanLP | hanlp/components/tokenizers/tok.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-12 13:08
from typing import Any, Callable
from hanlp.components.taggers.rnn_tagger import RNNTagger
from hanlp.datasets.tokenization.loaders.chunking_dataset import ChunkingDataset
from hanlp.metrics.chunking.chunking_f1 import ChunkingF1
from hanlp.utils.span_ut... | 55 | 2,041 |
HanLP | hanlp/components/tokenizers/multi_criteria_cws_transformer.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-10-21 19:55
from typing import List, Union
from hanlp.common.dataset import SamplerBuilder
from hanlp.components.taggers.transformers.transformer_tagger import TransformerTagger
from hanlp.components.tokenizers.transformer import TransformerTaggingTokenizer
from han... | 90 | 4,333 |
HanLP | hanlp/components/distillation/losses.py | .py | # Adopted from https://github.com/airaria/TextBrewer
# Apache License Version 2.0
import torch
import torch.nn.functional as F
from hanlp_common.configurable import AutoConfigurable
def kd_mse_loss(logits_S, logits_T, temperature=1):
'''
Calculate the mse loss between logits_S and logits_T
:param logit... | 286 | 15,061 |
HanLP | hanlp/components/distillation/distillable_component.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-10-17 20:30
from abc import ABC
from copy import copy
import hanlp
from hanlp.common.torch_component import TorchComponent
from hanlp.components.distillation.losses import KnowledgeDistillationLoss
from hanlp.components.distillation.schedulers import TemperatureSche... | 55 | 2,084 |
HanLP | hanlp/components/distillation/schedulers.py | .py | # Adopted from https://github.com/airaria/TextBrewer
# Apache License Version 2.0
from abc import ABC, abstractmethod
import torch
# x is between 0 and 1
from hanlp_common.configurable import AutoConfigurable
def linear_growth_weight_scheduler(x):
return x
def linear_decay_weight_scheduler(x):
return 1 - ... | 125 | 3,585 |
HanLP | hanlp/components/srl/span_bio/baffine_tagging.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-04 13:59
import math
import torch
from torch import nn
from hanlp.components.parsers.biaffine.biaffine import Biaffine
from hanlp.components.parsers.biaffine.mlp import MLP
from hanlp.layers.crf.crf import CRF
class BiaffineTaggingDecoder(nn.Module):
def ... | 76 | 2,306 |
HanLP | hanlp/components/srl/span_bio/span_bio.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-22 20:54
import logging
from copy import copy
from typing import Union, List, Callable, Dict, Any
from bisect import bisect
import torch
import torch.nn.functional as F
from torch import nn
from torch.utils.data import DataLoader
from hanlp_common.constant import... | 385 | 16,294 |
HanLP | hanlp/components/srl/span_rank/srl_eval_utils.py | .py | # Evaluation util functions for PropBank SRL.
import codecs
import collections
import operator
import tempfile
from collections import Counter
from hanlp.metrics.srl.srlconll import official_conll_05_evaluate
_SRL_CONLL_EVAL_SCRIPT = "../run_eval.sh"
def split_example_for_eval(example):
"""Split document-based... | 288 | 11,077 |
HanLP | hanlp/components/srl/span_rank/span_ranking_srl_model.py | .py | from typing import Dict
import hanlp.utils.torch_util
from hanlp.layers.feedforward import FeedForward
from hanlp.layers.time_distributed import TimeDistributed
from .highway_variational_lstm import *
import torch
from ...parsers.biaffine.biaffine import Biaffine
def initializer_1d(input_tensor, initializer):
... | 503 | 27,902 |
HanLP | hanlp/components/srl/span_rank/util.py | .py | # Adopted from https://github.com/KiroSummer/A_Syntax-aware_MTL_Framework_for_Chinese_SRL
import torch
def block_orth_normal_initializer(input_size, output_size):
weight = []
for o in output_size:
for i in input_size:
param = torch.FloatTensor(o, i)
torch.nn.init.orthogonal_(pa... | 13 | 387 |
HanLP | hanlp/components/srl/span_rank/layer.py | .py | # Adopted from https://github.com/KiroSummer/A_Syntax-aware_MTL_Framework_for_Chinese_SRL
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
import torch.nn.functional as F
from hanlp.components.srl.span_rank.util import block_orth_normal_initializer
def get_tensor_np(t):
... | 389 | 16,572 |
HanLP | hanlp/components/srl/span_rank/highway_variational_lstm.py | .py | # Adopted from https://github.com/KiroSummer/A_Syntax-aware_MTL_Framework_for_Chinese_SRL
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torch.autograd import Variable
from .layer import DropoutLayer, HighwayLSTMCell, VariationalLSTMCell
def initializer_1d(input_... | 251 | 12,805 |
HanLP | hanlp/components/srl/span_rank/inference_utils.py | .py | # Adopted from https://github.com/KiroSummer/A_Syntax-aware_MTL_Framework_for_Chinese_SRL
# Inference functions for the SRL model.
import numpy as np
def decode_spans(span_starts, span_ends, span_scores, labels_inv):
"""
Args:
span_starts: [num_candidates,]
span_scores: [num_candidates, num_labe... | 244 | 10,363 |
HanLP | hanlp/components/srl/span_rank/span_rank.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-07-09 18:13
import logging
from bisect import bisect
from typing import Union, List, Callable, Tuple, Dict, Any
from hanlp_common.constant import IDX
from hanlp.layers.transformers.utils import build_optimizer_scheduler_with_transformer
import torch
from torch.utils... | 418 | 18,146 |
HanLP | hanlp/components/ner/ner_tf.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-09-14 20:33
from abc import ABC
from typing import Union, Any, Tuple, Iterable
import tensorflow as tf
from hanlp.components.taggers.transformers.transformer_transform_tf import TransformerTransform
from hanlp.common.transform_tf import Transform
from hanlp.common... | 84 | 4,028 |
HanLP | hanlp/components/ner/rnn_ner.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-06-12 18:00
from typing import Any
import torch
from hanlp_common.util import merge_locals_kwargs
import hanlp.utils.span_util
from hanlp.components.taggers.rnn_tagger import RNNTagger
from hanlp.metrics.chunking.conlleval import SpanF1
class RNNNamedEntityRecogn... | 70 | 2,957 |
HanLP | hanlp/components/ner/transformer_ner.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-10-07 11:08
import functools
from typing import Union, List, Dict, Any, Set
from hanlp_trie import DictInterface, TrieDict
from hanlp.common.dataset import SamplerBuilder
from hanlp.components.taggers.transformers.transformer_tagger import TransformerTagger
from ha... | 241 | 11,407 |
HanLP | hanlp/components/ner/biaffine_ner/biaffine_ner_model.py | .py | from typing import Dict
import torch
import torch.nn.functional as F
from torch import nn
import hanlp.utils.torch_util
from hanlp.layers.time_distributed import TimeDistributed
from ...parsers.biaffine.biaffine import Biaffine
def initializer_1d(input_tensor, initializer):
assert len(input_tensor.size()) == 1
... | 128 | 6,168 |
HanLP | hanlp/components/ner/biaffine_ner/biaffine_ner.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-07-09 18:13
import logging
from typing import Union, List, Callable, Dict, Any
from hanlp_common.constant import IDX
from hanlp.common.structure import History
from hanlp.components.ner.biaffine_ner.biaffine_ner_model import BiaffineNamedEntityRecognitionModel
from ... | 402 | 17,717 |
HanLP | hanlp/components/lm/mlm.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2022-01-29 21:07
import logging
import math
from typing import Callable, Union, List
import torch
from hanlp_common.constant import IDX
from hanlp_common.util import reorder
from torch.utils.data import DataLoader
from transformers import AutoModelForMaskedLM
from transf... | 113 | 4,729 |
HanLP | hanlp/components/amr/seq2seq/evaluation.py | .py | from pathlib import Path
import penman
def write_predictions(predictions_path, tokenizer, graphs):
pieces = [penman.encode(g) for g in graphs]
text = '\n\n'.join(pieces)
if tokenizer:
text = text.replace(tokenizer.INIT, '')
Path(predictions_path).write_text(text)
return predictions_path
... | 25 | 681 |
HanLP | hanlp/components/amr/seq2seq/optim.py | .py | # taken from
import math
import torch
from torch.optim.optimizer import Optimizer
class RAdam(Optimizer):
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, degenerated_to_sgd=True):
if not 0.0 <= lr:
raise ValueError("Invalid learning rate: {}".format(lr))
... | 101 | 4,368 |
HanLP | hanlp/components/amr/seq2seq/seq2seq_amr_parser.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2021-04-28 17:33
import datetime
import functools
import logging
import os
from typing import Union, List, Callable
import torch
from torch.utils.data import DataLoader
from transformers import get_constant_schedule_with_warmup, T5ForConditionalGeneration
from transforme... | 511 | 23,026 |
HanLP | hanlp/components/amr/seq2seq/dataset/linearization.py | .py | import abc
import itertools
from collections import deque, defaultdict
import re
from typing import List, Optional, Dict, Any, Set, TypeVar
from dataclasses import dataclass
import networkx as nx
import penman
@dataclass
class SemanticGraph:
nodes_var: List[str]
"""
List of linearized nodes, with special ... | 409 | 13,590 |
HanLP | hanlp/components/amr/seq2seq/dataset/tokenization_bart.py | .py | import copy
import sys
from typing import Set, Iterable
import penman
import regex as re
import torch
from transformers import BartTokenizer
from . import postprocessing
from .linearization import AMRTokens, AMRLinearizer
from .penman import pm_encode
class AMRBartTokenizer(BartTokenizer):
ADDITIONAL = [
... | 672 | 26,401 |
HanLP | hanlp/components/amr/seq2seq/dataset/postprocessing.py | .py | from collections import defaultdict, Counter
import enum
import re
import networkx as nx
import penman
from hanlp.components.amr.seq2seq.dataset.penman import pm_encode
BACKOFF = penman.Graph([
penman.Triple('d2', ':instance', 'dog'),
penman.Triple('b1', ':instance', 'bark-01'),
penman.Triple('b1', ':ARG0... | 637 | 22,677 |
HanLP | hanlp/components/amr/seq2seq/dataset/IO.py | .py | import glob
from typing import List, Union, Iterable
from pathlib import Path
from .penman import pm_load as pm_load
def read_raw_amr_data(
paths: List[Union[str, Path]],
use_recategorization=False,
dereify=True,
remove_wiki=False,
):
assert paths
if not isinstance(paths, Iter... | 36 | 995 |
HanLP | hanlp/components/amr/seq2seq/dataset/penman.py | .py | from typing import List
from penman import load as load_, Graph, Triple
from penman import loads as loads_
from penman import encode as encode_
from penman.model import Model
from penman.models.noop import NoOpModel
from penman.models import amr
import penman
import logging
op_model = Model()
noop_model = NoOpModel()... | 86 | 1,916 |
HanLP | hanlp/components/amr/seq2seq/dataset/dataset.py | .py | from collections import Counter
from typing import Union, List, Callable, Tuple
import torch
import penman
from penman import Graph
from hanlp.common.dataset import TransformableDataset
from hanlp.components.amr.seq2seq.dataset.IO import read_raw_amr_data
from hanlp.components.amr.seq2seq.dataset.penman import role_is_... | 236 | 9,017 |
HanLP | hanlp/components/amr/seq2seq/dataset/tokenization_t5.py | .py | import copy
import sys
from typing import Set, Iterable, Dict
import penman
import regex as re
import torch
import traceback
from transformers import T5Tokenizer, T5TokenizerFast
from . import postprocessing
from .linearization import AMRTokens, AMRLinearizer
from .penman import pm_encode
class AMRT5Tokenizer(T5Tok... | 674 | 26,307 |
HanLP | hanlp/components/amr/amrbart/bart_amr_generation.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2022-12-05 17:56
import logging
import os.path
from typing import Callable, Union, List
import penman
import torch
from torch.utils.data import DataLoader
from hanlp.components.amr.amrbart.data_interface.dataset import AMR2TextDataSet
from hanlp.common.dataset import So... | 140 | 5,619 |
HanLP | hanlp/components/amr/amrbart/bart_amr_parser.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2022-12-05 17:56
import logging
import os.path
from typing import Callable, Union, List
import datetime
import torch
from torch.utils.data import DataLoader
from hanlp.components.amr.amrbart.data_interface.dataset import AMRParsingDataSet
from hanlp.common.dataset impor... | 209 | 8,970 |
HanLP | hanlp/components/amr/amrbart/preprocess/amr_io.py | .py | # coding:utf-8
# the code is migrated from https://github.com/SapienzaNLP/spring
# MIT License
#
# Copyright (c) 2022 xfbai
#
# 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 restrict... | 65 | 2,450 |
HanLP | hanlp/components/amr/amrbart/preprocess/penman_interface.py | .py | # coding:utf-8
# MIT License
#
# Copyright (c) 2022 xfbai
#
# 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... | 81 | 2,502 |
HanLP | hanlp/components/amr/amrbart/preprocess/read_and_process.py | .py | # coding:utf-8
# MIT License
#
# Copyright (c) 2022 xfbai
#
# 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... | 133 | 4,808 |
HanLP | hanlp/components/amr/amrbart/model_interface/tokenization_bart.py | .py | # coding:utf-8
# this is a simplified version of "https://github.com/SapienzaNLP/spring/blob/main/spring_amr/tokenization_bart.py"
# MIT License
#
# Copyright (c) 2022 xfbai
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Softw... | 475 | 18,600 |
HanLP | hanlp/components/amr/amrbart/model_interface/modeling_bart.py | .py | # coding=utf-8
# Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. 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/... | 1,894 | 88,401 |
HanLP | hanlp/components/amr/amrbart/data_interface/dataset.py | .py | # coding:utf-8
# MIT License
#
# Copyright (c) 2022 xfbai
#
# 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... | 75 | 3,300 |
HanLP | hanlp/components/amr/amrbart/common/postprocessing.py | .py | # coding:utf-8
# MIT License
#
# Copyright (c) 2022 xfbai
#
# 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... | 515 | 17,468 |
HanLP | hanlp/components/amr/amrbart/common/constant.py | .py | # coding:utf-8
# MIT License
#
# Copyright (c) 2022 xfbai
#
# 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... | 545 | 57,388 |
HanLP | docs/conf.py | .py | # -- Project information -----------------------------------------------------
import sys
import os
from datetime import datetime
sys.path.append(os.path.abspath('..'))
sys.path.append(os.path.abspath('../plugins/hanlp_common'))
sys.path.append(os.path.abspath('../plugins/hanlp_trie'))
sys.path.append(os.path.abspath(... | 157 | 4,781 |
HanLP | tests/__init__.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-06-13 23:43
import os
root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
def cdroot():
"""
cd to project root, so models are saved in the root folder
"""
os.chdir(root)
| 14 | 265 |
HanLP | tests/test_pipeline.py | .py | import unittest
import hanlp
class TestPipeLine(unittest.TestCase):
def test_copy(self):
pipe = hanlp.pipeline().append(hanlp.utils.rules.split_sentence)
copied_pipe = pipe.copy()
test_text = "今天天气真好。我要去散步。"
assert pipe is not copied_pipe
copied_pipe.append(lambda sent: "".... | 16 | 463 |
HanLP | tests/test_string_util.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2022-03-22 17:17
import unittest
from hanlp.utils.string_util import possible_tokenization
class TestStringUtility(unittest.TestCase):
def test_enumerate_tokenization(self):
text = '商品和服务'
toks = possible_tokenization(text)
assert len(set(to... | 20 | 475 |
HanLP | tests/test_config_tracker.py | .py | import unittest
from hanlp.common.structure import ConfigTracker
class MyClass(ConfigTracker):
def __init__(self, i_need_this='yes') -> None:
super().__init__(locals())
class TestConfigTracker(unittest.TestCase):
def test_init(self):
obj = MyClass()
self.assertEqual(obj.config.get('... | 19 | 397 |
HanLP | tests/test_rules.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2022-03-22 17:17
import unittest
from hanlp.utils.rules import split_sentence
class TestRules(unittest.TestCase):
def test_eos(self):
self.assertListEqual(list(split_sentence('叶')), ['叶'])
self.assertListEqual(list(split_sentence('他说:“加油。”谢谢')), ['他... | 18 | 538 |
HanLP | tests/test_mtl.py | .py | import hanlp
import unittest
from multiprocessing.dummy import Pool
from hanlp_common.document import Document
mtl = hanlp.load(hanlp.pretrained.mtl.CLOSE_TOK_POS_NER_SRL_DEP_SDP_CON_ELECTRA_SMALL_ZH, devices=-1)
def tokenize(mtl, text):
return mtl(text, tasks='tok/fine')['tok/fine']
class TestMultiTaskLearnin... | 112 | 3,930 |
HanLP | plugins/hanlp_restful/setup.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-28 19:26
from os.path import abspath, join, dirname
from setuptools import find_packages, setup
this_dir = abspath(dirname(__file__))
with open(join(this_dir, 'README.md'), encoding='utf-8') as file:
long_description = file.read()
setup(
name='hanlp_rest... | 39 | 1,286 |
HanLP | plugins/hanlp_restful/hanlp_restful/__init__.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-11-29 17:48
import json
from typing import Union, List, Optional, Dict, Any, Tuple
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from hanlp_common.document import Document
try:
# noinspection Py... | 586 | 29,197 |
HanLP | plugins/hanlp_restful/tests/test_client.py | .py | import unittest
from hanlp_restful import HanLPClient
class TestClient(unittest.TestCase):
def setUp(self) -> None:
self.HanLP = HanLPClient('https://hanlp.hankcs.com/api', auth=None) # Fill in your auth
def test_raw_text(self):
text = '2021年HanLPv2.1为生产环境带来次世代最先进的多语种NLP技术。阿婆主来到北京立方庭参观自然语义... | 77 | 5,051 |
HanLP | plugins/hanlp_trie/setup.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-28 19:26
from os.path import abspath, join, dirname
from setuptools import find_packages, setup
this_dir = abspath(dirname(__file__))
with open(join(this_dir, 'README.md'), encoding='utf-8') as file:
long_description = file.read()
setup(
name='hanlp_trie... | 39 | 1,282 |
HanLP | plugins/hanlp_trie/hanlp_trie/dictionary.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-11-29 17:53
from abc import ABC, abstractmethod
from typing import List, Tuple, Any, Dict, Union, Sequence, Iterable, Optional
from hanlp_common.configurable import Configurable
from hanlp_common.reflection import classpath_of
from hanlp_trie.trie import Trie
clas... | 217 | 8,677 |
HanLP | plugins/hanlp_trie/hanlp_trie/trie.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-01-04 23:46
from typing import Dict, Any, List, Tuple, Sequence, Union, Iterable, Optional
class Node(object):
def __init__(self, value=None) -> None:
"""A node in a trie tree.
Args:
value: The value associated with this node.
... | 165 | 5,727 |
HanLP | plugins/hanlp_trie/tests/test_trie_dict.py | .py | import unittest
from hanlp_trie import TrieDict
class TestTrieDict(unittest.TestCase):
def setUp(self) -> None:
super().setUp()
self.text = '第一个词语很重要,第二个词语也很重要'
self.trie_dict = TrieDict({'重要': 'important'})
def test_tokenize(self):
self.assertEqual([(6, 8, 'important'), (16... | 40 | 1,436 |
HanLP | plugins/hanlp_trie/tests/test_trie.py | .py | import unittest
from hanlp_trie import Trie
class TestTrie(unittest.TestCase):
def build_small_trie(self):
return Trie({'商品': 'goods', '和': 'and', '和服': 'kimono', '服务': 'service', '务': 'business'})
def assert_results_valid(self, text, results, trie):
for begin, end, value in results:
... | 52 | 1,789 |
HanLP | plugins/hanlp_common/setup.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-28 19:26
from os.path import abspath, join, dirname
from setuptools import find_packages, setup
this_dir = abspath(dirname(__file__))
with open(join(this_dir, 'README.md'), encoding='utf-8') as file:
long_description = file.read()
setup(
name='hanlp_comm... | 46 | 1,474 |
HanLP | plugins/hanlp_common/hanlp_common/structure.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-19 20:56
import json
from collections import OrderedDict
from hanlp_common.io import filename_is_json, save_pickle, load_pickle, save_json, load_json
class Serializable(object):
"""A super class for save/load operations."""
def save(self, path, fmt=Non... | 101 | 2,462 |
HanLP | plugins/hanlp_common/hanlp_common/io.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-16 22:38
import json
import os
import pickle
import sys
from typing import Union
def save_pickle(item, path):
with open(path, 'wb') as f:
pickle.dump(item, f)
def load_pickle(path):
with open(path, 'rb') as f:
return pickle.load(f)
de... | 42 | 1,026 |
HanLP | plugins/hanlp_common/hanlp_common/amr.py | .py | # MIT License
#
# Copyright (c) 2019 Sheng 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, ... | 964 | 35,784 |
HanLP | plugins/hanlp_common/hanlp_common/visualization.py | .py | # -*- coding:utf-8 -*-
# Modified from https://github.com/tylerneylon/explacy
import io
from collections import defaultdict
from pprint import pprint
from phrasetree.tree import Tree
def make_table(rows, insert_header=False):
col_widths = [max(len(s) for s in col) for col in zip(*rows[1:])]
rows[0] = [x[:l] ... | 307 | 10,303 |
HanLP | plugins/hanlp_common/hanlp_common/util.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-10-27 19:09
import math
from typing import Union, Any, List, Optional, Tuple, Iterable, Dict
import inspect
from itertools import chain, combinations
def powerset(iterable, descending=False):
"""
powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,... | 249 | 7,087 |
HanLP | plugins/hanlp_common/hanlp_common/reflection.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-28 16:41
import importlib
import inspect
def classpath_of(obj) -> str:
"""get the full class path of object
Args:
obj: return:
Returns:
"""
if inspect.isfunction(obj):
return module_path_of(obj)
return "{0}.{1}".format(ob... | 64 | 1,357 |
HanLP | plugins/hanlp_common/hanlp_common/conll.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-19 20:50
from typing import Union, List
from hanlp_common.structure import SerializableDict
from hanlp_common.visualization import pretty_tree_horizontal, make_table, markdown_table
class CoNLLWord(SerializableDict):
def __init__(self, id, form, lemma=None,... | 377 | 14,540 |
HanLP | plugins/hanlp_common/hanlp_common/constant.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-06-13 22:41
import os
PAD = '<pad>'
'''Padding token.'''
UNK = '<unk>'
'''Unknown token.'''
CLS = '[CLS]'
BOS = '<bos>'
EOS = '<eos>'
ROOT = BOS
IDX = '_idx_'
'''Key for index.'''
HANLP_URL = os.getenv('HANLP_URL', 'https://file.hankcs.com/hanlp/')
'''Resource URL.'... | 30 | 735 |
HanLP | plugins/hanlp_common/hanlp_common/configurable.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-16 22:24
from hanlp_common.reflection import str_to_type, classpath_of
class Configurable(object):
@staticmethod
def from_config(config: dict, **kwargs):
"""Build an object from config.
Args:
config: A ``dict`` holding paramete... | 49 | 1,753 |
HanLP | plugins/hanlp_common/hanlp_common/document.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-31 04:16
import json
import re
import warnings
from typing import List, Union
from phrasetree.tree import Tree
from hanlp_common.conll import CoNLLUWord, CoNLLSentence, CoNLLSentenceList
from hanlp_common.constant import PRED, IPYTHON
from hanlp_common.util impo... | 545 | 22,342 |
HanLP | plugins/hanlp_demo/setup.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-28 19:26
from os.path import abspath, join, dirname
from setuptools import find_packages, setup
this_dir = abspath(dirname(__file__))
with open(join(this_dir, 'README.md'), encoding='utf-8') as file:
long_description = file.read()
setup(
name='hanlp_demo... | 39 | 1,282 |
HanLP | plugins/hanlp_demo/hanlp_demo/sent_split.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-31 14:23
import hanlp
split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL)
output = split_sent('3.14 is pi. “你好!!!”——他说。劇場版「Fate/stay night [HF]」最終章公開カウントダウン!')
print('\n'.join(output))
# See also https://hanlp.hankcs.com/docs/api/hanlp/components/eos.htm... | 10 | 382 |
HanLP | plugins/hanlp_demo/hanlp_demo/mul/demo_mtl.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-31 13:51
import hanlp
from hanlp_common.document import Document
HanLP = hanlp.load(hanlp.pretrained.mtl.UD_ONTONOTES_TOK_POS_LEM_FEA_NER_SRL_DEP_SDP_CON_XLMR_BASE)
doc: Document = HanLP([
'In 2021, HanLPv2.1 delivers state-of-the-art multilingual NLP techniq... | 15 | 579 |
HanLP | plugins/hanlp_demo/hanlp_demo/mul/demo_lid.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2022-09-28 16:49
import hanlp
lid = hanlp.load(hanlp.pretrained.classifiers.LID_176_FASTTEXT_BASE)
print(lid('In 2021, HanLPv2.1 delivers state-of-the-art multilingual NLP techniques to production environments.'))
lang, prob = lid('2021年、HanLPv2.1は次世代の最先端多言語NLP技術を本番環境に導... | 20 | 874 |
HanLP | plugins/hanlp_demo/hanlp_demo/mul/demo_lid_restful.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2022-09-28 16:49
from hanlp_restful import HanLPClient
HanLP = HanLPClient('https://hanlp.hankcs.com/api', auth=None, language='mul')
print(HanLP.language_identification([
'In 2021, HanLPv2.1 delivers state-of-the-art multilingual NLP techniques to production enviro... | 13 | 526 |
HanLP | plugins/hanlp_demo/hanlp_demo/mul/train/mul_base.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-03 14:24
from hanlp.common.dataset import SortingSamplerBuilder
from hanlp.common.transform import NormalizeToken
from hanlp.components.mtl.multi_task_learning import MultiTaskLearning
from hanlp.components.mtl.tasks.tok.tag_tok import TaggingTokenization
from han... | 84 | 3,024 |
HanLP | plugins/hanlp_demo/hanlp_demo/en/demo_sdp.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-01-03 15:26
import hanlp
from hanlp_common.conll import CoNLLSentence
# semeval15 offers three independent annotations over the Penn Treebank (PTB)
semantic_parser = hanlp.load(hanlp.pretrained.sdp.SEMEVAL15_PAS_BIAFFINE_EN)
# semantic_parser = hanlp.load(hanlp.pret... | 21 | 689 |
HanLP | plugins/hanlp_demo/hanlp_demo/en/demo_pos.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-01-03 22:16
import hanlp
tagger = hanlp.load(hanlp.pretrained.pos.PTB_POS_RNN_FASTTEXT_EN)
print(tagger([['I', 'banked', '2', 'dollars', 'in', 'a', 'bank', '.'],
['Is', 'this', 'the', 'future', 'of', 'chamber', 'music', '?']]))
| 9 | 296 |
HanLP | plugins/hanlp_demo/hanlp_demo/en/demo_ner.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-01-03 22:50
import hanlp
recognizer = hanlp.load(hanlp.pretrained.ner.CONLL03_NER_BERT_BASE_CASED_EN)
print(recognizer(["President", "Obama", "is", "speaking", "at", "the", "White", "House", "."]))
| 8 | 252 |
HanLP | plugins/hanlp_demo/hanlp_demo/en/demo_lm.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-02-11 09:14
import hanlp
lm = hanlp.load(hanlp.pretrained.rnnlm.FLAIR_LM_FW_WMT11_EN_TF)
print(''.join(lm.generate_text(list('hello'))))
| 8 | 191 |
HanLP | plugins/hanlp_demo/hanlp_demo/en/demo_pipeline.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-01-04 21:05
import hanlp
from hanlp.utils.lang.en.english_tokenizer import tokenize_english
tokenizer = tokenize_english
tagger = hanlp.load(hanlp.pretrained.pos.PTB_POS_RNN_FASTTEXT_EN)
syntactic_parser = hanlp.load(hanlp.pretrained.dep.PTB_BIAFFINE_DEP_EN)
semanti... | 35 | 1,274 |
HanLP | plugins/hanlp_demo/hanlp_demo/en/demo_amr.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2022-01-25 19:09
import hanlp
amr_parser = hanlp.load(hanlp.pretrained.amr.AMR3_SEQ2SEQ_BART_LARGE)
amr = amr_parser('The boy wants the girl to believe him.')
print(amr)
| 9 | 219 |
HanLP | plugins/hanlp_demo/hanlp_demo/en/demo_sentiment_analysis.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-01-01 03:52
import hanlp
classifier = hanlp.load('SST2_ALBERT_BASE_EN')
print(classifier.predict('I feel lucky'))
| 8 | 168 |
HanLP | plugins/hanlp_demo/hanlp_demo/en/train_sst2_albert_base.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-11-10 17:41
import os
from hanlp.components.classifiers.transformer_classifier_tf import TransformerClassifierTF
from tests import cdroot
from hanlp.datasets.glu.glue import STANFORD_SENTIMENT_TREEBANK_2_DEV, STANFORD_SENTIMENT_TREEBANK_2_TRAIN, \
STANFORD_SEN... | 22 | 806 |
HanLP | plugins/hanlp_demo/hanlp_demo/en/demo_dep.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-01-01 17:55
import hanlp
syntactic_parser = hanlp.load(hanlp.pretrained.dep.PTB_BIAFFINE_DEP_EN)
sent = [('Is', 'VBZ'),
('this', 'DT'),
('the', 'DT'),
('future', 'NN'),
('of', 'IN'),
('chamber', 'NN'),
('music', 'NN'),... | 17 | 383 |
HanLP | plugins/hanlp_demo/hanlp_demo/en/demo_tok.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-01-02 19:41
from hanlp.utils.lang.en.english_tokenizer import tokenize_english
text = """\
Don't go gentle into that good night.
"""
print(tokenize_english(text))
| 10 | 217 |
HanLP | plugins/hanlp_demo/hanlp_demo/ja/demo_mtl.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2021-05-17 22:30
import hanlp
from hanlp_common.document import Document
HanLP = hanlp.load(hanlp.pretrained.mtl.NPCMJ_UD_KYOTO_TOK_POS_CON_BERT_BASE_CHAR_JA)
doc: Document = HanLP([
'2021年、HanLPv2.1は次世代の最先端多言語NLP技術を本番環境に導入します。',
'奈須きのこは1973年11月28日に千葉県円空山で生まれ、ゲーム... | 14 | 503 |
HanLP | plugins/hanlp_demo/hanlp_demo/zh/train_sota_bert_pku.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-08-11 02:47
from hanlp.common.dataset import SortingSamplerBuilder
from hanlp.components.tokenizers.transformer import TransformerTaggingTokenizer
from hanlp.datasets.tokenization.sighan2005.pku import SIGHAN2005_PKU_TRAIN_ALL, SIGHAN2005_PKU_TEST
from tests import c... | 30 | 946 |
HanLP | plugins/hanlp_demo/hanlp_demo/zh/demo_document.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2022-10-26 23:40
from hanlp_common.document import Document
# Create a document or get a document from HanLP.parse
doc = Document(
tok=[["晓美焰", "来到", "北京", "立方庭", "参观", "自然", "语义", "科技", "公司"]],
pos=[["NR", "VV", "NR", "NR", "VV", "NN", "NN", "NN", "NN"]],
ne... | 67 | 2,452 |
HanLP | plugins/hanlp_demo/hanlp_demo/zh/demo_custom_dict_stl.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-12-15 22:26
import hanlp
from hanlp.components.tokenizers.transformer import TransformerTaggingTokenizer
# 加载一个旧版本单任务模型演示分词错误(最新版已经修复):
tok: TransformerTaggingTokenizer = hanlp.load('https://file.hankcs.com/hanlp/tok/coarse_electra_small_20220220_013548.zip')
tok.d... | 25 | 1,178 |
HanLP | plugins/hanlp_demo/hanlp_demo/zh/demo_sts.py | .py | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2021-05-24 13:15
import hanlp
sim = hanlp.load(hanlp.pretrained.sts.STS_ELECTRA_BASE_ZH)
print(sim([
['看图猜一电影名', '看图猜电影'],
['无线路由器怎么无线上网', '无线上网卡和无线路由器怎么用'],
['北京到上海的动车票', '上海到北京的动车票'],
]))
| 12 | 361 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.