Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[flake8]
# Lint for real defects — pyflakes (unused imports/vars, undefined names, f-string
# bugs) and syntax errors (E9) — rather than fighting a formatter over whitespace
# and line length. Run: make lint
select = F,E9
exclude =
.git,
__pycache__,
build,
dist,
site,
.hypothesis,
.pytest_cache,
*.egg-info
24 changes: 24 additions & 0 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
name: Bug report
about: Something isn't working as documented
title: "[Bug] "
labels: bug
---

**What happened**
A clear description of the bug.

**Minimal reproduction**
The smallest code that triggers it, plus the shape/dtypes of the data it ran on:

```python
# ...
```

**Expected vs. actual behavior**

**Environment**
- philanthropy version:
- Python version:
- scikit-learn version:
- OS:
8 changes: 8 additions & 0 deletions .github/ISSUE_TEMPLATE/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
blank_issues_enabled: true
contact_links:
- name: 📖 Documentation
url: https://PhilanthroPy-Project.github.io/PhilanthroPy/
about: Check the docs first — many questions are answered there.
- name: 🔗 UniSchema (event source)
url: https://github.com/PhilanthroPy-Project/UniSchema
about: Issues about the ConstituentEvent stream itself belong in UniSchema.
17 changes: 17 additions & 0 deletions .github/ISSUE_TEMPLATE/feature_request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
name: Feature request
about: Suggest an estimator, transformer, metric, or improvement
title: "[Feature] "
labels: enhancement
---

**Problem / use case**
Which advancement or fundraising workflow does this serve?

**Proposed API**
Sketch the class or function. For estimators/transformers, note the intended
sklearn-compatible signature (`fit`/`transform`/`predict_*`).

**Alternatives considered**

**Would you be willing to open a PR?**
9 changes: 9 additions & 0 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
## What & why

<!-- What does this change and which problem/issue does it address? -->

## Checklist
- [ ] `make ci` passes locally (lint → collection → tests → coverage ≥ 85%)
- [ ] New/changed public API has docstrings and is exported in the subpackage `__init__.py`
- [ ] Tests added or updated
- [ ] `CHANGELOG.md` updated under `[Unreleased]`
4 changes: 3 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.11"]
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
Expand All @@ -20,6 +20,8 @@ jobs:
python-version: ${{ matrix.python-version }}
- name: Install package with dev deps
run: pip install -e ".[dev]"
- name: Lint (flake8 — real defects)
run: python -m flake8 philanthropy tests examples
- name: Check for import/collection errors (fast gate)
run: |
python -m pytest tests/ --collect-only -q || {
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,6 @@ jobs:
- name: Install dependencies
run: |
pip install pytest pytest-cov hypothesis scikit-learn pandas numpy
pip install -e .
pip install -e ".[viz]"
- name: Run all tests with coverage
run: pytest tests/ --cov=philanthropy --cov-fail-under=85
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@ All notable changes to PhilanthroPy are documented here.
Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)

## [Unreleased]
### Added
- `constituent_events_to_features` carries `first_name` / `last_name` through to
the donor feature table when the UniSchema feed supplies them (guarded; null
when absent).
- Community health files: `.github` issue/PR templates,
`CODE_OF_CONDUCT.md` (Contributor Covenant 2.1), and `SECURITY.md`.
- flake8 lint gate — `.flake8` (enforces pyflakes `F` + syntax `E9` defects),
a `make lint` target folded into `make ci`, and a CI step.

### Fixed
- Cleared 31 real-defect lint violations (unused imports/variables) across the
package and tests, including two dead code blocks.

## [0.4.0] - 2026-07-18
### Added
Expand Down
131 changes: 131 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
# Contributor Covenant Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual
identity and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to a positive environment for our
community include:

* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall
community

Examples of unacceptable behavior include:

* The use of sexualized language or imagery, and sexual attention or advances of
any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address,
without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.

Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official email address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
**shivamlalakiya151299@gmail.com**. All complaints will be reviewed and
investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the
reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series of
actions.

**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or permanent
ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within the
community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].

Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder][mozilla].

[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[mozilla]: https://github.com/mozilla/diversity

For answers to common questions about this code of conduct, see the FAQ at
[https://www.contributor-covenant.org/faq][faq].

[faq]: https://www.contributor-covenant.org/faq
3 changes: 2 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# Contributing to PhilanthroPy

Thanks for helping improve PhilanthroPy! This guide covers the local checks
every change must pass before it reaches CI.
every change must pass before it reaches CI. By participating you agree to abide
by our [Code of Conduct](CODE_OF_CONDUCT.md).

## Setup

Expand Down
8 changes: 6 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
.PHONY: check test coverage ci
.PHONY: lint check test coverage ci

lint:
@echo "==> Linting (flake8 — real defects)..."
python -m flake8 philanthropy tests examples

check:
@echo "==> Checking for collection errors..."
Expand All @@ -14,5 +18,5 @@ coverage: test
@echo "==> Checking coverage..."
python -m pytest tests/ --cov=philanthropy --cov-fail-under=85 --cov-report=term-missing

ci: coverage
ci: lint coverage
@echo "==> All CI checks passed locally."
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ features["affinity_score"] = model.predict_affinity_score(X)

| Column | Built from |
|---|---|
| `constituent_email`, `first_name`, `last_name` | identity fields, carried through when present |
| `total_gift_amount`, `gift_count`, `first_gift_date`, `last_gift_date` | `DONATION` events |
| `event_attendance_count` | `EVENT_REGISTRATION` events |
| `email_click_count` | `EMAIL_CLICK` events |
Expand Down
18 changes: 18 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Security Policy

## Supported versions

Security fixes land on the latest `0.4.x` release.

| Version | Supported |
| ------- | ------------------ |
| 0.4.x | :white_check_mark: |
| < 0.4 | :x: |

## Reporting a vulnerability

Please **do not open a public issue** for security problems.

Email **shivamlalakiya151299@gmail.com** with a description and, if possible, a
minimal reproduction. You can expect an acknowledgement within a few days and a
coordinated fix and disclosure.
1 change: 0 additions & 1 deletion philanthropy/experimental/_lapse.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.ensemble import RandomForestClassifier
from sklearn.utils.validation import check_X_y, check_is_fitted, check_array
Expand Down
43 changes: 34 additions & 9 deletions philanthropy/ingest/_constituent_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
# so an empty batch still yields a correctly-typed, downstream-safe frame.
_FEATURE_DTYPES: "dict[str, object]" = {
"constituent_email": "object",
"first_name": "object",
"last_name": "object",
"total_gift_amount": "float64",
"gift_count": "int64",
"event_attendance_count": "int64",
Expand Down Expand Up @@ -70,8 +72,9 @@ def constituent_events_to_features(
events : iterable of mapping, or DataFrame
Records following UniSchema's ``ConstituentEvent`` schema. Each event
carries at least ``constituentEmail``, ``eventType``, ``sourceSystem``,
and ``createdAt`` (ISO-8601); ``amount``, ``externalConstituentId``, and
``eventId`` are optional. Accepts the output of
and ``createdAt`` (ISO-8601); ``amount``, ``externalConstituentId``,
``eventId``, ``firstName``, and ``lastName`` are optional. Accepts the
output of
:func:`read_constituent_events`, a list of dicts, or a DataFrame of the
same fields.
reference_date : str or datetime-like, optional
Expand All @@ -89,8 +92,9 @@ def constituent_events_to_features(
features : pandas.DataFrame
One row per constituent, indexed by ``constituent_id`` (the
``externalConstituentId`` when present, else ``constituentEmail``), with
the columns declared in ``_FEATURE_DTYPES``. Rows are sorted by
``constituent_id`` for determinism.
the columns declared in ``_FEATURE_DTYPES`` (``first_name`` /
``last_name`` are populated from the feed when available, else null).
Rows are sorted by ``constituent_id`` for determinism.

Warns
-----
Expand Down Expand Up @@ -173,6 +177,12 @@ def constituent_events_to_features(
grouped = df.groupby("_constituent_id", sort=True)
out = pd.DataFrame(index=grouped.size().index)
out["constituent_email"] = grouped["constituentEmail"].first()
# Optional identity fields — carried through when the feed supplies them
# (the output is a donor-level table, not a de-identified feature store, so
# it already holds constituent_email). ``.first()`` skips nulls, so a donor
# whose name rode in on only some events still resolves. Absent column -> None.
for out_col, src in (("first_name", "firstName"), ("last_name", "lastName")):
out[out_col] = grouped[src].first() if src in df.columns else None
out["total_gift_amount"] = grouped["_gift_amount"].sum()
out["gift_count"] = grouped["_is_donation"].sum()
out["event_attendance_count"] = grouped["_is_event"].sum()
Expand Down Expand Up @@ -203,8 +213,11 @@ def read_constituent_events(

* a single ``.json`` file holding one event (object) or many (array);
* a ``.ndjson`` / ``.jsonl`` batch, one event per line;
* a directory, in which case every ``*.json``, ``*.ndjson``, and ``*.jsonl``
file directly inside it is read and concatenated (sorted by name).
* a directory, which is walked **recursively** — every ``*.json``,
``*.ndjson``, and ``*.jsonl`` file at any depth is read and concatenated,
sorted by relative path. This handles UniSchema's date-partitioned egress
(``{prefix}/{vendor}/{yyyy}/{mm}/{dd}/{eventId}.json``); a flat directory
still works too. ``*.manifest.json`` batch sidecars are skipped.

Parameters
----------
Expand All @@ -218,10 +231,22 @@ def read_constituent_events(
"""
p = Path(path)
if p.is_dir():
# UniSchema's local egress is date-partitioned — it writes each event to
# {prefix}/{vendor}/{yyyy}/{mm}/{dd}/{eventId}.json (see UniSchema
# src/egress/objectKey.ts), so the files sit several levels down and a
# non-recursive scan of the top dir finds nothing. Walk the whole tree.
events: "list[dict]" = []
for child in sorted(p.iterdir()):
if child.suffix.lower() in {".json", ".ndjson", ".jsonl"}:
events.extend(_read_events_file(child))
files = [
f
for f in p.rglob("*")
if f.is_file()
and f.suffix.lower() in {".json", ".ndjson", ".jsonl"}
# Skip S3 batch sidecars — batch metadata, not ConstituentEvents.
and not f.name.lower().endswith(".manifest.json")
]
# Sort by relative path so ordering is deterministic across platforms.
for child in sorted(files, key=lambda f: f.relative_to(p).as_posix()):
events.extend(_read_events_file(child))
return events
return _read_events_file(p)

Expand Down
Loading
Loading