tinyqa-1-moss / code /tinyqa /sieve.py
RysoAI's picture
Clean package: terminal code only, neutral names, no comments
da32fba verified
Raw History Blame Contribute Delete
3.52 kB
import collections, json, os, re, sys, time
from concurrent.futures import ThreadPoolExecutor
from . import pipeline as webqa
from .pipeline import QWORDS
_NAME = re.compile("\\b[A-Z][\\w'’.-]+(?:\\s+(?:(?:de|da|van|von|of|the|du|del|di|la|le)\\s+)?[A-Z][\\w'’.-]+){1,3}")
STOPCAP = {'The', 'This', 'That', 'These', 'There', 'What', 'When', 'Where', 'Which', 'Who', 'How', 'Why', 'In', 'On', 'At', 'For', 'From', 'With', 'After', 'Before', 'During', 'Since', 'His', 'Her', 'Its', 'Their', 'A', 'An', 'Of', 'To', 'By', 'And', 'Or', 'But', 'It', 'He', 'She', 'They', 'We', 'You', 'I', 'Yes', 'No'}
def content_words(q):
return [t for t in re.findall('[a-z0-9]+', q.lower()) if t not in QWORDS and len(t) > 2]
def entities_in(texts, exclude):
c = collections.Counter()
for t in texts:
for m in _NAME.findall(t):
m = m.strip(" .,'’")
toks = m.split()
if toks[0] in STOPCAP or len(m) > 40 or m.lower() in exclude:
continue
if any((w.lower() in exclude for w in toks)) and len(toks) <= 2:
continue
c[m] += 1
return c
def covers(text, w):
return re.search('(?<![a-z0-9])' + re.escape(w) + '(?![a-z0-9])', text.lower()) is not None
class Sieve:
def run(self, q, provider=None, k_ent=8):
t0 = time.time()
res = webqa.search(q, provider=provider)
cw = content_words(q)
qlow = {w for w in cw}
texts = [r['title'] + '. ' + r['body'] for r in res]
if webqa.PAGES:
texts += [c['sent'] for c in webqa.page_candidates(q, res, webqa.PAGES)]
ents = [e for e, _ in entities_in(texts, qlow).most_common(k_ent * 2) if not any((w in qlow for w in e.lower().split()))][:k_ent]
if not ents:
return {'sieve': None, 'why': 'no candidate entities', 'ms': round(1000 * (time.time() - t0))}
probe = ' '.join([w for w in cw if not any((w in e.lower() for e in ents))][:6])
with ThreadPoolExecutor(8) as ex:
packs = list(ex.map(lambda e: webqa.search(f'{e} {probe}', provider=provider), ents))
scored = []
for e, pack in zip(ents, packs):
hay = ' '.join((r['title'] + ' ' + r['body'] for r in pack))
cov = [w for w in cw if covers(hay, w)]
sents = [(r, s) for r in pack for s in webqa._SENT.split(r['body']) if len(s) > 20 and e.split()[-1].lower() in s.lower()]
best = None
if sents:
sc = self.verify.predict([(q, f"{r['title']}. {s}") for r, s in sents[:16]], batch_size=32, show_progress_bar=False)
j = max(range(len(sc)), key=lambda i: float(sc[i]))
best = (float(sc[j]), sents[j][1], sents[j][0])
scored.append({'entity': e, 'covered': len(cov), 'cov_words': cov, 'v': best[0] if best else -99.0, 'sent': best[1] if best else None, 'url': best[2]['href'] if best else None, 'title': best[2]['title'] if best else None})
scored.sort(key=lambda x: (-x['covered'], -x['v']))
top = scored[0]
runner = scored[1] if len(scored) > 1 else None
return {'sieve': top['entity'], 'covered': top['covered'], 'of': len(cw), 'cov_words': top['cov_words'], 'v': round(top['v'], 2), 'sent': top['sent'], 'url': top['url'], 'title': top['title'], 'runner_up': runner['entity'] if runner else None, 'runner_covered': runner['covered'] if runner else None, 'candidates': [s['entity'] for s in scored], 'ms': round(1000 * (time.time() - t0))}