"""Numeric candidate features shared by training and native replay.""" from collections import Counter from dataclasses import dataclass import re import numpy as np COUNT = 200 TOKEN = re.compile(r"[a-z0-9]+") CAMEL = re.compile(r"([a-z])([A-Z])") CLEAN = re.compile(r"<[^>]+>") STOP = set("there this that the to from with then by in on if is of for a an or as and when will it you i my we their our these those some it can want need does where what how which who why have has should be find please look lookups".split()) DIM = 24 def words(text): return [t for t in TOKEN.findall(CAMEL.sub(r"\1 \2", text).lower()) if t not in STOP and len(t) > 1] def term(text): return text[:-3] + "y" if len(text) > 5 and text.endswith("ies") else ( text[:-1] if len(text) > 4 and text.endswith("s") and not text.endswith("ss") else text) @dataclass class Fields: text: tuple tokens: set stems: set bigrams: set def field(text): lex = tuple(words(text)) return Fields(lex, set(lex), {term(s) for s in lex}, set(zip(lex, lex[1:]))) class PairFeatures: """Keep document terms pre-indexed. Score at most 200 candidate pairs.""" def __init__(self, documents): self.catalog = [] df = Counter() for d in documents: heading = d.get("heading", d["title"]) pref = d.get("page_title", d["title"]) text = CLEAN.sub(" ", d["text"]) items = tuple(field(s) for s in (heading, pref, text, text[:420])) self.catalog.append(items) df.update(items[2].tokens | items[0].tokens) self.weights = {t:float(np.log1p((len(documents)+0.5)/(c+0.5))) for t,c in df.items()} self.rare = float(np.log1p((len(documents)+0.5)/0.5)) def from_candidates(self, value, sparse, dense, scores, allowed=None): lexical = {int(i): j for j, i in enumerate(sparse, 1)} semantic = {int(i): j for j, i in enumerate(dense, 1)} union = lexical.keys() | semantic.keys() found = sorted(union if allowed is None else union & allowed) ids = np.full(COUNT, -1, dtype=np.int64) ids[:len(found)] = found data = np.zeros((COUNT, DIM), dtype=np.float32) query = field(value) weights = {w:self.weights.get(w, self.rare) for w in query.tokens} total = max(1., sum(weights.values())) if len(semantic) > 1: samples = scores[np.array(dense, dtype=int)] high = float(samples[0]) spread = max(float(high - samples[-1]), 1e-6) else: high, spread = 0., 1. for row, j in enumerate(found): a, b = lexical.get(j), semantic.get(j) raw_a, raw_b = (40/(40+a) if a else 0.), (40/(40+b) if b else 0.) margin = max(-2., min(1., 1. - (high-float(scores[j]))/spread)) features = [raw_a + 0.8*raw_b, raw_a, raw_b, 1./a if a else 0., 1./b if b else 0., margin, float(bool(a)), float(bool(b))] for d in self.catalog[j]: known = query.tokens & d.tokens features.extend((sum(weights[w] for w in known)/total, len(query.stems & d.stems)/max(1,len(query.stems)), len(query.bigrams & d.bigrams)/max(1,len(query.bigrams)), sum(weights[w] for w in known)/max(4,len(d.text))**0.5)) data[row] = features return data, ids