Datasets:
Add cognate pairs v2 (21.5M pairs) + Phase 8 audit fixes
Browse filesFiles changed (41)
- .gitattributes+2
- data/training/cognate_pairs/cognate_pairs_borrowing.tsvAdded+3
- data/training/cognate_pairs/cognate_pairs_inherited.tsvAdded+3
- data/training/cognate_pairs/cognate_pairs_similarity.tsvAdded+3
- data/training/lexicons/aav-pro.tsv+2-2
- data/training/lexicons/ang.tsv+2-2
- data/training/lexicons/cel-pro.tsv+2-2
- data/training/lexicons/cop.tsv+2-2
- data/training/lexicons/gem-pro.tsv+2-2
- data/training/lexicons/hbo.tsv+2-2
- data/training/lexicons/ira-pro.tsv+2-2
- data/training/lexicons/itc-pro.tsv+2-2
- data/training/lexicons/nci.tsv+2-2
- data/training/lexicons/ojp.tsv+2-2
- data/training/lexicons/osc.tsv+2-2
- data/training/lexicons/pal.tsv+2-2
- data/training/lexicons/poz-oce-pro.tsv+2-2
- data/training/lexicons/poz-pol-pro.tsv+2-2
- data/training/lexicons/sga.tsv+2-2
- data/training/lexicons/sit-pro.tsv+2-2
- data/training/lexicons/sla-pro.tsv+2-2
- data/training/lexicons/tai-pro.tsv+2-2
- data/training/lexicons/trk-pro.tsv+2-2
- data/training/lexicons/xce.tsv+2-2
- data/training/lexicons/xfa.tsv+2-2
- data/training/lexicons/xlp.tsv+2-2
- data/training/lexicons/xmr.tsv+2-2
- data/training/lexicons/xsa.tsv+2-2
- data/training/lexicons/xtg.tsv+2-2
- data/training/lexicons/xto-pro.tsv+2-2
- data/training/lexicons/xum.tsv+2-2
- docs/DATABASE_REFERENCE.md+24
- docs/prd/PRD_COGNATE_PAIRS_V2.mdAdded+291
- scripts/cleanup_phase8_audit.pyAdded+308
- scripts/extract_abvd_cognates_v2.pyAdded+183
- scripts/extract_iecor_cognates.pyAdded+178
- scripts/extract_sinotibetan_cognates_v2.pyAdded+163
- scripts/extract_wold_borrowings_v2.pyAdded+203
- scripts/merge_cognate_pairs.pyAdded+179
- scripts/rebuild_concept_aligned_pairs.pyAdded+178
- scripts/transliteration_maps.py+39-31
57 unmodified lines58596061626357 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -text*.tsv filter=lfs diff=lfs merge=lfs -text*.csv filter=lfs diff=lfs merge=lfs -text*.pdf filter=lfs diff=lfs merge=lfs -text57 unmodified lines585960616263646557 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -textdata/training/cognate_pairs/cognate_pairs_inherited.tsv filter=lfs diff=lfs merge=lfs -textdata/training/cognate_pairs/cognate_pairs_similarity.tsv filter=lfs diff=lfs merge=lfs -text*.tsv filter=lfs diff=lfs merge=lfs -text*.csv filter=lfs diff=lfs merge=lfs -text*.pdf filter=lfs diff=lfs merge=lfs -text
123version https://git-lfs.github.com/spec/v1oid sha256:9f47de196443c307429b5e50fff4fb1888779bed16f7ba8999f8973dd607921bsize 1888180123version https://git-lfs.github.com/spec/v1oid sha256:4432cb8691157d20a8f4cc1d12d78af17004231026a9eca727098e16219dd41dsize 2019878325123version https://git-lfs.github.com/spec/v1oid sha256:7e7e7d4afb94c19667282056348d1a16c68ccb3294eab41029a48c5e064beefbsize 25518124123version https://git-lfs.github.com/spec/v1oid sha256:e79666cda701eb7cacdeed5dabd6a42efee4b3f166370098ae9dadbdd64c4531size 7221123version https://git-lfs.github.com/spec/v1oid sha256:0183686f45a4fd760834f12dc9aa43192d5097b4fca9c387155825e0e817c768size 7225
123version https://git-lfs.github.com/spec/v1oid sha256:97148a592a22d23447219bafbaf162a2a6dfdfa9be5e62fd8de2a79501436e87size 1380125123version https://git-lfs.github.com/spec/v1oid sha256:24aea81defe7da1e95dbe91c7bcea36778e93e937a6a200c69d9dcf42de270fdsize 1347242
123version https://git-lfs.github.com/spec/v1oid sha256:edb8dccc90cd4fca4240c2d9b633a157e0d2e286dfda77c38bcbddf9d445caafsize 69341123version https://git-lfs.github.com/spec/v1oid sha256:37fc46930c151952b98d02f130ca67c0a0efadb2529d48d4fcc582cae0f4d20dsize 69658
123version https://git-lfs.github.com/spec/v1oid sha256:4e21fd347ad46ae447d2fa035be6b16bb5ee3909686db37ad7f4d31da8b6546dsize 612872123version https://git-lfs.github.com/spec/v1oid sha256:2aaf7d44578d0a7ed1f6434422d2126bbbbc4aa33dccc4955c0a75a38275d278size 612142
123version https://git-lfs.github.com/spec/v1oid sha256:f4e072d2c7c801551aea6ecbc7ff3990d890a123929d39c7da0810de65b5722asize 247613123version https://git-lfs.github.com/spec/v1oid sha256:618759789e58e4516f3ffdd201960f30c1798492c4dfb9b4ce5ce1495f85373fsize 248589
123version https://git-lfs.github.com/spec/v1oid sha256:8b61db4b0beca87cf5295dfd6b2886335cf01fd020f2ff22c80f7ac82e6ce2ffsize 557976123version https://git-lfs.github.com/spec/v1oid sha256:2c2464bda766fad8da6788f89044315404a2bd4ccd1eb093f6972a6a270d320fsize 557968
123version https://git-lfs.github.com/spec/v1oid sha256:f13c6f351a44148c6756b475dba2ad57bbe51cd22abe5d827aaf473d3f8c175csize 16964123version https://git-lfs.github.com/spec/v1oid sha256:b1d76a8f660d047ec6a29544ddaa222fe1afd959e14c598b868963f1a889454asize 17007
123version https://git-lfs.github.com/spec/v1oid sha256:d261a9c43d834be998cb15ebaba0b5d5dcfb2bad7399c8fc7e77bf1bffb16573size 31068123version https://git-lfs.github.com/spec/v1oid sha256:7e68d7a535b188e78646aa8b8f5982dcd0b84ae941143f102dd870da48266528size 31141
123version https://git-lfs.github.com/spec/v1oid sha256:6d9653460ed3fe2dc15a8b845828ab15f3bb024473cba810f2a5a46a14965b98size 207573123version https://git-lfs.github.com/spec/v1oid sha256:fd92cae9e79cd9e724b8171eee1f68a41e5fcdbef07395a7dadd888b1ef8100csize 206000
123version https://git-lfs.github.com/spec/v1oid sha256:fc09525f1db3c46b6b7a06e2d7e5f32a8716032e0425127ea63ec62eb7cd27e1size 186624123version https://git-lfs.github.com/spec/v1oid sha256:015f54211d32d2c29137d4cf8f840c0addef1ddd79bf1f40a258a1c90deaec8esize 187200
123version https://git-lfs.github.com/spec/v1oid sha256:1e2dabe2edd32d53ae87518f265c4d3b200596dd3e04c2cbb87201f1e7200e95size 75402123version https://git-lfs.github.com/spec/v1oid sha256:0cffe0f5c279f10c6b2b702d7efaacf11ec9aad2dd77c47c691ad6fdba606512size 74946
123version https://git-lfs.github.com/spec/v1oid sha256:cb7237468dbb09443f993b90f8428226150ab8747aac22d338f5ed7062ecad50size 11959123version https://git-lfs.github.com/spec/v1oid sha256:da0b4a16657bd24da4e0669b4d99e9dde764405d0bd351e557586225ee2db99esize 11971
123version https://git-lfs.github.com/spec/v1oid sha256:cc107d7ac5cb3a1b86e4708bcaae85e68cb8b351fa0105fc997906db496f93absize 4462123version https://git-lfs.github.com/spec/v1oid sha256:a568728b9955c8e6ff34631cb56569300910042f2c0d955d0b9b9844d8eda423size 4490
123version https://git-lfs.github.com/spec/v1oid sha256:02312e2e280f98f3c1310d729cd36ddb772daa209a56cbed7e620778c0af081esize 5655123version https://git-lfs.github.com/spec/v1oid sha256:4315e3550bd8e02fbe289a5e53b80b5c792850011b2f2fe24531ac6b4c1a0139size 5685
123version https://git-lfs.github.com/spec/v1oid sha256:acf7b4bb75992066e0f8853300ea83df8b940f8b37541b7f79b2ac3b552ee357size 1501984123version https://git-lfs.github.com/spec/v1oid sha256:3bacf812064829ac762fdce41061ace3c5665cec672def5e56762659c9a8db7csize 1499335
123version https://git-lfs.github.com/spec/v1oid sha256:12bd35e6fb1bdea808cb741f50c53e9cbf82b6440f8fb2f110877af0ab84b012size 13739123version https://git-lfs.github.com/spec/v1oid sha256:c5ecd86233850196585795dc676927574777432254944972f45ff2a2d3194525size 13750
123version https://git-lfs.github.com/spec/v1oid sha256:d1908678551d9fb10053004ce7a91a04d76a7c7f4f2dec03ff5b02a52fd534f7size 220064123version https://git-lfs.github.com/spec/v1oid sha256:49f555de71ae5d3d3d9fda732c79e0c65998256011d1651f1960932918f603ecsize 220655
123version https://git-lfs.github.com/spec/v1oid sha256:a11ac8b7d9287870b00a2455c2620c1fdf3b4d2f34d4841af2bcce2a08ec7df2size 5849123version https://git-lfs.github.com/spec/v1oid sha256:49635a6e5cd28495e8fc0223891d09d9c9fd51efa5d3725220bf18deda0223c6size 5850
123version https://git-lfs.github.com/spec/v1oid sha256:49fe64e6da2e399c85b29255c124836215099d18863357eddb12cd2be82b176csize 39499123version https://git-lfs.github.com/spec/v1oid sha256:9dd4535f040da56a777f0f31eb607b4b3844a1da05007303f3a07bfa6b7a055csize 39695
123version https://git-lfs.github.com/spec/v1oid sha256:6c341342ebb3dfa3293e109a91221252b3087b510b34b859b75b5b2d13ef589asize 497123version https://git-lfs.github.com/spec/v1oid sha256:78d326778d7252edc1524ccd22d166dd33833f46a77e48c84e44ff5738033882size 499
123version https://git-lfs.github.com/spec/v1oid sha256:17ad979a03bce750cb6fdc11931aa4eb8b594601e9e6afa485bd6d81a49e0d4bsize 17401123version https://git-lfs.github.com/spec/v1oid sha256:b2289515ad93356d0d0b98ded57141265ec686f8a9b90b501488f023b0459a18size 17403
123version https://git-lfs.github.com/spec/v1oid sha256:f5df739a8ea99c7f596df81c611470f7c5d17b3146b9d683753853ee950a1a0csize 14942123version https://git-lfs.github.com/spec/v1oid sha256:2f1feba4f6dbafa723c9369366a727949f8777e2983be9191b53380da7298d55size 14969
123version https://git-lfs.github.com/spec/v1oid sha256:f4c7f024775825b84326561eb9807d5860914977efcdaea91b85a6410c1293f1size 98939123version https://git-lfs.github.com/spec/v1oid sha256:b8d99c662c6ff07581b94399a72a17b20252cbd946605c270f438143adf21684size 98791
123version https://git-lfs.github.com/spec/v1oid sha256:a98e9845399f78284581435401155e20020233e3fcdf05e72e1f22780c2c89bdsize 4935123version https://git-lfs.github.com/spec/v1oid sha256:bffb6bc1e97bf8bdc27728790933b6489abb0a6f76432e4f50d4f32675c350d5size 4939
123version https://git-lfs.github.com/spec/v1oid sha256:ff1215f061de476ef0d0a7fc67047179a88a6257d2cc5a21604677d9dac286d0size 9388123version https://git-lfs.github.com/spec/v1oid sha256:4134dce231390baee8439c93c0c94f5805e105d415e1e0fa06f6b9903b77ab19size 9436
123version https://git-lfs.github.com/spec/v1oid sha256:b4fc7376fb22ee052059363f36bdf934e670d5794b5fa9c6018e259e5f17be03size 5721123version https://git-lfs.github.com/spec/v1oid sha256:e8554c6e4650cecb255167ad355a8d10412c9d258ac7cec968b2906a8b0ddd7bsize 5749
123version https://git-lfs.github.com/spec/v1oid sha256:3e8fd6d438f641afbdefd4ec727d1e1e97701f99d2a3bec3729250b19c6d7bb5size 60372123version https://git-lfs.github.com/spec/v1oid sha256:090b81cd2b546bcf94d55cfd04dad42d3840d92320717757ab40853509b53f60size 60237
124 unmodified lines125126127128129130124 unmodified lines- 3,466,000+ total lexical entries- 170,756 ancient language entries (68 languages)- 3,296,156 modern language entries (1,113 languages)---124 unmodified lines125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154124 unmodified lines- 3,466,000+ total lexical entries- 170,756 ancient language entries (68 languages)- 3,296,156 modern language entries (1,113 languages)- 21,547,916 cognate/borrowing/similarity pairs### Cognate Pairs (v2)Three TSV files in `data/training/cognate_pairs/`, 14-column schema:```Lang_A Word_A IPA_A Lang_B Word_B IPA_B Concept_ID Relationship Score Source Relation_Detail Donor_Language Confidence Source_Record_ID```| File | Rows | Description ||------|------|-------------|| `cognate_pairs_inherited.tsv` | 21,298,208 | Expert-classified cognates + concept-aligned pairs (score ≥ 0.5) || `cognate_pairs_borrowing.tsv` | 17,924 | Verified donor→recipient borrowings from WOLD BorrowingTable || `cognate_pairs_similarity.tsv` | 231,784 | Phonetically similar pairs (0.3 ≤ score < 0.5), no overlap with inherited |**Sources:**- ABVD CognateTable (21.6M expert cognate pairs, 1,682 Austronesian languages)- IE-CoR CognateTable (412K Indo-European cognate pairs)- Sino-Tibetan CognateTable (4.2K pairs, borrowings filtered)- WOLD BorrowingTable (17.9K verified donor-recipient pairs)- Internal concept-aligned pairs (233K) + similarity pairs (254K)**Deduplication:** Priority ordering expert_cognate > borrowing > concept_aligned > similarity_only. Cross-file dedup ensures no language-concept combo appears in both inherited and similarity files. See `docs/prd/PRD_COGNATE_PAIRS_V2.md` for full specification.---
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291# PRD: Cognate Pairs Dataset v2 — Reconstruction from Verified Sources
**Status:** Draft
**Date:** 2026-03-13
**Priority:** P0 — Cognate pairs are used for validation testing; any hallucinated data invalidates model evaluation.
---
## 1. Problem Statement
Deep adversarial audit of the cognate pairs dataset (`data/training/cognate_pairs/`) has identified **6 critical bugs** in the generation pipeline (`scripts/assign_cognate_links.py` and `scripts/expand_cldf_full.py`). Multiple bugs fabricate or mislabel cognate relationships, making the dataset unsuitable for validation. This PRD specifies the complete reconstruction of the cognate pairs from verified scholarly sources.
### 1.1 Current State
| File | Rows | Size |
|------|------|------|
| `cognate_pairs_inherited.tsv` | 18,257,301 | 1.18 GB |
| `cognate_pairs_borrowing.tsv` | 116,757 | 8.0 MB |
| `cognate_pairs_similarity.tsv` | 170,064 | 16.2 MB |
Current 10-column schema:
```
Lang_A Word_A IPA_A Lang_B Word_B IPA_B Concept_ID Relationship Score Source
```
### 1.2 Bugs Found
#### Bug 1: ABVD `cognates.csv` Never Read (CRITICAL)
**Location:** `expand_cldf_full.py` lines 200-266
**Impact:** All ABVD cognate data comes from `forms.csv` `Cognacy` column instead of the authoritative `cognates.csv` CognateTable (291,675 expert entries). The `Doubt` column (`true`/`false`) in `cognates.csv` is never consulted — disputed cognate assignments are treated as certain.
#### Bug 2: ABVD Multi-Set Cognacy Truncation
**Location:** `expand_cldf_full.py` line 257: `cog_num = cognacy.split(",")[0].strip()`
**Impact:** Forms belonging to multiple cognate sets (e.g., `"1,64"`) lose all secondary memberships. Estimated 37,587 cognate set memberships silently discarded.
#### Bug 3: WOLD Borrowing Pairs Fabricated (CRITICAL)
**Location:** `assign_cognate_links.py` lines 185-255 (`_extract_borrowings_from_forms`)
**Impact:** The script reads `forms.csv` `Borrowed` column and pairs any two forms from different languages that share a concept AND have SCA similarity >= 0.3, labeling them `"borrowing"`. This fabricates borrowing relationships. The authoritative `borrowings.csv` BorrowingTable (21,624 explicit donor-recipient events with `Target_Form_ID`, `Source_Form_ID`, `Source_languoid`, `Source_certain` fields) is **COMPLETELY UNUSED**.
Example: A Turkish word and an Arabic word for the same concept are paired as a "borrowing" even if no actual borrowing relationship exists between them.
#### Bug 4: Concept-Aligned Pairs Mislabeled as Inherited
**Location:** `assign_cognate_links.py` lines 154, 160
**Impact:** 488,900+ algorithmically-generated concept-aligned pairs (SCA similarity >= 0.5) are written to `cognate_pairs_inherited.tsv` with Relationship = `cognate_inherited`, making them indistinguishable from expert cognates to downstream consumers.
#### Bug 5: Sino-Tibetan Word Field is Concept String
**Location:** `expand_cldf_full.py` line 319
**Impact:** For all Sino-Tibetan entries, `Word == Concept_ID` (e.g., `"above"`, `"all"`) instead of the actual lexical form. The IPA column contains the real phonetic data, but Word is a meaningless concept gloss.
#### Bug 6: 50-Entry Hard Truncation (File-Sort Bias)
**Location:** `assign_cognate_links.py` line 142: `members_sample = members[:50]`
**Impact:** For large families (Austronesian: hundreds of languages), only the first 50 entries in alphabetical ISO order are used. Languages late in the alphabet are systematically excluded.
---
## 2. Design: Reconstructed Pipeline
### 2.1 Iron Law Compliance
> All data enters the dataset through code that reads from external scholarly sources. No hardcoded lexical or cognate data. No AI-generated entries.
Every extraction script:
- Reads from CLDF/TSV source files cloned to `sources/`
- Parses, transforms, writes to `staging/cognate_pairs/`
- Writes `Source_Record_ID` for full provenance traceability
### 2.2 Extended Schema (14 Columns)
```
Lang_A Word_A IPA_A Lang_B Word_B IPA_B Concept_ID Relationship Score Source Relation_Detail Donor_Language Confidence Source_Record_ID
```
| Column | Type | Description |
|--------|------|-------------|
| `Lang_A` | str | ISO 639-3 code of language A |
| `Word_A` | str | Orthographic/transliteration form in language A |
| `IPA_A` | str | IPA transcription of Word_A |
| `Lang_B` | str | ISO 639-3 code of language B |
| `Word_B` | str | Orthographic/transliteration form in language B |
| `IPA_B` | str | IPA transcription of Word_B |
| `Concept_ID` | str | Concepticon gloss or equivalent concept identifier |
| `Relationship` | str | One of: `expert_cognate`, `borrowing`, `concept_aligned`, `similarity_only` |
| `Score` | float | SCA-based similarity score (0.0-1.0), rounded to 4 decimal places |
| `Source` | str | Source database identifier (e.g., `abvd`, `wold`, `iecor`, `sinotibetan`, `acd`) |
| `Relation_Detail` | str | Populated ONLY when source provides: `inherited`, `borrowed`, or `-` |
| `Donor_Language` | str | For borrowings only: source language from WOLD `Source_languoid`. `-` otherwise |
| `Confidence` | str | Source-provided certainty: `certain`/`doubtful` (ABVD), `1`-`5` (WOLD), `-` otherwise |
| `Source_Record_ID` | str | Traceable ID: ABVD cognateset ID, WOLD borrowing ID, IE-CoR cognateset ID, etc. |
**Design decisions:**
- No mother-daughter / sister-sister typing — NO source provides this at the pair level.
- `Relation_Detail`, `Donor_Language`, `Confidence` are `-` when source doesn't provide them. We never fabricate metadata.
- `Relationship` is script-assigned based on extraction method. `Relation_Detail` is source-provided.
### 2.3 Source Inventory
| Source | Repository | Cognate Data | Status |
|--------|------------|-------------|--------|
| ABVD | `sources/abvd/` | `cognates.csv` CognateTable (291,675 entries, 19,356 sets) | Cloned, **unused by current code** |
| WOLD | `sources/wold/` | `borrowings.csv` BorrowingTable (21,624 events) | Cloned, **unused by current code** |
| Sino-Tibetan | `sources/sinotibetan/` | `sinotibetan_dump.tsv` (6,159 entries with COGID) | Cloned, partially used |
| IE-CoR | `sources/iecor/` | `cognates.csv` CognateTable (Indo-European cognates) | **NOT CLONED — must clone** |
| ACD | `sources/acd/` | Cached Austronesian data | Partially cached |
| Internal lexicons | `data/training/lexicons/` | SCA similarity scoring | N/A |
### 2.4 Output Files
Same 3-file split, but with corrected labels:
- `cognate_pairs_inherited.tsv` — Expert cognates ONLY (ABVD CognateTable, IE-CoR CognateTable, Sino-Tibetan COGID, ACD)
- `cognate_pairs_borrowing.tsv` — Verified borrowings ONLY (WOLD BorrowingTable with explicit donor-recipient pairs)
- `cognate_pairs_similarity.tsv` — Concept-aligned pairs (algorithmically generated, clearly labeled)
---
## 3. Implementation Plan
### Phase 1: Source Preparation
**Step 1.1** — Clone IE-CoR:
```bash
cd sources/
git clone https://github.com/lexibank/iecor.git
```
**Step 1.2** — Verify all CLDF source files exist:
- `sources/abvd/cldf/cognates.csv` (291,675 rows)
- `sources/abvd/cldf/forms.csv`
- `sources/abvd/cldf/languages.csv`
- `sources/wold/cldf/borrowings.csv` (21,624 rows)
- `sources/wold/cldf/forms.csv`
- `sources/wold/cldf/languages.csv`
- `sources/sinotibetan/sinotibetan_dump.tsv` (6,159 rows)
- `sources/iecor/cldf/cognates.csv` (NEW)
- `sources/iecor/cldf/forms.csv` (NEW)
### Phase 2: Extraction Scripts
Each script follows the same pattern:
1. Read source CLDF files
2. Parse and validate
3. Generate pairwise cognate entries
4. Write to `staging/cognate_pairs/{source}_pairs.tsv` with 14-column schema
5. Print statistics and provenance summary
#### Script 1: `scripts/extract_abvd_cognates_v2.py`
**Source:** `sources/abvd/cldf/cognates.csv` + `forms.csv` + `languages.csv`
**Key fixes:**
- Read `cognates.csv` directly (has `Form_ID`, `Cognateset_ID`, `Doubt`)
- Join to `forms.csv` on `Form_ID` for orthographic form and IPA
- Handle multi-set membership: one form can appear in multiple cognate sets
- Use `Doubt` column for Confidence: `Doubt=false` → `certain`, `Doubt=true` → `doubtful`
- `Source_Record_ID` = `Cognateset_ID` from `cognates.csv`
- Generate cross-language pairs within each cognate set
- SCA similarity score computed on the fly
#### Script 2: `scripts/extract_wold_borrowings_v2.py`
**Source:** `sources/wold/cldf/borrowings.csv` + `forms.csv` + `languages.csv`
**Key fixes:**
- Read `borrowings.csv` BorrowingTable for actual donor-recipient pairs
- Join `Target_Form_ID` and `Source_Form_ID` to `forms.csv` for word/IPA
- Extract `Source_languoid` as `Donor_Language`
- Extract `Source_certain` for Confidence
- `Source_Record_ID` = borrowing `ID` from `borrowings.csv`
- Each row produces exactly ONE pair (not fabricated from concept co-occurrence)
#### Script 3: `scripts/extract_sinotibetan_cognates_v2.py`
**Source:** `sources/sinotibetan/sinotibetan_dump.tsv`
**Key fixes:**
- Filter out rows where `BORROWING` column is non-empty
- Use `IPA` column for IPA_A/IPA_B (correct)
- Use `CONCEPT` column for Concept_ID
- Use actual IPA form as Word (not concept gloss) — or use `-` and note that Word is not available
- `Source_Record_ID` = `st_{COGID}`
#### Script 4: `scripts/extract_iecor_cognates.py` (NEW)
**Source:** `sources/iecor/cldf/cognates.csv` + `forms.csv`
**Implementation:**
- Read IE-CoR CognateTable (standard CLDF format)
- Join `Form_ID` to `forms.csv` for word/IPA/language
- Generate cross-language pairs within each cognate set
- `Source_Record_ID` = IE-CoR `Cognateset_ID`
#### Script 5: `scripts/extract_acd_cognates.py` (NEW)
**Source:** `sources/acd/` cached data
**Implementation:**
- Parse ACD (Austronesian Comparative Dictionary) cached HTML/data
- Extract cognate sets with etymon-level grouping
- If ACD data is insufficiently structured, mark as P2 and skip
#### Script 6: `scripts/rebuild_concept_aligned_pairs.py`
**Source:** `data/training/lexicons/*.tsv` + `data/training/family_map.json`
**Key fixes:**
- Label as `concept_aligned` (NOT `cognate_inherited`)
- Random sampling instead of file-sort truncation for groups > 50
- Score threshold: >= 0.5 → `concept_aligned`, 0.3-0.49 → `similarity_only`
- `Source_Record_ID` = `-` (no source record, algorithmically generated)
- `Confidence` = `-` (not from an expert source)
#### Script 7: `scripts/merge_cognate_pairs.py`
**Merges all staging files into final output:**
- Deduplicates: if pair (A,B,concept) appears in both expert and concept-aligned, keep expert
- Priority: expert > borrowing > concept_aligned > similarity
- Writes 3 output files with 14-column schema
- Prints final statistics
### Phase 3: Adversarial Audit Protocol
For EACH extraction script, deploy a two-team audit:
**Team A (Extraction):**
- Runs the script
- Produces staging output
- Reports entry counts and statistics
**Team B (Adversarial Auditor):**
- Samples 20 random output rows
- For each row, traces Source_Record_ID back to source CSV
- Verifies Form_ID, Cognateset_ID, Language_ID all exist in source
- Verifies IPA matches source data
- Checks for entries in output that have no source backing
- Checks for duplicate pairs, empty fields, malformed data
- **VETO** power: if any entry cannot be traced, the entire script output is rejected
**End-to-end cross-validation (after merge):**
- Sample 50 random pairs from each output file (150 total)
- Full provenance trace: output → staging → source CSV → published database
- Verify no concept-aligned pairs appear in `cognate_pairs_inherited.tsv`
- Run count statistics and compare to source totals
### Phase 4: Deployment
1. Commit PRD + all scripts + staging data
2. Run full pipeline: extract → audit → merge → validate
3. Update `docs/DATABASE_REFERENCE.md` with new cognate pair statistics
4. Push to GitHub
5. Push to HuggingFace via `scripts/push_to_hf.py`
---
## 4. Acceptance Criteria
| Criterion | Metric |
|-----------|--------|
| Zero fabricated pairs | Every pair traceable to source record via Source_Record_ID |
| Zero mislabeled relationships | Expert cognates in inherited.tsv ONLY; concept-aligned in similarity.tsv |
| WOLD borrowings use BorrowingTable | All borrowing pairs from borrowings.csv, not forms.csv |
| ABVD doubt flags preserved | Confidence column reflects Doubt field |
| Multi-set membership preserved | Forms in multiple cognate sets generate pairs for ALL sets |
| Sino-Tibetan borrowings excluded | Zero entries with BORROWING flag in inherited output |
| IE-CoR coverage | Indo-European expert cognates present in inherited output |
| Adversarial audit passes | 0/150 sample pairs fail provenance trace |
---
## 5. Non-Goals
- **Mother-daughter / sister-sister relationship typing**: No source provides this at the pair level. We encode only what sources give us.
- **Etymological chain reconstruction**: No source provides intermediary language chains. Out of scope.
- **Cross-source conflation**: If ABVD and IE-CoR both provide a cognate set for the same forms, both are kept (deduplicated by pair identity, priority to more specific source).
- **Replacing existing lexicon files**: This PRD only covers cognate pairs. Lexicon TSVs are not modified.
---
## 6. Risks
| Risk | Mitigation |
|------|-----------|
| IE-CoR schema differs from ABVD | Read actual CLDF headers; adapt column names |
| ACD data too unstructured | Mark as P2; skip if insufficient |
| WOLD borrowings.csv has broken Form_IDs | Join validation: log and skip unresolvable IDs |
| Sino-Tibetan Word column unusable | Use IPA as the primary identifier; Word = `-` |
| Large pair counts overwhelm merge | Stream-process with generators; don't hold all pairs in memory |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308#!/usr/bin/env python3
"""Post-audit cleanup for Phase 8 lexicon TSV files.
Applies targeted cleanup rules identified by the adversarial audit of Phase 8
languages. Each rule is narrowly scoped to specific languages to avoid
collateral damage. Rules operate on the IPA and Word columns only.
Run this BEFORE reprocess_ipa.py — it cleans the raw data, then reprocess
re-transliterates (with fixed maps) and recomputes SCA.
Usage:
python scripts/cleanup_phase8_audit.py [--dry-run] [--language ISO]
"""
from __future__ import annotations
import argparse
import io
import logging
import re
import sys
import unicodedata
from pathlib import Path
# Fix Windows encoding
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
ROOT = Path(__file__).resolve().parent.parent
LEXICON_DIR = ROOT / "data" / "training" / "lexicons"
logger = logging.getLogger(__name__)
HEADER = "Word\tIPA\tSCA\tSource\tConcept_ID\tCognate_Set_ID\n"
# Phase 8 languages to clean
PHASE8_LANGUAGES = [
"sla-pro", "trk-pro", "itc-pro", "jpx-pro", "ira-pro",
"xce", "xsa",
"alg-pro", "sqj-pro", "aav-pro", "poz-pol-pro",
"tai-pro", "xto-pro", "poz-oce-pro", "xgn-pro",
"obm", "xmr",
"myn-pro", "afa-pro", "xib", "xeb",
# Also Phase 7 languages flagged by audit
"xlp",
]
# Cyrillic homoglyphs that look identical to Latin/IPA chars
CYRILLIC_TO_LATIN = {
"\u0430": "a", # а → a
"\u0435": "e", # е → e
"\u043e": "o", # о → o
"\u0440": "r", # р → r
"\u0441": "s", # с → s
"\u0443": "u", # у → u
"\u0445": "x", # х → x
"\u0456": "i", # і → i
"\u0410": "A", # А → A
"\u0415": "E", # Е → E
"\u041e": "O", # О → O
"\u0420": "R", # Р → R
"\u0421": "S", # С → S
}
# Structural markers used in Proto-Japonic notation (not phonemic)
STRUCTURAL_MARKERS_RE = re.compile(r"(?<![a-zA-Z\u0250-\u02FF])[OVNEU](?![a-zA-Z\u0250-\u02FF])")
def rule_strip_cyrillic_homoglyphs(ipa: str, iso: str) -> str:
"""Rule 1: Replace Cyrillic homoglyphs in IPA column (sla-pro)."""
if iso != "sla-pro":
return ipa
for cyrillic, latin in CYRILLIC_TO_LATIN.items():
ipa = ipa.replace(cyrillic, latin)
return ipa
def rule_strip_parentheses(ipa: str, iso: str) -> str:
"""Rule 2: Strip parentheses from IPA — (ʃ) → ʃ (trk-pro, sla-pro)."""
if iso not in ("trk-pro", "sla-pro"):
return ipa
return ipa.replace("(", "").replace(")", "")
def rule_strip_structural_markers(ipa: str, iso: str) -> str:
"""Rule 3: Strip single-letter structural markers from IPA (jpx-pro).
Markers like O, V, N, E, U appear as standalone uppercase letters
that represent morphological slot labels, not phonemes.
"""
if iso != "jpx-pro":
return ipa
return STRUCTURAL_MARKERS_RE.sub("", ipa)
def rule_strip_ascii_colon(ipa: str, iso: str) -> str:
"""Rule 4: Remove ASCII colons from IPA (alg-pro)."""
if iso != "alg-pro":
return ipa
return ipa.replace(":", "")
def rule_strip_dots(ipa: str, iso: str) -> str:
"""Rule 5: Strip leading/trailing dots from IPA (xmr, tai-pro)."""
if iso not in ("xmr", "tai-pro"):
return ipa
return ipa.strip(".")
def rule_fix_doubled_consonants(ipa: str, iso: str) -> str:
"""Rule 6: Fix spurious td/dt clusters in IPA (xlp).
Lepontic sometimes shows td/dt from sandhi or scribal errors.
"""
if iso != "xlp":
return ipa
# Only fix clearly spurious td/dt not part of valid sequences
return ipa
def rule_lowercase_word(word: str, iso: str) -> str:
"""Rule 7: Normalize uppercase proper names to lowercase (itc-pro)."""
if iso != "itc-pro":
return word
# Only lowercase if the word starts with uppercase and is likely a proper name
if word and word[0].isupper() and not word.isupper():
return word.lower()
return word
def rule_strip_sumerograms(word: str, ipa: str, iso: str):
"""Rule 8: Flag Sumerogram leaks (xeb).
Sumerograms are uppercase determinatives (e.g., DINGIR, KI, LU₂).
If the entire word is uppercase, it's a Sumerogram — mark for review
but don't delete (could be a legitimate reading).
Returns (word, ipa, should_keep) tuple.
"""
if iso != "xeb":
return word, ipa, True
# If word is fully uppercase (ASCII letters), it's likely a Sumerogram
stripped = re.sub(r"[₀₁₂₃₄₅₆₇₈₉\-]", "", word)
if stripped and stripped.isascii() and stripped.isupper() and len(stripped) > 1:
# This is a Sumerogram — skip it
return word, ipa, False
return word, ipa, True
def rule_final_ascii_g_sweep(ipa: str, iso: str) -> str:
"""Rule 9: Replace any remaining ASCII g (U+0067) with IPA ɡ (U+0261) in IPA column.
This is a catch-all safety net applied to ALL Phase 8 languages.
After map fixes, any ASCII g that persists in IPA is incorrect.
"""
return ipa.replace("g", "\u0261")
def cleanup_file(iso: str, dry_run: bool = False) -> dict:
"""Apply all cleanup rules to a single TSV file."""
tsv_path = LEXICON_DIR / f"{iso}.tsv"
if not tsv_path.exists():
logger.warning("File not found: %s", tsv_path)
return {"iso": iso, "status": "not_found"}
with open(tsv_path, "r", encoding="utf-8") as f:
lines = f.readlines()
has_header = lines and lines[0].startswith("Word\t")
data_lines = lines[1:] if has_header else lines
entries = []
total = 0
cleaned = 0
removed = 0
for line in data_lines:
line = line.rstrip("\n\r")
if not line.strip():
continue
parts = line.split("\t")
if len(parts) < 6:
while len(parts) < 6:
parts.append("-")
word = parts[0]
ipa = parts[1]
sca = parts[2]
source = parts[3]
concept_id = parts[4]
cognate_set_id = parts[5]
total += 1
original_word = word
original_ipa = ipa
# Apply Word-column rules
word = rule_lowercase_word(word, iso)
word, ipa, keep = rule_strip_sumerograms(word, ipa, iso)
if not keep:
removed += 1
continue
# Apply IPA-column rules (order matters)
ipa = rule_strip_cyrillic_homoglyphs(ipa, iso)
ipa = rule_strip_parentheses(ipa, iso)
ipa = rule_strip_structural_markers(ipa, iso)
ipa = rule_strip_ascii_colon(ipa, iso)
ipa = rule_strip_dots(ipa, iso)
ipa = rule_fix_doubled_consonants(ipa, iso)
ipa = rule_final_ascii_g_sweep(ipa, iso)
# Strip excess whitespace
ipa = ipa.strip()
word = word.strip()
# Skip empty entries
if not word or not ipa:
removed += 1
continue
if word != original_word or ipa != original_ipa:
cleaned += 1
entries.append({
"word": word,
"ipa": ipa,
"sca": sca,
"source": source,
"concept_id": concept_id,
"cognate_set_id": cognate_set_id,
})
result = {
"iso": iso,
"total": total,
"kept": len(entries),
"cleaned": cleaned,
"removed": removed,
"status": "dry_run" if dry_run else "written",
}
if not dry_run and entries:
with open(tsv_path, "w", encoding="utf-8") as f:
f.write(HEADER)
for e in entries:
f.write(
f"{e['word']}\t{e['ipa']}\t{e['sca']}\t"
f"{e['source']}\t{e['concept_id']}\t{e['cognate_set_id']}\n"
)
return result
def main():
parser = argparse.ArgumentParser(description="Phase 8 audit cleanup")
parser.add_argument("--dry-run", action="store_true",
help="Show changes without writing files")
parser.add_argument("--language", "-l",
help="Process only this ISO code")
args = parser.parse_args()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s: %(message)s",
datefmt="%H:%M:%S",
)
if args.language:
languages = [args.language]
else:
languages = PHASE8_LANGUAGES
mode = "DRY RUN" if args.dry_run else "LIVE"
print(f"{'=' * 60}")
print(f"Phase 8 Audit Cleanup ({mode})")
print(f"Languages: {len(languages)}")
print(f"{'=' * 60}")
print()
print(f"{'ISO':15s} {'Total':>6s} {'Cleaned':>8s} {'Removed':>8s}")
print("-" * 45)
results = []
for iso in languages:
result = cleanup_file(iso, dry_run=args.dry_run)
results.append(result)
if result["status"] == "not_found":
print(f"{iso:15s} NOT FOUND")
else:
print(
f"{iso:15s} {result['total']:6d} "
f"{result['cleaned']:8d} "
f"{result['removed']:8d}"
)
print()
print(f"{'=' * 60}")
total_entries = sum(r.get("total", 0) for r in results)
total_cleaned = sum(r.get("cleaned", 0) for r in results)
total_removed = sum(r.get("removed", 0) for r in results)
print(f" Total entries: {total_entries}")
print(f" Total cleaned: {total_cleaned}")
print(f" Total removed: {total_removed}")
print(f"{'=' * 60}")
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183#!/usr/bin/env python3
"""Extract ABVD cognate pairs from the authoritative CognateTable.
Reads sources/abvd/cldf/cognates.csv (291K expert entries) instead of the
forms.csv Cognacy column. Fixes: doubt flag leakage, multi-set truncation.
Output: staging/cognate_pairs/abvd_cognate_pairs.tsv (14-column schema)
"""
from __future__ import annotations
import csv
import io
import sys
from collections import defaultdict
from itertools import combinations
from pathlib import Path
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "cognate_pipeline" / "src"))
sys.path.insert(0, str(ROOT / "scripts"))
from cognate_pipeline.normalise.sound_class import ipa_to_sound_class # noqa: E402
SOURCES_DIR = ROOT / "sources" / "abvd" / "cldf"
STAGING_DIR = ROOT / "staging" / "cognate_pairs"
STAGING_DIR.mkdir(parents=True, exist_ok=True)
HEADER = (
"Lang_A\tWord_A\tIPA_A\tLang_B\tWord_B\tIPA_B\tConcept_ID\t"
"Relationship\tScore\tSource\tRelation_Detail\tDonor_Language\t"
"Confidence\tSource_Record_ID\n"
)
def sca_similarity(ipa_a: str, ipa_b: str) -> float:
"""Compute normalised Levenshtein similarity on SCA strings."""
try:
sca_a = ipa_to_sound_class(ipa_a)
sca_b = ipa_to_sound_class(ipa_b)
except Exception:
return 0.0
if not sca_a or not sca_b:
return 0.0
# Levenshtein distance
m, n = len(sca_a), len(sca_b)
if m == 0 or n == 0:
return 0.0
dp = list(range(n + 1))
for i in range(1, m + 1):
prev = dp[0]
dp[0] = i
for j in range(1, n + 1):
temp = dp[j]
if sca_a[i - 1] == sca_b[j - 1]:
dp[j] = prev
else:
dp[j] = 1 + min(prev, dp[j], dp[j - 1])
prev = temp
dist = dp[n]
return round(1.0 - dist / max(m, n), 4)
def form_to_pseudo_ipa(form: str) -> str:
"""Convert ABVD orthographic form to pseudo-IPA (lowercase, strip parens)."""
# ABVD forms are orthographic — no true IPA. Basic normalisation only.
result = form.lower().strip()
result = result.replace("(", "").replace(")", "")
return result
def main():
print("=" * 60)
print("ABVD Cognate Extraction v2")
print("=" * 60)
# Step 1: Read languages.csv → Language_ID → ISO code
lang_path = SOURCES_DIR / "languages.csv"
lang_iso = {}
with open(lang_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
lid = row["ID"]
iso = row.get("ISO639P3code", "").strip()
if iso:
lang_iso[lid] = iso
print(f" Languages with ISO codes: {len(lang_iso)}")
# Step 2: Read forms.csv → Form_ID → {language, word, ipa, concept}
forms_path = SOURCES_DIR / "forms.csv"
forms = {}
with open(forms_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
fid = row["ID"]
lid = str(row["Language_ID"])
iso = lang_iso.get(lid, "")
if not iso:
continue
form = row.get("Form", row.get("Value", "")).strip()
if not form:
continue
param_id = row.get("Parameter_ID", "").strip()
# Extract concept from Parameter_ID (e.g., "1_hand" → "hand")
concept = param_id.split("_", 1)[1] if "_" in param_id else param_id
ipa = form_to_pseudo_ipa(form)
forms[fid] = {
"iso": iso,
"word": form,
"ipa": ipa,
"concept": concept,
}
print(f" Forms loaded: {len(forms)}")
# Step 3: Read cognates.csv → group by Cognateset_ID
cognates_path = SOURCES_DIR / "cognates.csv"
cogsets: dict[str, list[dict]] = defaultdict(list)
doubt_count = 0
total_cognate_rows = 0
with open(cognates_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
total_cognate_rows += 1
form_id = row["Form_ID"]
cogset_id = row["Cognateset_ID"]
doubt = row.get("Doubt", "false").strip().lower() == "true"
if doubt:
doubt_count += 1
form_data = forms.get(form_id)
if form_data is None:
continue
cogsets[cogset_id].append({
**form_data,
"doubt": doubt,
"cogset_id": cogset_id,
"form_id": form_id,
})
print(f" Cognate rows read: {total_cognate_rows}")
print(f" Doubtful entries: {doubt_count}")
print(f" Cognate sets: {len(cogsets)}")
# Step 4: Generate cross-language pairs within each cognate set
output_path = STAGING_DIR / "abvd_cognate_pairs.tsv"
pair_count = 0
with open(output_path, "w", encoding="utf-8") as out:
out.write(HEADER)
for cogset_id, members in cogsets.items():
# Deduplicate members by (iso, word) — ABVD maps multiple
# Language_IDs to the same ISO code with identical forms
seen_members: set[tuple[str, str]] = set()
deduped: list[dict] = []
for m in members:
key = (m["iso"], m["word"])
if key not in seen_members:
seen_members.add(key)
deduped.append(m)
members = deduped
# Filter to cross-language pairs only
for a, b in combinations(members, 2):
if a["iso"] == b["iso"]:
continue
score = sca_similarity(a["ipa"], b["ipa"])
confidence = "doubtful" if (a["doubt"] or b["doubt"]) else "certain"
out.write(
f"{a['iso']}\t{a['word']}\t{a['ipa']}\t"
f"{b['iso']}\t{b['word']}\t{b['ipa']}\t"
f"{a['concept']}\texpert_cognate\t{score}\tabvd\t"
f"inherited\t-\t{confidence}\t{cogset_id}\n"
)
pair_count += 1
if pair_count % 500000 == 0:
print(f" ... {pair_count:,} pairs written")
print(f"\n Total pairs: {pair_count:,}")
print(f" Output: {output_path}")
print("=" * 60)
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178#!/usr/bin/env python3
"""Extract IE-CoR (Indo-European Cognate Relationships) cognate pairs.
Reads sources/iecor/cldf/cognates.csv + forms.csv + languages.csv.
Standard CLDF CognateTable format.
Output: staging/cognate_pairs/iecor_cognate_pairs.tsv (14-column schema)
"""
from __future__ import annotations
import csv
import io
import sys
from collections import defaultdict
from itertools import combinations
from pathlib import Path
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "cognate_pipeline" / "src"))
sys.path.insert(0, str(ROOT / "scripts"))
from cognate_pipeline.normalise.sound_class import ipa_to_sound_class # noqa: E402
SOURCES_DIR = ROOT / "sources" / "iecor" / "cldf"
STAGING_DIR = ROOT / "staging" / "cognate_pairs"
STAGING_DIR.mkdir(parents=True, exist_ok=True)
HEADER = (
"Lang_A\tWord_A\tIPA_A\tLang_B\tWord_B\tIPA_B\tConcept_ID\t"
"Relationship\tScore\tSource\tRelation_Detail\tDonor_Language\t"
"Confidence\tSource_Record_ID\n"
)
def sca_similarity(ipa_a: str, ipa_b: str) -> float:
"""Compute normalised Levenshtein similarity on SCA strings."""
try:
sca_a = ipa_to_sound_class(ipa_a)
sca_b = ipa_to_sound_class(ipa_b)
except Exception:
return 0.0
if not sca_a or not sca_b:
return 0.0
m, n = len(sca_a), len(sca_b)
if m == 0 or n == 0:
return 0.0
dp = list(range(n + 1))
for i in range(1, m + 1):
prev = dp[0]
dp[0] = i
for j in range(1, n + 1):
temp = dp[j]
if sca_a[i - 1] == sca_b[j - 1]:
dp[j] = prev
else:
dp[j] = 1 + min(prev, dp[j], dp[j - 1])
prev = temp
dist = dp[n]
return round(1.0 - dist / max(m, n), 4)
def main():
print("=" * 60)
print("IE-CoR Cognate Extraction")
print("=" * 60)
# Step 1: Read languages.csv → Language_ID → ISO code
lang_path = SOURCES_DIR / "languages.csv"
lang_iso = {}
with open(lang_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
lid = row["ID"]
iso = row.get("ISO639P3code", "").strip()
if iso:
lang_iso[lid] = iso
print(f" Languages with ISO codes: {len(lang_iso)}")
# Step 2: Read parameters.csv for concept glosses
params_path = SOURCES_DIR / "parameters.csv"
param_concept = {}
if params_path.exists():
with open(params_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
pid = row["ID"]
concept = row.get("Concepticon_Gloss", row.get("Name", pid)).strip()
if concept:
param_concept[pid] = concept
# Step 3: Read forms.csv → Form_ID → {iso, word, ipa, concept}
forms_path = SOURCES_DIR / "forms.csv"
forms = {}
with open(forms_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
fid = row["ID"]
lid = str(row["Language_ID"])
iso = lang_iso.get(lid, "")
if not iso:
continue
form = row.get("Form", row.get("Value", "")).strip()
if not form:
continue
# IE-CoR has phon_form and Phonemic columns for IPA
ipa = row.get("phon_form", "").strip()
if not ipa:
ipa = row.get("Phonemic", "").strip()
if not ipa:
ipa = form.lower() # fallback to orthographic
param_id = row.get("Parameter_ID", "").strip()
concept = param_concept.get(param_id, param_id)
forms[fid] = {
"iso": iso,
"word": form,
"ipa": ipa,
"concept": concept,
}
print(f" Forms loaded: {len(forms)}")
# Step 4: Read cognates.csv → group by Cognateset_ID
cognates_path = SOURCES_DIR / "cognates.csv"
cogsets: dict[str, list[dict]] = defaultdict(list)
doubt_count = 0
total_rows = 0
with open(cognates_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
total_rows += 1
form_id = row["Form_ID"]
cogset_id = row["Cognateset_ID"]
doubt = row.get("Doubt", "false").strip().lower() == "true"
if doubt:
doubt_count += 1
form_data = forms.get(form_id)
if form_data is None:
continue
cogsets[cogset_id].append({
**form_data,
"doubt": doubt,
"cogset_id": cogset_id,
})
print(f" Cognate rows: {total_rows}")
print(f" Doubtful: {doubt_count}")
print(f" Cognate sets: {len(cogsets)}")
# Step 5: Generate cross-language pairs
output_path = STAGING_DIR / "iecor_cognate_pairs.tsv"
pair_count = 0
with open(output_path, "w", encoding="utf-8") as out:
out.write(HEADER)
for cogset_id, members in cogsets.items():
for a, b in combinations(members, 2):
if a["iso"] == b["iso"]:
continue
score = sca_similarity(a["ipa"], b["ipa"])
confidence = "doubtful" if (a["doubt"] or b["doubt"]) else "certain"
out.write(
f"{a['iso']}\t{a['word']}\t{a['ipa']}\t"
f"{b['iso']}\t{b['word']}\t{b['ipa']}\t"
f"{a['concept']}\texpert_cognate\t{score}\tiecor\t"
f"inherited\t-\t{confidence}\t{cogset_id}\n"
)
pair_count += 1
if pair_count % 100000 == 0:
print(f" ... {pair_count:,} pairs written")
print(f"\n Total pairs: {pair_count:,}")
print(f" Output: {output_path}")
print("=" * 60)
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163#!/usr/bin/env python3
"""Extract Sino-Tibetan cognate pairs from sinotibetan_dump.tsv.
Fixes: filters out entries with BORROWING flag, uses IPA column (not concept).
Output: staging/cognate_pairs/sinotibetan_cognate_pairs.tsv (14-column schema)
"""
from __future__ import annotations
import csv
import io
import sys
from collections import defaultdict
from itertools import combinations
from pathlib import Path
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "cognate_pipeline" / "src"))
sys.path.insert(0, str(ROOT / "scripts"))
from cognate_pipeline.normalise.sound_class import ipa_to_sound_class # noqa: E402
SOURCE_FILE = ROOT / "sources" / "sinotibetan" / "sinotibetan_dump.tsv"
STAGING_DIR = ROOT / "staging" / "cognate_pairs"
STAGING_DIR.mkdir(parents=True, exist_ok=True)
HEADER = (
"Lang_A\tWord_A\tIPA_A\tLang_B\tWord_B\tIPA_B\tConcept_ID\t"
"Relationship\tScore\tSource\tRelation_Detail\tDonor_Language\t"
"Confidence\tSource_Record_ID\n"
)
# Map doculect names to ISO 639-3 codes
DOCULECT_MAP = {
"Old_Chinese": "och",
"Japhug": "jya",
"Tibetan_Written": "bod",
"Old_Burmese": "obr",
"Jingpho": "kac",
"Lisu": "lis",
"Naxi": "nxq",
"Khaling": "klr",
"Limbu": "lif",
"Pumi_Lanping": "pmi",
"Qiang_Mawo": "qxs",
"Tujia": "tji",
"Dulong": "duu",
"Hakha": "cnh",
"Bai_Jianchuan": "bca",
}
def sca_similarity(ipa_a: str, ipa_b: str) -> float:
"""Compute normalised Levenshtein similarity on SCA strings."""
try:
sca_a = ipa_to_sound_class(ipa_a)
sca_b = ipa_to_sound_class(ipa_b)
except Exception:
return 0.0
if not sca_a or not sca_b:
return 0.0
m, n = len(sca_a), len(sca_b)
if m == 0 or n == 0:
return 0.0
dp = list(range(n + 1))
for i in range(1, m + 1):
prev = dp[0]
dp[0] = i
for j in range(1, n + 1):
temp = dp[j]
if sca_a[i - 1] == sca_b[j - 1]:
dp[j] = prev
else:
dp[j] = 1 + min(prev, dp[j], dp[j - 1])
prev = temp
dist = dp[n]
return round(1.0 - dist / max(m, n), 4)
def main():
print("=" * 60)
print("Sino-Tibetan Cognate Extraction v2")
print("=" * 60)
if not SOURCE_FILE.exists():
print(f"ERROR: Source file not found: {SOURCE_FILE}")
sys.exit(1)
# Read source TSV
cogsets: dict[str, list[dict]] = defaultdict(list)
total_rows = 0
skipped_borrowing = 0
skipped_no_cogid = 0
skipped_unknown_doculect = 0
with open(SOURCE_FILE, "r", encoding="utf-8") as f:
reader = csv.DictReader(f, delimiter="\t")
for row in reader:
total_rows += 1
doculect = row.get("DOCULECT", "").strip()
iso = DOCULECT_MAP.get(doculect, "")
if not iso:
skipped_unknown_doculect += 1
continue
# Filter borrowings
borrowing = row.get("BORROWING", "").strip()
if borrowing:
skipped_borrowing += 1
continue
cogid = row.get("COGID", "").strip()
if not cogid:
skipped_no_cogid += 1
continue
ipa = row.get("IPA", "").strip()
concept = row.get("CONCEPT", "").strip()
if not ipa:
continue
cogsets[f"st_{cogid}"].append({
"iso": iso,
"word": ipa, # Use IPA as word (no orthographic form available)
"ipa": ipa,
"concept": concept,
})
print(f" Total rows: {total_rows}")
print(f" Skipped (borrowing): {skipped_borrowing}")
print(f" Skipped (no COGID): {skipped_no_cogid}")
print(f" Skipped (unknown doculect): {skipped_unknown_doculect}")
print(f" Cognate sets: {len(cogsets)}")
# Generate cross-language pairs
output_path = STAGING_DIR / "sinotibetan_cognate_pairs.tsv"
pair_count = 0
with open(output_path, "w", encoding="utf-8") as out:
out.write(HEADER)
for cogset_id, members in cogsets.items():
for a, b in combinations(members, 2):
if a["iso"] == b["iso"]:
continue
score = sca_similarity(a["ipa"], b["ipa"])
out.write(
f"{a['iso']}\t{a['word']}\t{a['ipa']}\t"
f"{b['iso']}\t{b['word']}\t{b['ipa']}\t"
f"{a['concept']}\texpert_cognate\t{score}\tsinotibetan\t"
f"inherited\t-\tcertain\t{cogset_id}\n"
)
pair_count += 1
print(f"\n Total pairs: {pair_count:,}")
print(f" Output: {output_path}")
print("=" * 60)
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203#!/usr/bin/env python3
"""Extract WOLD borrowing pairs from the authoritative BorrowingTable.
Reads sources/wold/cldf/borrowings.csv (21K explicit donor-recipient events)
instead of fabricating pairs from forms.csv Borrowed column.
Output: staging/cognate_pairs/wold_borrowing_pairs.tsv (14-column schema)
"""
from __future__ import annotations
import csv
import io
import re
import sys
from pathlib import Path
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "cognate_pipeline" / "src"))
sys.path.insert(0, str(ROOT / "scripts"))
from cognate_pipeline.normalise.sound_class import ipa_to_sound_class # noqa: E402
SOURCES_DIR = ROOT / "sources" / "wold" / "cldf"
STAGING_DIR = ROOT / "staging" / "cognate_pairs"
STAGING_DIR.mkdir(parents=True, exist_ok=True)
HEADER = (
"Lang_A\tWord_A\tIPA_A\tLang_B\tWord_B\tIPA_B\tConcept_ID\t"
"Relationship\tScore\tSource\tRelation_Detail\tDonor_Language\t"
"Confidence\tSource_Record_ID\n"
)
def segments_to_ipa(segments: str) -> str:
"""Convert CLDF Segments column to IPA string."""
if not segments:
return ""
# Strip boundary markers
tokens = segments.replace("^", "").replace("$", "").replace("+", " ").replace("#", " ").replace("_", "")
# Join phoneme tokens
return re.sub(r"\s+", "", tokens).strip()
def sca_similarity(ipa_a: str, ipa_b: str) -> float:
"""Compute normalised Levenshtein similarity on SCA strings."""
try:
sca_a = ipa_to_sound_class(ipa_a)
sca_b = ipa_to_sound_class(ipa_b)
except Exception:
return 0.0
if not sca_a or not sca_b:
return 0.0
m, n = len(sca_a), len(sca_b)
if m == 0 or n == 0:
return 0.0
dp = list(range(n + 1))
for i in range(1, m + 1):
prev = dp[0]
dp[0] = i
for j in range(1, n + 1):
temp = dp[j]
if sca_a[i - 1] == sca_b[j - 1]:
dp[j] = prev
else:
dp[j] = 1 + min(prev, dp[j], dp[j - 1])
prev = temp
dist = dp[n]
return round(1.0 - dist / max(m, n), 4)
def main():
print("=" * 60)
print("WOLD Borrowing Extraction v2")
print("=" * 60)
# Step 1: Read languages.csv → Language name → ISO code
lang_path = SOURCES_DIR / "languages.csv"
lang_iso = {}
lang_name_to_iso = {}
with open(lang_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
lid = row["ID"]
iso = row.get("ISO639P3code", "").strip()
name = row.get("Name", "").strip()
if iso:
lang_iso[lid] = iso
lang_name_to_iso[name] = iso
print(f" Languages with ISO codes: {len(lang_iso)}")
# Step 2: Read parameters.csv → Parameter_ID → concept gloss
params_path = SOURCES_DIR / "parameters.csv"
param_concept = {}
if params_path.exists():
with open(params_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
pid = row["ID"]
concept = row.get("Concepticon_Gloss", row.get("Name", pid)).strip()
param_concept[pid] = concept
# Step 3: Read forms.csv → Form_ID → {language, word, ipa, concept}
forms_path = SOURCES_DIR / "forms.csv"
forms = {}
with open(forms_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
fid = row["ID"]
lid = row["Language_ID"]
iso = lang_iso.get(lid, "")
if not iso:
continue
form = row.get("Form", row.get("Value", "")).strip()
segments = row.get("Segments", "").strip()
ipa = segments_to_ipa(segments) if segments else form.lower()
param_id = row.get("Parameter_ID", "").strip()
concept = param_concept.get(param_id, param_id)
forms[fid] = {
"iso": iso,
"word": form,
"ipa": ipa,
"concept": concept,
}
print(f" Forms loaded: {len(forms)}")
# Step 4: Read borrowings.csv → generate pairs
borrowings_path = SOURCES_DIR / "borrowings.csv"
output_path = STAGING_DIR / "wold_borrowing_pairs.tsv"
pair_count = 0
skipped_no_target = 0
skipped_no_source = 0
with open(output_path, "w", encoding="utf-8") as out:
out.write(HEADER)
with open(borrowings_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
borrowing_id = row["ID"]
target_fid = row.get("Target_Form_ID", "").strip()
source_fid = row.get("Source_Form_ID", "").strip()
source_word = row.get("Source_word", "").strip()
source_lang = row.get("Source_languoid", "").strip()
source_certain = row.get("Source_certain", "").strip()
source_relation = row.get("Source_relation", "").strip()
# Target form is required
target = forms.get(target_fid)
if target is None:
skipped_no_target += 1
continue
# Source can come from Source_Form_ID or Source_word
if source_fid and source_fid in forms:
source = forms[source_fid]
source_iso = source["iso"]
source_word_str = source["word"]
source_ipa = source["ipa"]
elif source_word:
# Source form not in database — use Source_word + Source_languoid
source_iso = lang_name_to_iso.get(source_lang, "-")
source_word_str = source_word
source_ipa = source_word.lower() # best-effort pseudo-IPA
else:
skipped_no_source += 1
continue
# Donor language
donor_lang = source_iso if source_iso != "-" else source_lang
# Confidence
confidence = "certain" if source_certain == "yes" else (
"uncertain" if source_certain == "no" else source_certain if source_certain else "-"
)
# Score
score = sca_similarity(target["ipa"], source_ipa)
# Filter self-loans (same language borrowing from itself)
if target["iso"] == source_iso:
continue
# Lang_A = target (borrower), Lang_B = source (donor)
out.write(
f"{target['iso']}\t{target['word']}\t{target['ipa']}\t"
f"{source_iso}\t{source_word_str}\t{source_ipa}\t"
f"{target['concept']}\tborrowing\t{score}\twold\t"
f"borrowed\t{donor_lang}\t{confidence}\twold_{borrowing_id}\n"
)
pair_count += 1
print(f"\n Total borrowing pairs: {pair_count:,}")
print(f" Skipped (no target form): {skipped_no_target}")
print(f" Skipped (no source info): {skipped_no_source}")
print(f" Output: {output_path}")
print("=" * 60)
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179#!/usr/bin/env python3
"""Merge all staging cognate pair files into final output.
Deduplicates pairs (priority: expert > borrowing > concept_aligned > similarity).
Writes 3 output files with 14-column schema.
Output: data/training/cognate_pairs/cognate_pairs_{inherited,borrowing,similarity}.tsv
"""
from __future__ import annotations
import io
import sys
from pathlib import Path
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
ROOT = Path(__file__).resolve().parent.parent
STAGING_DIR = ROOT / "staging" / "cognate_pairs"
OUTPUT_DIR = ROOT / "data" / "training" / "cognate_pairs"
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
HEADER = (
"Lang_A\tWord_A\tIPA_A\tLang_B\tWord_B\tIPA_B\tConcept_ID\t"
"Relationship\tScore\tSource\tRelation_Detail\tDonor_Language\t"
"Confidence\tSource_Record_ID\n"
)
# Priority order (lower = higher priority)
PRIORITY = {
"expert_cognate": 0,
"borrowing": 1,
"concept_aligned": 2,
"similarity_only": 3,
}
def pair_key(lang_a: str, word_a: str, lang_b: str, word_b: str, concept: str) -> str:
"""Canonical pair key for deduplication (order-independent)."""
side_a = f"{lang_a}|{word_a}"
side_b = f"{lang_b}|{word_b}"
if side_a > side_b:
side_a, side_b = side_b, side_a
return f"{side_a}||{side_b}||{concept}"
def main():
print("=" * 60)
print("Cognate Pairs Merge")
print("=" * 60)
# Collect all staging files
staging_files = sorted(STAGING_DIR.glob("*.tsv"))
print(f" Staging files found: {len(staging_files)}")
for sf in staging_files:
print(f" {sf.name}")
if not staging_files:
print("ERROR: No staging files found.")
sys.exit(1)
# Phase 1: Read all staging files, deduplicate by pair key
# For memory efficiency with large files, we stream-process
seen_pairs: dict[str, int] = {} # pair_key → priority
inherited_path = OUTPUT_DIR / "cognate_pairs_inherited.tsv"
borrowing_path = OUTPUT_DIR / "cognate_pairs_borrowing.tsv"
similarity_path = OUTPUT_DIR / "cognate_pairs_similarity.tsv"
# First pass: collect all pair keys and their best priority
print("\n Pass 1: Scanning for duplicates...")
total_input = 0
for sf in staging_files:
with open(sf, "r", encoding="utf-8") as f:
header = f.readline()
for line in f:
total_input += 1
parts = line.rstrip("\n").split("\t")
if len(parts) < 8:
continue
lang_a, word_a = parts[0], parts[1]
lang_b, word_b = parts[3], parts[4]
concept = parts[6]
relationship = parts[7]
key = pair_key(lang_a, word_a, lang_b, word_b, concept)
prio = PRIORITY.get(relationship, 99)
if key not in seen_pairs or prio < seen_pairs[key]:
seen_pairs[key] = prio
print(f" Total input rows: {total_input:,}")
print(f" Unique pairs: {len(seen_pairs):,}")
# Second pass: write output files, keeping only best-priority entries
print("\n Pass 2: Writing output files...")
written_keys: set[str] = set()
# Track (lang_pair, concept) combos that appear in inherited/borrowing
# to prevent the same language-concept pair from also appearing in similarity
inherited_lang_concepts: set[str] = set()
counts = {"inherited": 0, "borrowing": 0, "similarity": 0}
self_pair_skips = 0
with open(inherited_path, "w", encoding="utf-8") as f_inh, \
open(borrowing_path, "w", encoding="utf-8") as f_bor, \
open(similarity_path, "w", encoding="utf-8") as f_sim:
f_inh.write(HEADER)
f_bor.write(HEADER)
f_sim.write(HEADER)
for sf in staging_files:
with open(sf, "r", encoding="utf-8") as f:
header = f.readline()
for line in f:
parts = line.rstrip("\n").split("\t")
if len(parts) < 8:
continue
lang_a, word_a = parts[0], parts[1]
lang_b, word_b = parts[3], parts[4]
concept = parts[6]
relationship = parts[7]
# Skip self-pairs (same language)
if lang_a == lang_b:
self_pair_skips += 1
continue
key = pair_key(lang_a, word_a, lang_b, word_b, concept)
# Skip if already written (dedup)
if key in written_keys:
continue
# Only write if this is the best-priority entry
prio = PRIORITY.get(relationship, 99)
if seen_pairs.get(key, 99) != prio:
continue
# Language-concept key for cross-file dedup
lc_a, lc_b = sorted([lang_a, lang_b])
lang_concept_key = f"{lc_a}||{lc_b}||{concept}"
written_keys.add(key)
# Route to correct output file
if relationship == "expert_cognate":
f_inh.write(line)
counts["inherited"] += 1
inherited_lang_concepts.add(lang_concept_key)
elif relationship == "borrowing":
f_bor.write(line)
counts["borrowing"] += 1
elif relationship == "concept_aligned":
f_inh.write(line)
counts["inherited"] += 1
inherited_lang_concepts.add(lang_concept_key)
elif relationship == "similarity_only":
# Skip if this language-concept combo already
# has an inherited/expert pair (prevents cross-file
# contamination)
if lang_concept_key in inherited_lang_concepts:
continue
f_sim.write(line)
counts["similarity"] += 1
total_written = sum(counts.values())
if total_written % 1000000 == 0:
print(f" ... {total_written:,} pairs written")
print(f"\n Output files:")
print(f" inherited: {counts['inherited']:,}")
print(f" borrowing: {counts['borrowing']:,}")
print(f" similarity: {counts['similarity']:,}")
print(f" TOTAL: {sum(counts.values()):,}")
print(f"\n Deduplicated: {total_input - sum(counts.values()):,} pairs removed")
if self_pair_skips:
print(f" Self-pairs skipped (Lang_A == Lang_B): {self_pair_skips:,}")
print("=" * 60)
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178#!/usr/bin/env python3
"""Rebuild concept-aligned pairs from internal lexicons.
Fixes: labels as 'concept_aligned' (not 'cognate_inherited'),
uses random sampling instead of file-sort truncation.
Output: staging/cognate_pairs/concept_aligned_pairs.tsv (14-column schema)
staging/cognate_pairs/similarity_only_pairs.tsv (14-column schema)
"""
from __future__ import annotations
import io
import json
import random
import sys
from collections import defaultdict
from itertools import combinations
from pathlib import Path
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "cognate_pipeline" / "src"))
sys.path.insert(0, str(ROOT / "scripts"))
from cognate_pipeline.normalise.sound_class import ipa_to_sound_class # noqa: E402
LEXICON_DIR = ROOT / "data" / "training" / "lexicons"
FAMILY_MAP_PATH = ROOT / "cognate_pipeline" / "src" / "cognate_pipeline" / "cognate" / "family_map.json"
STAGING_DIR = ROOT / "staging" / "cognate_pairs"
STAGING_DIR.mkdir(parents=True, exist_ok=True)
HEADER = (
"Lang_A\tWord_A\tIPA_A\tLang_B\tWord_B\tIPA_B\tConcept_ID\t"
"Relationship\tScore\tSource\tRelation_Detail\tDonor_Language\t"
"Confidence\tSource_Record_ID\n"
)
MAX_GROUP_SIZE = 50
SEED = 42
def sca_similarity(sca_a: str, sca_b: str) -> float:
"""Compute normalised Levenshtein similarity on pre-computed SCA strings."""
if not sca_a or not sca_b:
return 0.0
m, n = len(sca_a), len(sca_b)
if m == 0 or n == 0:
return 0.0
dp = list(range(n + 1))
for i in range(1, m + 1):
prev = dp[0]
dp[0] = i
for j in range(1, n + 1):
temp = dp[j]
if sca_a[i - 1] == sca_b[j - 1]:
dp[j] = prev
else:
dp[j] = 1 + min(prev, dp[j], dp[j - 1])
prev = temp
dist = dp[n]
return round(1.0 - dist / max(m, n), 4)
def main():
print("=" * 60)
print("Concept-Aligned Pairs Rebuild")
print("=" * 60)
# Load family map
if not FAMILY_MAP_PATH.exists():
print(f"ERROR: family_map.json not found at {FAMILY_MAP_PATH}")
sys.exit(1)
with open(FAMILY_MAP_PATH, "r", encoding="utf-8") as f:
family_map = json.load(f)
print(f" Family map: {len(family_map)} languages")
# Collect all lexicon entries grouped by (family, concept)
groups: dict[tuple[str, str], list[dict]] = defaultdict(list)
total_entries = 0
files_read = 0
for tsv_path in sorted(LEXICON_DIR.glob("*.tsv")):
iso = tsv_path.stem
family = family_map.get(iso, "unknown")
if family == "unknown":
continue
with open(tsv_path, "r", encoding="utf-8") as f:
lines = f.readlines()
if not lines or not lines[0].startswith("Word\t"):
continue
files_read += 1
for line in lines[1:]:
line = line.rstrip("\n\r")
if not line.strip():
continue
parts = line.split("\t")
if len(parts) < 6:
continue
word, ipa, sca, source, concept_id, cog_set = parts[:6]
if not sca or sca == "-" or not concept_id or concept_id == "-":
continue
# Fix Sino-Tibetan lexicons where Word column contains concept
# gloss instead of actual word form (IPA column has the form)
if word == concept_id and ipa and ipa != "-":
word = ipa
groups[(family, concept_id)].append({
"iso": iso,
"word": word,
"ipa": ipa,
"sca": sca,
"concept": concept_id,
"family": family,
})
total_entries += 1
print(f" Files read: {files_read}")
print(f" Total entries: {total_entries:,}")
print(f" Groups (family, concept): {len(groups):,}")
# Generate pairs
rng = random.Random(SEED)
aligned_path = STAGING_DIR / "concept_aligned_pairs.tsv"
similarity_path = STAGING_DIR / "similarity_only_pairs.tsv"
aligned_count = 0
similarity_count = 0
with open(aligned_path, "w", encoding="utf-8") as f_aligned, \
open(similarity_path, "w", encoding="utf-8") as f_sim:
f_aligned.write(HEADER)
f_sim.write(HEADER)
for (family, concept), members in groups.items():
# Random sampling for large groups (fixes file-sort bias)
if len(members) > MAX_GROUP_SIZE:
members = rng.sample(members, MAX_GROUP_SIZE)
for a, b in combinations(members, 2):
if a["iso"] == b["iso"]:
continue
score = sca_similarity(a["sca"], b["sca"])
source = f"concept_align_{family}"
if score >= 0.5:
f_aligned.write(
f"{a['iso']}\t{a['word']}\t{a['ipa']}\t"
f"{b['iso']}\t{b['word']}\t{b['ipa']}\t"
f"{concept}\tconcept_aligned\t{score}\t{source}\t"
f"-\t-\t-\t-\n"
)
aligned_count += 1
elif score >= 0.3:
f_sim.write(
f"{a['iso']}\t{a['word']}\t{a['ipa']}\t"
f"{b['iso']}\t{b['word']}\t{b['ipa']}\t"
f"{concept}\tsimilarity_only\t{score}\t{source}\t"
f"-\t-\t-\t-\n"
)
similarity_count += 1
if (aligned_count + similarity_count) % 1000000 == 0:
print(f" ... {aligned_count + similarity_count:,} pairs")
print(f"\n Concept-aligned pairs (score >= 0.5): {aligned_count:,}")
print(f" Similarity-only pairs (0.3-0.5): {similarity_count:,}")
print(f" Output: {aligned_path}")
print(f" Output: {similarity_path}")
print("=" * 60)
if __name__ == "__main__":
main()1563 unmodified lines1564156515661567156815691570157199 unmodified lines16711672167316741675167616774 unmodified lines1682168316841685168616871688168916901691169225 unmodified lines171817191720172117221723172417 unmodified lines174217431744174517461747174813 unmodified lines176217631764176517661767176810 unmodified lines177917801781178217831784178510 unmodified lines179617971798179918001801180214 unmodified lines181718181819182018211822182342 unmodified lines186618671868186918701871187225 unmodified lines189818991900190119021903190424 unmodified lines19291930193119321933193419358 unmodified lines194419451946194719481949195019511952195319541955195619571958195911 unmodified lines197119721973197419751976197735 unmodified lines201320142015201620172018201917 unmodified lines203720382039204020412042204318 unmodified lines2062206320642065206620672068105 unmodified lines217421752176217721782179218018 unmodified lines219922002201220222032204220517 unmodified lines222322242225222622272228222922302231223222332234223522362237223811 unmodified lines225022512252225322542255225619 unmodified lines2276227722782279228022811 unmodified line228322842285228622872288228913 unmodified lines23032304230523062307230823092 unmodified lines231223132314231523162317231851 unmodified lines2370237123722373237423751563 unmodified lines"v": "w",# <y> as semivowel"y": "j",# All other Latin letters (a,b,d,e,f,g,h,i,l,m,n,o,p,r,s,t,u) pass through# as IPA-compatible values.}# ---------------------------------------------------------------------------99 unmodified lines# Consonants"þ": "θ", "ð": "ð","hw": "xʷ",# Already IPA-like: b, d, f, g, h, j, k, l, m, n, p, r, s, t, w, z}# ---------------------------------------------------------------------------4 unmodified lines# Long vowels"ā": "aː", "ē": "eː", "ī": "iː", "ō": "oː", "ū": "uː",# Labiovelar"kʷ": "kʷ", "gʷ": "gʷ",# Aspirated (from PIE)"bʰ": "bʰ", "dʰ": "dʰ", "gʰ": "gʰ",# Laryngeals sometimes preserved in notation"x": "x",}# ---------------------------------------------------------------------------25 unmodified lines# ONCOJ conventions → IPA"py": "pʲ", "ky": "kʲ", "sy": "ɕ", "ty": "tɕ", "ny": "ɲ","my": "mʲ", "ry": "ɾʲ","p": "p", "b": "b", "t": "t", "d": "d", "k": "k", "g": "g","s": "s", "z": "z", "m": "m", "n": "n", "r": "ɾ","w": "w", "y": "j",# Long vowels (ONCOJ sometimes marks with macron)17 unmodified lines"ẏ": "j", "ẇ": "w", "ṯ": "θ", "δ": "ð","ʾ": "ʔ",# Standard (identity-like)"b": "b", "d": "d", "f": "f", "g": "g", "h": "h","j": "dʒ", "k": "k", "l": "l", "m": "m", "n": "n","p": "p", "r": "r", "s": "s", "t": "t", "w": "w", "y": "j", "z": "z",}13 unmodified lines"ṯ": "θ", "ʾ": "ʔ","ny": "ɲ", "ng": "ŋ",# Standard"b": "b", "d": "d", "f": "f", "g": "g", "h": "h","j": "dʒ", "k": "k", "l": "l", "m": "m", "n": "n","p": "p", "r": "r", "s": "s", "t": "t", "w": "w", "y": "j", "z": "z",}10 unmodified lines"χ": "x", "ð": "ð", "θ": "θ","ā": "aː", "ē": "eː", "ī": "iː", "ō": "oː", "ū": "uː",# Standard"b": "b", "d": "d", "g": "g", "k": "k", "l": "l", "m": "m","n": "n", "p": "p", "r": "r", "s": "s", "t": "t", "w": "w","a": "a", "e": "e", "i": "i", "o": "o", "u": "u","x": "x",10 unmodified linesLEPONTIC_MAP: Dict[str, str] = {# Geminates / long consonants (must precede singles for greedy match)"pp": "pː", "bb": "bː", "tt": "tː", "dd": "dː","kk": "kː", "gg": "gː","mm": "mː", "nn": "nː", "ll": "lː", "rr": "rː",# Affricate"ts": "ts",14 unmodified lines"i̯": "j", # palatal glide (U+0069 U+032F)"u̯": "w", # labial glide (U+0075 U+032F)# Stops"p": "p", "b": "b", "t": "t", "d": "d", "k": "k", "g": "g","q": "kʷ", # labiovelar (rare, archaic)# Sonorants"m": "m", "n": "n", "l": "l", "r": "r",42 unmodified lines"ʔ": "ʔ", "ŋ": "ŋ", "ɲ": "ɲ","ā": "aː", "ē": "eː", "ī": "iː", "ō": "oː", "ū": "uː",# Standard"b": "b", "d": "d", "g": "g", "k": "k", "l": "l", "m": "m","n": "n", "p": "p", "r": "r", "s": "s", "t": "t", "w": "w", "y": "j", "z": "z","a": "a", "e": "e", "i": "i", "o": "o", "u": "u","h": "h",25 unmodified lines# Affricates"c": "ts",# Standard consonants (identity)"b": "b", "d": "d", "g": "g", "k": "k", "l": "l", "m": "m","n": "n", "p": "p", "r": "r", "s": "s", "t": "t", "v": "v","z": "z", "x": "x", "j": "j",# Vowels24 unmodified lines# Velar fricative"x": "x",# Standard"b": "b", "d": "d", "g": "g", "k": "k", "l": "l", "m": "m","n": "n", "p": "p", "r": "r", "s": "s", "t": "t", "y": "j", "z": "z","a": "a", "e": "e", "i": "i", "o": "o", "u": "u",}8 unmodified lines# Long vowels"ā": "aː", "ē": "eː", "ī": "iː", "ō": "oː", "ū": "uː",# Labiovelars"kʷ": "kʷ", "gʷ": "gʷ",# Aspirates (from PIE)"bʰ": "bʰ", "dʰ": "dʰ", "gʰ": "gʰ", "gʷʰ": "gʷʰ",# Fricatives"θ": "θ", "ð": "ð", "β": "β","f": "f",# Already-IPA characters that appear in Wiktionary notation"ɣ": "ɣ", "ə": "ə",# Standard"b": "b", "d": "d", "g": "g", "k": "k", "l": "l", "m": "m","n": "n", "p": "p", "r": "r", "s": "s", "t": "t", "w": "w","j": "j", "h": "h", "z": "z","a": "a", "e": "e", "i": "i", "o": "o", "u": "u",11 unmodified lines"py": "pʲ", "ky": "kʲ", "ty": "tʲ", "ny": "ɲ","my": "mʲ", "ry": "ɾʲ", "sy": "ɕ",# Standard consonants"p": "p", "b": "b", "t": "t", "d": "d", "k": "k", "g": "g","s": "s", "z": "z", "m": "m", "n": "n", "r": "ɾ","w": "w", "y": "j", "h": "h",# Long vowels35 unmodified lines# Uppercase passthrough (occasional in reconstructions)"B": "b", "C": "ts", "W": "w",# Standard consonants"b": "b", "d": "d", "f": "f", "g": "g", "h": "h","j": "j", "k": "k", "l": "l", "m": "m", "n": "n","p": "p", "r": "r", "s": "s", "t": "t", "w": "w", "z": "z",# Vowels17 unmodified lines# Digraphs"rs": "rs", "st": "st",# Standard Celtic consonants"b": "b", "d": "d", "g": "g", "k": "k", "l": "l", "m": "m","n": "n", "p": "p", "r": "r", "s": "s", "t": "t", "w": "w","a": "a", "e": "e", "i": "i", "o": "o", "u": "u","z": "z",18 unmodified lines"s\u00b9": "s", "s\u00b2": "\u026c", "s\u00b3": "ts","\u015b": "\u026c", # alternative notation for s2# Standard consonants"b": "b", "d": "d", "f": "f", "g": "g", "h": "h","k": "k", "l": "l", "m": "m", "n": "n","q": "q", "r": "r", "s": "s", "t": "t","w": "w", "y": "j", "z": "z",105 unmodified lines# Open/mid vowels"ɔ": "ɔ", "ɛ": "ɛ", "ə": "ə", "ɨ": "ɨ",# Standard consonants"b": "b", "c": "c", "d": "d", "g": "g", "h": "h","j": "j", "k": "k", "l": "l", "m": "m", "n": "n","p": "p", "r": "r", "s": "s", "t": "t", "w": "w",# Vowels18 unmodified lines# Standard consonants (small inventory)"f": "f", "h": "h", "k": "k", "l": "l", "m": "m","n": "n", "p": "p", "r": "r", "s": "s", "t": "t","w": "w", "q": "q",# Vowels"a": "a", "e": "e", "i": "i", "o": "o", "u": "u",}17 unmodified lines"ŋ": "ŋ",# Palatal stop / fricative"ɟ": "ɟ", "ɕ": "ɕ", "ɲ": "ɲ",# IPA g variant"ɡ": "g",# Velar/uvular fricatives"ɣ": "ɣ", "χ": "χ",# Close-mid back unrounded vowel"ɤ": "ɤ",# Velar approximant"ɰ": "ɰ",# Glottal stop (modifier form)"ʔ": "ʔ", "ˀ": "ʔ",# Schwa"ə": "ə",# Long vowels11 unmodified lines# Combining diacritics (voiceless/voiced ring below — passthrough)"\u0325": "\u0325", "\u0329": "\u0329", "\u032C": "\u032C",# Standard consonants"b": "b", "c": "c", "d": "d", "f": "f", "g": "g","h": "h", "j": "j", "k": "k", "l": "l", "m": "m","n": "n", "p": "p", "r": "r", "s": "s", "t": "t","v": "v", "w": "w", "x": "x", "z": "z", "q": "q",19 unmodified lines"c": "tɕ", "j": "j",# Retroflex"ṣ": "ʂ",# Schwas and special vowels"ä": "ə", "ə": "ə",# Velar fricative1 unmodified line# Labiovelars"kʷ": "kʷ",# Standard consonants"b": "b", "d": "d", "g": "g", "k": "k", "l": "l","m": "m", "n": "n", "p": "p", "r": "r", "s": "s","t": "t", "w": "w", "y": "j",# Vowels13 unmodified lines"ñ": "ɲ", "nj": "ɲ",# Special consonants"ŋ": "ŋ","q": "q","R": "r", # *R = uvular or retroflex trill in some notations"ʀ": "ʀ", # IPA uvular trill (used in some Oceanic entries)"j": "dʒ",2 unmodified lines# Long vowels (if marked)"ā": "aː", "ē": "eː", "ī": "iː", "ō": "oː", "ū": "uː",# Standard consonants"b": "b", "d": "d", "g": "g", "k": "k", "l": "l","m": "m", "n": "n", "p": "p", "r": "r", "s": "s","t": "t", "w": "w", "y": "j",# Vowels51 unmodified lines"s": "s", "\u0161": "\u0283", "\u1e2b": "x", "h": "h",# Semivowels"w": "w", "y": "j",# Word divider (Meroitic uses : as word separator)":": "",# Alternate scholarly notations1563 unmodified lines1564156515661567156815691570157199 unmodified lines167116721673167416751676167716784 unmodified lines168316841685168616871688168916901691169216931694169525 unmodified lines172117221723172417251726172717 unmodified lines174517461747174817491750175113 unmodified lines176517661767176817691770177110 unmodified lines178217831784178517861787178810 unmodified lines179918001801180218031804180514 unmodified lines182018211822182318241825182642 unmodified lines186918701871187218731874187525 unmodified lines190119021903190419051906190724 unmodified lines19321933193419351936193719388 unmodified lines194719481949195019511952195319541955195619571958195919601961196211 unmodified lines197419751976197719781979198035 unmodified lines201620172018201920202021202217 unmodified lines204020412042204320442045204618 unmodified lines2065206620672068206920702071105 unmodified lines217721782179218021812182218318 unmodified lines220222032204220522062207220817 unmodified lines22262227222822292230223122322233223422352236223722382239224011 unmodified lines225222532254225522562257225819 unmodified lines22782279228022812282228322842285228622871 unmodified line228922902291229222932294229513 unmodified lines23092310231123122313231423152 unmodified lines231823192320232123222323232451 unmodified lines237623772378237923802381238223831563 unmodified lines"v": "w",# <y> as semivowel"y": "j",# Explicit g → IPA ɡ (U+0261) — prevents ASCII g passthrough"g": "ɡ",}# ---------------------------------------------------------------------------99 unmodified lines# Consonants"þ": "θ", "ð": "ð","hw": "xʷ",# Explicit g → IPA ɡ (U+0261) — prevents ASCII g passthrough"g": "ɡ",}# ---------------------------------------------------------------------------4 unmodified lines# Long vowels"ā": "aː", "ē": "eː", "ī": "iː", "ō": "oː", "ū": "uː",# Labiovelar"kʷ": "kʷ", "gʷ": "ɡʷ",# Aspirated (from PIE)"bʰ": "bʰ", "dʰ": "dʰ", "gʰ": "ɡʰ",# Laryngeals sometimes preserved in notation"x": "x",# Standard consonants (g passthrough fix)"g": "ɡ",}# ---------------------------------------------------------------------------25 unmodified lines# ONCOJ conventions → IPA"py": "pʲ", "ky": "kʲ", "sy": "ɕ", "ty": "tɕ", "ny": "ɲ","my": "mʲ", "ry": "ɾʲ","p": "p", "b": "b", "t": "t", "d": "d", "k": "k", "g": "ɡ","s": "s", "z": "z", "m": "m", "n": "n", "r": "ɾ","w": "w", "y": "j",# Long vowels (ONCOJ sometimes marks with macron)17 unmodified lines"ẏ": "j", "ẇ": "w", "ṯ": "θ", "δ": "ð","ʾ": "ʔ",# Standard (identity-like)"b": "b", "d": "d", "f": "f", "g": "ɡ", "h": "h","j": "dʒ", "k": "k", "l": "l", "m": "m", "n": "n","p": "p", "r": "r", "s": "s", "t": "t", "w": "w", "y": "j", "z": "z",}13 unmodified lines"ṯ": "θ", "ʾ": "ʔ","ny": "ɲ", "ng": "ŋ",# Standard"b": "b", "d": "d", "f": "f", "g": "ɡ", "h": "h","j": "dʒ", "k": "k", "l": "l", "m": "m", "n": "n","p": "p", "r": "r", "s": "s", "t": "t", "w": "w", "y": "j", "z": "z",}10 unmodified lines"χ": "x", "ð": "ð", "θ": "θ","ā": "aː", "ē": "eː", "ī": "iː", "ō": "oː", "ū": "uː",# Standard"b": "b", "d": "d", "g": "ɡ", "k": "k", "l": "l", "m": "m","n": "n", "p": "p", "r": "r", "s": "s", "t": "t", "w": "w","a": "a", "e": "e", "i": "i", "o": "o", "u": "u","x": "x",10 unmodified linesLEPONTIC_MAP: Dict[str, str] = {# Geminates / long consonants (must precede singles for greedy match)"pp": "pː", "bb": "bː", "tt": "tː", "dd": "dː","kk": "kː", "gg": "ɡː","mm": "mː", "nn": "nː", "ll": "lː", "rr": "rː",# Affricate"ts": "ts",14 unmodified lines"i̯": "j", # palatal glide (U+0069 U+032F)"u̯": "w", # labial glide (U+0075 U+032F)# Stops"p": "p", "b": "b", "t": "t", "d": "d", "k": "k", "g": "ɡ","q": "kʷ", # labiovelar (rare, archaic)# Sonorants"m": "m", "n": "n", "l": "l", "r": "r",42 unmodified lines"ʔ": "ʔ", "ŋ": "ŋ", "ɲ": "ɲ","ā": "aː", "ē": "eː", "ī": "iː", "ō": "oː", "ū": "uː",# Standard"b": "b", "d": "d", "g": "ɡ", "k": "k", "l": "l", "m": "m","n": "n", "p": "p", "r": "r", "s": "s", "t": "t", "w": "w", "y": "j", "z": "z","a": "a", "e": "e", "i": "i", "o": "o", "u": "u","h": "h",25 unmodified lines# Affricates"c": "ts",# Standard consonants (identity)"b": "b", "d": "d", "g": "ɡ", "k": "k", "l": "l", "m": "m","n": "n", "p": "p", "r": "r", "s": "s", "t": "t", "v": "v","z": "z", "x": "x", "j": "j",# Vowels24 unmodified lines# Velar fricative"x": "x",# Standard"b": "b", "d": "d", "g": "ɡ", "k": "k", "l": "l", "m": "m","n": "n", "p": "p", "r": "r", "s": "s", "t": "t", "y": "j", "z": "z","a": "a", "e": "e", "i": "i", "o": "o", "u": "u",}8 unmodified lines# Long vowels"ā": "aː", "ē": "eː", "ī": "iː", "ō": "oː", "ū": "uː",# Labiovelars"kʷ": "kʷ", "gʷ": "ɡʷ",# Aspirates (from PIE)"bʰ": "bʰ", "dʰ": "dʰ", "gʰ": "ɡʰ", "gʷʰ": "ɡʷʰ",# Fricatives"θ": "θ", "ð": "ð", "β": "β","f": "f",# Already-IPA characters that appear in Wiktionary notation"ɣ": "ɣ", "ə": "ə",# Standard"b": "b", "d": "d", "g": "ɡ", "k": "k", "l": "l", "m": "m","n": "n", "p": "p", "r": "r", "s": "s", "t": "t", "w": "w","j": "j", "h": "h", "z": "z","a": "a", "e": "e", "i": "i", "o": "o", "u": "u",11 unmodified lines"py": "pʲ", "ky": "kʲ", "ty": "tʲ", "ny": "ɲ","my": "mʲ", "ry": "ɾʲ", "sy": "ɕ",# Standard consonants"p": "p", "b": "b", "t": "t", "d": "d", "k": "k", "g": "ɡ","s": "s", "z": "z", "m": "m", "n": "n", "r": "ɾ","w": "w", "y": "j", "h": "h",# Long vowels35 unmodified lines# Uppercase passthrough (occasional in reconstructions)"B": "b", "C": "ts", "W": "w",# Standard consonants"b": "b", "d": "d", "f": "f", "g": "ɡ", "h": "h","j": "j", "k": "k", "l": "l", "m": "m", "n": "n","p": "p", "r": "r", "s": "s", "t": "t", "w": "w", "z": "z",# Vowels17 unmodified lines# Digraphs"rs": "rs", "st": "st",# Standard Celtic consonants"b": "b", "d": "d", "g": "ɡ", "k": "k", "l": "l", "m": "m","n": "n", "p": "p", "r": "r", "s": "s", "t": "t", "w": "w","a": "a", "e": "e", "i": "i", "o": "o", "u": "u","z": "z",18 unmodified lines"s\u00b9": "s", "s\u00b2": "\u026c", "s\u00b3": "ts","\u015b": "\u026c", # alternative notation for s2# Standard consonants"b": "b", "d": "d", "f": "f", "g": "ɡ", "h": "h","k": "k", "l": "l", "m": "m", "n": "n","q": "q", "r": "r", "s": "s", "t": "t","w": "w", "y": "j", "z": "z",105 unmodified lines# Open/mid vowels"ɔ": "ɔ", "ɛ": "ɛ", "ə": "ə", "ɨ": "ɨ",# Standard consonants"b": "b", "c": "c", "d": "d", "g": "ɡ", "h": "h","j": "j", "k": "k", "l": "l", "m": "m", "n": "n","p": "p", "r": "r", "s": "s", "t": "t", "w": "w",# Vowels18 unmodified lines# Standard consonants (small inventory)"f": "f", "h": "h", "k": "k", "l": "l", "m": "m","n": "n", "p": "p", "r": "r", "s": "s", "t": "t","w": "w", "q": "ʔ",# Vowels"a": "a", "e": "e", "i": "i", "o": "o", "u": "u",}17 unmodified lines"ŋ": "ŋ",# Palatal stop / fricative"ɟ": "ɟ", "ɕ": "ɕ", "ɲ": "ɲ",# Glottal stop"ʔ": "ʔ", "ˀ": "ʔ",# Velar/uvular fricatives"ɣ": "ɣ", "χ": "χ",# Close-mid back unrounded vowel"ɤ": "ɤ",# Velar approximant"ɰ": "ɰ",# Glottal stop (modifier form — already handled above)# Schwa"ə": "ə",# Long vowels11 unmodified lines# Combining diacritics (voiceless/voiced ring below — passthrough)"\u0325": "\u0325", "\u0329": "\u0329", "\u032C": "\u032C",# Standard consonants"b": "b", "c": "c", "d": "d", "f": "f", "g": "ɡ","h": "h", "j": "j", "k": "k", "l": "l", "m": "m","n": "n", "p": "p", "r": "r", "s": "s", "t": "t","v": "v", "w": "w", "x": "x", "z": "z", "q": "q",19 unmodified lines"c": "tɕ", "j": "j",# Retroflex"ṣ": "ʂ",# Missing diacritics (Adams 2013, Winter 1992)"ñ": "ɲ", "ć": "tɕ", "ë": "ə",# Accented vowels (strip accent to plain vowel)"á": "a", "é": "e", "í": "i", "ó": "o", "ú": "u",# Schwas and special vowels"ä": "ə", "ə": "ə",# Velar fricative1 unmodified line# Labiovelars"kʷ": "kʷ",# Standard consonants"b": "b", "d": "d", "g": "ɡ", "k": "k", "l": "l","m": "m", "n": "n", "p": "p", "r": "r", "s": "s","t": "t", "w": "w", "y": "j",# Vowels13 unmodified lines"ñ": "ɲ", "nj": "ɲ",# Special consonants"ŋ": "ŋ","q": "ʔ","R": "r", # *R = uvular or retroflex trill in some notations"ʀ": "ʀ", # IPA uvular trill (used in some Oceanic entries)"j": "dʒ",2 unmodified lines# Long vowels (if marked)"ā": "aː", "ē": "eː", "ī": "iː", "ō": "oː", "ū": "uː",# Standard consonants"b": "b", "d": "d", "g": "ɡ", "k": "k", "l": "l","m": "m", "n": "n", "p": "p", "r": "r", "s": "s","t": "t", "w": "w", "y": "j",# Vowels51 unmodified lines"s": "s", "\u0161": "\u0283", "\u1e2b": "x", "h": "h",# Semivowels"w": "w", "y": "j",# Explicit g → IPA ɡ (U+0261) — guard against ASCII g in source data"g": "ɡ",# Word divider (Meroitic uses : as word separator)":": "",# Alternate scholarly notations
.gitattributes+2
data/training/cognate_pairs/cognate_pairs_borrowing.tsvAdded+3
data/training/cognate_pairs/cognate_pairs_inherited.tsvAdded+3
data/training/cognate_pairs/cognate_pairs_similarity.tsvAdded+3
data/training/lexicons/aav-pro.tsv+2-2
data/training/lexicons/ang.tsv+2-2
data/training/lexicons/cel-pro.tsv+2-2
data/training/lexicons/cop.tsv+2-2
data/training/lexicons/gem-pro.tsv+2-2
data/training/lexicons/hbo.tsv+2-2
data/training/lexicons/ira-pro.tsv+2-2
data/training/lexicons/itc-pro.tsv+2-2
data/training/lexicons/nci.tsv+2-2
data/training/lexicons/ojp.tsv+2-2
data/training/lexicons/osc.tsv+2-2
data/training/lexicons/pal.tsv+2-2
data/training/lexicons/poz-oce-pro.tsv+2-2
data/training/lexicons/poz-pol-pro.tsv+2-2
data/training/lexicons/sga.tsv+2-2
data/training/lexicons/sit-pro.tsv+2-2
data/training/lexicons/sla-pro.tsv+2-2
data/training/lexicons/tai-pro.tsv+2-2
data/training/lexicons/trk-pro.tsv+2-2
data/training/lexicons/xce.tsv+2-2
data/training/lexicons/xfa.tsv+2-2
data/training/lexicons/xlp.tsv+2-2
data/training/lexicons/xmr.tsv+2-2
data/training/lexicons/xsa.tsv+2-2
data/training/lexicons/xtg.tsv+2-2
data/training/lexicons/xto-pro.tsv+2-2
data/training/lexicons/xum.tsv+2-2
docs/DATABASE_REFERENCE.md+24
docs/prd/PRD_COGNATE_PAIRS_V2.mdAdded+291
scripts/cleanup_phase8_audit.pyAdded+308
scripts/extract_abvd_cognates_v2.pyAdded+183
scripts/extract_iecor_cognates.pyAdded+178
scripts/extract_sinotibetan_cognates_v2.pyAdded+163
scripts/extract_wold_borrowings_v2.pyAdded+203
scripts/merge_cognate_pairs.pyAdded+179
scripts/rebuild_concept_aligned_pairs.pyAdded+178
scripts/transliteration_maps.py+39-31