-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind_grantors.py
More file actions
173 lines (148 loc) · 5.73 KB
/
find_grantors.py
File metadata and controls
173 lines (148 loc) · 5.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#!/usr/bin/env python3
"""
Charity Grantor Finder for Outward Bound NZ
Usage: python find_grantors.py input.csv output.csv
Input CSV must have a column 'name' (or first column used as charity name).
Queries the NZ Charities Register OData API and uses Claude to evaluate
each charity's likelihood of making grants to Outward Bound NZ.
"""
import csv
import json
import re
import sys
import time
import httpx
import anthropic
ODATA_URL = "https://www.odata.charities.govt.nz/GrpOrgLatestReturns"
OUTWARD_BOUND_PROFILE = """
Outward Bound NZ runs outdoor adventure and personal development courses
for young New Zealanders. They build resilience, leadership, teamwork and
life skills through wilderness experiences. They seek philanthropic grants
from foundations and charitable trusts to fund youth participation.
"""
def search_charity(name: str) -> list[dict]:
"""Query OData API for charities matching the given name."""
# Strip chars that break OData filter syntax (parentheses, quotes, etc.)
safe_name = re.sub(r"[()'\"]", "", name).strip()
params = {
"$format": "json",
"$filter": f"substringof('{safe_name}',Name) and RegistrationStatus eq 'Registered'",
"$select": (
"Name,CharityRegistrationNumber,Activities,Beneficiaries,Sectors,"
"MainActivityName,MainSectorName,MainBeneficiaryName,"
"CharitySummaryURL,PercentageSpentOverseas,"
"CharitablePurpose,"
"AnnualReturnId,YearEnded,AnnualReturnDueDate,IsCertifiedToBeCorrect,"
"TotalGrossIncome,TotalExpenditure,"
"TotalAssets,TotalEquity,NetSurplusDeficitForTheYear"
),
"$top": "5",
}
r = httpx.get(ODATA_URL, params=params, timeout=15)
r.raise_for_status()
return r.json().get("d", [])
def evaluate(name: str, results: list[dict], client: anthropic.Anthropic) -> dict:
"""Use Claude to evaluate whether the charity is likely to donate to Outward Bound NZ."""
if not results:
return {
"match_found": "no",
"charity_name_in_register": "",
"registration_number": "",
"activities": "",
"sectors": "",
"beneficiaries": "",
"charitable_purpose": "",
"likely_donor": "unknown",
"confidence": "",
"reasoning": "Not found in register",
}
prompt = f"""You are evaluating NZ charities as potential grant-makers for Outward Bound NZ.
CLIENT: {OUTWARD_BOUND_PROFILE}
CRITERIA for likely donor:
- Activities includes "Makes grants to organisations"
- Sector/beneficiaries: youth, education, sports/recreation, personal development, community
- Operates in NZ (not exclusively overseas)
CHARITY SEARCHED: "{name}"
REGISTER RESULTS (up to 5):
{json.dumps(results, indent=2)}
Tasks:
1. Identify which result (if any) matches the searched charity name.
2. Evaluate if that charity is likely to make grants to Outward Bound NZ.
Respond with valid JSON only:
{{
"match_found": "yes" | "no" | "uncertain",
"charity_name_in_register": "<matched name or empty>",
"registration_number": "<CC-XXXX or empty>",
"activities": "<Activities field value>",
"sectors": "<Sectors field value>",
"beneficiaries": "<Beneficiaries field value>",
"charitable_purpose": "<CharitablePurpose field value>",
"likely_donor": "yes" | "no" | "uncertain",
"confidence": "high" | "medium" | "low",
"reasoning": "<1-2 sentence explanation>"
}}"""
msg = client.messages.create(
model="claude-opus-4-6",
max_tokens=512,
messages=[{"role": "user", "content": prompt}],
)
print(msg)
text = msg.content[0].text.strip()
if text.startswith("```"):
text = text.split("```", 2)[1]
if text.startswith("json"):
text = text[4:]
text = text.rsplit("```", 1)[0]
return json.loads(text.strip())
def main():
if len(sys.argv) != 3:
print("Usage: python find_grantors.py input.csv output.csv", file=sys.stderr)
sys.exit(1)
input_path, output_path = sys.argv[1], sys.argv[2]
client = anthropic.Anthropic()
with open(input_path, newline="") as f:
reader = csv.DictReader(f)
fieldnames = reader.fieldnames
rows = list(reader)
name_col = next((c for c in fieldnames if c.lower() == "name"), fieldnames[0])
output_fields = fieldnames + [
"match_found",
"charity_name_in_register",
"registration_number",
"activities",
"sectors",
"beneficiaries",
"charitable_purpose",
"likely_donor",
"confidence",
"reasoning",
]
with open(output_path, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=output_fields)
writer.writeheader()
for i, row in enumerate(rows):
name = row[name_col]
print(f"Processing ({i + 1}/{len(rows)}): {name}", flush=True)
try:
results = search_charity(name)
evaluation = evaluate(name, results, client)
# print(json.dumps(results, indent=4))
except Exception as e:
print(f"ERROR: {e}", flush=True)
evaluation = {
"match_found": "error",
"charity_name_in_register": "",
"registration_number": "",
"activities": "",
"sectors": "",
"beneficiaries": "",
"charitable_purpose": "",
"likely_donor": "error",
"confidence": "",
"reasoning": str(e),
}
writer.writerow({**row, **evaluation})
if i < len(rows) - 1:
time.sleep(0.5)
if __name__ == "__main__":
main()