ofacmatch 0.1.0__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.
@@ -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,92 @@
1
+ # ofacmatch (Python)
2
+
3
+ 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.
4
+
5
+ > 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.
6
+
7
+ ## 1. Start the API (once)
8
+
9
+ ```bash
10
+ docker run -p 8080:8080 ghcr.io/krunalsolanki/ofacmatch-api
11
+ ```
12
+
13
+ It downloads the SDN list from OFAC at start-up and refreshes it daily.
14
+
15
+ ## 2. Install the client
16
+
17
+ ```bash
18
+ pip install ofacmatch
19
+ ```
20
+
21
+ Or straight from GitHub:
22
+
23
+ ```bash
24
+ pip install "git+https://github.com/krunalsolanki/ofac-match#subdirectory=clients/python"
25
+ ```
26
+
27
+ ## Screen from Python
28
+
29
+ ```python
30
+ from ofacmatch import Client
31
+
32
+ client = Client("http://localhost:8080") # api_key="..." if the server requires one
33
+
34
+ result = client.screen("Aymen Zawahri", year_of_birth=1951)
35
+ for match in result["matches"]:
36
+ print(match["score"], match["listedName"], match["explanation"])
37
+ ```
38
+
39
+ ### A whole customer list
40
+
41
+ ```python
42
+ customers = [
43
+ {"reference": "CUST-1001", "name": "Aymen Zawahri", "year_of_birth": 1951},
44
+ {"reference": "CUST-1002", "name": "Emily Carter", "year_of_birth": 1985, "country": "United States"},
45
+ # ... any number: sent 1,000 at a time
46
+ ]
47
+
48
+ result = client.screen_batch(customers, min_score=85)
49
+ print(result["summary"]) # {'screened': 2, 'review': 1, 'likelyDifferentPerson': 0, 'noMatch': 1, 'errors': 0}
50
+
51
+ for row in result["results"]:
52
+ if row["status"] in ("review", "likely_different_person"):
53
+ best = row["matches"][0]
54
+ print(row["reference"], best["score"], best["listedName"])
55
+ ```
56
+
57
+ Each result keeps your `reference` and has a `status`:
58
+
59
+ - `review`: a potential match; a person must review it
60
+ - `likely_different_person`: every match has a birth year that differs from the one you gave; still check it
61
+ - `no_match`: nothing at or above the minimum score
62
+ - `error`: that item was invalid (`row["error"]` says why); the rest are still screened
63
+
64
+ With pandas: `client.screen_batch(df.rename(columns={"id": "reference"}).to_dict("records"))`.
65
+
66
+ ### Other calls
67
+
68
+ ```python
69
+ client.compare("Jon Doe", "DOE, John") # how two names score, part by part
70
+ client.entry(2676) # the full SDN record behind a match
71
+ client.list_info() # which copy of the list the server uses
72
+ client.health() # ready once the list is loaded
73
+ ```
74
+
75
+ 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).
76
+
77
+ ## Command line
78
+
79
+ 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:
80
+
81
+ ```bash
82
+ ofacmatch csv customers.csv results.csv
83
+ ofacmatch screen "Aymen Zawahri" --yob 1951
84
+ ```
85
+
86
+ 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`.
87
+
88
+ ## Links
89
+
90
+ - [OfacMatch on GitHub](https://github.com/krunalsolanki/ofac-match): the library, evaluation and paper
91
+ - [REST API guide](https://github.com/krunalsolanki/ofac-match/blob/main/src/OfacMatch.Api/README.md)
92
+ - [Try it in the browser](https://krunalsolanki.github.io/ofac-match/), no install
@@ -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"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -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())
@@ -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}
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,13 @@
1
+ README.md
2
+ pyproject.toml
3
+ ofacmatch/__init__.py
4
+ ofacmatch/__main__.py
5
+ ofacmatch/cli.py
6
+ ofacmatch/client.py
7
+ ofacmatch/py.typed
8
+ ofacmatch.egg-info/PKG-INFO
9
+ ofacmatch.egg-info/SOURCES.txt
10
+ ofacmatch.egg-info/dependency_links.txt
11
+ ofacmatch.egg-info/entry_points.txt
12
+ ofacmatch.egg-info/top_level.txt
13
+ tests/test_client.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ofacmatch = ofacmatch.cli:main
@@ -0,0 +1 @@
1
+ ofacmatch
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ofacmatch"
7
+ version = "0.1.0"
8
+ description = "Python client for the self-hosted OfacMatch REST API: explainable OFAC SDN name screening that keeps your data on your own server."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ authors = [{ name = "Krunal Solanki" }]
13
+ keywords = ["ofac", "sdn", "sanctions", "screening", "aml", "kyc", "compliance", "fuzzy-matching"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "Intended Audience :: Financial and Insurance Industry",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Office/Business :: Financial",
20
+ "Typing :: Typed",
21
+ ]
22
+ dependencies = []
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/krunalsolanki/ofac-match"
26
+ Documentation = "https://github.com/krunalsolanki/ofac-match/blob/main/clients/python/README.md"
27
+ "REST API" = "https://github.com/krunalsolanki/ofac-match/blob/main/src/OfacMatch.Api/README.md"
28
+ Issues = "https://github.com/krunalsolanki/ofac-match/issues"
29
+
30
+ [project.scripts]
31
+ ofacmatch = "ofacmatch.cli:main"
32
+
33
+ [tool.setuptools.packages.find]
34
+ include = ["ofacmatch*"]
35
+
36
+ [tool.setuptools.package-data]
37
+ ofacmatch = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,221 @@
1
+ """Tests against a small fake API server, so they run without Docker or .NET.
2
+
3
+ Run from clients/python: python -m unittest discover -s tests
4
+ """
5
+
6
+ import csv
7
+ import io
8
+ import json
9
+ import os
10
+ import sys
11
+ import tempfile
12
+ import threading
13
+ import unittest
14
+ from contextlib import redirect_stdout
15
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
16
+
17
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
18
+
19
+ from ofacmatch import Client, OfacMatchError # noqa: E402
20
+ from ofacmatch.cli import main # noqa: E402
21
+
22
+ LIST = {"entries": 3, "aliases": 1, "source": "fake", "downloadedUtc": "2026-11-17 00:00:00Z"}
23
+ NOTICE = "Potential matches only. Checks the OFAC SDN list only."
24
+
25
+
26
+ def fake_match(score=97.0, dob_conflict=False):
27
+ return {
28
+ "score": score, "entryId": 100, "listedName": "DOE, John", "type": "Individual", "programs": ["SDGT"],
29
+ "matchedName": "DOE, John", "matchedNameKind": "Primary", "technique": "FullName",
30
+ "dateOfBirthConflict": dob_conflict, "countryConflict": False, "parts": [],
31
+ "explanation": "Score 97.0 via FullName against Primary name \"DOE, John\"",
32
+ }
33
+
34
+
35
+ class FakeApi(BaseHTTPRequestHandler):
36
+ batch_sizes = []
37
+ api_key = None
38
+
39
+ def log_message(self, *args):
40
+ pass
41
+
42
+ def send(self, status, body):
43
+ data = json.dumps(body).encode()
44
+ self.send_response(status)
45
+ self.send_header("Content-Type", "application/json")
46
+ self.send_header("Content-Length", str(len(data)))
47
+ self.end_headers()
48
+ self.wfile.write(data)
49
+
50
+ def authorised(self):
51
+ if self.api_key and self.headers.get("X-Api-Key") != self.api_key:
52
+ self.send(401, {"title": "Missing or wrong X-Api-Key header.", "status": 401})
53
+ return False
54
+ return True
55
+
56
+ def do_GET(self):
57
+ if not self.authorised():
58
+ return
59
+ if self.path == "/health":
60
+ self.send(200, {"status": "ok", "list": LIST})
61
+ elif self.path == "/v1/list":
62
+ self.send(200, LIST)
63
+ elif self.path == "/v1/entries/100":
64
+ self.send(200, {"entryId": 100, "name": "DOE, John"})
65
+ else:
66
+ self.send(404, {"title": "Not Found", "detail": "No SDN entry 999 in the list in use.", "status": 404})
67
+
68
+ def do_POST(self):
69
+ if not self.authorised():
70
+ return
71
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
72
+ if self.path == "/v1/screen":
73
+ if not body.get("name"):
74
+ self.send(400, {"title": "One or more validation errors occurred.", "status": 400, "errors": {"name": ["Name is required."]}})
75
+ return
76
+ matches = [fake_match()] if "doe" in body["name"].lower() else []
77
+ self.send(200, {"name": body["name"], "potentialMatches": len(matches), "matches": matches, "minScore": body.get("minScore", 85), "list": LIST, "notice": NOTICE, "echo": body})
78
+ elif self.path == "/v1/screen/batch":
79
+ items = body["items"]
80
+ FakeApi.batch_sizes.append(len(items))
81
+ results = []
82
+ for i, item in enumerate(items):
83
+ name = item.get("name") or ""
84
+ if not name:
85
+ results.append({"index": i, "reference": item.get("reference"), "name": "", "status": "error", "potentialMatches": 0, "matches": [], "error": "Name is required."})
86
+ elif "doe" in name.lower():
87
+ conflict = item.get("yearOfBirth") == 1990
88
+ status = "likely_different_person" if conflict else "review"
89
+ results.append({"index": i, "reference": item.get("reference"), "name": name.upper(), "status": status, "potentialMatches": 1, "matches": [fake_match(dob_conflict=conflict)], "error": None})
90
+ else:
91
+ results.append({"index": i, "reference": item.get("reference"), "name": name.upper(), "status": "no_match", "potentialMatches": 0, "matches": [], "error": None})
92
+ self.send(200, {"summary": {}, "results": results, "minScore": body.get("minScore", 85), "list": LIST, "notice": NOTICE})
93
+ elif self.path == "/v1/compare":
94
+ self.send(200, {"score": 92.0, "parts": [], "echo": body})
95
+ else:
96
+ self.send(404, {"title": "Not Found", "status": 404})
97
+
98
+
99
+ class ClientTests(unittest.TestCase):
100
+ @classmethod
101
+ def setUpClass(cls):
102
+ cls.server = ThreadingHTTPServer(("127.0.0.1", 0), FakeApi)
103
+ cls.url = f"http://127.0.0.1:{cls.server.server_address[1]}"
104
+ threading.Thread(target=cls.server.serve_forever, daemon=True).start()
105
+
106
+ @classmethod
107
+ def tearDownClass(cls):
108
+ cls.server.shutdown()
109
+
110
+ def setUp(self):
111
+ FakeApi.batch_sizes = []
112
+ FakeApi.api_key = None
113
+ self.client = Client(self.url)
114
+
115
+ def test_screen_sends_api_field_names(self):
116
+ result = self.client.screen("John Doe", type="individual", year_of_birth=1970, country="US", min_score=90, max_results=3)
117
+ self.assertEqual(result["potentialMatches"], 1)
118
+ self.assertEqual(result["echo"], {"name": "John Doe", "type": "individual", "yearOfBirth": 1970, "country": "US", "minScore": 90, "maxResults": 3})
119
+
120
+ def test_screen_leaves_out_unset_fields(self):
121
+ self.assertEqual(self.client.screen("Emily Carter")["echo"], {"name": "Emily Carter"})
122
+
123
+ def test_validation_error_is_raised_with_field_messages(self):
124
+ with self.assertRaises(OfacMatchError) as raised:
125
+ self.client.screen("")
126
+ self.assertEqual(raised.exception.status, 400)
127
+ self.assertEqual(raised.exception.errors, {"name": ["Name is required."]})
128
+ self.assertIn("Name is required.", str(raised.exception))
129
+
130
+ def test_batch_splits_large_lists_and_keeps_order(self):
131
+ items = [{"name": "John Doe" if i % 2 else "Emily Carter", "reference": f"C-{i}"} for i in range(2500)]
132
+ result = self.client.screen_batch(items)
133
+ self.assertEqual(FakeApi.batch_sizes, [1000, 1000, 500])
134
+ self.assertEqual([r["index"] for r in result["results"]], list(range(2500)))
135
+ self.assertEqual(result["results"][1999]["reference"], "C-1999")
136
+ self.assertEqual(result["summary"], {"screened": 2500, "review": 1250, "likelyDifferentPerson": 0, "noMatch": 1250, "errors": 0})
137
+
138
+ def test_batch_statuses_and_python_style_keys(self):
139
+ result = self.client.screen_batch([
140
+ {"name": "John Doe", "year_of_birth": 1970, "reference": 1},
141
+ {"name": "John Doe", "yearOfBirth": 1990},
142
+ {"name": ""},
143
+ {"name": "Emily Carter"},
144
+ ])
145
+ self.assertEqual([r["status"] for r in result["results"]], ["review", "likely_different_person", "error", "no_match"])
146
+ self.assertEqual(result["results"][0]["reference"], "1")
147
+ self.assertEqual(result["summary"]["errors"], 1)
148
+
149
+ def test_batch_rejects_empty_and_non_mappings(self):
150
+ with self.assertRaises(ValueError):
151
+ self.client.screen_batch([])
152
+ with self.assertRaises(TypeError):
153
+ self.client.screen_batch(["John Doe"])
154
+
155
+ def test_lookups(self):
156
+ self.assertEqual(self.client.health()["status"], "ok")
157
+ self.assertEqual(self.client.list_info()["entries"], 3)
158
+ self.assertEqual(self.client.entry(100)["name"], "DOE, John")
159
+ self.assertEqual(self.client.compare("Jon Doe", "DOE, John", companies=True)["echo"], {"name": "Jon Doe", "otherName": "DOE, John", "companies": True})
160
+ with self.assertRaises(OfacMatchError) as raised:
161
+ self.client.entry(999)
162
+ self.assertEqual(raised.exception.status, 404)
163
+ self.assertIn("No SDN entry 999", str(raised.exception))
164
+
165
+ def test_api_key(self):
166
+ FakeApi.api_key = "secret"
167
+ with self.assertRaises(OfacMatchError) as raised:
168
+ self.client.list_info()
169
+ self.assertEqual(raised.exception.status, 401)
170
+ self.assertEqual(Client(self.url, api_key="secret").list_info()["entries"], 3)
171
+
172
+ def test_unreachable_server(self):
173
+ with self.assertRaises(OfacMatchError) as raised:
174
+ Client("http://127.0.0.1:1", timeout=2).health()
175
+ self.assertIsNone(raised.exception.status)
176
+
177
+ def test_base_url_must_be_http(self):
178
+ with self.assertRaises(ValueError):
179
+ Client("localhost:8080")
180
+
181
+ def test_cli_csv(self):
182
+ with tempfile.TemporaryDirectory() as folder:
183
+ source = os.path.join(folder, "in.csv")
184
+ target = os.path.join(folder, "out.csv")
185
+ with open(source, "w", newline="", encoding="utf-8") as f:
186
+ f.write("Customer ID;First name;Last name;Date of birth;Country\n")
187
+ f.write("1001;John;Doe;15 Mar 1970;Freedonia\n")
188
+ f.write("1002;Emily;Carter;1985;United States\n")
189
+ f.write("1003;;;;\n")
190
+ f.write("=CMD();John;Doe;1990;\n")
191
+
192
+ out = io.StringIO()
193
+ with redirect_stdout(out):
194
+ code = main(["--url", self.url, "csv", source, target])
195
+ self.assertEqual(code, 0, out.getvalue())
196
+ self.assertIn("Screened 4", out.getvalue())
197
+
198
+ with open(target, newline="", encoding="utf-8-sig") as f:
199
+ rows = list(csv.DictReader(f))
200
+ self.assertEqual([r["result"] for r in rows], ["review", "no_match", "error: Name is required.", "likely_different_person"])
201
+ self.assertEqual(rows[0]["reference"], "1001")
202
+ self.assertEqual(rows[0]["best_listed_name"], "DOE, John")
203
+ self.assertEqual(rows[2]["reference"], "1003")
204
+ self.assertEqual(rows[3]["reference"], "'=CMD()")
205
+ self.assertIn("reviewer_decision", rows[0])
206
+
207
+ def test_cli_needs_a_name_column(self):
208
+ with tempfile.TemporaryDirectory() as folder:
209
+ source = os.path.join(folder, "in.csv")
210
+ with open(source, "w", encoding="utf-8") as f:
211
+ f.write("Customer ID,Phone\n1,555\n")
212
+ err = io.StringIO()
213
+ from contextlib import redirect_stderr
214
+ with redirect_stderr(err):
215
+ code = main(["--url", self.url, "csv", source, os.path.join(folder, "out.csv")])
216
+ self.assertEqual(code, 2)
217
+ self.assertIn("no Name column", err.getvalue())
218
+
219
+
220
+ if __name__ == "__main__":
221
+ unittest.main()