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
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ MODEL_ID=cardiffnlp/twitter-roberta-base-sentiment-latest
MODEL_REVISION=3216a57f2a0d9c45a2e6c20157c20c49fb4bf9c7
ENABLED_SOURCES=
DATA_RIGHTS_CONFIRMED=false
PERMISSIONS_PATH=pipeline/source_permissions.json
ALERTS_ENABLED=false
ASPECTS_ENABLED=false
FRESHNESS_HOURS=192
LOG_LEVEL=INFO
# Only needed for an authorized live NewsAPI run; paid production use is not provisioned.
Expand Down
29 changes: 27 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ jobs:
- run: make test
- run: brand-pipeline demo && brand-pipeline demo && brand-pipeline evaluate
- name: Secret scan (working tree)
run: detect-secrets scan -n --exclude-files '(requirements.*lock|docs/evidence/|docs/history/|docs/samples/|nlp/model_registry.json|data/|outputs/|nlp/manual_labels.csv)' > /tmp/secrets.json && python -m scripts.check_secret_scan /tmp/secrets.json
run: detect-secrets scan -n --exclude-files '(requirements.*lock|docs/evidence/|docs/history/|docs/samples/|nlp/model_registry.json|nlp/aspect_registry.json|pipeline/base_image.json|data/|outputs/|nlp/manual_labels.csv)' > /tmp/secrets.json && python -m scripts.check_secret_scan /tmp/secrets.json
- name: Dependency audit
run: pip-audit -r requirements.lock
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
Expand Down Expand Up @@ -57,5 +57,30 @@ jobs:
done
curl -fsS http://127.0.0.1:8000/v1/summary
test "$(curl -s -o /dev/null -w '%{http_code}' -X POST http://127.0.0.1:8000/run)" = "404"
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065
with:
python-version: '3.11'
- name: Prepare and build a hash-verified aggregate-only release
run: |
pip install -r requirements.lock
pip install -e . -c requirements.lock
mkdir -p runtime/release-source
brand-pipeline demo --db runtime/release-source/mentions.db --output runtime/release-source/reports > runtime/release-source/summary.json
brand-pipeline prepare-release --summary runtime/release-source/summary.json --destination runtime/release-bundle
brand-pipeline verify-release --directory runtime/release-bundle
docker build -t brand-reputation:release runtime/release-bundle
- name: Verify release image on a read-only filesystem
run: |
docker run -d --read-only --tmpfs /tmp --name reputation-release -p 127.0.0.1:8001:8000 brand-reputation:release
test "$(docker exec reputation-release id -u)" = "10001"
for attempt in $(seq 1 20); do
if curl -fsS http://127.0.0.1:8001/health/live; then break; fi
sleep 1
done
curl -fsS http://127.0.0.1:8001/v1/summary
test "$(curl -s -o /dev/null -w '%{http_code}' -X POST http://127.0.0.1:8001/run)" = "404"
- if: always()
run: docker logs reputation; docker rm -f reputation
run: |
docker logs reputation || true
docker logs reputation-release || true
docker rm -f reputation reputation-release || true
19 changes: 15 additions & 4 deletions .github/workflows/model-smoke.yml
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
name: Optional CPU model smoke
on:
workflow_dispatch:
push:
branches: [codex/flagship-upgrade]
paths:
- 'nlp/**'
- 'pipeline/**'
- 'evaluation/**'
- 'scripts/model_smoke.py'
- 'requirements-worker-linux.lock'
- '.github/workflows/model-smoke.yml'
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
permissions:
contents: read
concurrency:
group: cpu-model-smoke
cancel-in-progress: false
cancel-in-progress: true
jobs:
real-models:
runs-on: ubuntu-latest
Expand All @@ -26,11 +35,13 @@ jobs:
cache-dependency-path: requirements-worker-linux.lock
- run: pip install -r requirements-worker-linux.lock && pip install . -c requirements-worker-linux.lock && pip check
- name: Synthetic-only real-model comparison (no human quality claim)
run: brand-pipeline evaluate --transformers --output runtime/smoke
run: python -m scripts.model_smoke --output runtime/smoke
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
with:
name: cpu-model-smoke
path: |
runtime/smoke/metrics.json
runtime/smoke/summary.csv
runtime/smoke/synthetic-calibration.json
runtime/smoke/model-smoke.json
runtime/smoke/overall/metrics.json
runtime/smoke/overall/summary.csv
retention-days: 14
8 changes: 7 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,10 @@ Added typed configuration/data/prediction/report contracts; Unicode-preserving n

Security changes: removed unauthenticated execution endpoint; disabled unapproved source collectors; stopped weekly raw-data commits; removed conflicting scraper dependency hacks; updated dependencies after actual advisory findings. API v2 canonical summary changes the old `/health-score` payload. Old entrypoint names remain where safe; unsafe legacy live behavior fails explicitly. Existing data, historical metrics and Git history are preserved.

This candidate is **not released or production-ready**. Human/data rights, reproducible real ABSA, representative evaluation, hosted CI and deployment/runtime verification remain explicit release gates.
This candidate is **not released or production-ready**. Human/data rights, representative independent evaluation and public deployment remain explicit release gates.

## Next-stage readiness work — December 4, 2026

Added current scoped source-permission gates and exact export hashes; two prediction-blind annotation packets, disagreement/kappa, adjudication/exclusion and frozen splits; dev-only temperature/coverage fitting; pinned safetensors joint aspect spans with unknown/truncation semantics and additive persistence; concrete hash-verified aggregate-only release bundles with pinned base image; Linux CPU model smoke and read-only container verification. The first actual Linux install exposed CPU index resolution failure; the lock now uses the official wheel URL and SHA-256.

Owner confirmed no approved source access and deferred code-license selection. No source activation, human labels, operational threshold, public deployment, merge or release is claimed. See the readiness report for exact terminal outcomes.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ install:
demo:
brand-pipeline demo
test:
pytest --cov=config --cov=database --cov=pipeline --cov=analytics --cov=api --cov=nlp.evaluator --cov=nlp.sentiment_engine --cov=scrapers --cov=reports.report_generator --cov=reports.render_template --cov-report=term-missing --cov-report=xml
pytest --cov=config --cov=database --cov=pipeline --cov=analytics --cov=api --cov=nlp.evaluator --cov=nlp.sentiment_engine --cov=nlp.aspects --cov=evaluation --cov=scrapers --cov=reports.report_generator --cov=reports.render_template --cov-report=term-missing --cov-report=xml
lint:
ruff check .
ruff format --check .
Expand Down
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

A local-first NLP engineering project for turning timestamped brand mentions into auditable sentiment summaries and a read-only API. Versioned predictions, explicit coverage, transactional SQLite snapshots, keyless reports, and reproducible evaluation make the evidence inspectable.

**Status: release gates remain open.** Local verification is recorded in [the upgrade report](docs/flagship-upgrade-report.md). [Linux CI and Docker smoke checks passed](https://github.com/Axinion/brand-reputation-pipeline/actions/runs/47359108300). Public deployment has not been performed. No production SLA or demonstrated business impact is claimed.
**Status: release gates remain open.** Local verification is recorded in [the upgrade report](docs/flagship-upgrade-report.md). [Linux CI and Docker smoke checks passed](https://github.com/Axinion/brand-reputation-pipeline/actions/runs/47369365445). Public deployment has not been performed. No production SLA or demonstrated business impact is claimed.

The upgrade lives on `codex/flagship-upgrade`. The commands below check out that branch. See [publication status](docs/publication-status.md) for hosted verification.

Expand Down Expand Up @@ -54,6 +54,8 @@ For real CPU models install `requirements-worker.lock`. See [evaluation](docs/ev

**Actual exploratory ML result:** after excluding 81 synthetic historical annotations, only 19 legacy news examples remain (11 train / 4 development / 4 test). Train-majority, TF-IDF/logistic and RoBERTa each score 25% accuracy on those four test examples. This is not credible generalization evidence. Full per-class, coverage, calibration and uncertainty results are in [the executed artifact](docs/evidence/legacy-exploratory-evaluation.json). Historical metrics are preserved separately and must not be presented as current results.

Live Reddit/review adapters are disabled pending authorized access and rights review. NewsAPI is opt-in with explicit rights confirmation and credentials; its free developer plan is not a production hosting license. The weekly workflow now publishes synthetic aggregate artifacts, never raw databases. No source data, historical reports or Git history has been deleted.
[Next-stage readiness work](docs/readiness/stage-report.md) adds evidence-bound permission gates, blinded annotation/adjudication, development-only calibration, verified safetensors aspect extraction and immutable release preparation. Aspect extraction is opt-in and domain accuracy remains unvalidated.

Code license selection belongs to the owner. Existing source content and model weights have separate rights; this repository does not confer those rights.
Live Reddit/review adapters are disabled pending authorized access and rights review. NewsAPI is opt-in with a valid current owner permission record, explicit rights confirmation and credentials; its free developer plan is not a production hosting license. The weekly workflow now publishes synthetic aggregate artifacts, never raw databases. No source data, historical reports or Git history has been deleted.

The owner has left the code license undecided. See the [source permissions checklist](docs/readiness/source-permissions-checklist.md), [annotation protocol](docs/readiness/annotation-guide.md) and [deployment candidate](docs/readiness/deployment-candidate.md). Existing source content and model weights have separate rights; this repository does not confer those rights.
6 changes: 5 additions & 1 deletion config.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ class Settings(BaseModel):
model_revision: str = "3216a57f2a0d9c45a2e6c20157c20c49fb4bf9c7" # pragma: allowlist secret -- public model commit
enabled_sources: tuple[str, ...] = ()
data_rights_confirmed: bool = False
permissions_path: Path = ROOT / "pipeline/source_permissions.json"
alerts_enabled: bool = False
aspects_enabled: bool = False
freshness_hours: int = Field(default=192, ge=1, le=8760)
log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO"

Expand All @@ -38,7 +40,7 @@ def valid_timezone(cls, value: str) -> str:
ZoneInfo(value)
return value

@field_validator("db_path", "output_dir", mode="before")
@field_validator("db_path", "output_dir", "permissions_path", mode="before")
@classmethod
def absolute_path(cls, value: str | Path) -> Path:
p = Path(value).expanduser()
Expand All @@ -48,6 +50,8 @@ def absolute_path(cls, value: str | Path) -> Path:
def compatible(self):
if not self.keywords or any(not x.strip() for x in self.keywords):
raise ValueError("keywords must be nonempty")
if self.mode == "demo" and self.aspects_enabled:
raise ValueError("keyless demo cannot download real aspect weights; use model smoke")
if self.mode == "demo" and (self.enabled_sources or self.alerts_enabled):
raise ValueError("demo prohibits external sources and alerts")
if self.enabled_sources and not self.data_rights_confirmed:
Expand Down
45 changes: 44 additions & 1 deletion database.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,17 @@
term TEXT NOT NULL, category TEXT NOT NULL, label TEXT NOT NULL CHECK(label IN ('NEGATIVE','NEUTRAL','POSITIVE')),
confidence REAL NOT NULL CHECK(confidence BETWEEN 0 AND 1),
PRIMARY KEY(mention_id,model_version,term,category));
CREATE TABLE IF NOT EXISTS aspect_inference(
mention_id TEXT NOT NULL REFERENCES mentions_v2(id), model_version TEXT NOT NULL,
status TEXT NOT NULL CHECK(status IN ('scored','empty')), payload TEXT NOT NULL,
run_id TEXT NOT NULL REFERENCES runs(id), PRIMARY KEY(mention_id,model_version));
CREATE TABLE IF NOT EXISTS aspect_spans(
mention_id TEXT NOT NULL, model_version TEXT NOT NULL, start INTEGER NOT NULL CHECK(start>=0),
end INTEGER NOT NULL CHECK(end>start), term TEXT NOT NULL, category TEXT NOT NULL,
label TEXT NOT NULL CHECK(label IN ('NEGATIVE','NEUTRAL','POSITIVE','UNKNOWN','ABSTAIN')),
confidence REAL NOT NULL CHECK(confidence BETWEEN 0 AND 1), payload TEXT NOT NULL,
PRIMARY KEY(mention_id,model_version,start,end),
FOREIGN KEY(mention_id,model_version) REFERENCES aspect_inference(mention_id,model_version) ON DELETE CASCADE);
CREATE TABLE IF NOT EXISTS ingestion_events(
run_id TEXT NOT NULL REFERENCES runs(id), ordinal INTEGER NOT NULL, source TEXT NOT NULL,
status TEXT NOT NULL CHECK(status IN ('accepted','duplicate','rejected')), reason TEXT, reference TEXT,
Expand Down Expand Up @@ -107,6 +118,7 @@ def store_mention(db, mention: Mention):
if old and old[0] != mention.fingerprint:
db.execute("DELETE FROM predictions_v2 WHERE mention_id=?", (mention.id,))
db.execute("DELETE FROM aspects_v2 WHERE mention_id=?", (mention.id,))
db.execute("DELETE FROM aspect_inference WHERE mention_id=?", (mention.id,))
return "duplicate" if old and old[0] == mention.fingerprint else "accepted"


Expand All @@ -127,8 +139,39 @@ def store_predictions(db, predictions, fingerprints, run_id, aspects=()):
"DELETE FROM aspects_v2 WHERE mention_id=? AND model_version=?",
(p.mention_id, p.model_version),
)
db.execute(
"DELETE FROM aspect_inference WHERE mention_id=? AND model_version=?",
(p.mention_id, p.model_version),
)
for a in aspects:
db.execute("INSERT INTO aspects_v2 VALUES(?,?,?,?,?,?)", a)
if isinstance(a, dict):
db.execute(
"INSERT INTO aspect_inference VALUES(?,?,?,?,?)",
(
a["mention_id"],
a["model_version"],
"scored" if a["spans"] else "empty",
json.dumps(a, allow_nan=False),
run_id,
),
)
for span in a["spans"]:
db.execute(
"INSERT INTO aspect_spans VALUES(?,?,?,?,?,?,?,?,?)",
(
a["mention_id"],
a["model_version"],
span["start"],
span["end"],
span["term"],
span["category"],
span["label"],
span["confidence"],
json.dumps(span, allow_nan=False),
),
)
else:
db.execute("INSERT INTO aspects_v2 VALUES(?,?,?,?,?,?)", a)


def migrate(path):
Expand Down
8 changes: 7 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ Private raw text and normalized text live in validated mention rows. Rejected ra

Overall prediction is independent of aspects and review ratings. Each eligible input receives a valid prediction, abstention or error. The model/config version hashes checkpoint identity, threshold, taxonomy, normalization and extractor version. Predictions from old versions remain archived; active joins declare exactly one version and fingerprint. Changes invalidate outdated predictions/aspects. Batches use ordered IDs and strict cardinality/probability checks. Model objects load lazily once per process. CPU is default; unavailable explicitly requested accelerators fail instead of silently switching hardware.

The optional extractor interface returns separate term, polarity and confidence lists. Multiple terms in one category remain stored separately. Category aggregation collapses terms to a mean signed label per mention/category, then averages those mention scores; overall totals never count aspect rows. No reproducible PyABSA checkpoint artifact was supplied or verified, so default live extraction remains disabled rather than silently downloading an unpinned alias. Actual term/category/joint evaluation requires independent aspect annotations.
The optional pinned joint extractor loads standard Transformers code from verified safetensors with remote code disabled. It returns offset-preserving BIO spans with per-token probabilities and independent sentiment, not overall labels. Unknown polarity and truncated trailing spans are separate UNKNOWN/ABSTAIN states; neither becomes neutral. The legacy tuple extractor interface remains supported. Additive `aspect_inference` and `aspect_spans` tables preserve model-versioned processed/empty outcomes, repeated terms at distinct offsets and raw probabilities. Category aggregation averages known-polarity terms per mention/category; unknown/abstained/unmapped spans are excluded. Category mapping is heuristic. The report exposes aspect coverage and unvalidated quality. Default extraction stays disabled; `ASPECTS_ENABLED=true` is an explicit live-worker opt-in. No independent aspect gold or domain accuracy exists yet.

Live processing now checks the private permission manifest before collection/model initialization: explicit confirmation, approved and currently valid scopes, plus exact SHA-256 for imports. A Boolean alone cannot enable collection. Permission evidence records owner attestations; software cannot grant legal rights. All default sources remain pending. Annotation creation strips predictions/ratings, freezes exact-text-cluster splits, requires two blinded annotators and adjudication, and supports exclusion of unresolved ambiguity. Calibration only fits development probabilities and never auto-applies a threshold.

## Storage and publication

Expand Down Expand Up @@ -40,3 +42,7 @@ flowchart TB
```

Serving installs no ML stack, opens DB read-only, and runs sync database endpoints in FastAPI's threadpool. No subprocess/admin trigger is exposed. Configuration-only Render and Docker examples build a synthetic snapshot; ephemeral serving storage is never assumed to receive future workflow files. Live refresh and rollback remain explicit owner-controlled releases. `snapshot` creates an aggregate-only SQLite serving artifact from validated canonical JSON, re-renders HTML safely, and requires explicit rights approval for live-mode input; no raw mention/prediction rows are copied.

## Immutable release preparation

`prepare-release` copies a selected source/lock allowlist and aggregate-only synthetic snapshot into a new directory, pins the official Python image digest, and hashes each file. `verify-release` rejects path traversal, unexpected/tampered files and raw rows. The UID 10001 image supports a read-only root filesystem. This is a concrete reviewed artifact path; it does not authorize or execute public deployment. See [release candidate](readiness/deployment-candidate.md).
Loading
Loading