-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathdocument_rater.py
246 lines (206 loc) · 8.1 KB
/
document_rater.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import logging
import random
import re
from abc import abstractmethod
from functools import partial
from multiprocessing import Pool
import fasttext
from corpus_interface import Document, DocumentAnnotation, UnifiedGetter
from normalizer import ScoreNormalizer
from tqdm import tqdm
logger = logging.getLogger(__name__)
class DocumentRater:
_name = None
_require_doc_text = None
def __init__(
self, rater_name: str | None = None, normalizer: ScoreNormalizer | None = None, **kwargs
) -> None:
self._obj_name = rater_name if rater_name is not None else self._name
self.normalizer = normalizer
logger.info(
f"Initializing rater type: {self._name}, name: {self._obj_name}, normalizer: {self.normalizer}, args: {kwargs}"
)
def _annotate_doc(self, doc: Document, score: float | int) -> Document:
if self.normalizer is None:
return Document(
docid=doc.docid,
text=doc.text,
annotations=DocumentAnnotation({self.get_name(): score, **doc.annotations}),
)
logger.debug(f"Normalizing score: {self.get_name()}")
return Document(
docid=doc.docid,
text=doc.text,
annotations=DocumentAnnotation(
{
self.get_name(): score,
f"{self.get_name()}_{self.normalizer.get_name()}_normalized": self.normalizer(
score
),
**doc.annotations,
}
),
)
@abstractmethod
def __call__(self, docs: list[Document]) -> list[Document]: ...
def get_name(self) -> str | None:
return self._obj_name
@classmethod
def require_doc_text(cls) -> bool | None:
return cls._require_doc_text
class RandomRater(DocumentRater):
_name = "random_score"
_require_doc_text = False
def __init__(
self, rater_name: str | None = None, normalizer: ScoreNormalizer | None = None
) -> None:
super().__init__(rater_name=rater_name, normalizer=normalizer)
def __call__(self, docs: list[Document]) -> list[Document]:
random_scores = [random.random() for _ in range(len(docs))]
return [self._annotate_doc(doc, score) for doc, score in zip(docs, random_scores)]
class DocumentLengthRater(DocumentRater):
_name = "length"
_require_doc_text = True
def __init__(
self, rater_name: str | None = None, normalizer: ScoreNormalizer | None = None
) -> None:
super().__init__(rater_name=rater_name, normalizer=normalizer)
def __call__(self, docs: list[Document]) -> list[Document]:
length_scores = [len(doc.text) for doc in docs]
return [self._annotate_doc(doc, score) for doc, score in zip(docs, length_scores)]
class InlinkCountRater(DocumentRater):
_name = "inlink_count"
_require_doc_text = False
def __init__(
self,
unified_getter: UnifiedGetter,
rater_name: str | None = None,
normalizer: ScoreNormalizer | None = None,
num_workers: int = 1,
) -> None:
super().__init__(
rater_name=rater_name,
unified_getter=unified_getter,
normalizer=normalizer,
num_workers=num_workers,
)
self.unified_getter = unified_getter
self.num_workers = num_workers
def _count_inlinks(self, docid: str) -> int:
return len(self.unified_getter.get_inlinks(docid))
def __call__(self, docs: list[Document]) -> list[Document]:
if len(docs) <= 20000 or self.num_workers == 1:
inlink_counts = [
self._count_inlinks(doc.docid) for doc in tqdm(docs, desc="Counting inlinks")
]
else:
with Pool(self.num_workers) as pool:
inlink_counts = list(
tqdm(
pool.imap(self._count_inlinks, [doc.docid for doc in docs]),
total=len(docs),
desc="Counting inlinks",
)
)
return [self._annotate_doc(doc, score) for doc, score in zip(docs, inlink_counts)]
_model_fasttext = None
def _init_fasttext_model(model_path: str) -> None:
global _model_fasttext
_model_fasttext = fasttext.load_model(model_path)
def normalize_text(text: str) -> str:
text = re.sub(r"([.\!?,'/()])", r" \1 ", text)
text = text.lower()
text = re.sub(r"\s+", " ", text).strip()
return text
def _predict_worker_fasttext(text: str, text_normalize: bool = False) -> float:
global _model_fasttext
text = " ".join(text.strip().splitlines())
if text_normalize:
text = normalize_text(text)
pred = _model_fasttext.predict(text)
(pred_label, pred_prob) = pred
pred_label = pred_label[0]
hq_prob = pred_prob[0]
if pred_label == "__label__cc":
hq_prob = 1 - hq_prob
return hq_prob
class FasttextRater(DocumentRater):
_name = "fasttext_score"
_require_doc_text = True
def __init__(
self,
model_path: str,
rater_name: str | None = None,
normalizer: ScoreNormalizer | None = None,
text_normalize: bool = False,
num_workers: int = 1,
) -> None:
super().__init__(
rater_name=rater_name,
model_path=model_path,
normalizer=normalizer,
text_normalize=text_normalize,
num_workers=num_workers,
)
self.model_path = model_path
self.text_normalize = text_normalize
self.num_workers = num_workers
def _predict(self, text: str, text_normalize: bool = False) -> float:
text = " ".join(text.strip().splitlines())
if text_normalize:
text = normalize_text(text)
pred = self.model.predict(text)
(pred_label, pred_prob) = pred
pred_label = pred_label[0]
hq_prob = pred_prob[0]
if pred_label == "__label__cc":
hq_prob = 1 - hq_prob
return hq_prob
def __call__(self, docs: list[Document]) -> list[Document]:
results = []
if len(docs) <= 100000 or self.num_workers == 1:
# Load the model once in the main process
self.model = fasttext.load_model(self.model_path)
for doc in tqdm(docs, desc=f"Rating {self.get_name()}"):
text: str = doc.text
score = self._predict(text, self.text_normalize)
results.append(self._annotate_doc(doc, score))
else:
predict_worker_fasttext_partial = partial(
_predict_worker_fasttext, text_normalize=self.text_normalize
)
with Pool(
self.num_workers, initializer=_init_fasttext_model, initargs=(self.model_path,)
) as pool:
scores = list(
tqdm(
pool.imap(predict_worker_fasttext_partial, [doc.text for doc in docs]),
total=len(docs),
desc=f"Rating {self.get_name()}",
)
)
results = [self._annotate_doc(doc, score) for doc, score in zip(docs, scores)]
return results
class EnsembleRater(DocumentRater):
_name = "ensemble_score"
_require_doc_text = False
def __init__(
self,
raters_and_weights: list[dict],
rater_name: str | None = None,
normalizer: ScoreNormalizer | None = None,
) -> None:
super().__init__(
rater_name=rater_name, normalizer=normalizer, raters_and_weights=raters_and_weights
)
self.raters_and_weights = raters_and_weights
def __call__(self, docs: list[Document]) -> list[Document]:
scores = []
for doc in tqdm(docs, desc=f"Rating {self.get_name()}"):
total_score = 0
for rater_and_weight in self.raters_and_weights:
rater = rater_and_weight["rater_name"]
weight = rater_and_weight["weight"]
total_score += doc.annotations[rater] * weight
scores.append(total_score)
return [self._annotate_doc(doc, score) for doc, score in zip(docs, scores)]