nomenklatura-mpt 4.1.9__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. nomenklatura_mpt-4.1.9/.gitignore +21 -0
  2. nomenklatura_mpt-4.1.9/LICENSE +21 -0
  3. nomenklatura_mpt-4.1.9/PKG-INFO +159 -0
  4. nomenklatura_mpt-4.1.9/README.md +86 -0
  5. nomenklatura_mpt-4.1.9/nomenklatura/__init__.py +11 -0
  6. nomenklatura_mpt-4.1.9/nomenklatura/cache.py +194 -0
  7. nomenklatura_mpt-4.1.9/nomenklatura/cli.py +260 -0
  8. nomenklatura_mpt-4.1.9/nomenklatura/conflicting_match.py +80 -0
  9. nomenklatura_mpt-4.1.9/nomenklatura/data/er-unstable.pkl +0 -0
  10. nomenklatura_mpt-4.1.9/nomenklatura/data/regression-v1.pkl +0 -0
  11. nomenklatura_mpt-4.1.9/nomenklatura/db.py +139 -0
  12. nomenklatura_mpt-4.1.9/nomenklatura/delta.py +4 -0
  13. nomenklatura_mpt-4.1.9/nomenklatura/enrich/__init__.py +94 -0
  14. nomenklatura_mpt-4.1.9/nomenklatura/enrich/aleph.py +141 -0
  15. nomenklatura_mpt-4.1.9/nomenklatura/enrich/common.py +219 -0
  16. nomenklatura_mpt-4.1.9/nomenklatura/enrich/nominatim.py +72 -0
  17. nomenklatura_mpt-4.1.9/nomenklatura/enrich/opencorporates.py +233 -0
  18. nomenklatura_mpt-4.1.9/nomenklatura/enrich/openfigi.py +124 -0
  19. nomenklatura_mpt-4.1.9/nomenklatura/enrich/permid.py +201 -0
  20. nomenklatura_mpt-4.1.9/nomenklatura/enrich/wikidata.py +268 -0
  21. nomenklatura_mpt-4.1.9/nomenklatura/enrich/yente.py +116 -0
  22. nomenklatura_mpt-4.1.9/nomenklatura/exceptions.py +9 -0
  23. nomenklatura_mpt-4.1.9/nomenklatura/index/__init__.py +5 -0
  24. nomenklatura_mpt-4.1.9/nomenklatura/index/common.py +24 -0
  25. nomenklatura_mpt-4.1.9/nomenklatura/index/entry.py +89 -0
  26. nomenklatura_mpt-4.1.9/nomenklatura/index/index.py +170 -0
  27. nomenklatura_mpt-4.1.9/nomenklatura/index/tokenizer.py +92 -0
  28. nomenklatura_mpt-4.1.9/nomenklatura/judgement.py +21 -0
  29. nomenklatura_mpt-4.1.9/nomenklatura/kv.py +40 -0
  30. nomenklatura_mpt-4.1.9/nomenklatura/matching/__init__.py +47 -0
  31. nomenklatura_mpt-4.1.9/nomenklatura/matching/bench.py +32 -0
  32. nomenklatura_mpt-4.1.9/nomenklatura/matching/compare/__init__.py +0 -0
  33. nomenklatura_mpt-4.1.9/nomenklatura/matching/compare/addresses.py +71 -0
  34. nomenklatura_mpt-4.1.9/nomenklatura/matching/compare/countries.py +15 -0
  35. nomenklatura_mpt-4.1.9/nomenklatura/matching/compare/dates.py +83 -0
  36. nomenklatura_mpt-4.1.9/nomenklatura/matching/compare/gender.py +15 -0
  37. nomenklatura_mpt-4.1.9/nomenklatura/matching/compare/identifiers.py +30 -0
  38. nomenklatura_mpt-4.1.9/nomenklatura/matching/compare/names.py +157 -0
  39. nomenklatura_mpt-4.1.9/nomenklatura/matching/compare/util.py +51 -0
  40. nomenklatura_mpt-4.1.9/nomenklatura/matching/compat.py +66 -0
  41. nomenklatura_mpt-4.1.9/nomenklatura/matching/erun/__init__.py +0 -0
  42. nomenklatura_mpt-4.1.9/nomenklatura/matching/erun/countries.py +42 -0
  43. nomenklatura_mpt-4.1.9/nomenklatura/matching/erun/identifiers.py +64 -0
  44. nomenklatura_mpt-4.1.9/nomenklatura/matching/erun/misc.py +71 -0
  45. nomenklatura_mpt-4.1.9/nomenklatura/matching/erun/model.py +110 -0
  46. nomenklatura_mpt-4.1.9/nomenklatura/matching/erun/names.py +126 -0
  47. nomenklatura_mpt-4.1.9/nomenklatura/matching/erun/train.py +135 -0
  48. nomenklatura_mpt-4.1.9/nomenklatura/matching/erun/util.py +28 -0
  49. nomenklatura_mpt-4.1.9/nomenklatura/matching/logic_v1/__init__.py +0 -0
  50. nomenklatura_mpt-4.1.9/nomenklatura/matching/logic_v1/identifiers.py +104 -0
  51. nomenklatura_mpt-4.1.9/nomenklatura/matching/logic_v1/model.py +76 -0
  52. nomenklatura_mpt-4.1.9/nomenklatura/matching/logic_v1/multi.py +21 -0
  53. nomenklatura_mpt-4.1.9/nomenklatura/matching/logic_v1/phonetic.py +142 -0
  54. nomenklatura_mpt-4.1.9/nomenklatura/matching/logic_v2/__init__.py +0 -0
  55. nomenklatura_mpt-4.1.9/nomenklatura/matching/logic_v2/identifiers.py +124 -0
  56. nomenklatura_mpt-4.1.9/nomenklatura/matching/logic_v2/model.py +98 -0
  57. nomenklatura_mpt-4.1.9/nomenklatura/matching/logic_v2/names/__init__.py +3 -0
  58. nomenklatura_mpt-4.1.9/nomenklatura/matching/logic_v2/names/analysis.py +51 -0
  59. nomenklatura_mpt-4.1.9/nomenklatura/matching/logic_v2/names/distance.py +181 -0
  60. nomenklatura_mpt-4.1.9/nomenklatura/matching/logic_v2/names/magic.py +60 -0
  61. nomenklatura_mpt-4.1.9/nomenklatura/matching/logic_v2/names/match.py +195 -0
  62. nomenklatura_mpt-4.1.9/nomenklatura/matching/logic_v2/names/pairing.py +81 -0
  63. nomenklatura_mpt-4.1.9/nomenklatura/matching/logic_v2/names/util.py +89 -0
  64. nomenklatura_mpt-4.1.9/nomenklatura/matching/name_based/__init__.py +4 -0
  65. nomenklatura_mpt-4.1.9/nomenklatura/matching/name_based/misc.py +86 -0
  66. nomenklatura_mpt-4.1.9/nomenklatura/matching/name_based/model.py +59 -0
  67. nomenklatura_mpt-4.1.9/nomenklatura/matching/name_based/names.py +59 -0
  68. nomenklatura_mpt-4.1.9/nomenklatura/matching/pairs.py +42 -0
  69. nomenklatura_mpt-4.1.9/nomenklatura/matching/regression_v1/__init__.py +0 -0
  70. nomenklatura_mpt-4.1.9/nomenklatura/matching/regression_v1/misc.py +75 -0
  71. nomenklatura_mpt-4.1.9/nomenklatura/matching/regression_v1/model.py +110 -0
  72. nomenklatura_mpt-4.1.9/nomenklatura/matching/regression_v1/names.py +63 -0
  73. nomenklatura_mpt-4.1.9/nomenklatura/matching/regression_v1/train.py +87 -0
  74. nomenklatura_mpt-4.1.9/nomenklatura/matching/regression_v1/util.py +31 -0
  75. nomenklatura_mpt-4.1.9/nomenklatura/matching/svm_v1/__init__.py +5 -0
  76. nomenklatura_mpt-4.1.9/nomenklatura/matching/svm_v1/misc.py +94 -0
  77. nomenklatura_mpt-4.1.9/nomenklatura/matching/svm_v1/model.py +168 -0
  78. nomenklatura_mpt-4.1.9/nomenklatura/matching/svm_v1/names.py +81 -0
  79. nomenklatura_mpt-4.1.9/nomenklatura/matching/svm_v1/train.py +186 -0
  80. nomenklatura_mpt-4.1.9/nomenklatura/matching/svm_v1/util.py +30 -0
  81. nomenklatura_mpt-4.1.9/nomenklatura/matching/types.py +227 -0
  82. nomenklatura_mpt-4.1.9/nomenklatura/matching/util.py +62 -0
  83. nomenklatura_mpt-4.1.9/nomenklatura/publish/__init__.py +0 -0
  84. nomenklatura_mpt-4.1.9/nomenklatura/publish/dates.py +49 -0
  85. nomenklatura_mpt-4.1.9/nomenklatura/publish/edges.py +32 -0
  86. nomenklatura_mpt-4.1.9/nomenklatura/py.typed +0 -0
  87. nomenklatura_mpt-4.1.9/nomenklatura/resolver/__init__.py +6 -0
  88. nomenklatura_mpt-4.1.9/nomenklatura/resolver/common.py +2 -0
  89. nomenklatura_mpt-4.1.9/nomenklatura/resolver/edge.py +107 -0
  90. nomenklatura_mpt-4.1.9/nomenklatura/resolver/identifier.py +60 -0
  91. nomenklatura_mpt-4.1.9/nomenklatura/resolver/linker.py +101 -0
  92. nomenklatura_mpt-4.1.9/nomenklatura/resolver/resolver.py +565 -0
  93. nomenklatura_mpt-4.1.9/nomenklatura/settings.py +17 -0
  94. nomenklatura_mpt-4.1.9/nomenklatura/store/__init__.py +41 -0
  95. nomenklatura_mpt-4.1.9/nomenklatura/store/base.py +130 -0
  96. nomenklatura_mpt-4.1.9/nomenklatura/store/level.py +272 -0
  97. nomenklatura_mpt-4.1.9/nomenklatura/store/memory.py +102 -0
  98. nomenklatura_mpt-4.1.9/nomenklatura/store/redis_.py +131 -0
  99. nomenklatura_mpt-4.1.9/nomenklatura/store/sql.py +219 -0
  100. nomenklatura_mpt-4.1.9/nomenklatura/store/util.py +48 -0
  101. nomenklatura_mpt-4.1.9/nomenklatura/store/versioned.py +371 -0
  102. nomenklatura_mpt-4.1.9/nomenklatura/tui/__init__.py +17 -0
  103. nomenklatura_mpt-4.1.9/nomenklatura/tui/app.py +294 -0
  104. nomenklatura_mpt-4.1.9/nomenklatura/tui/app.tcss +52 -0
  105. nomenklatura_mpt-4.1.9/nomenklatura/tui/comparison.py +81 -0
  106. nomenklatura_mpt-4.1.9/nomenklatura/tui/util.py +35 -0
  107. nomenklatura_mpt-4.1.9/nomenklatura/util.py +26 -0
  108. nomenklatura_mpt-4.1.9/nomenklatura/versions.py +119 -0
  109. nomenklatura_mpt-4.1.9/nomenklatura/wikidata/__init__.py +14 -0
  110. nomenklatura_mpt-4.1.9/nomenklatura/wikidata/client.py +122 -0
  111. nomenklatura_mpt-4.1.9/nomenklatura/wikidata/lang.py +94 -0
  112. nomenklatura_mpt-4.1.9/nomenklatura/wikidata/model.py +139 -0
  113. nomenklatura_mpt-4.1.9/nomenklatura/wikidata/props.py +70 -0
  114. nomenklatura_mpt-4.1.9/nomenklatura/wikidata/qualified.py +49 -0
  115. nomenklatura_mpt-4.1.9/nomenklatura/wikidata/query.py +66 -0
  116. nomenklatura_mpt-4.1.9/nomenklatura/wikidata/value.py +87 -0
  117. nomenklatura_mpt-4.1.9/nomenklatura/xref.py +125 -0
  118. nomenklatura_mpt-4.1.9/pyproject.toml +82 -0
@@ -0,0 +1,21 @@
1
+ *.pyc
2
+ *.DS_Store
3
+ *.sqlite3
4
+ *.egg-info
5
+ *.perf
6
+ _store/*
7
+ .env
8
+ .mypy_cache
9
+ tests/fixtures/donations.frag.ijson
10
+ tests/fixtures/donations.rslv.ijson
11
+ .coverage
12
+ htmlcov/
13
+ /build/
14
+ /dist/
15
+ /data/
16
+ textual.log
17
+ .nk_cache.db
18
+ nomenklatura.db
19
+ /uv.lock
20
+ /.envrc
21
+ /.vscode
@@ -0,0 +1,21 @@
1
+ Copyright (c) 2013-2022, Friedrich Lindenberg
2
+ Copyright (c) 2023-2025, OpenSanctions Datenbanken GmbH
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a
5
+ copy of this software and associated documentation files (the
6
+ "Software"), to deal in the Software without restriction, including
7
+ without limitation the rights to use, copy, modify, merge, publish,
8
+ distribute, sublicense, and/or sell copies of the Software, and to
9
+ permit persons to whom the Software is furnished to do so, subject to
10
+ the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included
13
+ in all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,159 @@
1
+ Metadata-Version: 2.4
2
+ Name: nomenklatura_mpt
3
+ Version: 4.1.9
4
+ Summary: Make record linkages in followthemoney data.
5
+ Project-URL: Documentation, https://github.com/opensanctions/nomenklatura/
6
+ Project-URL: Repository, https://github.com/opensanctions/nomenklatura.git
7
+ Project-URL: Issues, https://github.com/opensanctions/nomenklatura/issues
8
+ Author-email: OpenSanctions <info@opensanctions.org>
9
+ License: Copyright (c) 2013-2022, Friedrich Lindenberg
10
+ Copyright (c) 2023-2025, OpenSanctions Datenbanken GmbH
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a
13
+ copy of this software and associated documentation files (the
14
+ "Software"), to deal in the Software without restriction, including
15
+ without limitation the rights to use, copy, modify, merge, publish,
16
+ distribute, sublicense, and/or sell copies of the Software, and to
17
+ permit persons to whom the Software is furnished to do so, subject to
18
+ the following conditions:
19
+
20
+ The above copyright notice and this permission notice shall be included
21
+ in all copies or substantial portions of the Software.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
26
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
27
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
28
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
29
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30
+ License-File: LICENSE
31
+ Classifier: Intended Audience :: Developers
32
+ Classifier: License :: OSI Approved :: MIT License
33
+ Classifier: Operating System :: OS Independent
34
+ Classifier: Programming Language :: Python :: 3.11
35
+ Classifier: Programming Language :: Python :: 3.12
36
+ Requires-Python: >=3.9
37
+ Requires-Dist: click
38
+ Requires-Dist: fingerprints
39
+ Requires-Dist: followthemoney
40
+ Requires-Dist: lxml
41
+ Requires-Dist: pydantic
42
+ Requires-Dist: rich
43
+ Requires-Dist: rigour
44
+ Requires-Dist: scikit-learn
45
+ Requires-Dist: shortuuid
46
+ Requires-Dist: sqlalchemy
47
+ Requires-Dist: textual
48
+ Provides-Extra: dev
49
+ Requires-Dist: build; extra == 'dev'
50
+ Requires-Dist: bump2version; extra == 'dev'
51
+ Requires-Dist: coverage>=4.1; extra == 'dev'
52
+ Requires-Dist: fakeredis; extra == 'dev'
53
+ Requires-Dist: flake8>=2.6.0; extra == 'dev'
54
+ Requires-Dist: lxml-stubs; extra == 'dev'
55
+ Requires-Dist: mypy; extra == 'dev'
56
+ Requires-Dist: plyvel<2.0.0; extra == 'dev'
57
+ Requires-Dist: psycopg2-binary; extra == 'dev'
58
+ Requires-Dist: pytest; extra == 'dev'
59
+ Requires-Dist: pytest-cov; extra == 'dev'
60
+ Requires-Dist: redis<7.0.0,>5.0.0; extra == 'dev'
61
+ Requires-Dist: requests-mock; extra == 'dev'
62
+ Requires-Dist: twine; extra == 'dev'
63
+ Requires-Dist: types-pyyaml; extra == 'dev'
64
+ Requires-Dist: types-redis; extra == 'dev'
65
+ Requires-Dist: types-requests; extra == 'dev'
66
+ Requires-Dist: types-setuptools; extra == 'dev'
67
+ Requires-Dist: wheel>=0.29.0; extra == 'dev'
68
+ Provides-Extra: leveldb
69
+ Requires-Dist: plyvel<2.0.0; extra == 'leveldb'
70
+ Provides-Extra: redis
71
+ Requires-Dist: redis<7.0.0,>5.0.0; extra == 'redis'
72
+ Description-Content-Type: text/markdown
73
+
74
+ # nomenklatura
75
+
76
+ Nomenklatura de-duplicates and integrates different [Follow the Money](https://followthemoney.tech/) entities. It serves to clean up messy data and to find links between different datasets.
77
+
78
+ ![screenshot](./docs/screenshot.png)
79
+
80
+ ## Usage
81
+
82
+ You can install `nomenklatura` via PyPI:
83
+
84
+ ```bash
85
+ $ pip install nomenklatura
86
+ ```
87
+
88
+ ### Command-line usage
89
+
90
+ Much of the functionality of `nomenklatura` can be used as a command-line tool. In the following example, we'll assume that you have a file containing [Follow the Money](https://followthemoney.tech/) entities in your local directory, named `entities.ijson`. If you just want try it out, you can use the file `tests/fixtures/donations.ijson` in this repository for testing (it contains German campaign finance data).
91
+
92
+ With the file in place, you will cross-reference the entities to generate de-duplication candidates, then run the interactive de-duplication UI in your console, and eventually apply the judgements to generate a new file with merged entities:
93
+
94
+ ```bash
95
+ # generate merge candidates using an in-memory index:
96
+ $ nomenklatura xref entities.ijson
97
+ # note there is now a sqlite database, `nomenklatura.db` that contains de-duplication info.
98
+ $ nomenklatura dedupe entities.ijson
99
+ # will pop up a user interface.
100
+ $ nomenklatura apply entities.ijson -o merged.ijson
101
+ # de-duplicated data goes into `merged.ijson`:
102
+ $ cat entities.ijson | wc -l
103
+ 474
104
+ $ cat merged.ijson | wc -l
105
+ 468
106
+ ```
107
+
108
+ The resolver graph database location can be customised by setting the environment variable `NOMENKLATURA_DB_URL`
109
+
110
+ ### Programmatic usage
111
+
112
+ The command-line use of `nomenklatura` is targeted at small datasets which need to be de-duplicated. For more involved scenarios, the package also offers a Python API which can be used to control the semantics of de-duplication.
113
+
114
+ * `nomenklatura.Dataset` - implements a basic dataset for describing a set of entities.
115
+ * `nomenklatura.Store` - a general purpose access mechanism for entities. By default, a store is used to access entity data stored in files as an in-memory cache, but the store can be subclassed to work with entities from a database system.
116
+ * `nomenklatura.Index` - a full-text in-memory search index for FtM entities. In the application, this is used to block de-duplication candidates, but the index can also be used to drive an API etc.
117
+ * `nomenklatura.index.TantivyIndex` - a wrapper around Tantivy for indexing and matching FtM entities.
118
+ * `nomenklatura.Resolver` - the core of the de-duplication process, the resolver is essentially a graph with edges made out of entity judgements. The resolver can be used to store judgements or get the canonical ID for a given entity.
119
+
120
+ All of the API classes have extensive type annotations, which should make their integration in any modern Python API simpler.
121
+
122
+ ## Design
123
+
124
+ This package offers an implementation of an in-memory data deduplication framework centered around the FtM data model. The idea is the following workflow:
125
+
126
+ * Accept FtM-shaped entities from a given loader (e.g. a JSON file, or a database)
127
+ * Build an in-memory inverted index of the entities for dedupe blocking
128
+ * Generate merge candidates using the blocking index and FtM compare
129
+ * Provide a file-based storage format for merge challenges and decisions
130
+ * Provide a text-based user interface to let users make merge decisions
131
+
132
+ Later on, the following might be added:
133
+
134
+ * A web application to let users make merge decisions on the web
135
+
136
+ ### Resolver graph
137
+
138
+ The key implementation detail of nomenklatura is the `Resolver`, a graph structure that
139
+ manages user decisions regarding entity identity. Edges are `Judgements` of whether
140
+ two entity IDs are the same, not the same, or undecided. The resolver implements an
141
+ algorithm for computing connected components, which can the be used to find the best
142
+ available ID for a cluster of entities. It can also be used to evaluate transitive
143
+ judgements, e.g. if A <> B, and B = C, then we don't need to ask if A = C.
144
+
145
+ ## Reading
146
+
147
+ * https://dedupe.readthedocs.org/en/latest/
148
+ * https://github.com/OpenRefine/OpenRefine/wiki/Reconcilable-Data-Sources
149
+ * https://github.com/OpenRefine/OpenRefine/wiki/Clustering-In-Depth
150
+ * https://github.com/OpenRefine/OpenRefine/wiki/Reconciliation-Service-API
151
+
152
+
153
+ ## Contact, contributions etc.
154
+
155
+ This codebase is licensed under the terms of an MIT license (see LICENSE).
156
+
157
+ We're keen for any contributions, bug fixes and feature suggestions, please use the GitHub issue tracker for this repository.
158
+
159
+ Nomenklatura is currently developed thanks to a Prototypefund grant for [OpenSanctions](https://opensanctions.org). Previous iterations of the package were developed with support from [Knight-Mozilla OpenNews](http://opennews.org) and the [Open Knowledge Foundation Labs](http://okfnlabs.org).
@@ -0,0 +1,86 @@
1
+ # nomenklatura
2
+
3
+ Nomenklatura de-duplicates and integrates different [Follow the Money](https://followthemoney.tech/) entities. It serves to clean up messy data and to find links between different datasets.
4
+
5
+ ![screenshot](./docs/screenshot.png)
6
+
7
+ ## Usage
8
+
9
+ You can install `nomenklatura` via PyPI:
10
+
11
+ ```bash
12
+ $ pip install nomenklatura
13
+ ```
14
+
15
+ ### Command-line usage
16
+
17
+ Much of the functionality of `nomenklatura` can be used as a command-line tool. In the following example, we'll assume that you have a file containing [Follow the Money](https://followthemoney.tech/) entities in your local directory, named `entities.ijson`. If you just want try it out, you can use the file `tests/fixtures/donations.ijson` in this repository for testing (it contains German campaign finance data).
18
+
19
+ With the file in place, you will cross-reference the entities to generate de-duplication candidates, then run the interactive de-duplication UI in your console, and eventually apply the judgements to generate a new file with merged entities:
20
+
21
+ ```bash
22
+ # generate merge candidates using an in-memory index:
23
+ $ nomenklatura xref entities.ijson
24
+ # note there is now a sqlite database, `nomenklatura.db` that contains de-duplication info.
25
+ $ nomenklatura dedupe entities.ijson
26
+ # will pop up a user interface.
27
+ $ nomenklatura apply entities.ijson -o merged.ijson
28
+ # de-duplicated data goes into `merged.ijson`:
29
+ $ cat entities.ijson | wc -l
30
+ 474
31
+ $ cat merged.ijson | wc -l
32
+ 468
33
+ ```
34
+
35
+ The resolver graph database location can be customised by setting the environment variable `NOMENKLATURA_DB_URL`
36
+
37
+ ### Programmatic usage
38
+
39
+ The command-line use of `nomenklatura` is targeted at small datasets which need to be de-duplicated. For more involved scenarios, the package also offers a Python API which can be used to control the semantics of de-duplication.
40
+
41
+ * `nomenklatura.Dataset` - implements a basic dataset for describing a set of entities.
42
+ * `nomenklatura.Store` - a general purpose access mechanism for entities. By default, a store is used to access entity data stored in files as an in-memory cache, but the store can be subclassed to work with entities from a database system.
43
+ * `nomenklatura.Index` - a full-text in-memory search index for FtM entities. In the application, this is used to block de-duplication candidates, but the index can also be used to drive an API etc.
44
+ * `nomenklatura.index.TantivyIndex` - a wrapper around Tantivy for indexing and matching FtM entities.
45
+ * `nomenklatura.Resolver` - the core of the de-duplication process, the resolver is essentially a graph with edges made out of entity judgements. The resolver can be used to store judgements or get the canonical ID for a given entity.
46
+
47
+ All of the API classes have extensive type annotations, which should make their integration in any modern Python API simpler.
48
+
49
+ ## Design
50
+
51
+ This package offers an implementation of an in-memory data deduplication framework centered around the FtM data model. The idea is the following workflow:
52
+
53
+ * Accept FtM-shaped entities from a given loader (e.g. a JSON file, or a database)
54
+ * Build an in-memory inverted index of the entities for dedupe blocking
55
+ * Generate merge candidates using the blocking index and FtM compare
56
+ * Provide a file-based storage format for merge challenges and decisions
57
+ * Provide a text-based user interface to let users make merge decisions
58
+
59
+ Later on, the following might be added:
60
+
61
+ * A web application to let users make merge decisions on the web
62
+
63
+ ### Resolver graph
64
+
65
+ The key implementation detail of nomenklatura is the `Resolver`, a graph structure that
66
+ manages user decisions regarding entity identity. Edges are `Judgements` of whether
67
+ two entity IDs are the same, not the same, or undecided. The resolver implements an
68
+ algorithm for computing connected components, which can the be used to find the best
69
+ available ID for a cluster of entities. It can also be used to evaluate transitive
70
+ judgements, e.g. if A <> B, and B = C, then we don't need to ask if A = C.
71
+
72
+ ## Reading
73
+
74
+ * https://dedupe.readthedocs.org/en/latest/
75
+ * https://github.com/OpenRefine/OpenRefine/wiki/Reconcilable-Data-Sources
76
+ * https://github.com/OpenRefine/OpenRefine/wiki/Clustering-In-Depth
77
+ * https://github.com/OpenRefine/OpenRefine/wiki/Reconciliation-Service-API
78
+
79
+
80
+ ## Contact, contributions etc.
81
+
82
+ This codebase is licensed under the terms of an MIT license (see LICENSE).
83
+
84
+ We're keen for any contributions, bug fixes and feature suggestions, please use the GitHub issue tracker for this repository.
85
+
86
+ Nomenklatura is currently developed thanks to a Prototypefund grant for [OpenSanctions](https://opensanctions.org). Previous iterations of the package were developed with support from [Knight-Mozilla OpenNews](http://opennews.org) and the [Open Knowledge Foundation Labs](http://okfnlabs.org).
@@ -0,0 +1,11 @@
1
+ from nomenklatura.resolver import Resolver
2
+ from nomenklatura.store import Store, View
3
+ from nomenklatura.index import Index
4
+
5
+ __version__ = "4.1.9"
6
+ __all__ = [
7
+ "Resolver",
8
+ "Index",
9
+ "Store",
10
+ "View",
11
+ ]
@@ -0,0 +1,194 @@
1
+ import math
2
+ import json
3
+ import logging
4
+ from random import randint
5
+ from dataclasses import dataclass
6
+ from typing import Any, cast, Dict, Optional, Union, Generator
7
+ from datetime import datetime, timedelta
8
+ from sqlalchemy import MetaData
9
+ from sqlalchemy import Table, Column, DateTime, Unicode
10
+ from sqlalchemy.engine import Engine, Connection, Transaction
11
+ from sqlalchemy.future import select
12
+ from sqlalchemy.sql.expression import delete
13
+ from sqlalchemy.exc import OperationalError, InvalidRequestError
14
+ from sqlalchemy.dialects.postgresql import insert as upsert
15
+ from rigour.time import naive_now
16
+ from followthemoney import Dataset
17
+
18
+ from nomenklatura.db import get_engine, get_metadata
19
+
20
+
21
+ log = logging.getLogger(__name__)
22
+ Value = Union[str, None]
23
+
24
+
25
+ @dataclass
26
+ class CacheValue:
27
+ key: str
28
+ dataset: Optional[str]
29
+ text: Value
30
+ timestamp: datetime
31
+
32
+
33
+ def randomize_cache(days: int) -> timedelta:
34
+ min_cache = max(1, math.ceil(days * 0.5))
35
+ max_cache = math.ceil(days * 1.3)
36
+ return timedelta(days=randint(min_cache, max_cache))
37
+
38
+
39
+ class Cache(object):
40
+ def __init__(
41
+ self, engine: Engine, metadata: MetaData, dataset: Dataset, create: bool = False
42
+ ) -> None:
43
+ self.dataset = dataset
44
+ self._engine = engine
45
+ self._conn: Optional[Connection] = None
46
+ self._transaction: Optional[Transaction] = None
47
+ self._table = Table(
48
+ "cache",
49
+ metadata,
50
+ Column("key", Unicode(), primary_key=True),
51
+ Column("text", Unicode(), nullable=True),
52
+ Column("dataset", Unicode(), nullable=False),
53
+ Column("timestamp", DateTime, index=True),
54
+ extend_existing=True,
55
+ )
56
+ if create:
57
+ metadata.create_all(bind=engine, checkfirst=True, tables=[self._table])
58
+
59
+ self._preload: Dict[str, CacheValue] = {}
60
+
61
+ @property
62
+ def conn(self) -> Connection:
63
+ if self._conn is None:
64
+ self._conn = self._engine.connect()
65
+ self._transaction = self._conn.begin()
66
+ return self._conn
67
+
68
+ def set(self, key: str, value: Value) -> None:
69
+ self._preload.pop(key, None)
70
+ cache = {
71
+ "timestamp": naive_now(),
72
+ "key": key,
73
+ "dataset": self.dataset.name,
74
+ "text": value,
75
+ }
76
+ try:
77
+ istmt = upsert(self._table).values(cache)
78
+ values = dict(
79
+ timestamp=istmt.excluded.timestamp,
80
+ text=istmt.excluded.text,
81
+ dataset=istmt.excluded.dataset,
82
+ )
83
+ stmt = istmt.on_conflict_do_update(index_elements=["key"], set_=values)
84
+ self.conn.execute(stmt)
85
+ except (OperationalError, InvalidRequestError) as exc:
86
+ log.exception("Error while saving to cache: %s" % exc)
87
+ self.reset()
88
+
89
+ def set_json(self, key: str, value: Any) -> None:
90
+ return self.set(key, json.dumps(value))
91
+
92
+ def get(self, key: str, max_age: Optional[int] = None) -> Optional[Value]:
93
+ if max_age is not None and max_age < 1:
94
+ return None
95
+
96
+ cache_cutoff = None
97
+ if max_age is not None:
98
+ cache_cutoff = naive_now() - randomize_cache(max_age)
99
+
100
+ cache = self._preload.get(key)
101
+ if cache is not None:
102
+ if cache_cutoff is not None and cache.timestamp < cache_cutoff:
103
+ return None
104
+ return cache.text
105
+
106
+ q = select(self._table.c.text)
107
+ q = q.filter(self._table.c.key == key)
108
+ if cache_cutoff is not None:
109
+ q = q.filter(self._table.c.timestamp > cache_cutoff)
110
+ q = q.order_by(self._table.c.timestamp.desc())
111
+ q = q.limit(1)
112
+ try:
113
+ result = self.conn.execute(q)
114
+ row = result.fetchone()
115
+ except InvalidRequestError as ire:
116
+ log.exception("Cache fetch error: %s", ire)
117
+ self.reset()
118
+ return None
119
+ if row is not None:
120
+ return cast(Optional[str], row.text)
121
+ return None
122
+
123
+ def get_json(self, key: str, max_age: Optional[int] = None) -> Optional[Any]:
124
+ text = self.get(key, max_age=max_age)
125
+ if text is None:
126
+ return None
127
+ return json.loads(text)
128
+
129
+ def has(self, key: str) -> bool:
130
+ return self.get(key) is not None
131
+
132
+ def delete(self, key: str) -> None:
133
+ self._preload.pop(key, None)
134
+ pq = delete(self._table)
135
+ pq = pq.where(self._table.c.key == key)
136
+ try:
137
+ self.conn.execute(pq)
138
+ except InvalidRequestError as ire:
139
+ log.exception("Cache delete error: %s", ire)
140
+ self.reset()
141
+ return None
142
+
143
+ def all(self, like: Optional[str]) -> Generator[CacheValue, None, None]:
144
+ q = select(self._table)
145
+ if like is not None:
146
+ q = q.filter(self._table.c.key.like(like))
147
+
148
+ result = self.conn.execute(q)
149
+ for row in result.yield_per(10000):
150
+ yield CacheValue(row.key, row.dataset, row.text, row.timestamp)
151
+
152
+ def preload(self, like: Optional[str] = None) -> None:
153
+ log.info("Pre-loading cache: %r", like)
154
+ for cache in self.all(like=like):
155
+ self._preload[cache.key] = cache
156
+
157
+ def clear(self) -> None:
158
+ try:
159
+ pq = delete(self._table)
160
+ pq = pq.where(self._table.c.dataset == self.dataset.name)
161
+ self.conn.execute(pq)
162
+ except InvalidRequestError:
163
+ log.exception("Cannot clear cache from database")
164
+ self.reset()
165
+
166
+ def reset(self) -> None:
167
+ if self._conn is not None:
168
+ self._conn.close()
169
+ self._conn = None
170
+ self._transaction = None
171
+
172
+ def flush(self) -> None:
173
+ # log.info("Flushing cache.")
174
+ if self._transaction is not None:
175
+ try:
176
+ self._transaction.commit()
177
+ except InvalidRequestError:
178
+ log.exception("Transaction was failed, cannot store cache state.")
179
+ self.reset()
180
+
181
+ def close(self) -> None:
182
+ self.flush()
183
+
184
+ def __repr__(self) -> str:
185
+ return f"<Cache({self._table!r})>"
186
+
187
+ def __hash__(self) -> int:
188
+ return hash((self.dataset.name, self._table.name))
189
+
190
+ @classmethod
191
+ def make_default(cls, dataset: Dataset) -> "Cache":
192
+ engine = get_engine()
193
+ metadata = get_metadata()
194
+ return cls(engine, metadata, dataset, create=True)