crf-query-xtract 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- crf_query_xtract/__init__.py +147 -0
- crf_query_xtract/kx_ca.pkl +0 -0
- crf_query_xtract/kx_da.pkl +0 -0
- crf_query_xtract/kx_de.pkl +0 -0
- crf_query_xtract/kx_en.pkl +0 -0
- crf_query_xtract/kx_eu.pkl +0 -0
- crf_query_xtract/kx_fr.pkl +0 -0
- crf_query_xtract/kx_gl.pkl +0 -0
- crf_query_xtract/kx_it.pkl +0 -0
- crf_query_xtract/kx_pt.pkl +0 -0
- crf_query_xtract/version.py +6 -0
- crf_query_xtract-0.1.1.dist-info/METADATA +15 -0
- crf_query_xtract-0.1.1.dist-info/RECORD +15 -0
- crf_query_xtract-0.1.1.dist-info/WHEEL +5 -0
- crf_query_xtract-0.1.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
from typing import List, Tuple
|
|
2
|
+
import os
|
|
3
|
+
import joblib
|
|
4
|
+
from brill_postaggers import BrillPostagger
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class SearchtermExtractorCRF:
|
|
8
|
+
"""
|
|
9
|
+
A CRF-based keyword extractor that uses keywords and sentence templates to train a model.
|
|
10
|
+
"""
|
|
11
|
+
def __init__(self, lang: str):
|
|
12
|
+
"""
|
|
13
|
+
Initialize the extractor with a given language.
|
|
14
|
+
Loads the keywords and sentences datasets and trains the CRF model.
|
|
15
|
+
"""
|
|
16
|
+
self.tagger = BrillPostagger.from_pretrained(lang)
|
|
17
|
+
self.lang: str = lang
|
|
18
|
+
self._keywords: List[str] = []
|
|
19
|
+
self._dataset: List[str] = []
|
|
20
|
+
self.model = None
|
|
21
|
+
|
|
22
|
+
@staticmethod
|
|
23
|
+
def from_pretrained(lang: str):
|
|
24
|
+
lang = lang.split("-")[0].lower()
|
|
25
|
+
model = f"kx_{lang}"
|
|
26
|
+
xtractor = SearchtermExtractorCRF(lang)
|
|
27
|
+
xtractor.load(f"{os.path.dirname(__file__)}/{model}.pkl")
|
|
28
|
+
return xtractor
|
|
29
|
+
|
|
30
|
+
def _word2features(self, sent: List[Tuple[str, str]], idx: int) -> dict:
|
|
31
|
+
"""
|
|
32
|
+
Extracts features for a given word in a sentence.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
sent: List of tuples (word, POS) for the sentence.
|
|
36
|
+
idx: Index of the token in the sentence.
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
A feature dictionary for the token at the given index.
|
|
40
|
+
"""
|
|
41
|
+
word, pos = sent[idx]
|
|
42
|
+
features = {
|
|
43
|
+
'word.lower()': word.lower(),
|
|
44
|
+
'pos': pos,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
# Previous features
|
|
48
|
+
if idx > 0:
|
|
49
|
+
prev_word, prev_pos = sent[idx - 1]
|
|
50
|
+
features.update({
|
|
51
|
+
'-1:word.lower()': prev_word.lower(),
|
|
52
|
+
'-1:pos': prev_pos,
|
|
53
|
+
})
|
|
54
|
+
else:
|
|
55
|
+
features['BOS'] = True # Beginning of Sentence
|
|
56
|
+
|
|
57
|
+
# Two words back
|
|
58
|
+
if idx > 1:
|
|
59
|
+
prev2_word, prev2_pos = sent[idx - 2]
|
|
60
|
+
features.update({
|
|
61
|
+
'-2:word.lower()': prev2_word.lower(),
|
|
62
|
+
'-2:pos': prev2_pos,
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
# Next features
|
|
66
|
+
if idx < len(sent) - 1:
|
|
67
|
+
next_word, next_pos = sent[idx + 1]
|
|
68
|
+
features.update({
|
|
69
|
+
'+1:word.lower()': next_word.lower(),
|
|
70
|
+
'+1:pos': next_pos,
|
|
71
|
+
})
|
|
72
|
+
else:
|
|
73
|
+
features['EOS'] = True # End of Sentence
|
|
74
|
+
|
|
75
|
+
if idx < len(sent) - 2:
|
|
76
|
+
next2_word, next2_pos = sent[idx + 2]
|
|
77
|
+
features.update({
|
|
78
|
+
'+2:word.lower()': next2_word.lower(),
|
|
79
|
+
'+2:pos': next2_pos,
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
return features
|
|
83
|
+
|
|
84
|
+
def _sent2features(self, sent: List[Tuple[str, str]]) -> List[dict]:
|
|
85
|
+
"""
|
|
86
|
+
Converts a sentence into a list of feature dictionaries.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
sent: List of tuples (word, POS).
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
A list of features for each token in the sentence.
|
|
93
|
+
"""
|
|
94
|
+
return [self._word2features(sent, i) for i in range(len(sent))]
|
|
95
|
+
|
|
96
|
+
def extract_keyword(self, text: str) -> str:
|
|
97
|
+
"""
|
|
98
|
+
Extracts keywords from a given text using the trained CRF model.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
text: The input text.
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
A string containing the extracted keywords.
|
|
105
|
+
"""
|
|
106
|
+
pos_tags = self.tagger.tag(text)
|
|
107
|
+
features = self._sent2features(pos_tags)
|
|
108
|
+
predicted_labels = self.model.predict([features])[0]
|
|
109
|
+
|
|
110
|
+
extracted_keywords = []
|
|
111
|
+
current_keyword = []
|
|
112
|
+
|
|
113
|
+
for (word, _), label in zip(pos_tags, predicted_labels):
|
|
114
|
+
if label == 'K':
|
|
115
|
+
current_keyword.append(word)
|
|
116
|
+
elif current_keyword:
|
|
117
|
+
extracted_keywords.append(" ".join(current_keyword))
|
|
118
|
+
current_keyword = []
|
|
119
|
+
if current_keyword:
|
|
120
|
+
extracted_keywords.append(" ".join(current_keyword))
|
|
121
|
+
extracted_keywords = [k for k in extracted_keywords if k]
|
|
122
|
+
|
|
123
|
+
# return first noun as fallback
|
|
124
|
+
if not extracted_keywords:
|
|
125
|
+
for word, tag in pos_tags:
|
|
126
|
+
if tag == 'NOUN':
|
|
127
|
+
return word
|
|
128
|
+
|
|
129
|
+
return " ".join(extracted_keywords)
|
|
130
|
+
|
|
131
|
+
def load(self, path):
|
|
132
|
+
self.model = joblib.load(path)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
if __name__ == "__main__":
|
|
136
|
+
|
|
137
|
+
kx = SearchtermExtractorCRF.from_pretrained("en")
|
|
138
|
+
|
|
139
|
+
test_sentences = ["who invented the telephone",
|
|
140
|
+
"what is the speed of light",
|
|
141
|
+
"who discovered fire"]
|
|
142
|
+
|
|
143
|
+
for sentence_text in test_sentences:
|
|
144
|
+
extracted = kx.extract_keyword(sentence_text)
|
|
145
|
+
print("Sentence:", sentence_text)
|
|
146
|
+
print("Extracted keywords:", extracted)
|
|
147
|
+
print("------")
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: crf-query-xtract
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Home-page: https://github.com/TigreGotico/crf_query_xtract
|
|
5
|
+
Author: JarbasAi
|
|
6
|
+
Author-email: jarbasai@mailfence.com
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Requires-Dist: ovos-utils
|
|
12
|
+
Requires-Dist: nltk
|
|
13
|
+
Requires-Dist: joblib
|
|
14
|
+
Requires-Dist: sklearn-crfsuite
|
|
15
|
+
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
crf_query_xtract/__init__.py,sha256=et45AHCT-prHFWW47v4hEpE_qFAvZ9jOkZOW6Wjho3U,4519
|
|
2
|
+
crf_query_xtract/kx_ca.pkl,sha256=uhQLQtSdjJUeBa0dhSGWCUzyuW8qCwAEkm1WCdaHOEk,1091703
|
|
3
|
+
crf_query_xtract/kx_da.pkl,sha256=vfQKQO27hxB-RQ_rpN8Tj5jQriZTt_rfxZDxvFpdTPU,1029272
|
|
4
|
+
crf_query_xtract/kx_de.pkl,sha256=-tvffyji4clAkq9k8jEyfvdrfznceP3nmVQjrP8cPKs,955433
|
|
5
|
+
crf_query_xtract/kx_en.pkl,sha256=EsHnjFwBeYavlH58mGT_NTjTdbBwh6baToNoL3wKVVE,793846
|
|
6
|
+
crf_query_xtract/kx_eu.pkl,sha256=VG0ilnBlb2cFSFPqFJrdXjUvXqEEbJ4yLundVKhL-Dg,1351592
|
|
7
|
+
crf_query_xtract/kx_fr.pkl,sha256=7txlwFHLlNYTAUlTag04bnZpdWWk6ECN56H8vu45Fl4,1052977
|
|
8
|
+
crf_query_xtract/kx_gl.pkl,sha256=y4CoLxE1WCQlRCX2uCKeu46a8yENS-nJJ3Ci1HVV7I8,1479003
|
|
9
|
+
crf_query_xtract/kx_it.pkl,sha256=WE4o3e9oScwQBeMngxWXdY4edSo7laGjePCrLelW53k,872367
|
|
10
|
+
crf_query_xtract/kx_pt.pkl,sha256=6sQPEl3gacGrkmgVuthgQpMGvvgj8mSnCDsFifRNl7o,1029457
|
|
11
|
+
crf_query_xtract/version.py,sha256=YO17Z54RmHA5oRw9Kj8GqtARGSultBm53Tz4k26JgYE,114
|
|
12
|
+
crf_query_xtract-0.1.1.dist-info/METADATA,sha256=lqjcM_EcDNJr4uE01UNb5MDEL5Zlm0UJc4ozmI0mTvw,443
|
|
13
|
+
crf_query_xtract-0.1.1.dist-info/WHEEL,sha256=tZoeGjtWxWRfdplE7E3d45VPlLNQnvbKiYnx7gwAy8A,92
|
|
14
|
+
crf_query_xtract-0.1.1.dist-info/top_level.txt,sha256=KU2ml53V83AHXOqFY4O9pYq_vk7BiR8pbTfXNeDxR6w,17
|
|
15
|
+
crf_query_xtract-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
crf_query_xtract
|