'' import re import unicodedata from fractions import Fraction from decimal import Decimal, localcontext ABBREVIATIONS = ('Mr','Mrs','Ms','Dr','Prof','Rev','Hon','St','Sr','Jr', 'Esq','Messrs','Mmes','Mlle','Mme','Capt','Col','Gen','Lt','Sgt') CARDINAL_MAX = 10**15-1 ORDINAL_MAX = 9999 ETC_ATOM = r'(?i:&c\.)(?!\w)' ORDINAL_ATOM = r'[0-9]+(?:,[0-9]+)*(?i:st|nd|rd|th)' TOKEN = re.compile(ETC_ATOM+r"|[^\W\d_]+(?:['’][^\W\d_]+)*(?:[-‐‑][^\W\d_]+(?:['’][^\W\d_]+)*)*|"+ORDINAL_ATOM+r"|[0-9]+(?:[.,][0-9]+)*|[$£€]", re.UNICODE) VOWELS = frozenset(('AA','AE','AH','AO','AW','AY','EH','ER','EY','IH','IY','OW','OY','UH','UW')) def lexical_spelling(s): return unicodedata.normalize('NFC',s).casefold().replace('’',"'").replace('‐','-').replace('‑','-') def _etc_period_context(s,end): tail=s[end:] gap=re.match(r'["\'”’\)\] \t\n]*',tail).group() following=tail[len(gap):] terminal=bool(re.search(r'\n[ \t]*\n',gap)) or not following continuation=bool(following) and (following[0] in ',;:' or following[0].islower()) return {'protect_period':not terminal and continuation, 'rule':'declared_context_heuristic_NOT_semantic_truth', 'context_class':'paragraph_or_body_end' if terminal else 'continuation' if continuation else 'possible_ending', 'ambiguous_capitalization_or_other':not terminal and not continuation} def word_tokens(s, trace=None): '' guard=list(s) etc_matches=list(re.finditer(ETC_ATOM,s)) for match in etc_matches:guard[match.start()]=' ' elisions=[] pattern=r'\byear[ \t]+(?P—)[ \t]*(?P[0-9]+)(?!(?:[A-Za-z0-9_]|[.,][0-9]))' for match in re.finditer(pattern,s,re.I): guard[match.start('marker')]=' ' elisions.append({'marker_span':list(match.span('marker')),'visible_span':list(match.span('visible')), 'kind':'elided_year_visible','omitted_prefix_unknown':True,'full_year_inferred':False}) guard=''.join(guard) if any((c.isnumeric() and c not in '0123456789') or (unicodedata.category(c).startswith('S') and c not in '$£€') or c in '%‰‱&@#' for c in guard): raise ValueError('unsupported numeric/semantic symbol; no silent omission') letter=r"[^\W\d_]" adjacent=list(guard) for match in re.finditer(r'(?1:raise ValueError('unsupported numeral') parts=token.split('.') words=cardinal(int(parts[0])) if len(parts)==2:words+=['point']+[SMALL[int(x)]for x in parts[1]] return words def orthographic_surrogate(token): '' s=lexical_spelling(token).replace('æ','ae').replace('œ','oe') s=''.join(c for c in unicodedata.normalize('NFKD',s) if 'a'<=c<='z') if not s:raise ValueError('no letters for orthographic surrogate') n=len(re.findall(r'[aeiouy]+',s)) if re.search(r'[^aeiouy]e$',s):n-=1 return max(1,n) def _options_value(token, lexicon, native_oov=None, native_context_categories=None, children=None, source_form=None): '' s=lexical_spelling(token) listed=s in lexicon positive=set(x for x in lexicon.get(s,()) if x>0) unresolved=listed and any(x==0 for x in lexicon[s]) category=(native_context_categories or {}).get(s) if native_oov is not None and s=='&c.' and category!='abbreviation': raise ValueError('native symbolic abbreviation needs explicit frozen abbreviation category') elided=(source_form or {}).get('kind')=='elided_year_visible' if elided and (not s.isdigit() or (source_form or {}).get('omitted_prefix_unknown') is not True or (source_form or {}).get('full_year_inferred') is not False): raise ValueError('invalid visible-year qualification') if native_oov is not None and elided and category!='elided_year_visible': raise ValueError('native visible-year reading requires its explicit frozen category') if native_oov is not None and s in native_oov: vals=native_oov[s] if not vals or any(not isinstance(x,int) or x<1 for x in vals): raise ValueError('invalid frozen native context reading') if category is None: if ordinal_expansion(s) is not None:category='ordinal' elif s[:1].isdigit():category='numeral_or_year' elif s in '$£€':category='symbol' elif unresolved:category='source_zero_nucleus_or_other_unresolved_pronunciation' elif not listed:category='unlisted_word' else:raise ValueError('unqualified override of resolved dictionary entry') if category in {'numeral_or_year','ordinal','Roman_numeral','symbol','abbreviation','elided_year_visible'}: if category=='numeral_or_year' and (not s[:1].isdigit() or ordinal_expansion(s) is not None):raise ValueError('wrong numeral category') if category=='ordinal' and ordinal_expansion(s) is None:raise ValueError('wrong ordinal category') if category=='elided_year_visible' and not elided:raise ValueError('unqualified elided-year category') if category=='Roman_numeral' and not re.fullmatch('[ivxlcdm]+',s):raise ValueError('wrong Roman category') if category=='symbol' and s not in '$£€':raise ValueError('wrong symbol category') return tuple(sorted(set(vals))), 'qualified-frozen-native-context-'+category if category=='unlisted_word' and listed:raise ValueError('listed entry cannot be called unlisted') if category=='unlisted_word' and '-' in s: parts=s.split('-') if all(p in lexicon and all(x>0 for x in lexicon[p]) for p in parts): raise ValueError('fully resolved compound cannot be overridden as native OOV') if category=='source_zero_nucleus_or_other_unresolved_pronunciation' and not unresolved: raise ValueError('no unresolved source reading to annotate') if category not in {'unlisted_word','source_zero_nucleus_or_other_unresolved_pronunciation'}: raise ValueError('unknown native annotation category') return tuple(sorted(positive|set(vals))), 'frozen-native-unresolved-plus-source-positives' if native_oov is not None and (s[:1].isdigit() or s in '$£€' or s=='&c.'): raise ValueError('unresolved native numeral/symbol reading') expansion=spoken_expansion(s) if expansion is not None: results=[options(w,lexicon,native_oov,native_context_categories,trace=children) for w in expansion] totals={0} for vals,_ in results:totals={a+b for a in totals for b in vals} component_provenance='|'.join(sorted(set(prov for _,prov in results))) return tuple(sorted(totals)), 'declared-spoken-expansion['+component_provenance+']' if listed and not unresolved:return tuple(sorted(positive)), 'cmu-listed-variants' if not listed and '-' in s: parts=s.split('-') if all(p in lexicon and all(x>0 for x in lexicon[p]) for p in parts): totals={0} for p in parts:totals={a+b for a in totals for b in lexicon[p]} return tuple(sorted(totals)), 'unlisted-compound-component-cmu-sum' if native_oov is not None: raise ValueError('unresolved native lexical item') surrogate=orthographic_surrogate(s) if listed: return tuple(sorted(positive|{surrogate})), 'cmu-positives-plus-unresolved-surrogate-NOT-verified' return (surrogate,), 'oov-orthographic-surrogate-NOT-verified' def options(token, lexicon, native_oov=None, native_context_categories=None, trace=None, source_form=None): '' children=[] values,provenance=_options_value(token,lexicon,native_oov,native_context_categories,children,source_form) spelling=lexical_spelling(token) expansion=provenance.startswith('declared-spoken-expansion[') qualified=provenance.startswith('qualified-frozen-native-context-') direct_zero=(not expansion and not qualified and spelling in lexicon and 0 in lexicon[spelling]) component_zero=(not expansion and not qualified and spelling not in lexicon and '-' in spelling and any(0 in lexicon.get(p,()) for p in spelling.split('-'))) if (source_form or {}).get('kind')=='elided_year_visible': provenance='visible-only-elided-year-unknown-prefix['+provenance+']' node={'graphic_token':token,'syllable_options':list(values),'provenance':provenance, 'fallback_used':('surrogate-NOT-verified' in provenance) or any(c['fallback_used']for c in children), 'source_zero_nucleus':direct_zero or component_zero or any(c['source_zero_nucleus']for c in children), 'direct_source_zero_nucleus':direct_zero,'component_source_zero_nucleus':component_zero, 'native_context_used':qualified or provenance.startswith('frozen-native-unresolved'), 'children':children,'source_form':source_form, 'omitted_prefix_unknown':bool((source_form or {}).get('omitted_prefix_unknown')), 'full_year_inferred':False} if trace is not None:trace.append(node) return values,provenance def adapted_readings(s,lexicon): '' forms=[];tokens=word_tokens(s,trace=forms) for token,form in zip(tokens,forms): reading=[] vals,provenance=options(token,lexicon,trace=reading,source_form=form['source_form']) yield {'source_span':form['span'],'source_spelling':token,'source_form':form['source_form'], 'syllable_options':vals,'provenance':provenance,'reading_trace':reading[0]} def flesch(words,sentences,syllables): if words<=0 or sentences<=0 or syllablesa_hi or b_lo>b_hi:raise ValueError('reversed envelope') if a_lo==a_hi==b_lo==b_hi:return 'tie' if a_hib_hi:r='above' else:return 'unresolved' if higher_is_lower_index:r={'above':'below','below':'above'}[r] return r def prepare_retained_body(anchored_text): '' chars=list(anchored_text); i=0 while i