sinonym 0.6.2__tar.gz → 0.7.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. {sinonym-0.6.2 → sinonym-0.7.2}/PKG-INFO +1 -1
  2. {sinonym-0.6.2 → sinonym-0.7.2}/docs/unicode_hyphen_policy_review.md +1 -1
  3. {sinonym-0.6.2 → sinonym-0.7.2}/pyproject.toml +8 -1
  4. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/coretypes/config.py +2 -2
  5. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/data/COMPOUND_SURNAMES.md +48 -20
  6. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/data/EAST_ASIAN_NAME_LEXICONS.md +2 -0
  7. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/data/README.md +25 -8
  8. sinonym-0.7.2/sinonym/data/allcaps_given_words.csv.gz +0 -0
  9. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/data/compound_surnames.csv.gz +0 -0
  10. sinonym-0.7.2/sinonym/data/given_name_words.csv.gz +0 -0
  11. sinonym-0.7.2/sinonym/data/glued_initial_prefixes.csv.gz +0 -0
  12. sinonym-0.7.2/sinonym/data/korean_given_words.csv.gz +0 -0
  13. sinonym-0.7.2/sinonym/data/surname_first_words.csv.gz +0 -0
  14. sinonym-0.7.2/sinonym/data/token_role_prior.csv.gz +0 -0
  15. sinonym-0.7.2/sinonym/data/two_token_order_prior.csv.gz +0 -0
  16. sinonym-0.7.2/sinonym/data/unsplit_given_words.csv.gz +0 -0
  17. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/detector.py +8 -1
  18. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/name_punctuation.py +195 -18
  19. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/batch_analysis.py +11 -5
  20. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/compound_surnames.py +13 -0
  21. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/east_asian_name_order.py +5 -2
  22. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/ethnicity.py +8 -1
  23. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/normalization.py +10 -2
  24. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/person_name_normalization.py +60 -11
  25. sinonym-0.7.2/sinonym/services/source_repairs.py +1112 -0
  26. sinonym-0.7.2/sinonym/services/suffix_display.py +120 -0
  27. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/text_processing/text_preprocessor.py +2 -0
  28. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/timo/_resolution.py +272 -22
  29. sinonym-0.7.2/sinonym/timo/interface.py +423 -0
  30. sinonym-0.7.2/sinonym/utils/allcaps_given_words.py +35 -0
  31. sinonym-0.7.2/sinonym/utils/given_name_words.py +53 -0
  32. sinonym-0.7.2/sinonym/utils/korean_given_names.py +106 -0
  33. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/utils/string_manipulation.py +79 -8
  34. sinonym-0.7.2/sinonym/utils/unsplit_given_words.py +145 -0
  35. {sinonym-0.6.2 → sinonym-0.7.2}/tests/data/hangul_name_order_gold.json +1 -1
  36. {sinonym-0.6.2 → sinonym-0.7.2}/tests/data/manufactured_initials_cohorts.json +2 -2
  37. sinonym-0.7.2/tests/data/name_regression_cases.csv +706 -0
  38. sinonym-0.7.2/tests/data/source_repair_cases.csv +146 -0
  39. {sinonym-0.6.2 → sinonym-0.7.2}/tests/data/timo_parity/manifest.json +2 -2
  40. {sinonym-0.6.2 → sinonym-0.7.2}/tests/data/timo_parity/requests.jsonl +2 -2
  41. {sinonym-0.6.2 → sinonym-0.7.2}/tests/data/vietnamese_name_order_gold.json +2 -2
  42. sinonym-0.7.2/tests/test_070_name_fixes.py +400 -0
  43. sinonym-0.7.2/tests/test_072_name_fixes.py +329 -0
  44. sinonym-0.7.2/tests/test_allcaps_given_words.py +75 -0
  45. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_compound_names.py +1 -1
  46. sinonym-0.7.2/tests/test_compound_surname_stability.py +140 -0
  47. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_east_asian_name_order.py +2 -1
  48. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_fixability_proposal_fixes.py +20 -15
  49. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_initial_policy_routing.py +1 -1
  50. sinonym-0.7.2/tests/test_korean_given_names.py +126 -0
  51. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_manufactured_initials.py +1 -1
  52. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_mixed_scripts.py +5 -5
  53. sinonym-0.7.2/tests/test_name_regression_cases.py +215 -0
  54. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_non_chinese_exact_source_fixes.py +6 -7
  55. sinonym-0.7.2/tests/test_order_prior_stability.py +129 -0
  56. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_person_name_normalization.py +4 -6
  57. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_regression_proposals.py +2 -2
  58. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_s2and_review_regressions.py +419 -8
  59. sinonym-0.7.2/tests/test_source_repairs.py +274 -0
  60. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_timo_interface.py +2 -2
  61. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_timo_parity_fixture.py +1 -1
  62. sinonym-0.6.2/sinonym/data/surname_first_words.csv.gz +0 -0
  63. sinonym-0.6.2/sinonym/data/token_role_prior.csv.gz +0 -0
  64. sinonym-0.6.2/sinonym/data/two_token_order_prior.csv.gz +0 -0
  65. sinonym-0.6.2/sinonym/timo/interface.py +0 -213
  66. {sinonym-0.6.2 → sinonym-0.7.2}/.gitignore +0 -0
  67. {sinonym-0.6.2 → sinonym-0.7.2}/LICENSE +0 -0
  68. {sinonym-0.6.2 → sinonym-0.7.2}/README.md +0 -0
  69. {sinonym-0.6.2 → sinonym-0.7.2}/docs/batch_processing.md +0 -0
  70. {sinonym-0.6.2 → sinonym-0.7.2}/docs/canonical_name_evaluation.md +0 -0
  71. {sinonym-0.6.2 → sinonym-0.7.2}/docs/scalar_source_surname_repartition_evaluation.md +0 -0
  72. {sinonym-0.6.2 → sinonym-0.7.2}/docs/timo.md +0 -0
  73. {sinonym-0.6.2 → sinonym-0.7.2}/scripts/README.md +0 -0
  74. {sinonym-0.6.2 → sinonym-0.7.2}/scripts/build_east_asian_name_lexicons.py +0 -0
  75. {sinonym-0.6.2 → sinonym-0.7.2}/scripts/check_test_status.py +0 -0
  76. {sinonym-0.6.2 → sinonym-0.7.2}/scripts/data/reviewed_japanese_possible_surnames.csv +0 -0
  77. {sinonym-0.6.2 → sinonym-0.7.2}/scripts/generate_name_statistics.py +0 -0
  78. {sinonym-0.6.2 → sinonym-0.7.2}/scripts/generate_surname_romanizations.py +0 -0
  79. {sinonym-0.6.2 → sinonym-0.7.2}/scripts/name_order_routing_rules.py +0 -0
  80. {sinonym-0.6.2 → sinonym-0.7.2}/scripts/train_ml_classifier_for_chinese_vs_japanese.py +0 -0
  81. {sinonym-0.6.2 → sinonym-0.7.2}/scripts/verify_multiprocess.py +0 -0
  82. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/__init__.py +0 -0
  83. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/chinese_names_data.py +0 -0
  84. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/coretypes/__init__.py +0 -0
  85. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/coretypes/results.py +0 -0
  86. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/coretypes/routing_resolution.py +0 -0
  87. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/data/acl_2025_authors.txt +0 -0
  88. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/data/chinese_japanese_classifier.skops +0 -0
  89. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/data/east_asian_roman_lexicons.json.gz +0 -0
  90. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/data/familyname_orcid.csv +0 -0
  91. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/data/given_position.csv +0 -0
  92. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/data/givenname_orcid.csv +0 -0
  93. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/data/japanese_native_lexicons.json.gz +0 -0
  94. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/data/model_features.json +0 -0
  95. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/data/name_order_routing/README.md +0 -0
  96. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/data/name_order_routing/pp_abstain_labels.jsonl +0 -0
  97. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/data/name_order_routing/pp_vys_abstain_labels.jsonl +0 -0
  98. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/data/surname_romanizations.csv +0 -0
  99. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/ml_fast_scorer.py +0 -0
  100. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/ml_flag_data.py +0 -0
  101. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/ml_model_components.py +0 -0
  102. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/patterns/__init__.py +0 -0
  103. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/patterns/compiled_patterns.py +0 -0
  104. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/patterns/regex_builders.py +0 -0
  105. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/pipeline/__init__.py +0 -0
  106. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/pipeline/name_order_routing.py +0 -0
  107. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/resources.py +0 -0
  108. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/__init__.py +0 -0
  109. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/cache.py +0 -0
  110. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/formatting.py +0 -0
  111. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/initialization.py +0 -0
  112. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/name_lookup.py +0 -0
  113. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/non_person.py +0 -0
  114. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/order_metadata.py +0 -0
  115. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/order_prior.py +0 -0
  116. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/parsing.py +0 -0
  117. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/process_pool.py +0 -0
  118. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/slavic_initials.py +0 -0
  119. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/surname_first_words.py +0 -0
  120. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/services/token_order_prior.py +0 -0
  121. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/text_processing/__init__.py +0 -0
  122. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/text_processing/compound_detector.py +0 -0
  123. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/text_processing/text_normalizer.py +0 -0
  124. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/timo/__init__.py +0 -0
  125. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/timo/config.yaml +0 -0
  126. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/timo/integration_test.py +0 -0
  127. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/utils/__init__.py +0 -0
  128. {sinonym-0.6.2 → sinonym-0.7.2}/sinonym/utils/thread_cache.py +0 -0
  129. {sinonym-0.6.2 → sinonym-0.7.2}/tests/_case_assertions.py +0 -0
  130. {sinonym-0.6.2 → sinonym-0.7.2}/tests/_korean_atomic_cases.py +0 -0
  131. {sinonym-0.6.2 → sinonym-0.7.2}/tests/conftest.py +0 -0
  132. {sinonym-0.6.2 → sinonym-0.7.2}/tests/data/reviewed_korean_source_assignments.tsv +0 -0
  133. {sinonym-0.6.2 → sinonym-0.7.2}/tests/data/reviewed_source_pattern_assignments.jsonl +0 -0
  134. {sinonym-0.6.2 → sinonym-0.7.2}/tests/data/spaced_cjk_name_order_gold.json +0 -0
  135. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_acl.py +0 -0
  136. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_all_chinese_inputs.py +0 -0
  137. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_basic_chinese_names.py +0 -0
  138. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_batch.py +0 -0
  139. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_batch_crash_guard.py +0 -0
  140. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_batch_scalar_parity.py +0 -0
  141. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_bug_report_fixes.py +0 -0
  142. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_canonical_name_integration.py +0 -0
  143. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_canonical_results.py +0 -0
  144. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_check_test_status.py +0 -0
  145. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_chinese_classification_evidence_gates.py +0 -0
  146. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_chinese_compound_surname_provenance.py +0 -0
  147. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_cjk_component_leaks.py +0 -0
  148. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_compound_surname_formats.py +0 -0
  149. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_config_immutability.py +0 -0
  150. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_detector_initialization_and_validation.py +0 -0
  151. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_east_asian_lexicon_builder.py +0 -0
  152. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_han_surname_readings.py +0 -0
  153. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_hangul_name_order_gold.py +0 -0
  154. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_initial_policy_chinese.py +0 -0
  155. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_initial_policy_non_chinese.py +0 -0
  156. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_middle_names.py +0 -0
  157. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_misc.py +0 -0
  158. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_mixed_production_cases.py +0 -0
  159. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_ml_fast_scorer.py +0 -0
  160. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_ml_japanese_detection.py +0 -0
  161. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_multiprocess_pool.py +0 -0
  162. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_name_formatting.py +0 -0
  163. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_name_order_routing_label_fixtures.py +0 -0
  164. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_name_order_routing_rules.py +0 -0
  165. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_name_statistics_data.py +0 -0
  166. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_non_chinese_rejection.py +0 -0
  167. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_package_metadata.py +0 -0
  168. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_performance.py +0 -0
  169. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_pr29_pr30_paper_context_repairs.py +0 -0
  170. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_reference_scripts.py +0 -0
  171. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_regional_variants.py +0 -0
  172. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_review_finding_regressions.py +0 -0
  173. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_reviewed_non_person_patterns.py +0 -0
  174. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_reviewed_structured_source_repairs.py +0 -0
  175. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_scalar_clean_source_surname_repartition.py +0 -0
  176. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_spaced_cjk_name_order_gold.py +0 -0
  177. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_strict_spaced_japanese_routing.py +0 -0
  178. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_surname_romanizations.py +0 -0
  179. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_timo_contract.py +0 -0
  180. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_timo_performance.py +0 -0
  181. {sinonym-0.6.2 → sinonym-0.7.2}/tests/test_vietnamese_name_order_gold.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sinonym
3
- Version: 0.6.2
3
+ Version: 0.7.2
4
4
  Summary: Chinese Name Detection and Normalization Module
5
5
  Project-URL: Homepage, https://github.com/allenai/sinonym
6
6
  Project-URL: Repository, https://github.com/allenai/sinonym
@@ -46,7 +46,7 @@ The full scan used the current review corpus, not a sample:
46
46
  - 106,873,287 distinct `nm` rows and 690,997,259 weighted mentions
47
47
  - Parquet size 1,881,981,435 bytes, 533 row groups
48
48
  - SHA-256 `36d6e49e31dfc09b3e98144a6d1bc44c4884abe003a0672bb00ec4c9be991ad1`
49
- - source object: `s3://s2-atalyaa/disambiguation/author-names/sinonym-0-4-x-review/corpus/distinct_author_names.parquet`
49
+ - source object: an internal export of the distinct corpus author names (not published)
50
50
  - matching 106,873,287-row Chinese-label map SHA-256 `4992da8513e23855f51662583e015237edea0071bc907222fdfc38462bd09dd4`
51
51
  - 9,520,175 rows in that aligned map have `chinese=true`
52
52
  - scan revision `b39bdbe35e18104bb77bff21014e1921342e18d2`; DuckDB 1.5.5; elapsed 269.712 seconds
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "sinonym"
7
- version = "0.6.2"
7
+ version = "0.7.2"
8
8
  description = "Chinese Name Detection and Normalization Module"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -96,6 +96,12 @@ ignore = ["S101", "T201"] # Allow assert statements and print statements
96
96
  "sinonym/services/ethnicity.py" = ["C901", "PLR0911", "PLR0912", "PLR0915", "PLR2004", "ARG002", "SLF001"]
97
97
  "scripts/generate_acl_data.py" = ["B007", "BLE001", "C901", "F841", "PLC0415", "PLR0912", "PLR0915", "PLR2004", "PLW2901", "PTH123", "SIM102", "SIM108", "SLF001"]
98
98
  "scripts/generate_chinese_name_corpus_data.py" = ["ARG001", "BLE001", "C901", "ERA001", "N806", "PLC0415", "PLR0912", "PLR2004", "PTH123", "SLF001", "TRY300"]
99
+ "scripts/build_unsplit_given_words.py" = ["S608"]
100
+ "scripts/build_allcaps_given_words.py" = ["S608"]
101
+ "scripts/build_given_name_words.py" = ["S608"]
102
+ "sinonym/services/source_repairs.py" = ["RUF001", "RUF002", "RUF003"]
103
+ "tests/test_070_name_fixes.py" = ["RUF001", "PLC0415"]
104
+ "scripts/build_korean_given_words.py" = ["S608"]
99
105
  "scripts/change_class_tally.py" = ["INP001", "PLR2004", "S608"]
100
106
  "scripts/check_test_status.py" = ["E501", "RUF001"]
101
107
  "scripts/profile_multiprocess.py" = ["EM101", "PLR0913", "TRY003"]
@@ -106,6 +112,7 @@ ignore = ["S101", "T201"] # Allow assert statements and print statements
106
112
  "sinonym/chinese_names_data.py" = ["ERA001"]
107
113
  "sinonym/coretypes/config.py" = ["E501", "RUF001", "RUF003"]
108
114
  "sinonym/ml_fast_scorer.py" = ["PLR0913", "PLR2004"]
115
+ "sinonym/name_punctuation.py" = ["C901", "PLR0911", "PLR0912", "PLR0915", "RUF003"]
109
116
  "sinonym/ml_model_components.py" = ["ARG002", "N803", "PLR2004", "UP038"]
110
117
  "sinonym/patterns/regex_builders.py" = ["N806", "PLR2004", "RUF001"]
111
118
  "sinonym/resources.py" = ["PLC0415", "TC003"]
@@ -132,8 +132,8 @@ class ChineseNameConfig:
132
132
  han_roman_splitter=HAN_ROMAN_SPLITTER,
133
133
  ascii_alpha_pattern=re.compile(r"[A-Za-z]"),
134
134
  clean_roman_pattern=re.compile(
135
- r"[^A-Za-z\u00C0-\u00FF\u0100-\u024F-''']",
136
- ), # PRESERVE ASCII letters, Latin-1 Supplement (À-ÿ), Latin Extended-A (Ā-ſ), Latin Extended-B (ǀ-ɏ), hyphens and apostrophes for romanization systems
135
+ r"[^A-Za-z\u00C0-\u00FF\u0100-\u024F\u1E00-\u1EFF-''']",
136
+ ), # PRESERVE ASCII letters, Latin-1 Supplement (À-ÿ), Latin Extended-A (Ā-ſ), Latin Extended-B (ǀ-ɏ), Latin Extended Additional (Ḁ-ỿ, Vietnamese ậ/ễ/ự), hyphens and apostrophes for romanization systems
137
137
  camel_case_finder=re.compile(r"[A-Z][a-z]+"),
138
138
  clean_pattern=CLEAN_PATTERN,
139
139
  forbidden_patterns_regex=FORBIDDEN_PATTERNS_REGEX,
@@ -45,7 +45,7 @@ Tiers, column `tier`:
45
45
  left out (surname-first sources put hyphenated given names such as `Zhong-Hua` in `last_name`). For this tier
46
46
  `mentions` counts the hyphenated mentions, `whole_share` includes them as whole, and `given_names` is the distinct
47
47
  given-name initials. A hyphen is any of `-`, U+2010, U+2011, U+2012, U+2013 (en dash) and U+2212 (minus sign).
48
- 2026-10-31 build from the October name counts (`name_counts_20261021_v2`, with the `oct2` partition and token
48
+ 2026-10-31 build from the October 2026 name counts (with token
49
49
  priors): 112,671 surfaces not already in another tier. Rows whose `first_name` is an East Asian surname (two or
50
50
  more letters) are not evidence: a surname-first source puts the hyphenated given name in `last_name`
51
51
  (`Wang / Cai-hon`, `Sakamoto / Shin-ichi`).
@@ -63,16 +63,15 @@ no identifiers.
63
63
 
64
64
  ## How it was built (2026-10-22, October snapshot) and how to rebuild from a later dump
65
65
 
66
- All steps are read-only and local except the first dump. Scripts live in
67
- `/Users/atalyaa/Documents/repos/author-names/pp_vys_orcid_conc/scripts/` unless noted; the final step is in this repo.
66
+ All steps are read-only and local except the first dump. Steps 1–5 and 7 use analysis scripts kept outside this
67
+ repo; step 6 is in this repo.
68
68
 
69
- 1. **Source-name counts.** One Athena pass over a post-backfill `paper_authors` snapshot
70
- (`author-names/NAME_COUNTS.md`, `pp_vys_orcid_conc/scripts/v4/athena_name_counts.sh`): one row per distinct
69
+ 1. **Source-name counts.** One pass over a post-backfill `paper_authors` snapshot: one row per distinct
71
70
  source triple, where the source name is **all** `original_*` fields when `original_last IS NOT NULL`, else the
72
71
  stored fields (never a per-field coalesce — it leaks sinonym's own middle into rewritten rows). Counts: mentions,
73
72
  distinct papers, distinct ORCIDs; no production `author_id`. 113.6M triples, 702.9M mentions (Oct 2026).
74
- 2. (The May 2026 build used a pre-sinonym dump, `pre_name_counts.py`; same schema.)
75
- 3. **Partition statistics.** `partition_prior.py "<out_dir>/*.parquet" partition_prior.parquet` → for each 2–4-word
73
+ 2. (The May 2026 build used a pre-sinonym dump with the same schema.)
74
+ 3. **Partition statistics.** `partition_prior.parquet`: for each 2–4-word
76
75
  surname tail (`middle` words + `last` words), how often the corpus puts k words in `middle`; `share_whole`
77
76
  = k = 0. Also writes `partition_prior_tokens.parquet`: per word, mentions as a given name vs as the surname word.
78
77
  4. **Candidate universe.** Mention-count thresholds (in `build_compound_surnames.py`): 2–3 words, ≥ 50 mentions,
@@ -80,14 +79,14 @@ All steps are read-only and local except the first dump. Scripts live in
80
79
  letters, no suffix tail (`junior`, `filho`, …), no East Asian surname head (Vietnamese `Nguyen Van`, Chinese
81
80
  `Liu Yang` are not compounds), no Vietnamese `van X` / `thi X` pair (`Van Le`, `Van Tran`), no Chinese compound
82
81
  head (`Au Yeung`, `Ou Yang` stay with sinonym's curated list).
83
- Kill test before anything ships: `sim_compound_canon.py --asset <csv.gz> --no-shrink --half A|B` applies the
84
- shipped rule to an existing routed arm and scores people united / split under the production block key on
85
- the held-out ORCID half. Without `--no-shrink` the simulation also cuts longer surnames down to the surface
86
- and over-counts (2026-10-21: 446 / 17) — the shipped rule's own numbers are in step 7.
87
- 5. **Person-level gate.** `scripts/v4/compound_orcid_gate_v4.py` over dataset v4 (every ORCID mention with its source
88
- name), excluding the ORCIDs of the 690k evaluation index: per surface, distinct people with the whole form, the
89
- split form, and both. `HALF=A` builds it on one ORCID half (last ORCID character not in 1 3 5 7 9 X) so the other
90
- half can score the asset; `HALF=all` for the shipped build.
82
+ Kill test before anything ships: apply the shipped rule to an existing routed arm and score people united /
83
+ split under the production block key on the held-out ORCID half. The simulation must not also cut longer
84
+ surnames down to the surface, which over-counts (2026-10-21: 446 / 17); the shipped rule's own numbers are in
85
+ step 7.
86
+ 5. **Person-level gate.** `compound_orcid_gate.parquet`, built over every ORCID mention with its source
87
+ name, excluding the ORCIDs of the 690k evaluation index: per surface, distinct people with the whole form, the
88
+ split form, and both. One build uses one ORCID half (last ORCID character not in 1 3 5 7 9 X) so the other
89
+ half can score the asset; the shipped build uses all ORCIDs.
91
90
  6. **Asset.** `uv run python scripts/build_compound_surnames.py --partition partition_prior.parquet --tokens
92
91
  partition_prior_tokens.parquet --orcid-gate compound_orcid_gate.parquet --output sinonym/data/compound_surnames.csv.gz`
93
92
  keeps the `listed` surfaces where both signals agree (≥ 3 people, ≥ 2 of them whole), derives the
@@ -95,11 +94,10 @@ All steps are read-only and local except the first dump. Scripts live in
95
94
  pair of the partition statistics built from them (≥ 5 mentions, same head-word given-name gate), then prints
96
95
  the sha256, and adds the `corpus` tier. 2026-10-23 October build (floor 0.15, construct prefixes): 7,240 listed
97
96
  + 1,719 vocabulary + 167,475 corpus surfaces.
98
- 7. **Acceptance.** Route the 690k index with the new build (`run_690k_*.sh`), score with `conc_arms.py`
99
- (FIXED/BROKE ≥ 5:1 on half B, no shared-block growth), run the detector (`weird_bugs.py`) and a blind judge
100
- sample (`judge_changes.py`), and the test suite at its baseline. Then the corpus-scale run (every ORCID,
101
- `author-names/ORCID_V4.md`): `scripts/v4/broke_v4.py` attributes every united / split person to the rule that
102
- moved it, and `scripts/v4/registry_agreement.py` scores each arm's surnames against the ORCID registry's
97
+ 7. **Acceptance.** Route the 690k index with the new build and score it (FIXED/BROKE ≥ 5:1 on half B, no
98
+ shared-block growth), run an anomaly detector and a blind judge sample, and the test suite at its baseline.
99
+ Then the corpus-scale run over every ORCID mention: attribute every united / split person to the rule that
100
+ moved it, and score each arm's surnames against the ORCID registry's
103
101
  self-declared family names (the name ground truth; the corpus share is a source convention, not a truth).
104
102
 
105
103
  Known limits: sources that drop a compound's head entirely (`Maza` alone) cannot be joined by any rule; the
@@ -113,3 +111,33 @@ surfaces removed from the asset). Across every tier, ORCID people who write such
113
111
  word alone more often than both words (`mohamed` 40% / 32%, `mohammad` 42% / 36%, `bin` 58% / 29%): the head is a
114
112
  given name or a patronymic (`Ahmed / Mohamed / Ali`, `Ahmad / bin / Ismail`). The other construct prefixes register
115
113
  both words (`abdul` 62% / 22%, `mohd` 81% / 9%) and stay.
114
+
115
+ ## Refreshing the table: only clear evidence changes a surface (since 0.7.1)
116
+
117
+ A rebuild from a newer snapshot decides every surface by that day's evidence. Pairs that ORCID registrants write about
118
+ as often whole as split (`rodrigues gomes`, `rodrigues oliveira`, `silva santana`, `srinivasa rao`: 40-60 % of the
119
+ registrants carrying the pair register both words) then cross the majority threshold in either direction. Rebuilding
120
+ every tier from the 2026-11-12 data with unchanged thresholds fixed the family name of 4,489 ORCID people but broke
121
+ 3,108, far below the 5:1 acceptance bar of step 7.
122
+
123
+ `scripts/stabilize_compound_surnames.py` therefore compares the rebuilt table with the shipped one, surface by surface.
124
+ Its evidence is, per surface, the ORCID people whose source-supplied mentions end their `middle + last` words with the
125
+ surface, split by their registered family name in the ORCID public data file: `join` when it is the surface or ends
126
+ with it, `tail` when it is the surface without its first word (the script's docstring gives the exact folding and the
127
+ input schema).
128
+
129
+ - `join + tail >= 20` and `join >= 0.67` of them: listed;
130
+ - `join + tail >= 20` and `tail >= 0.67` of them: not listed;
131
+ - anything else (ambiguous, too few registrants, or no registry evidence): the shipped status.
132
+
133
+ Thresholds were chosen on held-out people: evidence from ORCID half A (last iD character not 1 3 5 7 9 X), scored on
134
+ half B against the 0.7.0 table. Keeping the shipped status for ambiguous pairs at a 0.67 margin and 20 registrants
135
+ changed 3 held-out family names for the better and none for the worse; a 0.6 margin let the churn back in (support 5:
136
+ 300 fixed, 254 broken). The alternative of dropping ambiguous pairs, so that sinonym follows each source's own field
137
+ split (`--ambiguous abstain`), lost at every setting tried (0.67 and 20: 2,702 fixed, 3,642 broken), because sources
138
+ split pairs their authors registered whole about as often as the reverse. A surface that stays listed keeps its
139
+ shipped row.
140
+
141
+ The shipped 0.7.1 table was decided on the half-A evidence as well (unlike the `HALF=all` gate of step 5), so half B
142
+ stays a held-out set for the next refresh. It is the 0.7.0 table without `silva silva` (half A: 10 registrants with
143
+ both words, 25 with `Silva`; half B: 8 and 26).
@@ -59,6 +59,8 @@ suppress an earlier candidate and therefore do not change routing metadata for
59
59
  already-correct context-supported parses. All other reviewed surnames use the
60
60
  general, candidate-aware possible-surname rule.
61
61
 
62
+ `Fuji Ren` is a separate exact entry in `JAPANESE_PRESELECTION_GIVEN_FIRST_EXACT_SURFACES`, not in the reviewed CSV: it is a Chinese given-first name (ORCID family name `Ren`, 827 mentions in the 2026-11-12 name-counts export) whose two words are a Japanese surname and a Japanese given name, so the Japanese family-first inference would otherwise make `Fuji` the surname. The same person written surname-first, `Ren Fuji` (56 mentions in `content_ext.paper_authors` on 2026-11-25, all with his known co-authors), is in `IDENTITY_BACKED_EXACT_ROLES` as surname then given.
63
+
62
64
  ## Popular Names by Country Dataset
63
65
 
64
66
  Source: <https://github.com/sigpwned/popular-names-by-country-dataset>
@@ -47,30 +47,47 @@ Attribution: the 120W corpus is from [wainshine/Chinese-Names-Corpus](https://gi
47
47
  - The scoring hook reads `spelling` and `target_share` and (via initialization) loads each row's `surname_ppm_as_written` into the runtime surname frequency table, so full-share rows carry the target's mass and penalty CANTONESE keys carry the discounted mass. Corpus-derived estimates (e.g. ORCID with affiliation country) can replace the numbers without a schema change.
48
48
  ### Corpus-Derived Name Assets: Coverage, Provenance and Refresh
49
49
 
50
- Four assets are lookup tables built from Semantic Scholar author names:
50
+ Five assets are lookup tables built from Semantic Scholar author names:
51
51
 
52
52
  | asset | built by | snapshot | fires only when |
53
53
  |---|---|---|---|
54
- | `compound_surnames.csv.gz` | `scripts/build_compound_surnames.py`, `scripts/build_hyphen_compound_surnames.py` ([COMPOUND_SURNAMES.md](COMPOUND_SURNAMES.md)) | October 2026 | the multi-word surname is listed |
55
- | `two_token_order_prior.csv.gz` | `scripts/build_order_prior_asset.py` | May 2026 | the pair has >= 100 mentions and a >= 80% majority |
56
- | `token_role_prior.csv.gz` | `scripts/build_token_order_prior.py` | May 2026 | the token has >= 200 mentions and is >= 90% one role |
57
- | `surname_first_words.csv.gz` | `scripts/build_surname_first_words.py` | October 2026 | the word was seen in that shape and is mostly a surname (>= 3 mentions) |
54
+ | `compound_surnames.csv.gz` | `scripts/build_compound_surnames.py`, `scripts/build_hyphen_compound_surnames.py`, then `scripts/stabilize_compound_surnames.py` ([COMPOUND_SURNAMES.md](COMPOUND_SURNAMES.md)) | October 2026 | the multi-word surname is listed |
55
+ | `two_token_order_prior.csv.gz` | `scripts/build_order_prior_asset.py`, then `scripts/stabilize_order_priors.py` | November 2026 | the pair has >= 100 mentions and a >= 80% majority |
56
+ | `token_role_prior.csv.gz` | `scripts/build_token_order_prior.py`, then `scripts/stabilize_order_priors.py` | November 2026 | the token has >= 200 mentions and is >= 90% one role |
57
+ | `surname_first_words.csv.gz` | `scripts/build_surname_first_words.py` | November 2026 | the word was seen in that shape and is mostly a surname (>= 3 mentions) |
58
+ | `glued_initial_prefixes.csv.gz` | `scripts/build_glued_initial_prefixes.py` | November 2026 | the word before a glued capital is a first name >= 100 times and at least as often as a surname, and word + that letter is not itself a common first name |
58
59
 
59
60
  - **Unseen names.** A name a table does not list gets the behavior without that rule, never a guess, so new or rare
60
61
  names are not made worse; they just do not get the gain. Shape-based rules (digraph initials, glued initials, the
61
62
  Japanese given-first veto) apply to any name.
62
63
  - **Provenance.** Build every asset from source names as published, never from sinonym's output: per row, all
63
- `original_*` fields when `original_last` is set, else the stored fields, and never coalesce per field (the export is
64
- described in author-names `NAME_COUNTS.md`). An asset built from normalized names learns sinonym's own decisions.
64
+ `original_*` fields when `original_last` is set, else the stored fields, and never coalesce per field. An asset built from normalized names learns sinonym's own decisions.
65
65
  - **Refresh.** The tables age as new authors and conventions arrive. Rebuild them from a newer snapshot periodically,
66
66
  and in particular after each ORCID backfill (more linked people strengthens the ORCID-gated compound tier), then
67
67
  rerun the ORCID ledger, the registry agreement and the S2AND gold-cluster check before shipping.
68
68
  - **Measuring the gain on new names.** The held-out ORCID half guards against fitting particular people, but the tables
69
69
  were built from a snapshot that contains those names. To measure the gain on unseen names, build the tables from an
70
70
  older snapshot and score only names that first appear after it.
71
+ - **Current build (0.7.1).** Six tables were rebuilt on 2026-11-12 with the 0.7.0 builders and unchanged thresholds:
72
+ source-name counts from the Semantic Scholar `paper_authors` export of 2026-11-12, ORCID evidence only from iDs the
73
+ source supplied (iDs attached later by the ORCID profile backfill, which matches by name, are left out so the tables
74
+ do not learn from name matching), and the ORCID public data file of October 2026 (`korean_given_words.csv.gz`,
75
+ `allcaps_given_words.csv.gz`). Rows: two-token order prior 106,311 -> 107,787; token roles 238,677 -> 243,168 (the two order priors keep every 0.7.0 entry the rebuild dropped and add the rebuild's new ones, `scripts/stabilize_order_priors.py`: a dropped entry had only crossed a gate, and dropping it turned names such as `Petralia / Salvatore` back; entries kept from 0.7.0 keep their 0.7.0 counts, which the runtime does not read);
76
+ surname-first words 40,112 -> 42,178; glued-initial prefixes 112,710 -> 113,345; Korean given words 3,108 -> 3,670;
77
+ three-letter given words 881 -> 824. Two tables keep their 0.7.0 build, `unsplit_given_words.csv.gz` and
78
+ `given_name_words.csv.gz`; `compound_surnames.csv.gz` is the 0.7.0 table passed through
79
+ `scripts/stabilize_compound_surnames.py`, which changes a surface only on clear ORCID registry evidence
80
+ ([COMPOUND_SURNAMES.md](COMPOUND_SURNAMES.md)); this refresh drops one surface. Plain rebuilds of these tables broke
81
+ almost as many ORCID people's names as they fixed (compound surnames: 4,489 family names fixed, 3,108 broken, far
82
+ below the 5:1 acceptance bar; unsplit given words 26 / 21; given-name words 20 / 22), mostly pairs that registrants
83
+ write both ways about equally often, which the new data only moved across the majority threshold.
71
84
 
72
85
  ### Surname-First Words Before Dotted Initials
73
- - **`surname_first_words.csv.gz`**: 40,112 words (`word, surname_first_mentions, as_last, as_first`) that sources write as `first_name` before 2-3 dotted initials (`Dmitrieva / - / N.M.`, `Назарова / - / А.Р.`) and that the corpus otherwise uses as a surname (`as_last` >= 3 and > `as_first`). The rule that consumes it (`structured_surname_first_initials_assignment`) moves the word to the surname only when it is in this list, so given names written the same way (`Sowmya / - / K. R.`) stay unchanged. Generated by `scripts/build_surname_first_words.py` from the source-name counts export.
86
+ - **`surname_first_words.csv.gz`**: 42,178 words (`word, surname_first_mentions, as_last, as_first`) that sources write as `first_name` before 2-3 dotted initials (`Dmitrieva / - / N.M.`, `Назарова / - / А.Р.`) and that the corpus otherwise uses as a surname (`as_last` >= 3 and > `as_first`). The rule that consumes it (`structured_surname_first_initials_assignment`) moves the word to the surname only when it is in this list, so given names written the same way (`Sowmya / - / K. R.`) stay unchanged. Generated by `scripts/build_surname_first_words.py` from the source-name counts export.
87
+
88
+ ### Given Names Written in Capitals
89
+ - **`allcaps_given_words.csv.gz`**: 824 three-letter words (`word, name_people, initials_people, name_share`) that ORCID registry people write as their first given name (not in capitals, >= 10 people) making up at least 80% of those people plus the people whose three given names start with its letters. A given name of three capitals before a surname with lowercase letters stays in capitals as initials (`ESL Pedersen`, which S2AND reads as e + s + l) unless it is listed (`ANA Dias` -> `Ana`). Generated by `scripts/build_allcaps_given_words.py` from the ORCID public data file.
90
+ - **`given_name_words.csv.gz`**: 10,220 words (`word, given_people, family_people, family_head_people`) that at least 200 ORCID registry people use, at least 80% of them as a given name, and that fewer than 1.5% of those people use to open a multi-word family name. The 5,245 of them used by at least 95% as a given name and opened with by fewer than 0.5% (`jonathan`, `gareth`, `myriam`; not `andres`, `blanca`, `david`, which open Iberian double surnames) are not moved into the surname when the source wrote them in the given or middle field (`Q. / M. Jonathan / Wu` keeps surname `Wu`); before a one-word common Chinese surname all listed words are (`C. / L. Philip / Chen` keeps surname `Chen`). Generated by `scripts/build_given_name_words.py` from the ORCID public data file.
74
91
 
75
92
  ### Chinese vs Japanese Name Classifier
76
93
  - **`chinese_japanese_classifier.skops`**: Pre-trained scikit-learn model for distinguishing Chinese from Japanese names when written in Chinese characters. At runtime `sinonym.ml_fast_scorer` reads the fitted parameters directly from this archive without importing the training stack. The training script also writes a legacy `.joblib` copy for model-development comparisons; distributions omit that runtime-unused copy.
@@ -167,6 +167,7 @@ import math
167
167
  import platform
168
168
  import string
169
169
  import threading
170
+ import unicodedata
170
171
  from dataclasses import replace
171
172
  from typing import Literal
172
173
 
@@ -233,6 +234,7 @@ from sinonym.services.slavic_initials import is_digraph_initials_surname
233
234
  from sinonym.services.surname_first_words import load_surname_first_words, surname_first_initials
234
235
  from sinonym.services.token_order_prior import load_token_role_prior
235
236
  from sinonym.utils.string_manipulation import StringManipulationUtils
237
+ from sinonym.utils.unsplit_given_words import load_unsplit_given_words, standalone_words
236
238
 
237
239
  LOGGER = logging.getLogger(__name__)
238
240
 
@@ -341,6 +343,7 @@ class ChineseNameDetector:
341
343
  load_token_role_prior()
342
344
  load_order_prior()
343
345
  load_surname_first_words()
346
+ load_unsplit_given_words()
344
347
  surname_resolver = SurnameResolver(data, self._normalizer)
345
348
  ethnicity_service = EthnicityClassificationService(context)
346
349
  parsing_service = NameParsingService(context, weights=self._weights)
@@ -827,7 +830,7 @@ class ChineseNameDetector:
827
830
 
828
831
  def _clean_source_roman_token(self, token: str) -> str:
829
832
  """Clean a source Roman token while preserving source capitalization."""
830
- folded = token.translate(self._config.roman_punctuation_fold_tr)
833
+ folded = unicodedata.normalize("NFC", token.translate(self._config.roman_punctuation_fold_tr))
831
834
  return self._config.clean_roman_pattern.sub("", folded)
832
835
 
833
836
  def _roman_tokens_match_han_pinyin(self, roman_tokens: list[str], han_pinyin: tuple[str, ...]) -> bool:
@@ -1041,6 +1044,10 @@ class ChineseNameDetector:
1041
1044
  - success=True, result=formatted_name if Chinese name detected
1042
1045
  - success=False, error_message=reason if not Chinese name
1043
1046
  """
1047
+ with standalone_words(raw_name):
1048
+ return self._normalize_chinese_name_in_context(raw_name)
1049
+
1050
+ def _normalize_chinese_name_in_context(self, raw_name: str) -> ParseResult:
1044
1051
  initial_failure = self._initial_input_failure(raw_name)
1045
1052
  if initial_failure is not None:
1046
1053
  return initial_failure
@@ -115,7 +115,7 @@ PERSON_HYPHEN_LIKE = frozenset(
115
115
  # Invisible markup that carries no name content. These survive `clean_roman_pattern` (they are
116
116
  # neither Roman letters nor punctuation), leave the token unmatched by the tokenizer, and the
117
117
  # name then resolves as NON_PERSON_SOURCE_PASSTHROUGH -- so a real author is marked a non-person.
118
- # 24,933 rows of `paper_authors_full` carry one; a LEADING one also becomes the first initial in
118
+ # 24,933 rows of the paper-authors table carry one; a LEADING one also becomes the first initial in
119
119
  # scholar's `cluster_block_key`, because that key slices the raw first name.
120
120
  #
121
121
  # Deliberately EXCLUDED, per the measured split:
@@ -216,20 +216,29 @@ def fold_spaced_transliteration_apostrophes(value: str) -> str:
216
216
  return _DUTCH_T_SPACING_RE.sub(" 't", value)
217
217
 
218
218
 
219
+ # spacing diacritics; ASCII ^ and backtick are not marks here (a caret between a vowel and a consonant is handled
220
+ # on its own in ``_reattach_in_token``)
219
221
  _SPACING_TO_COMBINING = {
220
- "\u00a8": "\u0308", "\u02da": "\u030a", "\u00b4": "\u0301", "\u0060": "\u0300", "\u005e": "\u0302",
222
+ "\u00a8": "\u0308", "\u02da": "\u030a", "\u00b4": "\u0301",
221
223
  "\u02dc": "\u0303", "\u00b8": "\u0327", "\u02c7": "\u030c", "\u00af": "\u0304", "\u02d8": "\u0306",
222
- "\u02dd": "\u030b", "\u02d9": "\u0307",
224
+ "\u02dd": "\u030b", "\u02d9": "\u0307", "\u02db": "\u0328",
223
225
  }
224
- _APOSTROPHE_LIKE_MARKS = frozenset({"\u00b4", "\u0060"})
226
+ _APOSTROPHE_LIKE_MARKS = frozenset({"\u00b4"})
225
227
  _COMBINING_TO_SPACING = {combining: spacing for spacing, combining in _SPACING_TO_COMBINING.items()}
226
- _ANY_DETACHED_MARK_RE = re.compile("[" + "".join(_SPACING_TO_COMBINING) + "\\u0300-\\u036f]")
228
+ # a combining mark right after a letter or another mark is ordinary NFD text (``Iba\u0301n\u0303ez``, ``İ\u0307\u0307``) and
229
+ # is never moved; only spacing marks and combining marks that follow no letter are detached
230
+ _DETACHED_MARK = "(?:[" + "".join(_SPACING_TO_COMBINING) + "]|(?<![^\\W\\d_]|[\\u0300-\\u036f])[\\u0300-\\u036f])"
231
+ _ANY_DETACHED_MARK_RE = re.compile(_DETACHED_MARK)
227
232
  _TOKEN_MARK_RE = re.compile(
228
- "(?P<prev>[^\\W\\d_])?(?P<mark>[" + "".join(_SPACING_TO_COMBINING) + "\\u0300-\\u036f])(?P<next>[^\\W\\d_])?",
233
+ "(?P<prev>[^\\W\\d_])?(?P<mark>" + _DETACHED_MARK + ")(?P<next>[^\\W\\d_])?",
229
234
  re.UNICODE,
230
235
  )
231
236
 
232
237
 
238
+ def _base(ch: str) -> str:
239
+ return unicodedata.normalize("NFD", ch)[:1] if ch else ""
240
+
241
+
233
242
  def _compose(base: str, combining: str) -> str | None:
234
243
  if not base:
235
244
  return None
@@ -268,8 +277,53 @@ def _attach_caron(prev: str, nxt: str, *, mark_before_letter: bool = False) -> s
268
277
  return None
269
278
 
270
279
 
280
+ # letters and clusters that mark a Polish word (Turkish and Romanian names, the other cedilla users, have none):
281
+ # a cedilla after a or e there is the ogonek of ą ę (ie¸ is ę in 15 of 15 corpus words, a¸/e¸ elsewhere 73 of 276)
282
+ # (case-sensitive and anchored, so ``Ta¸skıran`` with its Turkish ı does not look Polish)
283
+ _POLISH_WORD_RE = re.compile("[łśżźćńŁŚŻŹĆŃwW]|[cC]z|[sS]z|[rR]z|[sScC]k[ia]$|ie\u00b8|i\u02dbe")
284
+ _ROMANIAN_WORD_RE = re.compile("escu$|eanu$|[şţșțâî]|^Dr[aeiou]\u02d8?g", re.IGNORECASE)
285
+ # a Czech or Slovak word: a caron letter or a detached caron, or a -sky/-cky ending (ý is extracted as y´ there)
286
+ _CZECH_WORD_RE = re.compile("[řšČčžěůďťňŘŠŽĚŮĎŤŇ]|\u02c7|[sScC][kK][yY]\u00b4$")
287
+ _MAX_REPAIRED_TOKEN = 200
288
+ _STRONG_POLISH_WORD_RE = re.compile("[łśżźćńŁŚŻŹĆŃ]|[cC]z|[sS]z|[rR]z|[sScC]k[ia]$|ie\u00b8|i\u02dbe")
289
+ _CARET_CIRCUMFLEX_RE = re.compile("([aeiouAEIOU])\\^(?=[b-df-hj-np-tv-z])")
290
+ _MARKUP_BEFORE_MARK_RE = re.compile("[" + "".join(sorted(INVISIBLE_MARKUP)) + "]+(?=[\\u0300-\\u036f])")
291
+ # à and  before a spacing mark are UTF-8 read as Latin-1 (``Antônio``, ``Søren``); such a word is decoded when it
292
+ # round-trips exactly
293
+ _MOJIBAKE_BEFORE_MARK_RE = re.compile("[ÃÂ][" + "".join(_SPACING_TO_COMBINING) + "]")
294
+ # Ä and Å before a spacing mark are other mojibake (cp1250 ``Ä˝ubica`` for Ľubica): such a word is left as written
295
+ _OTHER_MOJIBAKE_BEFORE_MARK_RE = re.compile("[ÄÅ][" + "".join(_SPACING_TO_COMBINING) + "]")
296
+ # a mid-word ´ after a letter with one of these marks is the next letter's acute (``Dvoř´ak``, ``Sagü´es``, ``Szczȩ´sniak``);
297
+ # after an acute, macron, tilde, circumflex or breve it is an apostrophe (``Sā´id``, ``Marí´a``, ``Iñ´aki``, ``Quô´c``)
298
+ _ACUTE_AFTER_MARKS = frozenset({"\u030c", "\u0308", "\u0327", "\u0328"})
299
+
300
+
271
301
  def _reattach_in_token(token: str) -> str:
272
- """One token, all or nothing: a mark that composes with neither neighbour leaves the token as it was."""
302
+ """Repair the detached marks of one token; a mark that composes with neither neighbour leaves the token as it was."""
303
+ if "`" in token:
304
+ return token # a backtick there makes ´ an apostrophe variant (``Le Bloc´`'h``), never an accent
305
+ if "^" in token:
306
+ # a caret between a vowel and a consonant is that vowel's circumflex (``Lemai^tre`` → ``Lemaître``, ``Jéro^me``);
307
+ # between two vowels it is ambiguous (``Beno^it`` is Benoît), and elsewhere (``Smith^1``, ``^hiyi``,
308
+ # ``Gomes^Neto``) it is a separator or footnote, so any other caret leaves the word alone
309
+ fixed = _CARET_CIRCUMFLEX_RE.sub(lambda m: unicodedata.normalize("NFC", m.group(1) + "\u0302"), token)
310
+ return token if "^" in fixed else _reattach_in_token(fixed)
311
+ if (len(token) > 1 and token[0] == token[-1] == "\u00b4") or "\u00b4\u00b4" in token:
312
+ return token # ``´Iñaki´`` and ``Ángel´´`` use ´ as quote marks, not accents
313
+ if _MOJIBAKE_BEFORE_MARK_RE.search(token):
314
+ # UTF-8 read as Latin-1 (``Søren``, ``Antônio``): decode it only when that round-trips exactly, else leave it
315
+ try:
316
+ decoded = token.encode("latin-1").decode("utf-8")
317
+ except UnicodeError:
318
+ return token
319
+ return _reattach_in_token(decoded) # ``STOJANOVIC´`` → ``STOJANOVIC´`` → ``STOJANOVIĆ``
320
+ if _OTHER_MOJIBAKE_BEFORE_MARK_RE.search(token):
321
+ return token
322
+ if len(token) > _MAX_REPAIRED_TOKEN:
323
+ return token # no name word is this long, and the per-mark repair is quadratic in the token length
324
+ original = token
325
+ # a spacing mark doubled by the extractor is one mark (``Mu¨¨ller``); a doubled ´ is a quote mark (``Ángel´´``)
326
+ token = re.sub("([" + "".join(m for m in _SPACING_TO_COMBINING if m != "\u00b4") + "])\\1+", "\\1", token)
273
327
  failed = False
274
328
  caron_before = 0
275
329
  for m in _TOKEN_MARK_RE.finditer(token):
@@ -283,29 +337,148 @@ def _reattach_in_token(token: str) -> str:
283
337
  failed = True
284
338
  return match.group(0)
285
339
 
340
+ current = token
341
+ all_caps = token.upper() == token
342
+ polish_word = _POLISH_WORD_RE.search(token) is not None
343
+ strong_polish_word = _STRONG_POLISH_WORD_RE.search(token) is not None
344
+ czech_word = _CZECH_WORD_RE.search(token) is not None
345
+ romanian_word = _ROMANIAN_WORD_RE.search(token) is not None
346
+
286
347
  def fix(match):
287
348
  nonlocal failed
288
349
  prev, nxt, mark = match.group("prev") or "", match.group("next") or "", match.group("mark")
289
350
  combining = _SPACING_TO_COMBINING.get(mark, mark)
351
+ start = match.start("mark")
352
+ if mark in _APOSTROPHE_LIKE_MARKS and not prev and nxt and start and unicodedata.combining(current[start - 1]):
353
+ # NFD text: the letter before ´ carries combining marks of its own (``Mari\u0301´a``); judge those marks as below
354
+ base_at = start
355
+ while base_at and unicodedata.combining(current[base_at - 1]):
356
+ base_at -= 1
357
+ if base_at and set(current[base_at:start]) & _ACUTE_AFTER_MARKS and (nxt in "aeiou" or nxt in "cnsz"):
358
+ out = _compose(nxt, combining)
359
+ if out is not None:
360
+ return out
361
+ return match.group(0)
290
362
  if mark in _APOSTROPHE_LIKE_MARKS and prev and nxt:
291
- return match.group(0) # mid-word ´ and ` are apostrophe variants (``Cui´e``), not accents
292
- if mark == combining and prev:
293
- # a combining mark right after a letter is already attached (Turkish ``i̇`` has no
294
- # precomposed form); only spacing marks and marks left after a space are detached
363
+ # a mid-word ´ is an acute or an apostrophe (José, Maz'ya, Ken'ichi, Ćosić), so it is left as written, except
364
+ # right after a letter that already carries a mark, where it is the next vowel's acute (``Dvoř´ak``, ``Sagü´es``)
365
+ vowel_next = nxt in "aeiou" or (all_caps and nxt in "AEIOU")
366
+ prev_marks = set(unicodedata.normalize("NFD", prev)[1:])
367
+ # a letter takes one accent, so after a marked vowel the acute is the consonant's (``Szczȩ´sniak``, ``ˇS´CETA``)
368
+ consonant_next = nxt in "cnsz" or (all_caps and nxt in "CNSZ")
369
+ if prev_marks & _ACUTE_AFTER_MARKS and (vowel_next or consonant_next):
370
+ out = _compose(nxt, combining)
371
+ if out is not None:
372
+ return prev + out
373
+ return match.group(0)
374
+ prev_base = _base(prev).lower()
375
+ polish_ending = current.lower().endswith(("ien\u00b4", "yn\u00b4")) # Bień, Kwiecień, Horyń
376
+ # a bare w is too weak a sign here (``Brown´``, ``Owen´``)
377
+ polish_letter = (prev_base in "nsz" and strong_polish_word) or (prev_base == "n" and polish_ending)
378
+ czech_y = prev_base == "y" and czech_word
379
+ if mark == "\u00b4" and not nxt and prev_base not in "aeiouc" and not polish_letter and not czech_y:
380
+ # a word-final ´ is an accent only on a vowel or c (``Jose´``, ``Ružic´``), on y in a Czech or Slovak word
381
+ # (``Sechovsky´``), or on n/s/z in a Polish word (``Grzes´``); otherwise it is an elision, a soft sign or stray
382
+ # left as written (``Dell´``, ``Igor´``, ``Vasyl´``, ``Fernandes´``, ``Nancy´``, ``Istvan´``)
383
+ return match.group(0)
384
+ after_next = current[match.end() : match.end() + 1]
385
+ polish_s_cluster = nxt in "sS" and after_next in "wlrcmnpWLRCMNP" # Św Śl Śr Śc (``´Swia¸tek``, ``´Sliwa``)
386
+ if mark == "\u00b4" and not prev and nxt and not (
387
+ nxt in "aeiouAEIOU" or (nxt in "cnszCNSZ" and polish_word) or polish_s_cluster
388
+ ):
389
+ # a word-initial ´ goes on a vowel, on ś before a consonant, or on ć ń ś ź in a Polish word; before any other
390
+ # consonant it is stray (``´Pedraza``, ``´Castro``, ``´Silva``)
391
+ return match.group(0)
392
+ if mark == combining and start and current[start - 1] not in "-\u2010":
393
+ # a combining mark after any other mark (``Mu\u1dc4\u0301ller``) or after punctuation (``O.\u0301scar``) is not a
394
+ # detached accent we can place; only one at a word start or after a hyphen is
295
395
  return match.group(0)
296
396
  if combining == "\u030c":
297
397
  return _attach_caron(prev, nxt, mark_before_letter=caron_before > 0) or _fail(match)
298
- vowel_next = nxt.lower() in "aeiouy" and prev.lower() not in "aeiouy"
299
- order = ((nxt, True), (prev, False)) if vowel_next or not prev else ((prev, False), (nxt, True))
398
+ # a tilde next to n is the Spanish ñ on either side (``Ya˜nez`` → ``Yañez``, ``Mun˜oz`` → ``Muñoz``): of the
399
+ # corpus's 1,795 such mentions only ``N˜ao-Linear`` (not a name) wanted ã; Portuguese ã/õ sit between vowels
400
+ tilde = combining == "\u0303"
401
+ after = current[match.end() : match.end() + 1].lower()
402
+ dot = combining == "\u0307"
403
+ # next to a lowercase i, a z or e on the other side takes the dot (``Gi˙zewska``); a capital I is always İ (``I˙zzet``)
404
+ dot_base_other = ((nxt and nxt in "zeZE") or (prev and prev in "zeZE")) and polish_word # Turkish Fi˙li˙z keeps i's dot
405
+ capital_i = prev == "I" or nxt == "I"
406
+ if dot and ((prev and prev in "iI") or (nxt and nxt in "iI")) and (capital_i or not dot_base_other):
407
+ # a dot next to i is the i's own dot: dropped on a lowercase i (``Meli˙ha``), İ on a capital (``I˙nci``)
408
+ if prev and prev in "iI":
409
+ return ("\u0130" if prev == "I" else prev) + nxt
410
+ return prev + ("\u0130" if nxt == "I" else nxt)
411
+ g_before = prev and prev in "gG" and match.start("prev") > 0 # Turkish words never start with ğ (``G˘ain˘a``)
412
+ g_after = nxt and nxt in "gG" and prev and prev.lower() in "aeiou"
413
+ romanian = romanian_word # ă before g in Drăgan, Călugăreanu
414
+ if combining == "\u0306" and not prev and nxt and nxt in "gG":
415
+ failed = True # a breve before a word-initial g is not ğ (Turkish words never start with ğ)
416
+ return match.group(0)
417
+ if combining == "\u0306" and (g_after or g_before) and not romanian:
418
+ # a breve next to g is the Turkish ğ (``Do˘gan``, ``Ça˘glar``: 343 corpus mentions, none on the vowel)
419
+ out = _compose(nxt if nxt in "gG" else prev, combining)
420
+ if out is not None:
421
+ return prev + out if nxt in "gG" else out + nxt
422
+ if tilde and prev and prev in "oO" and nxt and nxt in "nN" and after in ("u", "i"):
423
+ out = _compose(prev, combining) # Estonian õ before n (``To˜nu`` → ``Tõnu``), not Spanish ñ
424
+ if out is not None:
425
+ return out + nxt
426
+ portuguese = ("ao", "ae", "oe")
427
+ if tilde and nxt and (nxt + after).lower() in portuguese and (prev + nxt).lower() not in portuguese:
428
+ order = ((nxt, True), (prev, False)) # the tilde opens an ão/ãe/õe diphthong (``Jo˜ao`` → ``João``)
429
+ elif tilde and prev and nxt and prev in "nN" and nxt.lower() in "aeiou":
430
+ order = ((prev, False), (nxt, True))
431
+ elif tilde and prev and nxt and nxt in "nN" and prev.lower() in "aeiou":
432
+ order = ((nxt, True), (prev, False))
433
+ else:
434
+ vowel_next = nxt.lower() in "aeiouy" and prev.lower() not in "aeiouy"
435
+ order = ((nxt, True), (prev, False)) if vowel_next or not prev else ((prev, False), (nxt, True))
436
+ next_is_accented = match.end() < len(current) and "\u0300" <= current[match.end()] <= "\u036f"
437
+ if dot:
438
+ # names take a dot above only on ż ė (``Z˙ylicz`` → ``Żylicz``); ċ ġ are rare, and a dot by c or g is more often a
439
+ # misread dot below (``Ngo˙c`` is Ngọc), so it is left
440
+ order = tuple((base, is_next) for base, is_next in order if base and base in "zeZE")
441
+ elif combining == "\u0327":
442
+ if prev and prev in "aeAE" and polish_word:
443
+ # in a Polish word a cedilla after a or e is a misread ogonek (``Wie¸cek`` → ``Więcek``, ``Wa¸s`` → ``Wąs``)
444
+ out = _compose(prev, "\u0328")
445
+ if out is not None:
446
+ return out + nxt
447
+ # otherwise it is ç ş ţ far more often than ȩ or a Latvian ņ (``Güne¸s`` → ``Güneş``, ``Du¨zgu¨n¸cınar``)
448
+ order = tuple(sorted(order, key=lambda o: o[0] not in "cstCST"))
449
+ elif combining == "\u0328" and not prev:
450
+ failed = True # no Polish word starts with ą or ę (``B | ˛aczkowska`` lost its B to another field)
451
+ return match.group(0)
452
+ elif combining == "\u0328":
453
+ # an ogonek goes only on a or e, the Polish ą ę (``Pi˛ekos`` → ``Piękos``); with neither neighbour the word is
454
+ # left as it was rather than composing ǫ į ų onto a misread cedilla (``Franc˛ois``)
455
+ polish = polish_word # before its vowel only in a Polish word (``S˛ahin`` is Şahin)
456
+ order = tuple(
457
+ (b, n) for b, n in sorted(order, key=lambda o: not o[1]) if b and b in "aeAE" and ((not n and nxt) or polish)
458
+ ) # after its vowel at a word end also only in a Polish word (``SUKHORUKOVA˛``)
300
459
  for base, is_next in order:
460
+ if is_next and next_is_accented:
461
+ continue # a letter that already carries a combining mark takes no second one (``Oz˙óg`` → ``Ożóg``)
301
462
  out = _compose(base, combining)
302
463
  if out is not None:
303
464
  return prev + out if is_next else out + nxt
304
465
  failed = True
305
466
  return match.group(0)
306
467
 
307
- repaired = _TOKEN_MARK_RE.sub(fix, token)
308
- return token if failed else repaired
468
+ # one mark at a time on the text repaired so far, so a letter between two marks is seen by both
469
+ # (``Conceic¸a˜o`` → ``Conceição``; a single substitution pass handed the a to the cedilla match and put the tilde on o)
470
+ pos = 0
471
+ while (match := _TOKEN_MARK_RE.search(current, pos)) is not None:
472
+ replacement = fix(match)
473
+ if failed:
474
+ return original
475
+ nxt = match.group("next") or ""
476
+ if replacement == match.group(0):
477
+ pos = match.end() - len(nxt)
478
+ continue
479
+ current = current[: match.start()] + replacement + current[match.end() :]
480
+ pos = match.start() + max(len(replacement) - 1, 0)
481
+ return current
309
482
 
310
483
 
311
484
  def strip_soft_hyphens(text: str) -> str:
@@ -327,12 +500,16 @@ def attach_detached_diacritics(text: str) -> str:
327
500
  composes with, the vowel first (``¨ovel`` → ``övel``, ``Jose´`` → ``José``); a bare
328
501
  combining mark after a space is the NFKC rendering of such a mark and joins the next
329
502
  token. A token with a mark that composes with nothing is left exactly as it was
330
- (``S˘c˘epin``), and mid-word ``´``/`` ` `` stay apostrophe variants.
503
+ (``S˘c˘epin``). A combining mark after a letter or another mark is ordinary NFD text and is never moved.
331
504
  """
332
- if not _ANY_DETACHED_MARK_RE.search(text):
505
+ # invisible markup between a letter and its accent would make the accent look detached (``Iba\u0301n\u200e\u0303ez``);
506
+ # only that markup is removed here, so names without a detached-looking mark are untouched
507
+ text = _MARKUP_BEFORE_MARK_RE.sub("", text)
508
+ if not _ANY_DETACHED_MARK_RE.search(text) and "^" not in text:
333
509
  return text
334
510
  # a combining mark after a space is the NFKC remnant of a spacing mark: restore the spacing form so the
335
- # token repair may move it to the letter it composes with (an attached combining mark is never moved)
511
+ # token repair may move it to the letter it composes with (an attached combining mark is never moved); between
512
+ # spaces it stays a spacing mark (``O ́ connor``), which later reads as an apostrophe
336
513
  text = re.sub("(?<=[^\\W\\d_]) ([\\u0300-\\u036f])", lambda m: " " + _COMBINING_TO_SPACING.get(m.group(1), m.group(1)), text)
337
514
  text = re.sub("(?<=\\s)([\\u0300-\\u036f])(?=[^\\W\\d_])", lambda m: _COMBINING_TO_SPACING.get(m.group(1), m.group(1)), text)
338
515
  parts = re.split(r"(\s+)", text)