File size: 2,330 Bytes
0dff23d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# CallOpeningDetX v0.1. Licence: CDLA-Permissive-2.0 (see LICENSE).
"""The input string of a call, and the gold evidence spans in its coordinates.

    from render import render, gold_spans
    text = render(record)                      # what a system reads; span offsets refer to this string
    spans = gold_spans(record)                 # [(start, end, type)], types AGENT INST NOTICE PURPOSE NEGATED DISTRACTOR

The string is a metadata line followed by one line per turn:

    metadata: starts at call start: <yes|no|not given>; automated notice: <text|not given>
    Agent: ...
    Customer: ...
"""
FIELD_TYPE = {"agent_identification": "AGENT", "institution_identification": "INST",
              "recording_notice": "NOTICE", "recording_purpose": "PURPOSE"}


def _layout(r):
    m = r.get("meta") or {}
    start = {True: "yes", False: "no"}.get(m.get("starts_at_call_start"), "not given")
    auto = m.get("automated_notice_played")
    head = f"metadata: starts at call start: {start}; automated notice: "
    text = head + ("not given" if auto is None else str(auto))
    meta_auto = len(head) if auto is not None else None
    starts = []
    for t in r["turns"]:
        text += f"\n{t['speaker_role']}: "
        starts.append(len(text))
        text += t["text"]
    return text, starts, meta_auto


def render(r):
    return _layout(r)[0]


def span_type(e):
    if e.get("polarity") == "negated":
        return "NEGATED"
    if e.get("polarity") == "distractor":
        return "DISTRACTOR"
    return FIELD_TYPE[e["field"]]


def gold_spans(r):
    """Evidence of the opening (late mentions are not spans). Empty for rows without span supervision."""
    if r.get("span_supervision") is False:
        return []
    text, starts, meta_auto = _layout(r)
    out = []
    for e in r.get("evidence", []):
        if e.get("turn_id") is None:                       # evidence in the automated-notice metadata
            if meta_auto is None or not e.get("text"):
                continue
            i = text.lower().find(e["text"].lower(), meta_auto)
            if 0 <= i < (starts[0] if starts else len(text)):
                out.append((i, i + len(e["text"]), span_type(e)))
            continue
        b = starts[e["turn"]]
        out.append((b + e["start"], b + e["end"], span_type(e)))
    return out