Download runtime/phonetic_math.py from guga-guga/GeoPOI: direct link, hf CLI and curl.
- Browser
- Download file 9.92 kB
-
https://huggingface.co/guga-guga/GeoPOI/resolve/main/runtime/phonetic_math.py
- Command line
-
hf download hf://guga-guga/GeoPOI/runtime/phonetic_math.py
-
curl -L -o phonetic_math.py https://huggingface.co/guga-guga/GeoPOI/resolve/main/runtime/phonetic_math.py
9.92 kB
| from collections import Counter | |
| import unicodedata | |
| MAX_RAW_CHARACTERS = 4096 | |
| MAX_CATALOG_PHONE_LENGTH = 45 | |
| def need(condition, message): | |
| if not condition: | |
| raise ValueError(message) | |
| def literal_normalize(text): | |
| need(type(text) is str, 'literal input must be a string') | |
| return ''.join(unicodedata.normalize('NFKC', text).casefold().split()) | |
| def build_local_families(catalog_pairs): | |
| families = {} | |
| stats = Counter(input_pairs=0, unsupported_phone_pairs=0, uncertain_literal_mapping_pairs=0, duplicate_pairs=0) | |
| for item in catalog_pairs: | |
| need(isinstance(item, (tuple, list)) and len(item) == 2, 'only explicit (original canonical string, complete pronunciation IDs)') | |
| canonical, phones = item | |
| need(type(canonical) is str and bool(canonical.strip()), 'original nonempty canonical string') | |
| need(isinstance(phones, (tuple, list)) and 0 < len(phones) <= MAX_CATALOG_PHONE_LENGTH, 'complete original catalog pronunciation, no truncation') | |
| need(all((type(value) is int and 1 <= value < 427 for value in phones)), 'catalog original427 only; PAD0 and invented symbols forbidden') | |
| stats['input_pairs'] += 1 | |
| if 1 in phones: | |
| stats['unsupported_phone_pairs'] += 1 | |
| continue | |
| key = tuple(phones) | |
| literal = literal_normalize(canonical) | |
| safe_literal = len(literal) == len(key) and bool(literal) and all((unicodedata.category(ch)[0] in ('L', 'N') for ch in literal)) | |
| if not safe_literal: | |
| stats['uncertain_literal_mapping_pairs'] += 1 | |
| family = families.setdefault(key, {'literals': set(), 'literal_mapping_uncertain': False}) | |
| if literal in family['literals']: | |
| stats['duplicate_pairs'] += 1 | |
| family['literals'].add(literal) | |
| family['literal_mapping_uncertain'] |= not safe_literal | |
| closed = {key: {'literals': tuple(sorted(value['literals'])), 'literal_mapping_uncertain': value['literal_mapping_uncertain']} for key, value in families.items()} | |
| stats['supported_distinct_phone_keys'] = len(closed) | |
| stats['ambiguous_phone_keys'] = sum((len(value['literals']) > 1 for value in closed.values())) | |
| stats['distinct_key_literal_pairs'] = sum((len(value['literals']) for value in closed.values())) | |
| return {'families': closed, 'statistics': dict(stats)} | |
| def whole_context_mapping(text, raw_values, whole_tokens, normalize_tokens, symbol_to_id): | |
| need(type(text) is str and len(text) <= MAX_RAW_CHARACTERS, 'same bounded raw NULL prediction, no truncation') | |
| need(isinstance(raw_values, (tuple, list)) and all((type(value) is str for value in raw_values)), 'whole lazy_pinyin raw string values are required') | |
| need(isinstance(whole_tokens, (tuple, list)) and all((type(value) is str for value in whole_tokens)), 'frozen whole default_pinyin_tokens output required') | |
| need(callable(normalize_tokens) and isinstance(symbol_to_id, dict), 'injected frozen normalizer and original427 map') | |
| need(len(symbol_to_id) == 427 and set(symbol_to_id.values()) == set(range(427)), 'one exact original427 ID namespace; Root separately pins original vocabulary bytes') | |
| per_value = [tuple(normalize_tokens([value])) for value in raw_values] | |
| flat = tuple((token for values in per_value for token in values)) | |
| need(flat == tuple(normalize_tokens(raw_values)) == tuple(whole_tokens), 'per-raw-value normalized concatenation must equal original whole default G2P') | |
| literal = literal_normalize(text) | |
| per_char_literals = [literal_normalize(character) for character in text] | |
| unicode_mapping_exact = ''.join(per_char_literals) == literal | |
| raw_char_count_equal = len(raw_values) == len(text) | |
| uncertain_view = not (unicode_mapping_exact and raw_char_count_equal) | |
| characters = [] | |
| reason_counts = Counter() | |
| if not uncertain_view: | |
| for index, (character, lit, values) in enumerate(zip(text, per_char_literals, per_value)): | |
| reasons = [] | |
| if len(lit) != 1: | |
| reasons.append('literal_deleted_or_expanded') | |
| if unicodedata.category(character)[0] not in ('L', 'N'): | |
| reasons.append('source_punctuation_space_symbol_or_other_gap') | |
| if len(lit) == 1 and unicodedata.category(lit)[0] not in ('L', 'N'): | |
| reasons.append('normalized_non_letter_or_number') | |
| if len(values) != 1: | |
| reasons.append('raw_value_has_zero_or_multiple_phones') | |
| phone = symbol_to_id.get(values[0], 1) if len(values) == 1 else None | |
| if phone is not None and (not 2 <= phone < 427): | |
| reasons.append('unknown_or_unsupported_phone') | |
| reason_counts.update(reasons) | |
| characters.append(dict(original_index=index, original_character=character, literal=lit, normalized_phone_tokens=values, phone_id=phone if not reasons else None, barrier=bool(reasons), reasons=tuple(reasons))) | |
| else: | |
| reason_counts['whole_unicode_mapping_not_exact'] = int(not unicode_mapping_exact) | |
| reason_counts['raw_values_count_not_original_characters'] = int(not raw_char_count_equal) | |
| return dict(text=text, literal=literal, whole_tokens=tuple(whole_tokens), per_raw_value_normalized_tokens=tuple(per_value), whole_default_equivalence_verified=True, raw_values_count=len(raw_values), original_characters=len(text), whole_unicode_mapping_exact=unicode_mapping_exact, raw_char_count_equal=raw_char_count_equal, alignment_uncertain=uncertain_view, characters=characters, barrier_reason_counts=dict(reason_counts)) | |
| def analyze_consistency(mapping, local_families, include_matches=True): | |
| need(type(include_matches) is bool, 'explicit bounded qualification detail policy') | |
| need(mapping.get('whole_default_equivalence_verified') is True, 'unqualified whole-context mapping') | |
| families = local_families['families'] | |
| if mapping['alignment_uncertain']: | |
| return dict(status='UNCERTAIN_WHOLE_TEXT_ALIGNMENT', view_retained=True, unique_literal_mismatch_fraction=None, matches=[] if include_matches else None, matching_spans=0, supported_local_phone_keys=len(families), catalog_statistics=local_families['statistics'], alignment_uncertain=True, new_model_or_score_created=False) | |
| characters = mapping['characters'] | |
| counts = Counter() | |
| phone_covered, literal_supported, mismatch_covered, ambiguous_covered, uncertain_covered = (set(), set(), set(), set(), set()) | |
| matches = [] | |
| maximum = max((len(key) for key in families), default=0) | |
| for start in range(len(characters)): | |
| if characters[start]['barrier']: | |
| continue | |
| key = [] | |
| for stop in range(start, min(start + maximum, len(characters))): | |
| item = characters[stop] | |
| if item['barrier']: | |
| break | |
| need(item['original_index'] == stop, 'unaltered continuous original character coordinates') | |
| key.append(item['phone_id']) | |
| family = families.get(tuple(key)) | |
| if family is None: | |
| continue | |
| end = stop + 1 | |
| surface = literal_normalize(mapping['text'][start:end]) | |
| need(surface == ''.join((value['literal'] for value in characters[start:end])) and len(surface) == end - start, 'one supported phone per unchanged contiguous literal character') | |
| literals = family['literals'] | |
| ambiguous = len(literals) > 1 | |
| uncertain = bool(family['literal_mapping_uncertain']) | |
| in_family = surface in literals | |
| mismatch = not ambiguous and (not uncertain) and (not in_family) | |
| positions = set(range(start, end)) | |
| phone_covered.update(positions) | |
| if in_family: | |
| literal_supported.update(positions) | |
| if ambiguous: | |
| ambiguous_covered.update(positions) | |
| if uncertain: | |
| uncertain_covered.update(positions) | |
| if mismatch: | |
| mismatch_covered.update(positions) | |
| counts['all_complete_phone_matches'] += 1 | |
| counts['literal_supported_matches'] += int(in_family) | |
| counts['ambiguous_matches'] += int(ambiguous) | |
| counts['uncertain_literal_family_matches'] += int(uncertain) | |
| counts['unique_literal_mismatch_matches'] += int(mismatch) | |
| if include_matches: | |
| matches.append(dict(start_character=start, stop_character=end, complete_phone_key=tuple(key), literal_surface=surface, local_distinct_canonical_count=len(literals), literal_in_local_phone_family=in_family, ambiguous=ambiguous, uncertain_literal_mapping=uncertain, unique_literal_mismatch=mismatch, unique_local_literal=literals[0] if len(literals) == 1 else None)) | |
| denominator = max(len(mapping['literal']), 1) | |
| return dict(status='ALIGNED_WITH_EXPLICIT_BARRIERS', view_retained=True, unique_literal_mismatch_fraction=len(mismatch_covered) / denominator, literal_normalized_characters=len(mapping['literal']), complete_phone_covered_characters=len(phone_covered), literal_supported_covered_characters=len(literal_supported), unique_mismatch_covered_characters=len(mismatch_covered), ambiguous_covered_characters=len(ambiguous_covered), uncertain_family_covered_characters=len(uncertain_covered), original_character_barriers=sum((value['barrier'] for value in characters)), barrier_reason_counts=mapping['barrier_reason_counts'], matching_spans=counts['all_complete_phone_matches'], counts=dict(counts), supported_local_phone_keys=len(families), catalog_statistics=local_families['statistics'], alignment_uncertain=False, partially_uncertain=bool(any((value['barrier'] for value in characters)) or uncertain_covered or local_families['statistics']['unsupported_phone_pairs']), matches=matches if include_matches else None, compatibility_not_error_or_correctness_truth=True, no_gold_Ret_scores_or_action_outputs_used=True, new_model_or_score_created=False) | |