crf-query-xtract 0.1.1__tar.gz

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.
@@ -0,0 +1,10 @@
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
@@ -0,0 +1,64 @@
1
+ ######
2
+
3
+ ## Overview
4
+
5
+ 🔎 The **Searchterm Extractor CRF** is a keyword extraction module designed for **OVOS (Open Voice OS)** common query skills, such as Wikipedia and DuckDuckGo (DDG). It helps identify the most relevant search keywords from a user’s spoken or typed query.
6
+
7
+ ## How It Works 🚀
8
+
9
+ This extractor uses a **Conditional Random Field (CRF)** model trained on keyword patterns and sentence structures. It processes input text by tagging each word with **Part-of-Speech (POS) information** and then predicts which words are most relevant as search terms. The model relies only on **word features and POS tags**, making it lightweight and efficient for real-time applications.
10
+
11
+ ### Conditional Random Fields (CRF) 🧠
12
+
13
+ CRFs are a type of probabilistic model used for **sequence labeling** tasks, such as **Named Entity Recognition (NER)** and **Part-of-Speech Tagging**. Unlike simpler models, CRFs consider the context of surrounding words to make more accurate predictions, making them well-suited for extracting meaningful search terms from natural language queries.
14
+
15
+ ### Brill POS Tagger 🏷️
16
+
17
+ The system uses a **Brill POS Tagger**, a rule-based part-of-speech tagger that assigns grammatical categories (e.g., noun, verb) to words based on a predefined rule set. This helps the model better understand sentence structure before extracting relevant search terms. Unlike statistical models, the Brill tagger applies transformation-based learning to iteratively refine POS labels.
18
+
19
+ ### Example ✨
20
+
21
+ Given the input:
22
+
23
+ ```plaintext
24
+ "Who invented the telephone?"
25
+ ```
26
+
27
+ The extractor identifies **"telephone"** as the key search term.
28
+
29
+ ## Installation 📦
30
+
31
+ ```bash
32
+ pip install crf_query_xtract
33
+ ```
34
+
35
+ ## Usage 🛠️
36
+
37
+ ```python
38
+ from searchterm_extractor import SearchtermExtractorCRF
39
+
40
+ kx = SearchtermExtractorCRF.from_pretrained("en")
41
+
42
+ sentence = "What is the speed of light?"
43
+ keywords = kx.extract_keyword(sentence)
44
+
45
+ print("Extracted keywords:", keywords)
46
+ ```
47
+
48
+ ### Expected Output
49
+
50
+ ```plaintext
51
+ Extracted keywords: speed of light
52
+ ```
53
+
54
+ ## Notes 📝
55
+
56
+ - This extractor is specifically designed for **search queries** and works best with OVOS common query skills.
57
+ - It **does not** use deep learning or advanced semantics—only **word and POS-based features**.
58
+ - If no clear keyword is found, it defaults to returning the **first noun** in the query.
59
+ - Currently depends on pre-trained models from **[brill\_postaggers](https://github.com/TigreGotico/brill_postaggers)**. Future updates will make this configurable.
60
+
61
+ ## License 📜
62
+
63
+ MIT License
64
+
@@ -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("------")
@@ -0,0 +1,6 @@
1
+ # START_VERSION_BLOCK
2
+ VERSION_MAJOR = 0
3
+ VERSION_MINOR = 1
4
+ VERSION_BUILD = 1
5
+ VERSION_ALPHA = 0
6
+ # END_VERSION_BLOCK
@@ -0,0 +1,10 @@
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
@@ -0,0 +1,18 @@
1
+ README.md
2
+ setup.py
3
+ crf_query_xtract/__init__.py
4
+ crf_query_xtract/kx_ca.pkl
5
+ crf_query_xtract/kx_da.pkl
6
+ crf_query_xtract/kx_de.pkl
7
+ crf_query_xtract/kx_en.pkl
8
+ crf_query_xtract/kx_eu.pkl
9
+ crf_query_xtract/kx_fr.pkl
10
+ crf_query_xtract/kx_gl.pkl
11
+ crf_query_xtract/kx_it.pkl
12
+ crf_query_xtract/kx_pt.pkl
13
+ crf_query_xtract/version.py
14
+ crf_query_xtract.egg-info/PKG-INFO
15
+ crf_query_xtract.egg-info/SOURCES.txt
16
+ crf_query_xtract.egg-info/dependency_links.txt
17
+ crf_query_xtract.egg-info/requires.txt
18
+ crf_query_xtract.egg-info/top_level.txt
@@ -0,0 +1,4 @@
1
+ ovos-utils
2
+ nltk
3
+ joblib
4
+ sklearn_crfsuite
@@ -0,0 +1 @@
1
+ crf_query_xtract
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,67 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ import os
4
+ import os.path
5
+
6
+ from setuptools import setup
7
+
8
+ BASEDIR = os.path.abspath(os.path.dirname(__file__))
9
+
10
+
11
+ def get_version():
12
+ version_file = os.path.join(BASEDIR, 'crf_query_xtract', 'version.py')
13
+ major, minor, build, alpha = (None, None, None, None)
14
+ with open(version_file) as f:
15
+ for line in f:
16
+ if 'VERSION_MAJOR' in line:
17
+ major = line.split('=')[1].strip()
18
+ elif 'VERSION_MINOR' in line:
19
+ minor = line.split('=')[1].strip()
20
+ elif 'VERSION_BUILD' in line:
21
+ build = line.split('=')[1].strip()
22
+ elif 'VERSION_ALPHA' in line:
23
+ alpha = line.split('=')[1].strip()
24
+
25
+ if ((major and minor and build and alpha) or
26
+ '# END_VERSION_BLOCK' in line):
27
+ break
28
+ version = f"{major}.{minor}.{build}"
29
+ if int(alpha):
30
+ version += f"a{alpha}"
31
+ return version
32
+
33
+
34
+ with open(os.path.join(BASEDIR, "README.md"), "r") as f:
35
+ long_description = f.read()
36
+
37
+
38
+ def required(requirements_file):
39
+ """ Read requirements file and remove comments and empty lines. """
40
+ with open(os.path.join(BASEDIR, requirements_file), 'r') as f:
41
+ requirements = f.read().splitlines()
42
+ if 'MYCROFT_LOOSE_REQUIREMENTS' in os.environ:
43
+ print('USING LOOSE REQUIREMENTS!')
44
+ requirements = [r.replace('==', '>=') for r in requirements]
45
+ return [pkg for pkg in requirements
46
+ if pkg.strip() and not pkg.startswith("#")]
47
+
48
+
49
+ setup(
50
+ name="crf_query_xtract",
51
+ version=get_version(),
52
+ author="JarbasAi",
53
+ author_email="jarbasai@mailfence.com",
54
+ url="https://github.com/TigreGotico/crf_query_xtract",
55
+ packages=find_packages(),
56
+ install_requires=required('requirements.txt'),
57
+ classifiers=[
58
+ 'Programming Language :: Python :: 3',
59
+ 'License :: OSI Approved :: MIT License',
60
+ 'Operating System :: OS Independent',
61
+ ],
62
+ python_requires='>=3.9',
63
+ include_package_data=True,
64
+ package_data={
65
+ '': ['*.pkl'], # Include your .pkl model files in the distribution
66
+ },
67
+ )