Skip to content

Commit d4fbe48

Browse files
authored
Merge pull request #822 from PyThaiNLP/add-el
Add pythainlp.el
2 parents cc3a2d1 + 9133b5f commit d4fbe48

File tree

8 files changed

+278
-0
lines changed

8 files changed

+278
-0
lines changed

docs/api/el.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
.. currentmodule:: pythainlp.el
2+
3+
pythainlp.el
4+
============
5+
The :class:`pythainlp.el` is Thai Entity Linking with PyThaiNLP.
6+
7+
.. autoclass:: EntityLinker
8+
:members:

docs/notes/installation.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ where ``extras`` can be
3838
- ``coreference_resolution`` (to support coreference esolution with all engine)
3939
- ``wangchanglm`` (to support wangchanglm model)
4040
- ``wsd`` (to support pythainlp.wsd)
41+
- ``el`` (to support pythainlp.el)
4142
- ``full`` (install everything)
4243

4344
For dependency details, look at `extras` variable in `setup.py <https://github.com/PyThaiNLP/pythainlp/blob/dev/setup.py>`_.

notebooks/test_el.ipynb

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "code",
5+
"execution_count": 1,
6+
"id": "c09e8c4b-9cb7-485b-a4f9-c04693a36e06",
7+
"metadata": {},
8+
"outputs": [],
9+
"source": [
10+
"import os\n",
11+
"os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\""
12+
]
13+
},
14+
{
15+
"cell_type": "code",
16+
"execution_count": 2,
17+
"id": "062b3aa5-b3ff-4f1f-b126-3036dbea821d",
18+
"metadata": {
19+
"tags": []
20+
},
21+
"outputs": [],
22+
"source": [
23+
"from pythainlp.el import EntityLinker"
24+
]
25+
},
26+
{
27+
"cell_type": "code",
28+
"execution_count": 3,
29+
"id": "aa91fee8-5574-424b-9058-7312f39a2abe",
30+
"metadata": {
31+
"tags": []
32+
},
33+
"outputs": [
34+
{
35+
"name": "stderr",
36+
"output_type": "stream",
37+
"text": [
38+
"/usr/local/lib/python3.8/dist-packages/hydra/experimental/initialize.py:80: UserWarning: hydra.experimental.initialize_config_module() is no longer experimental. Use hydra.initialize_config_module().\n",
39+
" deprecation_warning(message=message)\n",
40+
"/usr/local/lib/python3.8/dist-packages/hydra/experimental/initialize.py:82: UserWarning: \n",
41+
"The version_base parameter is not specified.\n",
42+
"Please specify a compatability version level, or None.\n",
43+
"Will assume defaults for version 1.1\n",
44+
" self.delegate = real_initialize_config_module(\n",
45+
"/usr/local/lib/python3.8/dist-packages/hydra/experimental/compose.py:25: UserWarning: hydra.experimental.compose() is no longer experimental. Use hydra.compose()\n",
46+
" deprecation_warning(message=message)\n",
47+
"/usr/local/lib/python3.8/dist-packages/hydra/_internal/defaults_list.py:251: UserWarning: In 'joint_el_mel_new': Defaults list is missing `_self_`. See https://hydra.cc/docs/1.2/upgrades/1.0_to_1.1/default_composition_order for more information\n",
48+
" warnings.warn(msg, UserWarning)\n",
49+
"/usr/local/lib/python3.8/dist-packages/hydra/core/default_element.py:124: UserWarning: In 'trainer/gpu_1_host': Usage of deprecated keyword in package header '# @package _group_'.\n",
50+
"See https://hydra.cc/docs/1.2/upgrades/1.0_to_1.1/changes_to_package_header for more information\n",
51+
" deprecation_warning(\n",
52+
"/usr/local/lib/python3.8/dist-packages/hydra/core/default_element.py:124: UserWarning: In 'task/optim/adamw': Usage of deprecated keyword in package header '# @package _group_'.\n",
53+
"See https://hydra.cc/docs/1.2/upgrades/1.0_to_1.1/changes_to_package_header for more information\n",
54+
" deprecation_warning(\n",
55+
"/usr/local/lib/python3.8/dist-packages/hydra/core/default_element.py:124: UserWarning: In 'task/model/xlmr_large': Usage of deprecated keyword in package header '# @package _group_'.\n",
56+
"See https://hydra.cc/docs/1.2/upgrades/1.0_to_1.1/changes_to_package_header for more information\n",
57+
" deprecation_warning(\n",
58+
"/usr/local/lib/python3.8/dist-packages/hydra/core/default_element.py:124: UserWarning: In 'task/transform/joint_el_xlmr_raw_transform_large': Usage of deprecated keyword in package header '# @package _group_'.\n",
59+
"See https://hydra.cc/docs/1.2/upgrades/1.0_to_1.1/changes_to_package_header for more information\n",
60+
" deprecation_warning(\n",
61+
"/usr/local/lib/python3.8/dist-packages/hydra/core/default_element.py:124: UserWarning: In 'datamodule/joint_el_datamodule': Usage of deprecated keyword in package header '# @package _group_'.\n",
62+
"See https://hydra.cc/docs/1.2/upgrades/1.0_to_1.1/changes_to_package_header for more information\n",
63+
" deprecation_warning(\n",
64+
"/usr/local/lib/python3.8/dist-packages/hydra/core/default_element.py:124: UserWarning: In 'checkpoint_callback/default': Usage of deprecated keyword in package header '# @package _group_'.\n",
65+
"See https://hydra.cc/docs/1.2/upgrades/1.0_to_1.1/changes_to_package_header for more information\n",
66+
" deprecation_warning(\n",
67+
"/usr/local/lib/python3.8/dist-packages/hydra/core/default_element.py:124: UserWarning: In 'task/joint_el_task': Usage of deprecated keyword in package header '# @package _group_'.\n",
68+
"See https://hydra.cc/docs/1.2/upgrades/1.0_to_1.1/changes_to_package_header for more information\n",
69+
" deprecation_warning(\n"
70+
]
71+
},
72+
{
73+
"name": "stdout",
74+
"output_type": "stream",
75+
"text": [
76+
"Setting ds_accelerator to cuda (auto detect)\n"
77+
]
78+
},
79+
{
80+
"name": "stderr",
81+
"output_type": "stream",
82+
"text": [
83+
"Some weights of the model checkpoint at xlm-roberta-large were not used when initializing XLMRobertaModel: ['lm_head.bias', 'lm_head.layer_norm.weight', 'lm_head.dense.weight', 'lm_head.layer_norm.bias', 'lm_head.dense.bias']\n",
84+
"- This IS expected if you are initializing XLMRobertaModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n",
85+
"- This IS NOT expected if you are initializing XLMRobertaModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n",
86+
"/usr/local/lib/python3.8/dist-packages/faiss/contrib/torch_utils.py:51: UserWarning: TypedStorage is deprecated. It will be removed in the future and UntypedStorage will be the only storage class. This should only matter to you if you are using storages directly. To access UntypedStorage directly, use tensor.untyped_storage() instead of tensor.storage()\n",
87+
" x.storage().data_ptr() + x.storage_offset() * 4)\n"
88+
]
89+
}
90+
],
91+
"source": [
92+
"el = EntityLinker(device=\"cuda\")"
93+
]
94+
},
95+
{
96+
"cell_type": "code",
97+
"execution_count": 4,
98+
"id": "9cd853bc-dea8-4579-affe-6db85596fcae",
99+
"metadata": {
100+
"tags": []
101+
},
102+
"outputs": [
103+
{
104+
"data": {
105+
"text/plain": [
106+
"[{'offsets': [11, 23],\n",
107+
" 'lengths': [6, 7],\n",
108+
" 'entities': ['Q484876', 'Q312'],\n",
109+
" 'md_scores': [0.30301809310913086, 0.6399497389793396],\n",
110+
" 'el_scores': [0.7142490744590759, 0.8657019734382629]}]"
111+
]
112+
},
113+
"execution_count": 4,
114+
"metadata": {},
115+
"output_type": "execute_result"
116+
}
117+
],
118+
"source": [
119+
"el.get_el(\"จ๊อบเคยเป็นซีอีโอบริษัทแอปเปิล\")"
120+
]
121+
}
122+
],
123+
"metadata": {
124+
"kernelspec": {
125+
"display_name": "Python 3 (ipykernel)",
126+
"language": "python",
127+
"name": "python3"
128+
},
129+
"language_info": {
130+
"codemirror_mode": {
131+
"name": "ipython",
132+
"version": 3
133+
},
134+
"file_extension": ".py",
135+
"mimetype": "text/x-python",
136+
"name": "python",
137+
"nbconvert_exporter": "python",
138+
"pygments_lexer": "ipython3",
139+
"version": "3.8.10"
140+
}
141+
},
142+
"nbformat": 4,
143+
"nbformat_minor": 5
144+
}

pythainlp/el/__init__.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# -*- coding: utf-8 -*-
2+
# Copyright (C) 2016-2023 PyThaiNLP Project
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
"""
16+
pythainlp.el
17+
"""
18+
19+
__all__ = ["EntityLinker"]
20+
21+
from pythainlp.el.core import EntityLinker

pythainlp/el/_multiel.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# -*- coding: utf-8 -*-
2+
# Copyright (C) 2016-2023 PyThaiNLP Project
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
16+
17+
class MultiEL:
18+
def __init__(self, model_name="bela", device="cuda"):
19+
self.model_name = model_name
20+
self.device = device
21+
self.load_model()
22+
def load_model(self):
23+
try:
24+
from multiel import BELA
25+
except ImportError:
26+
raise ImportError(
27+
"Can't import multiel package, you can install by pip install multiel."
28+
)
29+
self._bela_run = BELA(device=self.device)
30+
def process_batch(self, list_text):
31+
if isinstance(list_text, str):
32+
list_text = [list_text]
33+
return self._bela_run.process_batch(list_text)

pythainlp/el/core.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# -*- coding: utf-8 -*-
2+
# Copyright (C) 2016-2023 PyThaiNLP Project
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
from typing import List, Union
16+
17+
18+
class EntityLinker:
19+
def __init__(self, model_name:str="bela", device:str="cuda", tag:str="wikidata"):
20+
"""
21+
EntityLinker
22+
23+
:param str model_name: model name (bela)
24+
:param str device: device for running model
25+
:param str tag: Entity linking tag (wikidata)
26+
"""
27+
self.model_name = model_name
28+
self.device = device
29+
self.tag = tag
30+
if self.model_name not in ["bela"]:
31+
raise NotImplementedError(f"EntityLinker doesn't support {model_name} model.")
32+
if self.tag not in ["wikidata"]:
33+
raise NotImplementedError(f"EntityLinker doesn't support {tag} tag.")
34+
from pythainlp.el._multiel import MultiEL
35+
self.model = MultiEL(model_name=self.model_name, device=self.device)
36+
def get_el(self, list_text:Union[List[str], str])->Union[List[dict], str]:
37+
"""
38+
Get Entity Linking from Thai Text
39+
40+
:param str Union[List[str], str]: list thai text or text
41+
:return: list of entity linking
42+
:rtype: Union[List[dict], str]
43+
44+
:Example:
45+
::
46+
47+
from pythainlp.el import EntityLinker
48+
49+
el = EntityLinker(device="cuda")
50+
print(el.get_el("จ๊อบเคยเป็นซีอีโอบริษัทแอปเปิล"))
51+
# output: [{'offsets': [11, 23],
52+
# 'lengths': [6, 7],
53+
# 'entities': ['Q484876', 'Q312'],
54+
# 'md_scores': [0.30301809310913086, 0.6399497389793396],
55+
# 'el_scores': [0.7142490744590759, 0.8657019734382629]}]
56+
"""
57+
return self.model.process_batch(list_text)

setup.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,9 @@
125125
"wsd":{
126126
"sentence-transformers>=2.2.2"
127127
},
128+
"el":{
129+
"multiel>=0.5"
130+
},
128131
"full": [
129132
"PyYAML>=5.3.1",
130133
"attacut>=1.0.4",

tests/test_el.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# -*- coding: utf-8 -*-
2+
import unittest
3+
from pythainlp.el import EntityLinker
4+
5+
6+
class TestElPackage(unittest.TestCase):
7+
def test_EntityLinker(self):
8+
with self.assertRaises(NotImplementedError):
9+
EntityLinker(model_name="cat")
10+
with self.assertRaises(NotImplementedError):
11+
EntityLinker(tag="cat")

0 commit comments

Comments
 (0)