samename 0.1.3__py3-none-any.whl
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.
- samename/__init__.py +18 -0
- samename/__main__.py +3 -0
- samename/cli.py +186 -0
- samename/distance.py +242 -0
- samename/index.py +150 -0
- samename/lexicon.py +637 -0
- samename/match.py +423 -0
- samename/parse.py +193 -0
- samename/phonemes.py +302 -0
- samename-0.1.3.dist-info/METADATA +381 -0
- samename-0.1.3.dist-info/RECORD +15 -0
- samename-0.1.3.dist-info/WHEEL +5 -0
- samename-0.1.3.dist-info/entry_points.txt +2 -0
- samename-0.1.3.dist-info/licenses/LICENSE +21 -0
- samename-0.1.3.dist-info/top_level.txt +1 -0
samename/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""samename - match East Slavic personal names across scripts, romanizations and languages.
|
|
2
|
+
|
|
3
|
+
>>> import samename
|
|
4
|
+
>>> samename.is_match("Володимир Зеленський", "Vladimir Zelensky")
|
|
5
|
+
True
|
|
6
|
+
>>> samename.is_match("Oleksandr Kovalenko", "Oleksii Kovalenko")
|
|
7
|
+
False
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from .index import NameIndex, dedupe
|
|
11
|
+
from .match import DEFAULT_THRESHOLD, Match, compare, is_match, keys, score
|
|
12
|
+
from .parse import parse_name
|
|
13
|
+
|
|
14
|
+
__version__ = "0.1.3"
|
|
15
|
+
__all__ = [
|
|
16
|
+
"compare", "score", "is_match", "keys", "parse_name",
|
|
17
|
+
"Match", "NameIndex", "dedupe", "DEFAULT_THRESHOLD", "__version__",
|
|
18
|
+
]
|
samename/__main__.py
ADDED
samename/cli.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Command line interface: ``samename compare | key | search | dedupe``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import csv
|
|
7
|
+
import json
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .index import NameIndex, dedupe
|
|
12
|
+
from .match import DEFAULT_THRESHOLD, compare, keys
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _fail(message: str):
|
|
16
|
+
"""Report a usage error: message on stderr, exit code 2."""
|
|
17
|
+
print(f"samename: {message}", file=sys.stderr)
|
|
18
|
+
raise SystemExit(2)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
#: First-row cells that mark a header row (compared case-insensitively, with
|
|
22
|
+
#: spaces and hyphens read as "_"), for a CSV / TSV column chosen by number or
|
|
23
|
+
#: a single-column file read without --column.
|
|
24
|
+
HEADER_WORDS = frozenset({
|
|
25
|
+
"name", "names", "full_name", "fullname", "person", "person_name", "personal_name",
|
|
26
|
+
"first_name", "given_name", "last_name", "surname", "family_name", "patronymic",
|
|
27
|
+
"middle_name", "name_surname", "surname_name",
|
|
28
|
+
"імя", "ім'я", "прізвище", "піб", "по_батькові", "імя_по_батькові",
|
|
29
|
+
"имя", "фамилия", "фио", "отчество", "ф.и.о.", "п.і.б.",
|
|
30
|
+
"імя_прозвішча", "прозвішча", "імя_і_прозвішча",
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _is_header(cell: str) -> bool:
|
|
35
|
+
key = cell.strip().lower().replace("’", "'").replace("ʼ", "'")
|
|
36
|
+
key = "_".join(key.replace("-", " ").split())
|
|
37
|
+
return key in HEADER_WORDS
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _read_names(path: str, column, has_header=None):
|
|
41
|
+
"""Read names from a text file (one per line) or a CSV / TSV column.
|
|
42
|
+
|
|
43
|
+
Header rule for CSV / TSV files: a column given by name always skips the
|
|
44
|
+
header row. Otherwise (a column given by 0-based number, or a one-column
|
|
45
|
+
file without --column) the first row is skipped when ``has_header`` is True,
|
|
46
|
+
kept when it is False, and, by default (None), skipped only if its cell is
|
|
47
|
+
a header word such as ``name`` or ``full_name`` (see :data:`HEADER_WORDS`).
|
|
48
|
+
"""
|
|
49
|
+
try:
|
|
50
|
+
with open(path, encoding="utf-8-sig", newline="") as fh:
|
|
51
|
+
if column is None and not path.lower().endswith((".csv", ".tsv")):
|
|
52
|
+
return [line.strip() for line in fh if line.strip()]
|
|
53
|
+
dialect = "excel-tab" if path.lower().endswith(".tsv") else "excel"
|
|
54
|
+
rows = [r for r in csv.reader(fh, dialect) if r]
|
|
55
|
+
except OSError as exc:
|
|
56
|
+
_fail(f"cannot read {path!r}: {exc.strerror or exc}")
|
|
57
|
+
except UnicodeDecodeError:
|
|
58
|
+
_fail(f"{path!r} is not UTF-8 text")
|
|
59
|
+
if not rows:
|
|
60
|
+
return []
|
|
61
|
+
header = rows[0]
|
|
62
|
+
width = max(len(r) for r in rows)
|
|
63
|
+
if column is None:
|
|
64
|
+
if width > 1:
|
|
65
|
+
_fail(f"{path!r} has {width} columns; choose one with --column (header is {header})")
|
|
66
|
+
col = 0
|
|
67
|
+
elif column.isdigit():
|
|
68
|
+
col = int(column)
|
|
69
|
+
if col >= width:
|
|
70
|
+
_fail(f"column {col} is out of range; {path!r} has {width} column(s), numbered from 0")
|
|
71
|
+
elif column in header:
|
|
72
|
+
col = header.index(column)
|
|
73
|
+
else:
|
|
74
|
+
_fail(f"column {column!r} not found; header is {header}")
|
|
75
|
+
if column is not None and not column.isdigit():
|
|
76
|
+
skip = True
|
|
77
|
+
elif has_header is None:
|
|
78
|
+
skip = len(header) > col and _is_header(header[col])
|
|
79
|
+
else:
|
|
80
|
+
skip = has_header
|
|
81
|
+
body = rows[1:] if skip else rows
|
|
82
|
+
return [r[col].strip() for r in body if len(r) > col and r[col].strip()]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _add_file_options(parser):
|
|
86
|
+
parser.add_argument("-c", "--column", help="CSV column name or 0-based number")
|
|
87
|
+
g = parser.add_mutually_exclusive_group()
|
|
88
|
+
g.add_argument("--header", dest="has_header", action="store_true", default=None,
|
|
89
|
+
help="the CSV first row is a header (default: only if it reads like one, e.g. full_name)")
|
|
90
|
+
g.add_argument("--no-header", dest="has_header", action="store_false",
|
|
91
|
+
help="the CSV first row is a name, not a header")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _add_options(parser, compare_options=True):
|
|
95
|
+
parser.add_argument("--no-cross-language", action="store_true",
|
|
96
|
+
help="do not equate Ukrainian / Russian / Belarusian forms of a given name")
|
|
97
|
+
parser.add_argument("--diminutives", action="store_true",
|
|
98
|
+
help="accept short forms for full names (Sasha = Oleksandr)")
|
|
99
|
+
if compare_options:
|
|
100
|
+
parser.add_argument("--gender-insensitive-surnames", action="store_true",
|
|
101
|
+
help="accept Ivanov / Ivanova as the same surname")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _options(args, compare_options=True) -> dict:
|
|
105
|
+
out = {"cross_language": not args.no_cross_language, "diminutives": args.diminutives}
|
|
106
|
+
if compare_options:
|
|
107
|
+
out["gender_insensitive_surnames"] = args.gender_insensitive_surnames
|
|
108
|
+
return out
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def main(argv=None) -> int:
|
|
112
|
+
for stream in (sys.stdout, sys.stderr):
|
|
113
|
+
try:
|
|
114
|
+
stream.reconfigure(encoding="utf-8")
|
|
115
|
+
except (AttributeError, ValueError):
|
|
116
|
+
pass
|
|
117
|
+
|
|
118
|
+
p = argparse.ArgumentParser(
|
|
119
|
+
prog="samename",
|
|
120
|
+
description="Match East Slavic personal names across Cyrillic, Latin romanizations and languages.",
|
|
121
|
+
epilog="Exit codes: 0 = match / hits found, 1 = no match / no hits, 2 = usage or file error.")
|
|
122
|
+
p.add_argument("--version", action="version", version=f"samename {__version__}")
|
|
123
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
124
|
+
|
|
125
|
+
c = sub.add_parser("compare", help="compare two names")
|
|
126
|
+
c.add_argument("a")
|
|
127
|
+
c.add_argument("b")
|
|
128
|
+
c.add_argument("--json", action="store_true")
|
|
129
|
+
c.add_argument("-t", "--threshold", type=float, default=DEFAULT_THRESHOLD)
|
|
130
|
+
_add_options(c)
|
|
131
|
+
|
|
132
|
+
k = sub.add_parser("key", help="print the script-independent blocking keys of a name")
|
|
133
|
+
k.add_argument("name")
|
|
134
|
+
_add_options(k, compare_options=False)
|
|
135
|
+
|
|
136
|
+
s = sub.add_parser("search", help="find a name in a file of names")
|
|
137
|
+
s.add_argument("file")
|
|
138
|
+
s.add_argument("query")
|
|
139
|
+
_add_file_options(s)
|
|
140
|
+
s.add_argument("-n", "--limit", type=int, default=10)
|
|
141
|
+
s.add_argument("-m", "--min-score", type=float, default=0.7)
|
|
142
|
+
s.add_argument("--json", action="store_true")
|
|
143
|
+
_add_options(s)
|
|
144
|
+
|
|
145
|
+
d = sub.add_parser("dedupe", help="group names in a file that refer to the same person")
|
|
146
|
+
d.add_argument("file")
|
|
147
|
+
_add_file_options(d)
|
|
148
|
+
d.add_argument("-t", "--threshold", type=float, default=DEFAULT_THRESHOLD)
|
|
149
|
+
d.add_argument("--json", action="store_true")
|
|
150
|
+
_add_options(d)
|
|
151
|
+
|
|
152
|
+
args = p.parse_args(argv)
|
|
153
|
+
|
|
154
|
+
if args.cmd == "compare":
|
|
155
|
+
m = compare(args.a, args.b, args.threshold, **_options(args))
|
|
156
|
+
print(json.dumps(m.to_dict(), ensure_ascii=False, indent=2) if args.json else m.explain())
|
|
157
|
+
return 0 if m.is_match else 1
|
|
158
|
+
|
|
159
|
+
if args.cmd == "key":
|
|
160
|
+
print(" ".join(keys(args.name, **_options(args, compare_options=False))))
|
|
161
|
+
return 0
|
|
162
|
+
|
|
163
|
+
names = _read_names(args.file, args.column, args.has_header)
|
|
164
|
+
if args.cmd == "search":
|
|
165
|
+
hits = NameIndex(names, **_options(args)).search(args.query, args.limit, args.min_score)
|
|
166
|
+
if args.json:
|
|
167
|
+
print(json.dumps([{"name": n, "score": round(sc, 4)} for n, sc in hits], ensure_ascii=False, indent=2))
|
|
168
|
+
else:
|
|
169
|
+
for n, sc in hits:
|
|
170
|
+
print(f"{sc:.2f} {n}")
|
|
171
|
+
return 0 if hits else 1
|
|
172
|
+
|
|
173
|
+
clusters = dedupe(names, args.threshold, **_options(args))
|
|
174
|
+
if args.json:
|
|
175
|
+
print(json.dumps([[names[i] for i in g] for g in clusters], ensure_ascii=False, indent=2))
|
|
176
|
+
else:
|
|
177
|
+
for n, g in enumerate(clusters, 1):
|
|
178
|
+
print(f"# group {n}")
|
|
179
|
+
for i in g:
|
|
180
|
+
print(f" {names[i]}")
|
|
181
|
+
print(f"{len(clusters)} group(s) of likely duplicates among {len(names)} names", file=sys.stderr)
|
|
182
|
+
return 0
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
if __name__ == "__main__":
|
|
186
|
+
raise SystemExit(main())
|
samename/distance.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
"""Weighted phonetic edit distance between two phoneme sequences.
|
|
2
|
+
|
|
3
|
+
Unlike an abjad, Cyrillic writes its vowels, so vowels carry real information
|
|
4
|
+
here: only the vowel changes that romanization and the Ukrainian / Russian /
|
|
5
|
+
Belarusian sound correspondences actually produce are cheap.
|
|
6
|
+
|
|
7
|
+
* i / y (и, і, ы) are nearly free; a / o (akanye), e / i (Сергій / Сергей),
|
|
8
|
+
e / o (ё written as е) are cheap; a / i or u / y are not confusable at all.
|
|
9
|
+
* g / h (the letter г), h / kh, v / f / w, s / z, ts / s, sh / s and the like
|
|
10
|
+
are cheap between scripts, because romanization systems disagree on them.
|
|
11
|
+
Between two Cyrillic spellings only the cross-language pairs are allowed.
|
|
12
|
+
* The glide "j" is cheap wherever romanizations drop it (Yevhen / Evhen,
|
|
13
|
+
Lyudmila / Ludmila, Yuriy / Yuri) and expensive elsewhere.
|
|
14
|
+
* A final "a" is never dropped cheaply: it is what separates Ivanov from
|
|
15
|
+
Ivanova and Oleksandr from Oleksandra.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from itertools import islice, product
|
|
21
|
+
|
|
22
|
+
INF = 99.0
|
|
23
|
+
_ALT = 0.08 # using a secondary reading of an ambiguous Latin spelling
|
|
24
|
+
_FINAL_A = 2.5 # dropping the vowel that marks a feminine form
|
|
25
|
+
_FINAL_V = 1.0
|
|
26
|
+
|
|
27
|
+
_CONS_PAIRS = {
|
|
28
|
+
("g", "h"): 0.15, ("g", "ɣ"): 0.0, ("h", "ɣ"): 0.0, ("h", "x"): 0.15, ("ɣ", "x"): 0.5,
|
|
29
|
+
("k", "x"): 0.4, ("v", "f"): 0.25, ("v", "w"): 0.05, ("f", "w"): 0.3,
|
|
30
|
+
("s", "z"): 0.35, ("s", "c"): 0.3, ("z", "c"): 0.4, ("c", "č"): 0.35, ("c", "t"): 0.4,
|
|
31
|
+
("s", "š"): 0.4, ("z", "ž"): 0.4, ("š", "ž"): 0.3, ("š", "č"): 0.35,
|
|
32
|
+
("d", "t"): 0.6, ("b", "p"): 0.6, ("g", "k"): 0.6, ("m", "n"): 0.7,
|
|
33
|
+
}
|
|
34
|
+
# what differs between the Ukrainian, Russian and Belarusian spelling of one name
|
|
35
|
+
_CROSS_LANGUAGE = {("g", "h"), ("g", "ɣ"), ("h", "ɣ"), ("v", "w"), ("c", "t")}
|
|
36
|
+
_VOWEL_PAIRS = {
|
|
37
|
+
("i", "y"): 0.05, ("a", "o"): 0.35, ("e", "i"): 0.35, ("e", "y"): 0.35,
|
|
38
|
+
("e", "o"): 0.3, ("o", "i"): 0.5, ("a", "e"): 0.6, ("o", "u"): 0.6,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
CONS, CONS_CY, VOWELS = {}, {}, {}
|
|
42
|
+
for (_a, _b), _c in _CONS_PAIRS.items():
|
|
43
|
+
CONS[(_a, _b)] = CONS[(_b, _a)] = _c
|
|
44
|
+
if (_a, _b) in _CROSS_LANGUAGE:
|
|
45
|
+
CONS_CY[(_a, _b)] = CONS_CY[(_b, _a)] = _c
|
|
46
|
+
for (_a, _b), _c in _VOWEL_PAIRS.items():
|
|
47
|
+
VOWELS[(_a, _b)] = VOWELS[(_b, _a)] = _c
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def weight(x) -> float:
|
|
51
|
+
"""Context-free weight of a phoneme, used to normalise the distance."""
|
|
52
|
+
if x.t == "V":
|
|
53
|
+
return 0.7
|
|
54
|
+
if x.p == "j":
|
|
55
|
+
return 0.2
|
|
56
|
+
return 0.5 if x.p == "w" else 1.0
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def sub_cost(x, y) -> float:
|
|
60
|
+
if x.t == "V" and y.t == "V":
|
|
61
|
+
if x.p == y.p:
|
|
62
|
+
return 0.0
|
|
63
|
+
return VOWELS.get((x.p, y.p), INF)
|
|
64
|
+
if x.t == "C" and y.t == "C":
|
|
65
|
+
if x.p == y.p:
|
|
66
|
+
return 0.0
|
|
67
|
+
table = CONS_CY if (x.src == "cy" and y.src == "cy") else CONS
|
|
68
|
+
best = table.get((x.p, y.p), INF)
|
|
69
|
+
if x.alt or y.alt:
|
|
70
|
+
for i, a in enumerate((x.p,) + x.alt):
|
|
71
|
+
for j, b in enumerate((y.p,) + y.alt):
|
|
72
|
+
if i == 0 and j == 0:
|
|
73
|
+
continue
|
|
74
|
+
c = 0.0 if a == b else table.get((a, b), INF)
|
|
75
|
+
c += _ALT * ((i > 0) + (j > 0))
|
|
76
|
+
if c < best:
|
|
77
|
+
best = c
|
|
78
|
+
return best
|
|
79
|
+
c, v = (x, y) if x.t == "C" else (y, x)
|
|
80
|
+
if c.p == "j" and v.p in "iy":
|
|
81
|
+
return 0.0 if v.glide else 0.1
|
|
82
|
+
if v.p == "u":
|
|
83
|
+
if c.p == "w":
|
|
84
|
+
return 0.05
|
|
85
|
+
if c.p == "v":
|
|
86
|
+
return 0.3
|
|
87
|
+
return INF
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _del_costs(seq) -> list:
|
|
91
|
+
"""Cost of leaving each phoneme of ``seq`` without a partner."""
|
|
92
|
+
n = len(seq)
|
|
93
|
+
out = []
|
|
94
|
+
for i, x in enumerate(seq):
|
|
95
|
+
prev = seq[i - 1] if i else None
|
|
96
|
+
nxt = seq[i + 1] if i + 1 < n else None
|
|
97
|
+
last = nxt is None
|
|
98
|
+
if x.t == "C":
|
|
99
|
+
if x.p == "j":
|
|
100
|
+
if prev is None:
|
|
101
|
+
c = 0.05 if (nxt and nxt.p == "e") else 0.1 if (nxt and nxt.p in "iy") else 0.7
|
|
102
|
+
elif prev.t == "C": # marks a soft consonant
|
|
103
|
+
c = 0.8 if (nxt and nxt.p == "a") else 0.1
|
|
104
|
+
elif last:
|
|
105
|
+
c = 0.05 if prev.p in "iy" else 0.25
|
|
106
|
+
elif nxt.t == "V":
|
|
107
|
+
c = 0.1 if prev.p in "iy" else 0.15
|
|
108
|
+
else:
|
|
109
|
+
c = 0.4
|
|
110
|
+
elif x.p == "č" and prev is not None and prev.p == "š":
|
|
111
|
+
c = 0.2 # щ simplified to sh
|
|
112
|
+
elif x.p == "z" and prev is not None and prev.p == "d" and nxt is not None and nxt.t == "V":
|
|
113
|
+
c = 0.5 # Belarusian дз for д
|
|
114
|
+
elif x.p == "w":
|
|
115
|
+
c = 0.5
|
|
116
|
+
else:
|
|
117
|
+
c = 1.0
|
|
118
|
+
else:
|
|
119
|
+
if last and n >= 3:
|
|
120
|
+
if x.p == "a":
|
|
121
|
+
aja = n >= 4 and prev.p == "j" and seq[i - 2].p == "a"
|
|
122
|
+
c = 0.2 if aja else _FINAL_A # -ska / -skaya are one form
|
|
123
|
+
elif x.p == "e" and x.src == "la" and n >= 4 and prev.t == "C" and prev.p != "j":
|
|
124
|
+
c = 0.15 # silent French -e (Alexandre)
|
|
125
|
+
else:
|
|
126
|
+
c = _FINAL_V
|
|
127
|
+
elif x.glide:
|
|
128
|
+
c = 0.8 if (nxt and nxt.p == "a") else 0.15
|
|
129
|
+
elif x.p in "iy" and nxt is not None and nxt.p == "j" and i + 2 < n and seq[i + 2].t == "V":
|
|
130
|
+
c = 0.1 # Mariya / Marya, Nataliya / Natalya
|
|
131
|
+
elif x.p in "iy" and prev is not None and prev.p == "j" and prev.t == "C" and i > 1:
|
|
132
|
+
c = 0.15 # Zaika / Заїка
|
|
133
|
+
elif prev is None:
|
|
134
|
+
c = 0.9
|
|
135
|
+
else:
|
|
136
|
+
c = 0.7
|
|
137
|
+
out.append(c)
|
|
138
|
+
return out
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
_IOTATED = 0.25
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _is_iotated(first, second) -> bool:
|
|
145
|
+
"""Soft consonant + a / o, which other spellings write as plain "e":
|
|
146
|
+
Belarusian Сяргей / Sergey, Пятро / Petro; Russian Фёдор / Fedor."""
|
|
147
|
+
return second.t == "V" and second.p in "ao" and (first.soft or first.glide)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def distance(a, b):
|
|
151
|
+
"""Return ``(distance, weight_a, weight_b)`` for two non-empty sequences."""
|
|
152
|
+
n, m = len(a), len(b)
|
|
153
|
+
da, db = _del_costs(a), _del_costs(b)
|
|
154
|
+
D = [[0.0] * (m + 1) for _ in range(n + 1)]
|
|
155
|
+
for i in range(1, n + 1):
|
|
156
|
+
D[i][0] = D[i - 1][0] + da[i - 1]
|
|
157
|
+
for j in range(1, m + 1):
|
|
158
|
+
D[0][j] = D[0][j - 1] + db[j - 1]
|
|
159
|
+
for i in range(1, n + 1):
|
|
160
|
+
x = a[i - 1]
|
|
161
|
+
row, up = D[i], D[i - 1]
|
|
162
|
+
for j in range(1, m + 1):
|
|
163
|
+
y = b[j - 1]
|
|
164
|
+
best = up[j] + da[i - 1]
|
|
165
|
+
c = row[j - 1] + db[j - 1]
|
|
166
|
+
if c < best:
|
|
167
|
+
best = c
|
|
168
|
+
s = sub_cost(x, y)
|
|
169
|
+
if s < INF:
|
|
170
|
+
c = up[j - 1] + s
|
|
171
|
+
if c < best:
|
|
172
|
+
best = c
|
|
173
|
+
if i >= 2 and y.p == "e" and _is_iotated(a[i - 2], x):
|
|
174
|
+
c = D[i - 2][j - 1] + _IOTATED
|
|
175
|
+
if c < best:
|
|
176
|
+
best = c
|
|
177
|
+
if j >= 2 and x.p == "e" and _is_iotated(b[j - 2], y):
|
|
178
|
+
c = up[j - 2] + _IOTATED
|
|
179
|
+
if c < best:
|
|
180
|
+
best = c
|
|
181
|
+
row[j] = best
|
|
182
|
+
return D[n][m], sum(weight(x) for x in a), sum(weight(x) for x in b)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def similarity(a, b) -> float:
|
|
186
|
+
"""Similarity in [0, 1] between two phoneme sequences."""
|
|
187
|
+
if not a or not b:
|
|
188
|
+
return 1.0 if (not a and not b) else 0.0
|
|
189
|
+
d, wa, wb = distance(a, b)
|
|
190
|
+
w = max(wa, wb)
|
|
191
|
+
if w <= 0:
|
|
192
|
+
return 1.0 if d == 0 else 0.0
|
|
193
|
+
return max(0.0, 1.0 - d / w)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
_KEY = {
|
|
197
|
+
"b": "B", "p": "P", "v": "V", "f": "V", "w": "V", "d": "D", "t": "T",
|
|
198
|
+
"z": "S", "s": "S", "c": "S", "ž": "J", "š": "J", "č": "J",
|
|
199
|
+
"g": "K", "h": "K", "ɣ": "K", "x": "K", "k": "K",
|
|
200
|
+
"l": "L", "m": "M", "n": "N", "r": "R", "j": "",
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def skeletons(seq) -> tuple:
|
|
205
|
+
"""Coarse consonant skeletons of a sequence, used as blocking keys.
|
|
206
|
+
|
|
207
|
+
Usually one; an ambiguous Latin spelling ("ch", "c") yields up to four.
|
|
208
|
+
"""
|
|
209
|
+
options = []
|
|
210
|
+
after_stop = [] # option positions whose consonant directly follows a t / d
|
|
211
|
+
n = len(seq)
|
|
212
|
+
for i, x in enumerate(seq):
|
|
213
|
+
if x.t != "C":
|
|
214
|
+
# a Latin "u" between a vowel and a consonant may be the Belarusian ў
|
|
215
|
+
# (Yauhen = Яўген, Paulau = Паўлаў), which other spellings write as v
|
|
216
|
+
if x.p == "u" and x.src == "la" and 0 < i < n - 1 and seq[i - 1].t == "V" and seq[i + 1].t == "C":
|
|
217
|
+
options.append(["", "V"])
|
|
218
|
+
continue
|
|
219
|
+
if x.p == "z" and i and seq[i - 1].p == "d":
|
|
220
|
+
continue # дз / д
|
|
221
|
+
ks = [_KEY[x.p]]
|
|
222
|
+
for alt in x.alt:
|
|
223
|
+
k = _KEY[alt]
|
|
224
|
+
if k not in ks:
|
|
225
|
+
ks.append(k)
|
|
226
|
+
if x.p == "c" and i + 1 < n and seq[i + 1].p in "iej":
|
|
227
|
+
ks.append("T") # Belarusian ц for т (Ціхан / Тихон)
|
|
228
|
+
after_stop.append(len(options) if (i and seq[i - 1].t == "C" and seq[i - 1].p in "td") else -1)
|
|
229
|
+
options.append(ks)
|
|
230
|
+
affricate = {pos for pos in after_stop if pos >= 0}
|
|
231
|
+
out = []
|
|
232
|
+
for combo in islice(product(*options), 4):
|
|
233
|
+
key = []
|
|
234
|
+
for pos, k in enumerate(combo):
|
|
235
|
+
if k == "J" and pos in affricate and key and key[-1] in "TD":
|
|
236
|
+
key.pop() # тч / дж / "tch" / "dzh": one affricate (Гнатчук = Gnatchuk)
|
|
237
|
+
if k and (not key or key[-1] != k):
|
|
238
|
+
key.append(k)
|
|
239
|
+
key = "".join(key) or "0"
|
|
240
|
+
if key not in out:
|
|
241
|
+
out.append(key)
|
|
242
|
+
return tuple(out)
|
samename/index.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Search and de-duplicate lists of names without comparing every pair."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .distance import skeletons
|
|
6
|
+
from .match import DEFAULT_THRESHOLD, compare, token_keys
|
|
7
|
+
from .parse import parse_name
|
|
8
|
+
from .phonemes import phonemes
|
|
9
|
+
|
|
10
|
+
__all__ = ["NameIndex", "dedupe"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _join_keys(name: str) -> tuple:
|
|
14
|
+
"""Blocking keys of every two adjacent name parts written as one word.
|
|
15
|
+
|
|
16
|
+
One group per adjacent pair, so that "Anna-Maria" / "Annamaria" and
|
|
17
|
+
"Bila Tserkva" / "Bilatserkva" share a key. Mirrors the joining that
|
|
18
|
+
:func:`samename.compare` does (two plain name parts in one script).
|
|
19
|
+
"""
|
|
20
|
+
toks = parse_name(name)
|
|
21
|
+
out = []
|
|
22
|
+
for u, v in zip(toks, toks[1:]):
|
|
23
|
+
if u.kind == "name" and v.kind == "name" and u.script == v.script:
|
|
24
|
+
group = skeletons(phonemes(u.script, u.text + v.text, u.lang))
|
|
25
|
+
if group:
|
|
26
|
+
out.append(tuple(group))
|
|
27
|
+
return tuple(out)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class NameIndex:
|
|
31
|
+
"""An in-memory index of names that can be searched in any script.
|
|
32
|
+
|
|
33
|
+
The keyword options are those of :func:`samename.compare` and apply to
|
|
34
|
+
every search.
|
|
35
|
+
|
|
36
|
+
>>> idx = NameIndex(["Тарас Шевченко", "Olena Kovalenko", "Сергей Иванов"])
|
|
37
|
+
>>> [name for name, _ in idx.search("Serhii Ivanov")]
|
|
38
|
+
['Сергей Иванов']
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, names=(), *, cross_language: bool = True, diminutives: bool = False,
|
|
42
|
+
gender_insensitive_surnames: bool = False):
|
|
43
|
+
self._options = {
|
|
44
|
+
"cross_language": bool(cross_language),
|
|
45
|
+
"diminutives": bool(diminutives),
|
|
46
|
+
"gender_insensitive_surnames": bool(gender_insensitive_surnames),
|
|
47
|
+
}
|
|
48
|
+
self._key_options = {"cross_language": bool(cross_language), "diminutives": bool(diminutives)}
|
|
49
|
+
self._names: list = []
|
|
50
|
+
self._ids: list = []
|
|
51
|
+
self._parts: list = [] # number of name parts of each stored name
|
|
52
|
+
self._buckets: dict = {} # blocking key -> positions
|
|
53
|
+
self._joined: dict = {} # key of two adjacent parts written as one -> positions
|
|
54
|
+
for name in names:
|
|
55
|
+
self.add(name)
|
|
56
|
+
|
|
57
|
+
def __len__(self) -> int:
|
|
58
|
+
return len(self._names)
|
|
59
|
+
|
|
60
|
+
def add(self, name: str, id=None) -> None:
|
|
61
|
+
"""Add a name. ``id`` is returned by :meth:`search_ids` (default: position)."""
|
|
62
|
+
pos = len(self._names)
|
|
63
|
+
groups = token_keys(name, **self._key_options)
|
|
64
|
+
self._names.append(name)
|
|
65
|
+
self._ids.append(pos if id is None else id)
|
|
66
|
+
self._parts.append(len(groups))
|
|
67
|
+
for k in {k for g in groups for k in g}:
|
|
68
|
+
self._buckets.setdefault(k, []).append(pos)
|
|
69
|
+
for k in {k for g in _join_keys(name) for k in g}:
|
|
70
|
+
self._joined.setdefault(k, []).append(pos)
|
|
71
|
+
|
|
72
|
+
def _candidates(self, name: str, after: int = -1) -> list:
|
|
73
|
+
"""Stored names sharing a key for two name parts (one, for 1-part names).
|
|
74
|
+
|
|
75
|
+
A part of one name that equals two adjacent parts of the other written
|
|
76
|
+
as one word (Annamaria / Anna-Maria) counts as one shared part.
|
|
77
|
+
"""
|
|
78
|
+
groups = token_keys(name, **self._key_options)
|
|
79
|
+
hits: dict = {}
|
|
80
|
+
|
|
81
|
+
def count(group, *buckets):
|
|
82
|
+
seen = set()
|
|
83
|
+
for k in group:
|
|
84
|
+
for b in buckets:
|
|
85
|
+
seen.update(b.get(k, ()))
|
|
86
|
+
for pos in seen:
|
|
87
|
+
if pos > after:
|
|
88
|
+
hits[pos] = hits.get(pos, 0) + 1
|
|
89
|
+
|
|
90
|
+
for g in groups:
|
|
91
|
+
count(g, self._buckets, self._joined) # a part, or a part = two joined stored parts
|
|
92
|
+
for g in _join_keys(name):
|
|
93
|
+
count(g, self._buckets) # two joined query parts = a stored part
|
|
94
|
+
n = len(groups)
|
|
95
|
+
parts = self._parts
|
|
96
|
+
return sorted(pos for pos, c in hits.items() if c >= min(2, n, parts[pos]))
|
|
97
|
+
|
|
98
|
+
def _score(self, a: str, b: str) -> float:
|
|
99
|
+
return compare(a, b, **self._options).score
|
|
100
|
+
|
|
101
|
+
def _search(self, query, limit, min_score, exhaustive):
|
|
102
|
+
cands = range(len(self._names)) if exhaustive else self._candidates(query)
|
|
103
|
+
hits = []
|
|
104
|
+
for pos in cands:
|
|
105
|
+
s = self._score(query, self._names[pos])
|
|
106
|
+
if s >= min_score:
|
|
107
|
+
hits.append((s, pos))
|
|
108
|
+
hits.sort(key=lambda h: (-h[0], h[1]))
|
|
109
|
+
return hits[:limit] if limit else hits
|
|
110
|
+
|
|
111
|
+
def search(self, query: str, limit: int = 10, min_score: float = 0.7, exhaustive: bool = False) -> list:
|
|
112
|
+
"""Return ``[(name, score), ...]`` best first.
|
|
113
|
+
|
|
114
|
+
Candidates are found through blocking keys, which is fast but can miss
|
|
115
|
+
a rare spelling; pass ``exhaustive=True`` to score every stored name.
|
|
116
|
+
"""
|
|
117
|
+
return [(self._names[p], s) for s, p in self._search(query, limit, min_score, exhaustive)]
|
|
118
|
+
|
|
119
|
+
def search_ids(self, query: str, limit: int = 10, min_score: float = 0.7, exhaustive: bool = False) -> list:
|
|
120
|
+
"""Like :meth:`search` but returns ``[(id, score), ...]``."""
|
|
121
|
+
return [(self._ids[p], s) for s, p in self._search(query, limit, min_score, exhaustive)]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def dedupe(names, threshold: float = DEFAULT_THRESHOLD, **options) -> list:
|
|
125
|
+
"""Group names that refer to the same person.
|
|
126
|
+
|
|
127
|
+
Returns a list of clusters, each a list of indexes into ``names``; only
|
|
128
|
+
clusters with two or more members are returned. Matching is transitive
|
|
129
|
+
(single linkage), so review large clusters before merging records.
|
|
130
|
+
``options`` are those of :func:`samename.compare`.
|
|
131
|
+
"""
|
|
132
|
+
names = list(names)
|
|
133
|
+
index = NameIndex(names, **options)
|
|
134
|
+
parent = list(range(len(names)))
|
|
135
|
+
|
|
136
|
+
def find(x):
|
|
137
|
+
while parent[x] != x:
|
|
138
|
+
parent[x] = parent[parent[x]]
|
|
139
|
+
x = parent[x]
|
|
140
|
+
return x
|
|
141
|
+
|
|
142
|
+
for i, name in enumerate(names):
|
|
143
|
+
for j in index._candidates(name, after=i):
|
|
144
|
+
ri, rj = find(i), find(j)
|
|
145
|
+
if ri != rj and index._score(name, names[j]) >= threshold:
|
|
146
|
+
parent[max(ri, rj)] = min(ri, rj)
|
|
147
|
+
groups: dict = {}
|
|
148
|
+
for pos in range(len(names)):
|
|
149
|
+
groups.setdefault(find(pos), []).append(pos)
|
|
150
|
+
return [g for g in groups.values() if len(g) > 1]
|