ofacmatch 0.1.0__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.
- ofacmatch/__init__.py +13 -0
- ofacmatch/__main__.py +5 -0
- ofacmatch/cli.py +164 -0
- ofacmatch/client.py +197 -0
- ofacmatch/py.typed +0 -0
- ofacmatch-0.1.0.dist-info/METADATA +112 -0
- ofacmatch-0.1.0.dist-info/RECORD +10 -0
- ofacmatch-0.1.0.dist-info/WHEEL +5 -0
- ofacmatch-0.1.0.dist-info/entry_points.txt +2 -0
- ofacmatch-0.1.0.dist-info/top_level.txt +1 -0
ofacmatch/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Python client for the self-hosted OfacMatch REST API.
|
|
2
|
+
|
|
3
|
+
Run the API on your own server (``docker run -p 8080:8080 ghcr.io/krunalsolanki/ofacmatch-api``),
|
|
4
|
+
then screen names from Python. Names go only to that server, never anywhere else.
|
|
5
|
+
|
|
6
|
+
Potential matches only: a score measures how alike two names are written, not whether they are
|
|
7
|
+
the same party. A person must review every potential match. Checks the OFAC SDN list only.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from .client import Client, OfacMatchError
|
|
11
|
+
|
|
12
|
+
__all__ = ["Client", "OfacMatchError"]
|
|
13
|
+
__version__ = "0.1.0"
|
ofacmatch/__main__.py
ADDED
ofacmatch/cli.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Command line: screen one name, or a whole CSV file, through an OfacMatch API server.
|
|
2
|
+
|
|
3
|
+
ofacmatch screen "Aymen Zawahri" --yob 1951
|
|
4
|
+
ofacmatch csv customers.csv results.csv
|
|
5
|
+
ofacmatch --url http://screening.internal:8080 --api-key KEY csv customers.csv results.csv
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import csv
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import sys
|
|
16
|
+
from typing import Dict, List, Optional, Sequence
|
|
17
|
+
|
|
18
|
+
from . import __version__
|
|
19
|
+
from .client import Client, OfacMatchError
|
|
20
|
+
|
|
21
|
+
_YEAR = re.compile(r"\b(1[89]\d\d|20\d\d)\b")
|
|
22
|
+
|
|
23
|
+
# Header names recognised in an input CSV (compared without case, spaces or punctuation).
|
|
24
|
+
_COLUMNS = {
|
|
25
|
+
"name": ["name", "fullname", "customername", "customer", "partyname", "legalname"],
|
|
26
|
+
"first": ["firstname", "givenname", "forename"],
|
|
27
|
+
"middle": ["middlename"],
|
|
28
|
+
"last": ["lastname", "surname", "familyname"],
|
|
29
|
+
"year": ["yearofbirth", "yob", "birthyear", "dateofbirth", "dob", "birthdate"],
|
|
30
|
+
"country": ["country", "nationality", "citizenship", "countryofresidence"],
|
|
31
|
+
"type": ["type", "partytype", "entitytype"],
|
|
32
|
+
"reference": ["id", "reference", "ref", "customerid", "customerno", "accountnumber", "account"],
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
_OUTPUT = [
|
|
36
|
+
"reference", "input_name", "result", "potential_matches", "best_score", "best_listed_name",
|
|
37
|
+
"best_entry_id", "best_programs", "date_of_birth_conflict", "country_conflict", "explanation",
|
|
38
|
+
"reviewer_decision", "reviewer_name", "reviewer_notes",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
43
|
+
parser = argparse.ArgumentParser(prog="ofacmatch", description="Screen names against the OFAC SDN list through your own OfacMatch API server.")
|
|
44
|
+
parser.add_argument("--url", default=os.environ.get("OFACMATCH_URL", "http://localhost:8080"), help="API server (default: $OFACMATCH_URL or http://localhost:8080)")
|
|
45
|
+
parser.add_argument("--api-key", default=os.environ.get("OFACMATCH_API_KEY"), help="API key, if the server requires one (default: $OFACMATCH_API_KEY)")
|
|
46
|
+
parser.add_argument("--version", action="version", version=f"ofacmatch {__version__}")
|
|
47
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
48
|
+
|
|
49
|
+
one = commands.add_parser("screen", help="screen one name and print the result as JSON")
|
|
50
|
+
one.add_argument("name")
|
|
51
|
+
one.add_argument("--yob", type=int, help="year of birth")
|
|
52
|
+
one.add_argument("--country")
|
|
53
|
+
one.add_argument("--type", choices=["individual", "entity", "vessel", "aircraft"])
|
|
54
|
+
one.add_argument("--min", type=float, dest="min_score", help="minimum score, 0-100 (default 85)")
|
|
55
|
+
|
|
56
|
+
many = commands.add_parser("csv", help="screen every row of a CSV file and write a results CSV")
|
|
57
|
+
many.add_argument("input", help="CSV with a Name column (or First and Last name columns)")
|
|
58
|
+
many.add_argument("output", help="results CSV to write (one row per input row)")
|
|
59
|
+
many.add_argument("--min", type=float, dest="min_score", help="minimum score, 0-100 (default 85)")
|
|
60
|
+
|
|
61
|
+
args = parser.parse_args(argv)
|
|
62
|
+
client = Client(args.url, api_key=args.api_key)
|
|
63
|
+
try:
|
|
64
|
+
if args.command == "screen":
|
|
65
|
+
result = client.screen(args.name, type=args.type, year_of_birth=args.yob, country=args.country, min_score=args.min_score)
|
|
66
|
+
print(json.dumps(result, indent=2, ensure_ascii=False))
|
|
67
|
+
return 0
|
|
68
|
+
return _screen_csv(client, args.input, args.output, args.min_score)
|
|
69
|
+
except OfacMatchError as error:
|
|
70
|
+
print(f"ofacmatch: {error}", file=sys.stderr)
|
|
71
|
+
return 2
|
|
72
|
+
except (OSError, ValueError) as error:
|
|
73
|
+
print(f"ofacmatch: {error}", file=sys.stderr)
|
|
74
|
+
return 2
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _screen_csv(client: Client, input_path: str, output_path: str, min_score: Optional[float]) -> int:
|
|
78
|
+
with open(input_path, newline="", encoding="utf-8-sig") as f:
|
|
79
|
+
sample = f.read(4096)
|
|
80
|
+
f.seek(0)
|
|
81
|
+
try:
|
|
82
|
+
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t")
|
|
83
|
+
except csv.Error:
|
|
84
|
+
dialect = csv.excel
|
|
85
|
+
rows = list(csv.reader(f, dialect))
|
|
86
|
+
|
|
87
|
+
if not rows:
|
|
88
|
+
raise ValueError(f"{input_path} is empty")
|
|
89
|
+
|
|
90
|
+
columns = _find_columns(rows[0])
|
|
91
|
+
if "name" not in columns and not ("first" in columns or "last" in columns):
|
|
92
|
+
raise ValueError("no Name column found (or First name and Last name columns); add a header row")
|
|
93
|
+
|
|
94
|
+
items: List[Dict[str, object]] = []
|
|
95
|
+
for number, row in enumerate(rows[1:], start=2):
|
|
96
|
+
def cell(key: str) -> str:
|
|
97
|
+
index = columns.get(key)
|
|
98
|
+
return row[index].strip() if index is not None and index < len(row) else ""
|
|
99
|
+
|
|
100
|
+
name = cell("name") or " ".join(p for p in (cell("first"), cell("middle"), cell("last")) if p)
|
|
101
|
+
year = _YEAR.search(cell("year"))
|
|
102
|
+
items.append({
|
|
103
|
+
"name": name,
|
|
104
|
+
"reference": cell("reference") or f"row {number}",
|
|
105
|
+
"year_of_birth": int(year.group(1)) if year else None,
|
|
106
|
+
"country": cell("country") or None,
|
|
107
|
+
"type": cell("type") or None,
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
if not items:
|
|
111
|
+
raise ValueError(f"{input_path} has a header but no rows")
|
|
112
|
+
|
|
113
|
+
response = client.screen_batch(items, min_score=min_score)
|
|
114
|
+
with open(output_path, "w", newline="", encoding="utf-8-sig") as f:
|
|
115
|
+
writer = csv.writer(f)
|
|
116
|
+
writer.writerow(_OUTPUT)
|
|
117
|
+
for item, result in zip(items, response["results"]):
|
|
118
|
+
best = (result.get("matches") or [None])[0]
|
|
119
|
+
writer.writerow([_safe(v) for v in [
|
|
120
|
+
item["reference"],
|
|
121
|
+
item["name"],
|
|
122
|
+
result.get("error") and f"error: {result['error']}" or result.get("status"),
|
|
123
|
+
result.get("potentialMatches", 0),
|
|
124
|
+
best and best["score"],
|
|
125
|
+
best and best["listedName"],
|
|
126
|
+
best and best["entryId"],
|
|
127
|
+
best and ", ".join(best["programs"]),
|
|
128
|
+
best and best["dateOfBirthConflict"],
|
|
129
|
+
best and best["countryConflict"],
|
|
130
|
+
best and best["explanation"],
|
|
131
|
+
"", "", "",
|
|
132
|
+
]])
|
|
133
|
+
|
|
134
|
+
summary = response["summary"]
|
|
135
|
+
print(
|
|
136
|
+
f"Screened {summary['screened']}: {summary['review']} to review, "
|
|
137
|
+
f"{summary['likelyDifferentPerson']} likely a different person, {summary['noMatch']} no match, "
|
|
138
|
+
f"{summary['errors']} not screened. Results: {output_path}"
|
|
139
|
+
)
|
|
140
|
+
print("Potential matches only: a person must review each one. OFAC SDN list only.")
|
|
141
|
+
return 0
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _find_columns(header: Sequence[str]) -> Dict[str, int]:
|
|
145
|
+
found: Dict[str, int] = {}
|
|
146
|
+
for index, title in enumerate(header):
|
|
147
|
+
key = re.sub(r"[^a-z]", "", title.lower())
|
|
148
|
+
for column, names in _COLUMNS.items():
|
|
149
|
+
if key in names and column not in found:
|
|
150
|
+
found[column] = index
|
|
151
|
+
return found
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _safe(value: object) -> object:
|
|
155
|
+
"""Stops a spreadsheet from running a cell as a formula."""
|
|
156
|
+
if value is None:
|
|
157
|
+
return ""
|
|
158
|
+
if isinstance(value, str) and value[:1] in ("=", "+", "-", "@", "\t", "\r"):
|
|
159
|
+
return "'" + value
|
|
160
|
+
return value
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
if __name__ == "__main__":
|
|
164
|
+
sys.exit(main())
|
ofacmatch/client.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""HTTP client for the OfacMatch REST API. Standard library only."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional
|
|
10
|
+
|
|
11
|
+
#: The API accepts at most this many items per batch request; larger lists are split automatically.
|
|
12
|
+
MAX_BATCH = 1000
|
|
13
|
+
|
|
14
|
+
_USER_AGENT = "ofacmatch-python/0.1.0"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class OfacMatchError(Exception):
|
|
18
|
+
"""The API refused a request or could not be reached.
|
|
19
|
+
|
|
20
|
+
``status`` is the HTTP status (None if the server could not be reached) and ``errors`` holds
|
|
21
|
+
the per-field messages of a 400 response, for example ``{"name": ["Name is required."]}``.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(self, message: str, status: Optional[int] = None, errors: Optional[Dict[str, List[str]]] = None):
|
|
25
|
+
super().__init__(message)
|
|
26
|
+
self.status = status
|
|
27
|
+
self.errors = errors or {}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Client:
|
|
31
|
+
"""Talks to one OfacMatch API server.
|
|
32
|
+
|
|
33
|
+
>>> client = Client("http://localhost:8080")
|
|
34
|
+
>>> result = client.screen("Aymen Zawahri", year_of_birth=1951)
|
|
35
|
+
>>> result["potentialMatches"]
|
|
36
|
+
1
|
|
37
|
+
|
|
38
|
+
Responses are returned as plain dictionaries, exactly as the API sends them
|
|
39
|
+
(see the API guide for every field).
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(self, base_url: str = "http://localhost:8080", api_key: Optional[str] = None, timeout: float = 60.0):
|
|
43
|
+
if not base_url.startswith(("http://", "https://")):
|
|
44
|
+
raise ValueError("base_url must start with http:// or https://")
|
|
45
|
+
self.base_url = base_url.rstrip("/")
|
|
46
|
+
self.api_key = api_key
|
|
47
|
+
self.timeout = timeout
|
|
48
|
+
|
|
49
|
+
# Screening -----------------------------------------------------------------------------
|
|
50
|
+
|
|
51
|
+
def screen(
|
|
52
|
+
self,
|
|
53
|
+
name: str,
|
|
54
|
+
*,
|
|
55
|
+
type: Optional[str] = None,
|
|
56
|
+
year_of_birth: Optional[int] = None,
|
|
57
|
+
country: Optional[str] = None,
|
|
58
|
+
min_score: Optional[float] = None,
|
|
59
|
+
max_results: Optional[int] = None,
|
|
60
|
+
) -> Dict[str, Any]:
|
|
61
|
+
"""Screens one name. ``type`` is individual, entity, vessel or aircraft (default: all)."""
|
|
62
|
+
body = _drop_none(
|
|
63
|
+
name=name,
|
|
64
|
+
type=type,
|
|
65
|
+
yearOfBirth=year_of_birth,
|
|
66
|
+
country=country,
|
|
67
|
+
minScore=min_score,
|
|
68
|
+
maxResults=max_results,
|
|
69
|
+
)
|
|
70
|
+
return self._request("POST", "/v1/screen", body)
|
|
71
|
+
|
|
72
|
+
def screen_batch(
|
|
73
|
+
self,
|
|
74
|
+
items: Iterable[Mapping[str, Any]],
|
|
75
|
+
*,
|
|
76
|
+
min_score: Optional[float] = None,
|
|
77
|
+
max_results: Optional[int] = None,
|
|
78
|
+
) -> Dict[str, Any]:
|
|
79
|
+
"""Screens a list of names, sending at most 1,000 per request.
|
|
80
|
+
|
|
81
|
+
Each item is a mapping with ``name`` and optionally ``reference`` (your own ID, returned
|
|
82
|
+
unchanged), ``type``, ``year_of_birth`` (or ``yearOfBirth``) and ``country``.
|
|
83
|
+
|
|
84
|
+
Returns one combined response: ``results`` in the same order as ``items`` (each with
|
|
85
|
+
``index``, ``reference``, ``status`` and ``matches``) and a ``summary`` with the counts.
|
|
86
|
+
``status`` is review, likely_different_person, no_match or error.
|
|
87
|
+
"""
|
|
88
|
+
results: List[Dict[str, Any]] = []
|
|
89
|
+
last: Dict[str, Any] = {}
|
|
90
|
+
offset = 0
|
|
91
|
+
for chunk in _chunks((_item(i) for i in items), MAX_BATCH):
|
|
92
|
+
body = _drop_none(items=chunk, minScore=min_score, maxResults=max_results)
|
|
93
|
+
last = self._request("POST", "/v1/screen/batch", body)
|
|
94
|
+
for result in last.get("results", []):
|
|
95
|
+
result["index"] = result.get("index", 0) + offset
|
|
96
|
+
results.append(result)
|
|
97
|
+
offset += len(chunk)
|
|
98
|
+
|
|
99
|
+
if offset == 0:
|
|
100
|
+
raise ValueError("items is empty: give at least one name to screen")
|
|
101
|
+
|
|
102
|
+
counts = {"review": 0, "likely_different_person": 0, "no_match": 0, "error": 0}
|
|
103
|
+
for result in results:
|
|
104
|
+
counts[result.get("status", "error")] = counts.get(result.get("status", "error"), 0) + 1
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
"summary": {
|
|
108
|
+
"screened": len(results),
|
|
109
|
+
"review": counts["review"],
|
|
110
|
+
"likelyDifferentPerson": counts["likely_different_person"],
|
|
111
|
+
"noMatch": counts["no_match"],
|
|
112
|
+
"errors": counts["error"],
|
|
113
|
+
},
|
|
114
|
+
"results": results,
|
|
115
|
+
"minScore": last.get("minScore"),
|
|
116
|
+
"list": last.get("list"),
|
|
117
|
+
"notice": last.get("notice"),
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
def compare(self, name: str, other_name: str, *, companies: bool = False) -> Dict[str, Any]:
|
|
121
|
+
"""Explains how two names score against each other."""
|
|
122
|
+
return self._request("POST", "/v1/compare", {"name": name, "otherName": other_name, "companies": companies})
|
|
123
|
+
|
|
124
|
+
# Lookups -------------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
def entry(self, entry_id: int) -> Dict[str, Any]:
|
|
127
|
+
"""The full SDN record behind a match (names, aliases, dates of birth, addresses, remarks)."""
|
|
128
|
+
return self._request("GET", f"/v1/entries/{int(entry_id)}")
|
|
129
|
+
|
|
130
|
+
def list_info(self) -> Dict[str, Any]:
|
|
131
|
+
"""Which copy of the SDN list the server is using."""
|
|
132
|
+
return self._request("GET", "/v1/list")
|
|
133
|
+
|
|
134
|
+
def health(self) -> Dict[str, Any]:
|
|
135
|
+
"""``{"status": "ok", ...}`` once the server has loaded the list. Raises OfacMatchError (503) before that."""
|
|
136
|
+
return self._request("GET", "/health")
|
|
137
|
+
|
|
138
|
+
# Transport -----------------------------------------------------------------------------
|
|
139
|
+
|
|
140
|
+
def _request(self, method: str, path: str, body: Optional[Mapping[str, Any]] = None) -> Dict[str, Any]:
|
|
141
|
+
data = None if body is None else json.dumps(body).encode("utf-8")
|
|
142
|
+
request = urllib.request.Request(self.base_url + path, data=data, method=method)
|
|
143
|
+
request.add_header("Accept", "application/json")
|
|
144
|
+
request.add_header("User-Agent", _USER_AGENT)
|
|
145
|
+
if data is not None:
|
|
146
|
+
request.add_header("Content-Type", "application/json")
|
|
147
|
+
if self.api_key:
|
|
148
|
+
request.add_header("X-Api-Key", self.api_key)
|
|
149
|
+
|
|
150
|
+
try:
|
|
151
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
|
152
|
+
return json.loads(response.read().decode("utf-8"))
|
|
153
|
+
except urllib.error.HTTPError as error:
|
|
154
|
+
raise _api_error(error) from None
|
|
155
|
+
except urllib.error.URLError as error:
|
|
156
|
+
raise OfacMatchError(f"Could not reach the OfacMatch API at {self.base_url}: {error.reason}") from None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _api_error(error: urllib.error.HTTPError) -> OfacMatchError:
|
|
160
|
+
try:
|
|
161
|
+
problem = json.loads(error.read().decode("utf-8"))
|
|
162
|
+
except (ValueError, UnicodeDecodeError):
|
|
163
|
+
problem = {}
|
|
164
|
+
|
|
165
|
+
errors = problem.get("errors") or {}
|
|
166
|
+
details = "; ".join(m for messages in errors.values() for m in messages)
|
|
167
|
+
message = problem.get("detail") or problem.get("title") or error.reason or "Request failed"
|
|
168
|
+
if details:
|
|
169
|
+
message = f"{message}: {details}"
|
|
170
|
+
return OfacMatchError(f"HTTP {error.code}: {message}", status=error.code, errors=errors)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _item(item: Mapping[str, Any]) -> Dict[str, Any]:
|
|
174
|
+
if not isinstance(item, Mapping):
|
|
175
|
+
raise TypeError("each batch item must be a mapping such as {'name': 'John Doe'}")
|
|
176
|
+
return _drop_none(
|
|
177
|
+
name=item.get("name"),
|
|
178
|
+
reference=None if item.get("reference") is None else str(item.get("reference")),
|
|
179
|
+
type=item.get("type"),
|
|
180
|
+
yearOfBirth=item.get("year_of_birth", item.get("yearOfBirth")),
|
|
181
|
+
country=item.get("country"),
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _chunks(items: Iterator[Dict[str, Any]], size: int) -> Iterator[List[Dict[str, Any]]]:
|
|
186
|
+
chunk: List[Dict[str, Any]] = []
|
|
187
|
+
for item in items:
|
|
188
|
+
chunk.append(item)
|
|
189
|
+
if len(chunk) == size:
|
|
190
|
+
yield chunk
|
|
191
|
+
chunk = []
|
|
192
|
+
if chunk:
|
|
193
|
+
yield chunk
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _drop_none(**values: Any) -> Dict[str, Any]:
|
|
197
|
+
return {key: value for key, value in values.items() if value is not None}
|
ofacmatch/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ofacmatch
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client for the self-hosted OfacMatch REST API: explainable OFAC SDN name screening that keeps your data on your own server.
|
|
5
|
+
Author: Krunal Solanki
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/krunalsolanki/ofac-match
|
|
8
|
+
Project-URL: Documentation, https://github.com/krunalsolanki/ofac-match/blob/main/clients/python/README.md
|
|
9
|
+
Project-URL: REST API, https://github.com/krunalsolanki/ofac-match/blob/main/src/OfacMatch.Api/README.md
|
|
10
|
+
Project-URL: Issues, https://github.com/krunalsolanki/ofac-match/issues
|
|
11
|
+
Keywords: ofac,sdn,sanctions,screening,aml,kyc,compliance,fuzzy-matching
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# ofacmatch (Python)
|
|
22
|
+
|
|
23
|
+
Python client for the self-hosted [OfacMatch REST API](https://github.com/krunalsolanki/ofac-match/blob/main/src/OfacMatch.Api/README.md): explainable OFAC SDN name screening that runs on **your own server**, so the names you screen never leave your network. Free and open source (Apache-2.0), with no dependencies outside the Python standard library.
|
|
24
|
+
|
|
25
|
+
> Potential matches only. A score measures how alike two names are written, not whether they are the same party. A person must review every potential match. It checks the OFAC SDN list only. Not legal advice.
|
|
26
|
+
|
|
27
|
+
## 1. Start the API (once)
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
docker run -p 8080:8080 ghcr.io/krunalsolanki/ofacmatch-api
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
It downloads the SDN list from OFAC at start-up and refreshes it daily.
|
|
34
|
+
|
|
35
|
+
## 2. Install the client
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install ofacmatch
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Or straight from GitHub:
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install "git+https://github.com/krunalsolanki/ofac-match#subdirectory=clients/python"
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Screen from Python
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from ofacmatch import Client
|
|
51
|
+
|
|
52
|
+
client = Client("http://localhost:8080") # api_key="..." if the server requires one
|
|
53
|
+
|
|
54
|
+
result = client.screen("Aymen Zawahri", year_of_birth=1951)
|
|
55
|
+
for match in result["matches"]:
|
|
56
|
+
print(match["score"], match["listedName"], match["explanation"])
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### A whole customer list
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
customers = [
|
|
63
|
+
{"reference": "CUST-1001", "name": "Aymen Zawahri", "year_of_birth": 1951},
|
|
64
|
+
{"reference": "CUST-1002", "name": "Emily Carter", "year_of_birth": 1985, "country": "United States"},
|
|
65
|
+
# ... any number: sent 1,000 at a time
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
result = client.screen_batch(customers, min_score=85)
|
|
69
|
+
print(result["summary"]) # {'screened': 2, 'review': 1, 'likelyDifferentPerson': 0, 'noMatch': 1, 'errors': 0}
|
|
70
|
+
|
|
71
|
+
for row in result["results"]:
|
|
72
|
+
if row["status"] in ("review", "likely_different_person"):
|
|
73
|
+
best = row["matches"][0]
|
|
74
|
+
print(row["reference"], best["score"], best["listedName"])
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Each result keeps your `reference` and has a `status`:
|
|
78
|
+
|
|
79
|
+
- `review`: a potential match; a person must review it
|
|
80
|
+
- `likely_different_person`: every match has a birth year that differs from the one you gave; still check it
|
|
81
|
+
- `no_match`: nothing at or above the minimum score
|
|
82
|
+
- `error`: that item was invalid (`row["error"]` says why); the rest are still screened
|
|
83
|
+
|
|
84
|
+
With pandas: `client.screen_batch(df.rename(columns={"id": "reference"}).to_dict("records"))`.
|
|
85
|
+
|
|
86
|
+
### Other calls
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
client.compare("Jon Doe", "DOE, John") # how two names score, part by part
|
|
90
|
+
client.entry(2676) # the full SDN record behind a match
|
|
91
|
+
client.list_info() # which copy of the list the server uses
|
|
92
|
+
client.health() # ready once the list is loaded
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Errors raise `ofacmatch.OfacMatchError` with `.status` (HTTP status, or None if the server can't be reached) and `.errors` (per-field messages for invalid input).
|
|
96
|
+
|
|
97
|
+
## Command line
|
|
98
|
+
|
|
99
|
+
Screen a CSV (for example an Excel sheet saved as CSV) and get a results CSV with the best match, the explanation, and empty columns for the reviewer's decision:
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
ofacmatch csv customers.csv results.csv
|
|
103
|
+
ofacmatch screen "Aymen Zawahri" --yob 1951
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
The input needs a header row with a **Name** column (or **First name** and **Last name**). Optional: **ID** or **Reference**, **Year of birth** or **Date of birth**, **Country**, **Type**. Use `--url` and `--api-key` (or `OFACMATCH_URL` and `OFACMATCH_API_KEY`) for a server other than `http://localhost:8080`.
|
|
107
|
+
|
|
108
|
+
## Links
|
|
109
|
+
|
|
110
|
+
- [OfacMatch on GitHub](https://github.com/krunalsolanki/ofac-match): the library, evaluation and paper
|
|
111
|
+
- [REST API guide](https://github.com/krunalsolanki/ofac-match/blob/main/src/OfacMatch.Api/README.md)
|
|
112
|
+
- [Try it in the browser](https://krunalsolanki.github.io/ofac-match/), no install
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
ofacmatch/__init__.py,sha256=F_tAF3kli6jqU-rSGSkgu67VOkb5Td513hDrO4gvVts,535
|
|
2
|
+
ofacmatch/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
|
|
3
|
+
ofacmatch/cli.py,sha256=yXKHs8Dwuj-J-a3gUfE2j3XOfdFSLrAIhKhYa0QccKc,7073
|
|
4
|
+
ofacmatch/client.py,sha256=-bBfYo9dt_tGkQ5yBUMFtjIqj7ms40we_ZpVpO39TuA,7940
|
|
5
|
+
ofacmatch/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
ofacmatch-0.1.0.dist-info/METADATA,sha256=ceUaugch6vYs_wqGPmsBzNOmmdOqiScKCdHRaWQfw-Y,4788
|
|
7
|
+
ofacmatch-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
ofacmatch-0.1.0.dist-info/entry_points.txt,sha256=3IednVu1WPpeZ5v-w6rf46SypX3t9hUA1YYXMKap7d0,49
|
|
9
|
+
ofacmatch-0.1.0.dist-info/top_level.txt,sha256=MSAFmmmYgnXln-D3gKWoGoNOLR9uuggtMxOKPr_hC4c,10
|
|
10
|
+
ofacmatch-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ofacmatch
|