"""Execute the declared finite-file Austen comparison; never a reader-ability model.""" from pathlib import Path import sys,json,hashlib,unicodedata,itertools,datetime,csv,io,argparse from fractions import Fraction as Q from decimal import Decimal,localcontext ROOT=Path(__file__).resolve().parent B=ROOT parser=argparse.ArgumentParser(description='Reproduce a bounded Austen formula-output comparison from exact external source inputs.') parser.add_argument('--inputs',type=Path,required=True,help='Directory containing exact pg*.txt and four CMU members.') parser.add_argument('--out',type=Path,required=True,help='New results directory, separate from package and source inputs.') args=parser.parse_args();INPUT=args.inputs.resolve();OUT=args.out.resolve() if OUT==ROOT or OUT==INPUT:raise SystemExit('Results directory must differ from package and inputs.') OUT.mkdir(parents=True,exist_ok=True) sys.dont_write_bytecode=True sys.path.insert(0,str(ROOT)) if not __debug__:raise SystemExit('Run without -O: source and scientific checks must remain enabled.') import operators as op from native_ledger_tools import validate_case,canonical_sha256 def sha(z):return hashlib.sha256(z).hexdigest() def load(p):return json.loads(p.read_text(encoding='utf-8-sig')) def serial(x): if isinstance(x,Q):return f'{x.numerator}/{x.denominator}' if isinstance(x,Decimal):return str(x) if isinstance(x,dict):return {k:serial(v) for k,v in x.items()} if isinstance(x,(tuple,list)):return [serial(v) for v in x] return x def write(name,obj): (OUT/name).write_text(json.dumps(serial(obj),ensure_ascii=False,indent=2)+'\n',encoding='utf-8',newline='\n') manifest=load(B/'RECIPE-MANIFEST.json') for row in manifest['files']: z=(B/row['path']).read_bytes() if len(z)!=row['bytes'] or sha(z)!=row['sha256']:raise SystemExit('Package hash mismatch: '+row['path']) bindings=load(B/'corpus-bindings.json')['cases'] if [c['pg_id'] for c in bindings]!=[161,1342,141,158,121,105]:raise SystemExit('Changed fixed cases') lex_pin=load(B/'lexicon.json')['required_members'] for name in ('cmudict.dict','cmudict.symbols','LICENSE','cmudict.phones'): z=(INPUT/name).read_bytes();pin=lex_pin[name] if len(z)!=pin['bytes'] or sha(z)!=pin['sha256']:raise SystemExit('Exact CMU member mismatch: '+name) lex=op.parse_cmudict((INPUT/'cmudict.dict').read_text(encoding='utf-8'),set((INPUT/'cmudict.symbols').read_text().split())) cases=load(B/'reference-occurrences.json')['cases'] provenance=load(B/'reference-export-provenance.json') if sha((B/'reference-occurrences.json').read_bytes())!=provenance['public_occurrences_sha256']:raise SystemExit('Frozen reference mismatch') if [c['pg_id'] for c in cases]!=[161,1342,141,158,121,105]:raise SystemExit('Changed reference cases') def n_pool(bank,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)} def a_pool(text,offset=0): sentences=op.sentence_spans(text) out={'words':0,'sentences':len(sentences),'syllables_lo':0,'syllables_hi':0, 'polysyllables_lo':0,'polysyllables_hi':0,'unterminated_tails':sum(s[2] for s in sentences), 'fallback_occurrences':0,'zero_nucleus_occurrences':0,'expanded_component_fallbacks':0, 'provenance':{},'source_form_diagnostics':[]} def child_fallback(nodes):return sum(int(n['fallback_used'])+child_fallback(n['children']) for n in nodes) for row in op.adapted_readings(text,lex): lo=min(row['syllable_options']);hi=max(row['syllable_options']);trace=row['reading_trace'] out['words']+=1;out['syllables_lo']+=lo;out['syllables_hi']+=hi out['polysyllables_lo']+=int(lo>=3);out['polysyllables_hi']+=int(hi>=3) out['fallback_occurrences']+=int(trace['fallback_used']) out['zero_nucleus_occurrences']+=int(trace['source_zero_nucleus']) out['expanded_component_fallbacks']+=child_fallback(trace['children']) out['provenance'][row['provenance']]=out['provenance'].get(row['provenance'],0)+1 if row['source_form'] is not None: form=dict(row['source_form']) for key in ('marker_span','visible_span'): if key in form:form[key]=[x+offset for x in form[key]] out['source_form_diagnostics'].append({'source_span':[x+offset for x in row['source_span']],**form}) return out def total(pools): keys=('words','sentences','syllables_lo','syllables_hi','polysyllables_lo','polysyllables_hi', 'unterminated_tails','fallback_occurrences','zero_nucleus_occurrences','expanded_component_fallbacks') out={k:sum(p.get(k,0) for p in pools) for k in keys} out['provenance']={};out['source_form_diagnostics']=[] for p in pools: for k,v in p.get('provenance',{}).items():out['provenance'][k]=out['provenance'].get(k,0)+v out['source_form_diagnostics']+=p.get('source_form_diagnostics',[]) return out def flesch(y,s): asl=Q(s['words'],s['sentences']);asw_lo=Q(y['syllables_lo'],y['words']);asw_hi=Q(y['syllables_hi'],y['words']) return {'asl':asl,'asw_lo':asw_lo,'asw_hi':asw_hi,'lo':op.flesch_from_rates(asl,asw_hi),'hi':op.flesch_from_rates(asl,asw_lo)} def smog(p): assert p['sentences']>0 and 0<=p['polysyllables_lo']<=p['polysyllables_hi'] return {'lo':Q(30*p['polysyllables_lo'],p['sentences']),'hi':Q(30*p['polysyllables_hi'],p['sentences']), 'score_lo_decimal80':op.smog_d(p['polysyllables_lo'],p['sentences']), 'score_hi_decimal80':op.smog_d(p['polysyllables_hi'],p['sentences'])} outputs=[];samples=[] for binding,case in zip(bindings,cases): ident=binding['pg_id'];print('START',ident,flush=True) raw=(INPUT/f'pg{ident}.txt').read_bytes() assert len(raw)==binding['raw_bytes'] and sha(raw)==binding['raw_sha256'] normalized=unicodedata.normalize('NFC',raw.decode('utf-8-sig').replace('\r\n','\n').replace('\r','\n')) a,z=binding['start_inclusive'],binding['end_exclusive'] witness=normalized[max(0,a-160):a+160]+'\n\n'+normalized[z-160:z+160] assert sha(witness.encode())==binding['endpoint_context_sha256'] anchored=normalized[a:z];assert sha(anchored.encode())==binding['body_substring_sha256_before_exclusions'] body=op.prepare_retained_body(anchored);assert sha(body.encode())==binding['prepared_body_sha256'] for token in case['native_tokens']: x,y=token['span'];token['source_spelling']=body[x:y];token['lookup_spelling']=op.lexical_spelling(body[x:y]) token['context_rationale']='Frozen occurrence-specific reference category and syllable alternatives; reconstruction is not new annotation.' validate_case(case,body,lex,binding['raw_sha256']) bank={t['token_id']:t for t in case['native_tokens']} np={'flesch_syllable_pool':n_pool(bank,[x for s in case['flesch_samples'] for x in s['first100_token_ids']],0), 'flesch_sentence_pool':n_pool(bank,[x for s in case['flesch_samples'] for x in s['sentence_length_token_ids']],sum(len(s['thought_unit_spans']) for s in case['flesch_samples'])), 'smog_pool':n_pool(bank,[x for block in case['smog_blocks'] for ids in block['token_ids_by_sentence'] for x in ids],30)} first=[];end=[];sm=[] for sample in case['flesch_samples']: span=sample['first100_span'];f=a_pool(body[span[0]:span[1]],span[0]);first.append(f) span2=sample['sentence_length_span'];e=a_pool(body[span2[0]:span2[1]],span2[0]);end.append(e) samples.append({'pg_id':ident,'kind':'Flesch','k':sample['k'],'first100_span':span,'first100_sha256':sha(body[span[0]:span[1]].encode()),'ending_span':span2,'ending_sha256':sha(body[span2[0]:span2[1]].encode()),'M_first':f,'M_ending':e}) for block in case['smog_blocks']: span=block['span'];p=a_pool(body[span[0]:span[1]],span[0]);sm.append(p) samples.append({'pg_id':ident,'kind':'SMOG','block':block['block_id'],'span':span,'sha256':sha(body[span[0]:span[1]].encode()),'M_pool':p}) mp={'flesch_syllable_pool':total(first),'flesch_sentence_pool':total(end),'smog_pool':total(sm)} full=a_pool(body) fs={'N':flesch(np['flesch_syllable_pool'],np['flesch_sentence_pool']), 'M':flesch(mp['flesch_syllable_pool'],mp['flesch_sentence_pool']),'F':flesch(full,full)} ss={'N':smog(np['smog_pool']),'M':smog(mp['smog_pool']),'F':smog(full)} changes={} for src,dst in [('N','M'),('M','F'),('N','F')]: low=fs[dst]['lo']-fs[src]['hi'];high=fs[dst]['hi']-fs[src]['lo'] sentence=-Q(1015,1000)*(fs[dst]['asl']-fs[src]['asl']) sylo=-Q(846,10)*(fs[dst]['asw_hi']-fs[src]['asw_lo']);syhi=-Q(846,10)*(fs[dst]['asw_lo']-fs[src]['asw_hi']) assert (sentence+sylo,sentence+syhi)==(low,high) changes[src+'->'+dst]={'Flesch':{'lo':low,'hi':high,'sentence_component':sentence,'syllable_component_lo':sylo,'syllable_component_hi':syhi}, 'SMOG_density_change_lo':ss[dst]['lo']-ss[src]['hi'],'SMOG_density_change_hi':ss[dst]['hi']-ss[src]['lo']} outputs.append({'pg_id':ident,'title':binding['title'],'prepared_body_sha256':sha(body.encode()), 'features':{'N':np,'M':mp,'F':{'full_pool':full}},'Flesch':fs,'SMOG':ss,'changes':changes}) write('progress.json',{'completed_cases':[x['pg_id'] for x in outputs]}) print('DONE',ident,'Fwords',full['words'],flush=True) pairs=[] for a,b in itertools.combinations(outputs,2): for formula in ('Flesch','SMOG'): for admin in ('N','M','F'): x,y=a[formula][admin],b[formula][admin] pairs.append({'left':a['pg_id'],'right':b['pg_id'],'formula':formula,'administration':admin, 'raw_index_relation':op.oriented_relation(x['lo'],x['hi'],y['lo'],y['hi']), 'conventional_oriented_relation':op.oriented_relation(x['lo'],x['hi'],y['lo'],y['hi'],formula=='Flesch')}) assert len(pairs)==90 write('aggregate-results.json',{'cases':outputs,'pairwise_cells':pairs, 'inference':'finite conditional marginal envelopes; not confidence/error bounds or reader difficulty', 'reference':'Reference conventions, not validated ability', 'input_package_manifest_sha256':provenance['source_attachment_manifest_sha256'],'native_export_receipt_sha256':provenance['source_export_receipt_sha256']}) write('sample-pools.json',samples) print('COMPLETE six cases,36 formula/administration outputs,90 pair cells',flush=True) # Derived human-readable tables; exact rational columns govern comparisons. from table_exports import export_tables export_tables(OUT,outputs,pairs,samples) print('Wrote complete JSON, CSV and accessible HTML tables; no network was used.')