File size: 2,922 Bytes
6a48c9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reversible controlled English. This is grammar round-trip checking, not open-ended semantic understanding."""
import random,re,string
from common import REGISTRY, digest
STYLE_NAMES=['facts_then_request','request_then_facts','numbered_conditions','compact_exam','request_with_context','explanatory','reverse_information','line_separated']

def compile_clause(s):
 parts=[];seen=set()
 for literal,key,fmt,conv in string.Formatter().parse(s):
  parts.append(re.escape(literal))
  if key:
   parts.append('(?P='+key+')' if key in seen else '(?P<'+key+'>-?\\d+)');seen.add(key)
 return re.compile(''.join(parts))

def render(record,seed,style_index=None):
 t=REGISTRY[record['template_id']];rng=random.Random(seed);p=record['parameters'];drawn_style=rng.randrange(8);style=style_index if style_index is not None else drawn_style
 idx=[rng.randrange(len(c)) for c in t['clauses']];target_id=rng.randrange(len(t['targets']))
 facts=[alts[i].format(**p) for alts,i in zip(t['clauses'],idx)];target=t['targets'][target_id]
 if style==0:q=' '.join(facts+[target])
 elif style==1:q=target+' '+' '.join(facts)
 elif style==2:q='Use the following conditions. '+' '.join(f'({i+1}) {f}' for i,f in enumerate(facts))+' '+target
 elif style==3:q=' '.join(facts)+' '+target
 elif style==4:q=target+' The relevant information follows. '+' '.join(facts)
 elif style==5:q='Consider the following information. '+' '.join(facts)+' '+target
 elif style==6:q=' '.join(reversed(facts))+' '+target
 else:q='\n'.join(facts+[target])
 return q,{'style':STYLE_NAMES[style],'style_index':style,'clause_variants':idx,'target_variant':target_id}

_PATTERNS={}
def recover(tid,text):
 t=REGISTRY[tid]
 if tid not in _PATTERNS:_PATTERNS[tid]=[[compile_clause(s) for s in alts] for alts in t['clauses']]
 params={};spans=[]
 for patterns in _PATTERNS[tid]:
  matches=[m for pat in patterns for m in pat.finditer(text)]
  # Several realizations may coincide verbatim only if grammar design is wrong.
  if len(matches)!=1:raise ValueError('missing_or_repeated_clause')
  m=matches[0];spans.append(m.span())
  for k,v in m.groupdict().items():
   v=int(v)
   if k in params and params[k]!=v:raise ValueError('contradictory_parameter')
   params[k]=v
 targets=[s for s in t['targets'] if s in text]
 if len(targets)!=1:raise ValueError('missing_or_repeated_target')
 target=targets[0]
 if text.count(target)!=1:raise ValueError('repeated_target')
 spans.append((text.index(target),text.index(target)+len(target)))
 # Reject extra unparsed claims, including an injected misleading sentence.
 residual=text
 for a,b in sorted(spans,reverse=True):residual=residual[:a]+' '+residual[b:]
 for phrase in ['Use the following conditions.','The relevant information follows.','Consider the following information.']:
  residual=residual.replace(phrase,'')
 residual=re.sub(r'\(\d+\)','',residual)
 if residual.strip():raise ValueError('unparsed_text')
 return params