'' import hashlib import json from independent_operators import spelling, syllable_options CASE_ORDER = [161,1342,141,158,121,105] CONTEXT_CATEGORIES = {'numeral_or_year','ordinal','Roman_numeral','symbol','abbreviation', 'unlisted_word','source_zero_nucleus_or_other_unresolved_pronunciation','elided_year_visible'} def canonical_sha256(value): return hashlib.sha256(json.dumps(value,ensure_ascii=False,sort_keys=True,separators=(',',':')).encode('utf-8')).hexdigest() def paragraph_starts(body): result=[]; position=0 for paragraph in body.split('\n\n'): if not paragraph: raise ValueError('not a prepared paragraph sequence') result.append(position); position += len(paragraph)+2 return result def flesch_start_design(body): starts=paragraph_starts(body); n=len(starts) if n < 25: raise ValueError('fewer than25 paragraphs; no resampling') indices=[k*(n-1)//25 for k in range(25)] if len(set(indices)) != 25: raise ValueError('duplicate fixed paragraph indices') return [(k,index,starts[index]) for k,index in enumerate(indices)] def _interval(span, length): if not isinstance(span,list) or len(span)!=2 or any(type(x)is not int for x in span): raise ValueError('half-open code-point interval required') a,b=span if not 0<=ab['span'][0] for a,b in zip(tokens,tokens[1:])): raise ValueError('unordered/overlapping native word references') return tokens def candidate(c,start): end=c['end'];_interval([start,end],len(body)) tokens=references(c['token_ids'],start,end); units=c['thought_unit_spans'] if not units: raise ValueError('zero native thought-unit denominator') previous=start for unit in units: a,b=_interval(unit,len(body)) if aend: raise ValueError('thought-unit overlap/outside sample') if not any(a<=t['span'][0]100 or key=='after' and count<100: raise ValueError('nearest ending witness on wrong side') available.append((abs(count-100),c['end'],key,c)) if not available: raise ValueError('no valid native ending') chosen=min(available,key=lambda x:(x[0],x[1])) c=chosen[3] same=next((x for x in available if x[2]==candidates['selection']),None) if same is None or (same[0],same[1])!=(chosen[0],chosen[1]): raise ValueError('nearest-ending/tie rule violated') if sample['sentence_length_span']!=[start,c['end']] or sample['sentence_length_token_ids']!=c['token_ids'] or sample['thought_unit_spans']!=c['thought_unit_spans']: raise ValueError('sentence pool changed from selected native ending') blocks=case['smog_blocks'] if len(blocks)!=3 or [b['block_id'] for b in blocks]!=['beginning','midpoint','end']: raise ValueError('incomplete SMOG design') spans=[] for block in blocks: a,b=_interval(block['span'],len(body));spans.append((a,b)) sentences=block['printed_sentence_spans'];lists=block['token_ids_by_sentence'] if len(sentences)!=10 or len(lists)!=10: raise ValueError('native block must contain10 complete sentences') if a!=sentences[0][0] or b!=sentences[-1][1]: raise ValueError('SMOG block envelope mismatch') last=a for sentence,ids in zip(sentences,lists): c,d=_interval(sentence,len(body)) if cb: raise ValueError('native printed sentences overlap') references(ids,c,d);last=d if block['block_id']=='midpoint' and (block.get('midpoint_anchor')!=len(body)//2 or ab[0] for a,b in zip(spans,spans[1:])): raise ValueError('overlapping native SMOG blocks') return True def native_feature_pools(case): '' bank={t['token_id']:t for t in case['native_tokens']} def pool(ids, sentences): vals=[bank[x]['syllable_options'] for x in ids] return {'words':len(vals),'sentences':sentences, 'syllables_lo':sum(min(v)for v in vals),'syllables_hi':sum(max(v)for v in vals), 'polysyllables_lo':sum(min(v)>=3 for v in vals),'polysyllables_hi':sum(max(v)>=3 for v in vals)} first=[x for s in case['flesch_samples'] for x in s['first100_token_ids']] ending=[x for s in case['flesch_samples'] for x in s['sentence_length_token_ids']] smog=[x for b in case['smog_blocks']for ids in b['token_ids_by_sentence']for x in ids] return {'flesch_syllable_pool':pool(first,0), 'flesch_sentence_pool':pool(ending,sum(len(s['thought_unit_spans'])for s in case['flesch_samples'])), 'smog_pool':pool(smog,30)} def compare_annotation_payloads(a,b): '' for ledger in (a,b): if ledger.get('artifact_kind')!='native_reference_annotation': raise ValueError('not a native reference ledger') who=ledger['annotator'] if who.get('human_annotation') is not False or who.get('automated_matched_full_scores_seen') is not False or who.get('independently_authored_before_other_ledger_read')is not True: raise ValueError('native independence/pre-score declaration not satisfied') if a['annotator']['reference_label']==b['annotator']['reference_label']: raise ValueError('same annotator is not independent') for key in ('protocol_sha256','source_boundary_sha256','source_rule4_addendum_sha256','lexicon_dictionary_sha256'): if a.get(key)!=b.get(key):raise ValueError('native ledgers bind different scientific inputs') if [c['pg_id'] for c in a['cases']]!=CASE_ORDER or [c['pg_id'] for c in b['cases']]!=CASE_ORDER: raise ValueError('all six fixed native cases required') left=canonical_sha256([_coordinate_payload(c) for c in a['cases']]);right=canonical_sha256([_coordinate_payload(c) for c in b['cases']]) return {'identical_cases':left==right,'ledger_a_payload_sha256':left,'ledger_b_payload_sha256':right, 'requires_explicit_disagreement_adjudication':left!=right, 'scores_or_automated_outputs_may_be_exposed':False, 'reason':'Both ledgers and genuine reconciliation/freeze must still be bound; equality alone is not approval.'} def _coordinate_payload(case): '' lookup={t['token_id']:t['span'] for t in case['native_tokens']} def convert(value, key='', refs=False): refs=refs or 'token_ids' in key if refs and isinstance(value,str): if value not in lookup: raise ValueError('unknown occurrence reference') return lookup[value] if isinstance(value,list): return [convert(v,key,refs) for v in value] if isinstance(value,dict): result={k:convert(v,k) for k,v in value.items() if k not in ('token_id','context_rationale')} if 'native_tokens' in result: result['native_tokens']=sorted(result['native_tokens'],key=lambda t:t['span']) return result return value return convert(case)