File size: 3,995 Bytes
da32fba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations
import os, re
MODEL = os.environ.get('MOSS_READER_SPAN', 'deepset/minilm-uncased-squad2')
_QA = None
_OFF = os.environ.get('MOSS_EXTRACT', '1') == '0'

class _SpanModel:

    def __init__(self, name):
        import torch
        from transformers import AutoTokenizer, AutoModelForQuestionAnswering
        torch.set_num_threads(int(os.environ.get('MOSS_EXTRACT_THREADS', '4')))
        self.tok = AutoTokenizer.from_pretrained(name)
        self.model = AutoModelForQuestionAnswering.from_pretrained(name).eval()

    def __call__(self, question, context, max_answer_tokens=24):
        import torch
        enc = self.tok(question, context, truncation='only_second', max_length=384, return_offsets_mapping=True, return_tensors='pt')
        offsets = enc.pop('offset_mapping')[0].tolist()
        seq_ids = enc.sequence_ids(0)
        with torch.no_grad():
            out = self.model(**enc)
        start, end = (out.start_logits[0], out.end_logits[0])
        null = float(start[0] + end[0])
        ctx_idx = [i for i, sid in enumerate(seq_ids) if sid == 1]
        if not ctx_idx:
            return {'answer': '', 'score': 0.0}
        best, best_s = (None, -1000000000.0)
        s_top = sorted(ctx_idx, key=lambda i: -float(start[i]))[:20]
        e_top = sorted(ctx_idx, key=lambda i: -float(end[i]))[:20]
        for i in s_top:
            for j in e_top:
                if j < i or j - i + 1 > max_answer_tokens:
                    continue
                sc = float(start[i] + end[j])
                if sc > best_s:
                    best_s, best = (sc, (i, j))
        if best is None or best_s <= null:
            return {'answer': '', 'score': 0.0, 'null_margin': null - best_s if best else None}
        a, b = (offsets[best[0]][0], offsets[best[1]][1])
        span = context[a:b]
        import math
        conf = 1.0 / (1.0 + math.exp(-(best_s - null) / 2.0))
        return {'answer': span, 'score': conf}

def get():
    global _QA, _OFF
    if _OFF:
        return None
    if _QA is None:
        try:
            os.environ.setdefault('TOKENIZERS_PARALLELISM', 'false')
            _QA = _SpanModel(MODEL)
        except Exception:
            _OFF = True
            return None
    return _QA
_DATE = re.compile('\\b(?:\\d{1,2}\\s+)?(?:january|february|march|april|may|june|july|august|september|october|november|december)\\b.*?\\d{4}|\\b(?:1[0-9]{3}|20[0-9]{2})\\b', re.I)
_NUM = re.compile('\\d[\\d,.]*')
_NAME = re.compile("^[A-Z][\\w'’.-]*(?:\\s+(?:of|the|de|da|di|von|van|and|&)\\s+)?(?:\\s*[A-Z][\\w'’.-]*){0,5}$")

def type_ok(span: str, answer_type: str | None) -> bool:
    s = span.strip()
    if not s or len(s) > 80:
        return False
    if answer_type == 'date':
        return bool(_DATE.search(s))
    if answer_type == 'number':
        return bool(_NUM.search(s))
    if answer_type in ('person', 'place', 'organization'):
        return bool(_NAME.match(s)) or (s[:1].isupper() and len(s.split()) <= 6)
    return True

def normalize(s: str) -> str:
    return re.sub('[^a-z0-9 ]', '', s.lower()).strip()

def extract(question: str, candidates: list[tuple[str, str]], answer_type: str | None=None, min_score: float=0.15) -> dict | None:
    qa = get()
    if qa is None or not candidates:
        return None
    best, votes = (None, {})
    for ctx, tag in candidates[:4]:
        try:
            r = qa(question, ctx[:2000])
        except Exception:
            continue
        span = (r.get('answer') or '').strip(' .,;:"\'“”')
        score = float(r.get('score') or 0.0)
        if not span or score < min_score or (not type_ok(span, answer_type)):
            continue
        key = normalize(span)
        votes[key] = votes.get(key, 0) + 1
        if best is None or score > best['score']:
            best = {'answer': span, 'score': round(score, 3), 'tag': tag}
    if best is None:
        return None
    best['votes'] = votes.get(normalize(best['answer']), 1)
    return best