Spaces:
Runtime error
Runtime error
Sync platform from lab mainline: dev instance ready to deploy
Browse filesFull feature set: accounts (email/password + feature-flagged Google via
Supabase PKCE), anonymous tiers (3 runs/day, delete-after-analysis, 24h
purge), saved-run cap, construct upload from CSV/XLSX, structured
warnings + language detection, model registry (MiniLM/E5), per-run
reproduction scripts, corpus-embedding cache, storage interface (local/
R2), sample-data test kit, MANUAL_TESTING.md.
Rights guard: only the 5 original seed constructs ship in this public
repo; the imported lab collection stays out pending the redistribution
decision. HF remote URL detokenized. 64 tests passing.
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .env.exampleAdded+56
- .gitignore+1
- DEPLOY.md+36-68
- Dockerfile+27-16
- MANUAL_TESTING.mdAdded+163
- README.md+40-78
- backend/app/auth.pyAdded+159
- backend/app/auth_google.pyAdded+99
- backend/app/ccr.py+57-27
- backend/app/construct_files.pyAdded+110
- backend/app/construct_lib.pyAdded+121
- backend/app/db.py+45-1
- backend/app/ingest.py+54-32
- backend/app/jobs.py+167-25
- backend/app/main.py+473-40
- backend/app/models.py+25-3
- backend/app/registry.pyAdded+134
- backend/app/reproducibility.pyAdded+118
- backend/app/retention.pyAdded+123
- backend/app/schemas.py+29-1
- backend/app/seed_constructs.pyDeleted-66
- backend/app/storage.pyAdded+140
- backend/app/warnings_engine.pyAdded+151
- backend/requirements.txt+3
- backend/static/assets/index-BUzS6usZ.jsDeleted
- backend/static/assets/index-C356-0ZT.cssDeleted-1
- backend/static/assets/index-CN_FzJfm.cssAdded+1
- backend/static/assets/index-DrFcy6bH.jsAdded
- backend/static/index.html+3-3
- backend/tests/conftest.py+3
- backend/tests/test_accounts_limits_retention.pyAdded+311
- backend/tests/test_api.py+111-5
- backend/tests/test_auth_tiers_and_lifecycle.pyAdded+138
- backend/tests/test_auto_migration.pyAdded+42
- backend/tests/test_ccr.py+1-1
- backend/tests/test_google_auth.pyAdded+89
- backend/tests/test_registry_and_prefixes.pyAdded+110
- backend/tests/test_storage_backends.pyAdded+154
- frontend/src/App.jsx+280-34
- frontend/src/ConstructPicker.jsxAdded+206
- frontend/src/ResultsView.jsx+35-21
- frontend/src/Workspace.jsx+278-77
- frontend/src/api.js+15
- frontend/src/styles.css+317-11
- packages/ccr_engine/README.mdAdded+11
- packages/construct_library/constructs/collectivism_horizontal.yamlAdded+21
- packages/construct_library/constructs/individualism_horizontal.yamlAdded+21
- packages/construct_library/constructs/mfq_care.yamlAdded+21
- packages/construct_library/constructs/mfq_fairness.yamlAdded+21
- packages/construct_library/constructs/satisfaction_with_life.yamlAdded+25
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556# CCR Platform environment. Everything has a safe local-dev default; the# variables under "Deployment" should be set explicitly on a real instance.
# ---- Deployment (set these in production) ----# REQUIRED in production: sessions survive restarts only with a fixed secret.# Generate one: python -c "import secrets; print(secrets.token_hex(32))"# CCR_SESSION_SECRET=
# Set to 1 when serving over HTTPS (marks cookies Secure).# CCR_COOKIE_SECURE=1
# Anonymous-data TTL purge in hours. 0 disables (local-dev default);# deployments should set 24 (PI retention decision, 2026-07-10).# CCR_ANON_TTL_HOURS=24
# Preload the default embedding model at startup so the first run is fast.# CCR_WARM_MODEL=1
# ---- Tiers and limits (defaults shown) ----# CCR_ANON_MAX_BYTES=2097152 # 2 MB anonymous upload cap# CCR_ANON_MAX_ROWS=500 # anonymous row cap per file# CCR_ANON_MAX_RUNS_PER_DAY=3 # anonymous runs/day, then sign-in# CCR_USER_MAX_SAVED_RUNS=15 # saved-run cap for signed-in users
# ---- Storage and processing ----# File storage backend: "local" (default; files under CCR_DATA_DIR) or "s3"# (any S3-compatible store; Cloudflare R2 recommended - zero egress fees).# The s3 path is production-ready; enabling it is config, not development.# CCR_STORAGE=s3# CCR_S3_ENDPOINT=https://<accountid>.r2.cloudflarestorage.com# CCR_S3_BUCKET=ccr-platform# CCR_S3_ACCESS_KEY_ID=# CCR_S3_SECRET_ACCESS_KEY=
# Where the DB, uploaded corpora, results, and embedding cache live (default: backend/data)# CCR_DATA_DIR=/absolute/path# Row ceiling for uploads (default 100000; hosted demo uses 20000)# CCR_MAX_ROWS=20000# Corpus-embedding cache (default on; set 0 to disable)# CCR_EMB_CACHE=1
# ---- Development / CI only ----# Force the deterministic fake embedder (never production)# CCR_FAKE_EMBEDDINGS=1
# ---- Google sign-in via Supabase (optional; button hidden when unset) ----# Supabase dashboard > Project Settings > API. The anon key is public-facing# by design; the service_role key is never used and never leaves the dashboard.# SUPABASE_URL=https://YOUR_PROJECT_REF.supabase.co# SUPABASE_ANON_KEY=# Public base URL of this app (Google redirect target).# CCR_APP_URL=http://127.0.0.1:8000
# ---- Phase 2 (not read yet; reserved names) ----# DATABASE_URL=postgresql://...# ADMIN_EMAILS=devaanand@umass.edu,matari@umass.edu11 unmodified lines12131411 unmodified lines# os.DS_Store11 unmodified lines1213141511 unmodified lines# os.DS_Store.env
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081# Deploying the demo## Option A — Hugging Face Spaces (free, recommended for the demo)Free Docker Spaces: 2 vCPU / 16 GB RAM, no credit card. Bonus: the originalCCR online tool lives on HF Spaces, so the prototype sits where the CCRcommunity already works.1. Create the Space at https://huggingface.co/new-space →SDK: **Docker** → visibility: Public → name: `ccr-platform`.2. HF reads deployment config from YAML frontmatter at the top of theSpace's `README.md`. Add this block (top of the file) before pushing:```yaml---title: CCR Platformemoji: 🧭colorFrom: redcolorTo: graysdk: dockerapp_port: 7860pinned: false---```3. Push this repo to the Space:```bashgit remote add hf https://huggingface.co/spaces/<your-username>/ccr-platformgit push hf main```First build takes ~5–10 min (model bakes into the image). Watch thebuild logs in the Space's "Logs" tab.4. Optional hardening for the public instance — in Space Settings →Variables, set `CCR_MAX_ROWS=20000` (tighter ceiling than the100k default while strangers can reach it).Notes:- Storage is **ephemeral** — uploads/results vanish on restart or rebuild.Fine for a demo; the email and the in-app welcome text both say so.- Free Spaces sleep after ~48h without traffic. Visit the URL theevening before and the morning of the interview so it's warm.- The direct app URL (no HF frame) is`https://<username>-ccr-platform.hf.space` — send that one.## Option B — Google Cloud Run (few dollars, more "prod-like" URL)```bashgcloud run deploy ccr-platform \--source . \--region us-central1 \--allow-unauthenticated \--memory 2Gi \--cpu 2 \--min-instances 1 \--max-instances 1 \--concurrency 20```- `--min-instances 1`: no cold starts while he plays with it (~a fewdollars for the week; delete the service after the process ends).- `--max-instances 1`: SQLite + in-process queue assume one instance —documented demo trade-off, not an oversight.## Pre-send checklist (either host)1. Open the URL in an **incognito window and on your phone (off Wi-Fi)**.2. Full run: new project → upload `sample_data/sample_corpus.csv` →Satisfaction with Life → Run → results render → Export CSV downloads.3. Second run (Individualism) finishes in seconds (model + item cache warm).4. Upload your own messy CSV (Excel export with a BOM, or semicolon-delimited) — parses, and any fallback is flagged in the UI.5. Upload rejects a bogus file (.txt/.exe) with a clean error.6. Refresh the page — SPA loads, project still listed.7. Morning of the interview: open the URL once (warm the instance),re-run step 2 quickly.If anything fails, fix before sending. No link is better than a broken link.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849# Deploying the dev instance (Hugging Face Space)The Space builds from this repo's Dockerfile. One-time setup lives in theSpace settings; after that, deploys are just `git push hf main`.## Space secrets (Settings > Variables and secrets)| Secret | Value ||---|---|| CCR_SESSION_SECRET | `python3 -c "import secrets; print(secrets.token_hex(32))"` || SUPABASE_URL | from Supabase > Project Settings > API || SUPABASE_ANON_KEY | from the same page (anon public key, NOT service_role) || CCR_APP_URL | https://devaanand-ccr-platform.hf.space || CCR_COOKIE_SECURE | 1 |Retention (CCR_ANON_TTL_HOURS=24) and model pre-warm are already defaults inthe Dockerfile.## Supabase setup for Google sign-in (one time)1. supabase.com > New project (free tier).2. Authentication > Providers > Google > Enable. Copy the shown callback URL(https://PROJECT_REF.supabase.co/auth/v1/callback).3. console.cloud.google.com > OAuth consent screen (External) > Credentials >Create OAuth client ID (Web application) > add the Supabase callback URL asan authorized redirect URI. Paste client id/secret back into the SupabaseGoogle provider form.4. Authentication > URL Configuration: add BOTH redirect URLs:- http://127.0.0.1:8000/api/auth/google/callback- https://devaanand-ccr-platform.hf.space/api/auth/google/callback5. Project Settings > API: copy the Project URL and anon key into the Spacesecrets (and your local .env).## Push```bashgit push origin main # GitHubgit push hf main # Hugging Face Space (rebuilds + redeploys)```The hf remote has no stored token; use your HF username and a WRITE token asthe password when prompted (or a credential helper).## Caveats of the free dev instance- Ephemeral disk: SQLite resets on rebuild/restart. Google users are recreatedon next sign-in automatically; password accounts must re-register. Fine forfeedback; a persistent volume or Postgres arrives with the launch decision.- The Space sleeps after ~48 h idle; first visit wakes it (~1 min).
1234567891011121314151617181920212223242526272829303132333435# CCR Platform — Cloud Run / container deployment.# The embedding model is baked into the image so the first request# doesn't trigger a ~90 MB download (critical for demo cold starts).FROM python:3.11-slim# Data + caches in /tmp so the container runs under any UID# (Hugging Face Spaces runs containers as a non-root user).ENV PYTHONUNBUFFERED=1 \HF_HOME=/opt/hf-cache \CCR_DATA_DIR=/tmp/ccr-dataWORKDIR /srvCOPY backend/requirements.txt .RUN pip install --no-cache-dir -r requirements.txt# Pre-download ALL offered models into the image layer — a user picking a# non-default model must not trigger a multi-hundred-MB download mid-job# (looks like a hang). Make the cache usable by any runtime UID.RUN python -c "from sentence_transformers import SentenceTransformer; \[SentenceTransformer(m) for m in ( \'sentence-transformers/all-MiniLM-L6-v2', \'sentence-transformers/all-mpnet-base-v2', \'sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2')]" \&& chmod -R 777 /opt/hf-cacheCOPY backend/app ./appCOPY backend/static ./static# Demo note: SQLite + uploads live on the container's ephemeral disk —# data resets on restart/redeploy. Acceptable for a demo; use# Postgres + S3/GCS object storage before any real use.EXPOSE 7860CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PORT:-7860}"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546# CCR Platform - single-container deployment (one deployable unit: FastAPI# serves both the JSON API and the prebuilt React SPA from backend/static).## Build: docker build -t ccr-platform .# Ephemeral demo: docker run -p 7860:7860 ccr-platform# Persistent: docker run -p 7860:7860 \# -e CCR_SESSION_SECRET=$(python -c "import secrets;print(secrets.token_hex(32))") \# -e CCR_DATA_DIR=/data -e CCR_COOKIE_SECURE=1 \# -v ccr_data:/data ccr-platform## NOTE: run `npm run build` in frontend/ before building the image - the# committed backend/static is what ships (no Node stage; keeps HF Spaces# builds fast and the image small).FROM python:3.11-slim# Defaults favor a hosted instance: retention purge on, model pre-warmed.# Data dir defaults to /tmp so the container runs under any UID (HF Spaces);# persistent deployments override CCR_DATA_DIR to a mounted volume.ENV PYTHONUNBUFFERED=1 \HF_HOME=/opt/hf-cache \CCR_DATA_DIR=/tmp/ccr-data \CCR_ANON_TTL_HOURS=24 \CCR_WARM_MODEL=1WORKDIR /srvCOPY backend/requirements.txt .RUN pip install --no-cache-dir -r requirements.txt# Bake the DEFAULT model (MiniLM, ~90 MB - the CCR reference model) into the# image so the first run never stalls on a download. The E5 models are large# (1+ GB) and lazy-load into HF_HOME on first use instead; the dir stays# writable for any runtime UID.RUN python -c "from sentence_transformers import SentenceTransformer; \SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')" \&& chmod -R 777 /opt/hf-cacheCOPY backend/app ./appCOPY backend/static ./static# registry.py/construct_lib.py resolve packages/ two levels above app/# (= "/" here), so /packages is exactly where they look.COPY packages /packagesEXPOSE 7860CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PORT:-7860}"]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163# Manual testing guide
Everything built so far, as click-through scenarios. Each scenario says what todo and exactly what you should see. Files referenced live in `sample_data/`(see `sample_data/README.md` for what each one triggers).
## 0. Setup
```bashcd backendpip install -r requirements.txtuvicorn app.main:app --reload --port 8000```
Open http://127.0.0.1:8000. First start downloads MiniLM (~90 MB) on the firstreal run; set `CCR_WARM_MODEL=1` to preload it at startup instead.
To test quickly without models: `CCR_FAKE_EMBEDDINGS=1 uvicorn ...` (scores arefake but every flow works; never use for real analysis).
## 1. Projects and sidebar
1. Create three projects. They appear under "Today", newest activity first.2. Type in the sidebar search box: list filters as you type.3. Archive a project (project header > Archive): it moves into the collapsed "Archived" group; Unarchive brings it back. No data is lost either way.4. Delete a project: requires typing the project name; removes its datasets, runs, and files permanently.
## 2. Upload paths (Step 1 card)
| Upload | Expect ||---|---|| `sample_corpus.csv` | Parses, 60 rows, `text` column suggested || `multi_column_demo.csv` | 5 columns; `comment_text` marked "(suggested)" || `semicolon_delimited_demo.csv` | Parses into exactly id + text (commas inside texts intact) || `latin1_encoding_demo.csv` | Parses with a ⚠ note: decoded as latin-1; fiancée/café render correctly || `xlsx_upload_demo.xlsx` | Parses like a CSV || a `.txt` or `.pdf` file | Rejected: unsupported file type |
Anonymous limits (signed out): the Step 1 hint shows 2 MB / 500 rows and saysuploads are deleted after analysis. Upload `large_demo.csv` (800 rows): rejectedwith a "Sign in (top right)" message. Sign in and retry: accepted.
## 3. Construct selection (Step 2 card)
1. Open the picker: search field + panel below it, library grouped by category, with "Recently used" pinned on top after your first runs.2. Type "GAD" or "empathy": matches by name and category; Arrow keys + Enter work.3. Select any imported construct: items listed, plus the "not yet verified verbatim" notice (expected for the whole imported library for now).
### Custom construct, typed
1. "+ Custom construct" > name it, paste items one per line.2. Append `(R)` to one line: the form shows "1 item(s) marked reverse-scored".3. Save: it appears in the picker under "My custom constructs"; run metadata will carry the reverse flag (check via Results > metadata download).
### Custom construct, from file (new)
1. "+ Custom construct" > "Upload items from CSV/XLSX".2. Try a CSV with `item,reverse` columns (1/true/yes/R = reverse) or a single-column file with `(R)` markers.3. Expect: items fill the textarea ((R) appended where flagged), the filename becomes the suggested name, and parse notes list skipped blanks/duplicates. Nothing is saved until you review and press Save. Item files are never retained on the server.
## 4. Language, models, and warnings (Step 3 card + results)
Run each of these and open the results page; the amber warnings panel shouldshow exactly:
| Corpus | Selection | Expected warnings ||---|---|---|| `warnings_showcase.csv` | en + MiniLM | EMPTY_ROWS_DROPPED (2), DUPLICATE_TEXTS (2), TEXT_TOO_SHORT (3), TEXTS_MAYBE_TRUNCATED (2); no language warnings || `french_demo.csv` | en + MiniLM | LANGUAGE_MISMATCH (detected fr, 100%) || `french_demo.csv` | fr + MiniLM | MODEL_LANGUAGE_UNSUPPORTED || `french_demo.csv` | fr + Multilingual E5 | no language warnings || `mixed_language_demo.csv` | en + MiniLM | LANGUAGE_UNCERTAIN (majority 50%) || `long_documents_demo.csv` | en + MiniLM | TEXTS_MAYBE_TRUNCATED (4) + LANGUAGE_UNCERTAIN (only 10 rows, below the 20-row minimum - by design) |
Warnings are per-run snapshots: changing language/model requires a NEW run;old result pages don't update.
## 5. Results and reproducibility
1. Run `moral_foundations_demo.csv` against two different MFQ-2 foundations: top texts change per foundation; the 6 neutral rows sink to the bottom.2. Results page: histogram, mean/SD/min/max, per-item loadings, top/bottom texts.3. Downloads: results CSV (input columns + sim_item_N + ccr_score), metadata JSON (model revision, construct snapshot + item hash, language block, environment pins), reproduction script + requirements file.4. Reproduction check: `pip install -r requirements-repro.txt`, then `python reproduce_analysis.py your_corpus.csv` on a machine with no platform access; values should match the export (target ~1e-5 with real models).
## 6. Accounts
1. Sign in (top right) > "Create a free account" > email + password (min 8 chars).2. You're signed in immediately; header shows your name.3. Sign out, sign back in; wrong password gives "Incorrect email or password"; registering the same email again gives "already exists".4. Email is case-insensitive. There is no self-service password reset yet (interim local accounts; Google/Supabase swap planned) - reset = admin action.
## 7. Anonymous tiers (test signed OUT)
1. Upload caps: see section 2.2. Run limit: run 3 analyses (default). The Step 3 card counts "X of 3 free runs used today". The 4th run is refused with a sign-in prompt (HTTP 429). Counter resets next day (UTC). Signing in removes the limit.3. Delete-after-analysis: run any corpus, open results (fine, downloadable), note the info warning "uploaded file was deleted after this analysis". Re-running that same corpus: refused ("upload again, or sign in").4. TTL purge: with `CCR_ANON_TTL_HOURS=24` (deployment default; 0 = off in local dev), anonymous projects older than 24h are deleted entirely, startup + hourly.
## 8. Signed-in tier
1. Sign in, upload, run: no ANONYMOUS_DATA_REMOVED warning; re-running the same corpus works (file kept).2. Saved-run cap: Step 3 card shows "N of 15 saved runs used". At the cap, new runs are refused until you delete old runs/projects (nothing is auto-deleted).3. Ownership: your projects are invisible to signed-out visitors and other accounts (they get 403 on any modification). Anonymous projects stay shared.
## 9. Performance behaviors
1. Corpus-embedding cache: run the SAME corpus with a second construct (signed in, same model): the run skips document embedding and completes in seconds; metadata shows `"doc_embeddings_from_cache": true`.2. Duplicate texts are embedded once (`warnings_showcase.csv` has 2 dupes): identical scores for identical texts, less compute.3. API responses are gzip-compressed (check the response headers).
## 10. Robustness
1. Restart the server mid-run: the orphaned job is marked failed with an explanation, never stuck at "running".2. A DB from an older version gains new columns automatically at startup (additive auto-migration) - no more "no such column" 500s.3. Tampered session cookie = treated as signed out, no error.
## 11. Deployment (container)
```bashcd frontend && npm run build && cd ..docker build -t ccr-platform .docker run -p 7860:7860 \ -e CCR_SESSION_SECRET=$(python3 -c "import secrets;print(secrets.token_hex(32))") \ -e CCR_DATA_DIR=/data -e CCR_COOKIE_SECURE=1 \ -v ccr_data:/data ccr-platform```
Checklist before giving the URL to real users:- [ ] `CCR_SESSION_SECRET` set (sessions survive restarts)- [ ] `CCR_COOKIE_SECURE=1` (HTTPS only)- [ ] `CCR_DATA_DIR` on a persistent volume (default /tmp is ephemeral)- [ ] `CCR_ANON_TTL_HOURS=24` (default in the image)- [ ] Smoke test: sections 2, 4, 6, 7 above9 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969 unmodified lines# CCR PlatformA web platform for **Contextualized Construct Representations (CCR)** — theory-driven psychological text analysis ([Atari, Omrani, et al.](https://github.com/Ali-Omrani/CCR); [Chen et al., EMNLP 2024](https://aclanthology.org/2024.emnlp-main.151/)).Researchers upload a text corpus, select (or define) a psychological construct backed by a validated self-report scale, run a CCR analysis with a locally-hosted sentence-embedding model, inspect the results, and export scores — with a reproducibility record attached to every run.**Method in one line:** embed the validated scale items and the texts with a contextual language model; the cosine similarity between a text and each item is the text's *loading* on the construct; the mean loading is its CCR score.## QuickstartRequires Python 3.10+. No Node needed — the dashboard ships prebuilt.```bash./run.sh# then open http://127.0.0.1:8000```First run creates a virtualenv and installs dependencies; the default embedding model (~90 MB) downloads on first analysis. To verify the install end-to-end:```bashsource backend/.venv/bin/activatepython scripts/verify_install.py```**Try it:** create a project → upload `sample_data/sample_corpus.csv` (60 synthetic texts) → choose *Satisfaction with Life* → Run. Then re-run the same corpus against *Individualism* vs *Collectivism* and compare the top-scoring texts.## What the platform adds over the existing CCR toolsThe published [R/Python packages](https://github.com/Ali-Omrani/CCR) and the single-run web demo cover one-off analyses. This platform adds the workflow around the method: **projects** that persist corpora and runs, a **construct library** of validated scales (plus custom constructs), **async jobs** with live progress on large corpora, a **results dashboard** (score distribution, per-item loadings, highest/lowest-scoring texts for face-validity checks), **CSV export** in the same shape as `ccr_wrapper` output, and a **reproducibility record** (model + version, item hash, package versions, timestamps) downloadable per run.## Architecture```Browser (React SPA, prebuilt → served by FastAPI)│ REST /api/*FastAPI (backend/app/main.py)│── SQLite (projects, corpora, constructs, jobs) backend/data/ccr.db│── File storage (uploaded corpora, result CSVs) backend/data/└── Background jobs (backend/app/jobs.py)└── CCR engine (backend/app/ccr.py)└── sentence-transformers (local, pinned)```| Component | Choice | Why (and what it's not) ||---|---|---|| Embeddings | Local `sentence-transformers`, default `all-MiniLM-L6-v2` | Matches published CCR; pinned weights = reproducible results; text never leaves the deployment (IRB-friendly when self-hosted). Not an embeddings API: per-call cost, data leaves your control, models get deprecated mid-study. || Database | SQLite | Right-sized for single-node, few writers. Schema is Postgres-portable; the upgrade trigger is concurrent multi-user writes. || Job execution | FastAPI `BackgroundTasks`, state in DB | Zero extra infrastructure; lab-scale corpora embed in seconds–minutes. Known limits (no restart survival, no retries) are accepted MVP trade-offs; upgrade trigger to Celery+Redis is long/frequent jobs — the API contract doesn't change because job state already lives in the DB. || Model dependency | Injected `EmbeddingBackend` interface | Tests/CI run a deterministic hash embedder (no torch), so the full pipeline is testable in seconds. Production backend is swappable per job. || Frontend | React (Vite), served as static files by the API | Single deployable, no CORS in production, no Node required to run. |## Processing robustness (bring your own corpus)Research files are messy, so ingestion is tolerant by design: encoding fallback (UTF-8 with BOM → latin-1, with a user-facing note when fallback was needed), delimiter sniffing (`,` `;` tab `|`), ragged-row skipping, a configurable row ceiling (`CCR_MAX_ROWS`, default 100k), and a text-column suggestion heuristic. The exact parse configuration (format, encoding, delimiter) is stored per corpus and echoed into each run's reproducibility record. Runs execute on a dedicated worker queue with persisted state — jobs orphaned by a restart are marked failed with an explanation instead of hanging — and results carry data-quality notes (empty rows dropped, duplicates detected, texts likely truncated by the model's token window) so silent data issues become visible ones.## Reproducibility & data handlingEvery run records: model name + `sentence-transformers` version, embedding dimension, SHA-256 of the exact item wordings, text column, row counts (including empty rows dropped), timestamps, and library versions — downloadable as JSON next to the results CSV. Exports mirror the `ccr_wrapper` output shape (input columns + `sim_item_i` + `ccr_score`) so they drop into existing CCR workflows.Processing is self-contained: embeddings are computed on the server running the app — text is never sent to third-party AI APIs. Run locally (`./run.sh`) and corpora never leave your machine, which is the recommended mode for sensitive data. Uploaded corpora and results live in the data directory (`backend/data/` locally; ephemeral on the hosted demo, which may reset at any time — don't upload sensitive or identifiable data there).## Construct library — verify before research useThe seeded scales (SWLS; MFQ Care & Fairness; Triandis & Gelfand Individualism/Collectivism) carry citations, but item wordings must be **verified verbatim against the original publications before research use** — CCR's validity rests on using the validated instrument as published.## Known limitations / roadmap- **Method nuance:** cosine similarity captures construct *relatedness* more than stance — a text lamenting life dissatisfaction can sit near SWLS items in embedding space. Reverse-scored items need care, and results should be validated against human-annotated subsets for new constructs/corpora.- No auth/multi-user yet (single-lab, local deployment); add before any public hosting, along with per-user quotas.- `BackgroundTasks` → Celery+Redis when corpora grow; SQLite → Postgres with multi-user concurrency; local files → S3/GCS if deployed off-machine.- Embedding cache keyed on (model, item-set hash) to make repeated runs on the same construct instant.## Development```bash# backend tests (fast — no ML deps needed)cd backend && pip install -r requirements-dev.txt && python -m pytest tests/ -q# frontend dev server (proxies /api to :8000)cd frontend && npm install && npm run dev# rebuild the shipped dashboardcd frontend && npm run build # outputs to backend/static/```Tests cover the CCR engine (determinism, normalization, scoring) and the full API flow: project → upload → job lifecycle → results summary → export shape → validation errors.9 unmodified lines101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657589 unmodified lines# CCR PlatformA web platform for **Contextualized Construct Representations (CCR)** - theory-drivenpsychological text analysis ([Atari, Omrani, et al.](https://github.com/Ali-Omrani/CCR);[EMNLP 2024](https://aclanthology.org/2024.emnlp-main.151/)). Built for the Culture andMorality Lab (UMass Amherst); this instance is the lab's **dev/testing environment**.Upload a corpus (CSV/XLSX), pick a validated construct from the library or define yourown (typed or uploaded from a file), choose a language and embedding model, run theanalysis, inspect results (distributions, per-item loadings, top/bottom texts,data-quality warnings), and export everything - including a Python script thatreproduces the run on any machine.## Features- Anonymous try-it tier: 3 runs/day, uploads deleted right after analysis, sessionspurged after 24 h. Free accounts (email/password, optional Google sign-in) liftlimits and keep your work (15 saved runs).- Construct library (versioned, append-only, item-hashed) + custom constructs withreverse-scored flags; searchable grouped picker.- Model registry: MiniLM default (the CCR reference model), E5-large-v2,Multilingual-E5; E5 prefix policy handled automatically; language coverage warnings.- Structured data-quality warnings (language mismatch/uncertainty, short texts,truncation, duplicates, encoding fallback) - stable machine-readable codes.- Per-run reproducibility: metadata JSON + offline-runnable script + pinnedrequirements. Corpus-embedding cache makes re-runs on the same corpus near-instant.- Storage: local disk by default; S3-compatible (Cloudflare R2) via env config.## Run locally```bashcd backendpip install -r requirements.txtuvicorn app.main:app --reload --port 8000 --env-file ../.env```Open http://127.0.0.1:8000. See `MANUAL_TESTING.md` for a full click-through testscript and `sample_data/README.md` for what each sample file demonstrates.Configuration: copy `.env.example` to `.env` and fill what you need.## Notes- Do not upload sensitive or identifiable data to this shared dev instance; anonymousstorage is ephemeral and the instance may reset.- The construct library here carries the 5 original seed scales; the lab's fullimported collection ships separately pending a redistribution-rights decision.- Tests: `cd backend && CCR_FAKE_EMBEDDINGS=1 python -m pytest -q` (64 tests, no MLdownloads needed).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""Accounts, sessions, and usage tiers.
Local email+password accounts - the "best cheap option available now" (Deva,2026-07-11): zero external dependencies, zero cost, real password security viastdlib scrypt. This deliberately does NOT implement email verification orself-service password reset; at lab scale a reset is an admin action. Themanaged-provider swap (Supabase: Google + email/password, design doc §8)replaces token creation/verification here - get_current_user() stays the onlyintegration point the rest of the app knows about.
Sessions: HMAC-signed cookie carrying {uid, email, name}. Secret fromCCR_SESSION_SECRET (REQUIRED in production - random per process otherwise,which signs everyone out on restart).
Anonymous usage tiers (PI decisions, 2026-07-10): * upload caps (bytes/rows), * run limit per day (signed cookie counter - a nudge toward accounts, not a security boundary; clearing cookies evades it and that is acceptable), * data removed after analysis (see retention.py).Signed-in users: caps lifted, runs persist up to a saved-run cap."""
from __future__ import annotations
import base64import hashlibimport hmacimport jsonimport osimport reimport secretsfrom datetime import datetime, timezone
from fastapi import Request
COOKIE_NAME = "ccr_session"RUNS_COOKIE_NAME = "ccr_runs"_SECRET = (os.environ.get("CCR_SESSION_SECRET") or secrets.token_hex(32)).encode()
ANON_MAX_BYTES_DEFAULT = 2 * 1024 * 1024ANON_MAX_ROWS_DEFAULT = 500ANON_MAX_RUNS_PER_DAY_DEFAULT = 3USER_MAX_SAVED_RUNS_DEFAULT = 15ANON_TTL_HOURS_DEFAULT = 0 # 0 = purge disabled (local dev); deployments set 24
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")MIN_PASSWORD_LEN = 8
# ------------------------------------------------------------- env knobsdef anon_max_bytes() -> int: return int(os.environ.get("CCR_ANON_MAX_BYTES", ANON_MAX_BYTES_DEFAULT))
def anon_max_rows() -> int: return int(os.environ.get("CCR_ANON_MAX_ROWS", ANON_MAX_ROWS_DEFAULT))
def anon_max_runs_per_day() -> int: return int(os.environ.get("CCR_ANON_MAX_RUNS_PER_DAY", ANON_MAX_RUNS_PER_DAY_DEFAULT))
def user_max_saved_runs() -> int: return int(os.environ.get("CCR_USER_MAX_SAVED_RUNS", USER_MAX_SAVED_RUNS_DEFAULT))
def anon_ttl_hours() -> int: return int(os.environ.get("CCR_ANON_TTL_HOURS", ANON_TTL_HOURS_DEFAULT))
def cookies_secure() -> bool: """Set CCR_COOKIE_SECURE=1 behind HTTPS in production.""" return os.environ.get("CCR_COOKIE_SECURE") == "1"
# ---------------------------------------------------------- passwordsdef hash_password(password: str) -> str: salt = secrets.token_bytes(16) digest = hashlib.scrypt(password.encode(), salt=salt, n=16384, r=8, p=1, dklen=64) return f"scrypt${salt.hex()}${digest.hex()}"
def verify_password(password: str, stored: str) -> bool: try: algo, salt_hex, digest_hex = stored.split("$") if algo != "scrypt": return False digest = hashlib.scrypt( password.encode(), salt=bytes.fromhex(salt_hex), n=16384, r=8, p=1, dklen=64 ) return hmac.compare_digest(digest.hex(), digest_hex) except Exception: return False
def valid_email(email: str) -> bool: return bool(_EMAIL_RE.match(email.strip().lower()))
# ------------------------------------------------- signed cookie payloadsdef _sign(payload: bytes) -> str: return hmac.new(_SECRET, payload, hashlib.sha256).hexdigest()
def sign_payload(data: dict) -> str: payload = base64.urlsafe_b64encode(json.dumps(data, separators=(",", ":")).encode()).decode() return f"{payload}.{_sign(payload.encode())}"
def verify_payload(token: str | None) -> dict | None: if not token or "." not in token: return None payload, signature = token.rsplit(".", 1) if not hmac.compare_digest(signature, _sign(payload.encode())): return None try: data = json.loads(base64.urlsafe_b64decode(payload.encode()).decode()) return data if isinstance(data, dict) else None except Exception: return None
# ------------------------------------------------------------- sessionsdef create_session_token(user_id: str, email: str, name: str) -> str: return sign_payload({"uid": user_id, "email": email, "name": name})
def get_current_user(request: Request) -> dict | None: """THE auth integration point (design doc §8). A managed provider (Supabase) replaces this body with provider-session verification; callers only ever see {"id", "email", "name", "tier"} or None.""" data = verify_payload(request.cookies.get(COOKIE_NAME)) if not data or "uid" not in data: return None return { "id": data["uid"], "email": data.get("email", ""), "name": data.get("name", ""), "tier": "member", }
# ------------------------------------------- anonymous daily run counterdef _today() -> str: return datetime.now(timezone.utc).date().isoformat()
def runs_used_today(request: Request) -> int: data = verify_payload(request.cookies.get(RUNS_COOKIE_NAME)) if not data or data.get("d") != _today(): return 0 # missing, tampered, or from a previous day - counter resets try: return max(0, int(data.get("n", 0))) except (TypeError, ValueError): return 0
def run_counter_token(count: int) -> str: return sign_payload({"d": _today(), "n": int(count)})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""Google sign-in via Supabase Auth (server-side PKCE flow).
Feature-flagged: everything here is inert until SUPABASE_URL andSUPABASE_ANON_KEY are set, so local dev and tests run unchanged without anySupabase project. When configured, the flow is:
1. GET /api/auth/google/login -> redirect to Supabase's Google authorize URL with a PKCE challenge; the verifier rides in a short-lived signed cookie (never stored server-side). 2. Google -> Supabase -> GET /api/auth/google/callback?code=... 3. The backend exchanges code+verifier for the Supabase user (stdlib urllib - no new dependencies), finds-or-creates a local User row by email, and issues OUR normal session cookie (auth.py).
Design consequence: Supabase verifies identity at sign-in time only; thesession, tiers, and ownership model are exactly the same as email/passwordaccounts. Google users have an empty password_hash and cannot password-login(a clear message says to use Google). Because users are re-created on nextsign-in by email, an ephemeral-disk dev instance losing its SQLite file is anuisance, not a lockout.
No frontend SDK: the button is a plain link, keeping the react+react-dom-onlydependency rule intact."""
from __future__ import annotations
import base64import hashlibimport jsonimport osimport secretsimport urllib.errorimport urllib.parseimport urllib.request
VERIFIER_COOKIE = "ccr_pkce"VERIFIER_TTL_SECONDS = 600
def configured() -> bool: return bool(os.environ.get("SUPABASE_URL") and os.environ.get("SUPABASE_ANON_KEY"))
def _supabase_url() -> str: return os.environ["SUPABASE_URL"].rstrip("/")
def app_url() -> str: """Public base URL of THIS app (redirect target). Local default matches the dev server; deployments set CCR_APP_URL.""" return os.environ.get("CCR_APP_URL", "http://127.0.0.1:8000").rstrip("/")
def begin() -> tuple[str, str]: """Return (authorize_url, code_verifier).""" verifier = secrets.token_urlsafe(64) challenge = ( base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()) .decode() .rstrip("=") ) params = urllib.parse.urlencode( { "provider": "google", "redirect_to": f"{app_url()}/api/auth/google/callback", "code_challenge": challenge, "code_challenge_method": "s256", } ) return f"{_supabase_url()}/auth/v1/authorize?{params}", verifier
def exchange(code: str, verifier: str) -> dict: """Exchange the PKCE code for the Supabase user. Returns {email, name}. Raises ValueError with a user-safe message on any failure.""" body = json.dumps({"auth_code": code, "code_verifier": verifier}).encode() req = urllib.request.Request( f"{_supabase_url()}/auth/v1/token?grant_type=pkce", data=body, headers={ "apikey": os.environ["SUPABASE_ANON_KEY"], "Content-Type": "application/json", }, method="POST", ) try: with urllib.request.urlopen(req, timeout=15) as resp: payload = json.load(resp) except (urllib.error.URLError, urllib.error.HTTPError, json.JSONDecodeError) as exc: raise ValueError("Google sign-in could not be completed. Please try again.") from exc
user = payload.get("user") or {} email = (user.get("email") or "").strip().lower() if not email: raise ValueError("Google sign-in returned no email address.") meta = user.get("user_metadata") or {} name = (meta.get("full_name") or meta.get("name") or email.split("@")[0]).strip() return {"email": email, "name": name}12342 unmodified lines7891011121314 unmodified lines2829303132333435363738394041424344454647488 unmodified lines575859606162636465666768697050 unmodified lines1211221231241251261271281291301 unmodified line13213313413513613713813914014112 unmodified lines1541551561571581591601611 unmodified line1631641651661671681691 unmodified line1711721731741751761778 unmodified lines18618718818919019119219319411 unmodified lines206207208209"""CCR engine — Contextualized Construct Representations.Method (Atari, Omrani et al.): embed validated questionnaire items and thetexts to be analyzed with a contextual sentence-embedding model, then take2 unmodified linesoverall CCR score.The embedding model is injected behind a small interface so that:* production uses sentence-transformers (local, pinned, reproducible —corpora never leave the machine), and* tests/CI use a deterministic hash-based embedder with no ML dependency."""14 unmodified linesFAKE_MODEL_NAME = "fake-deterministic"AVAILABLE_MODELS = [{"name": "sentence-transformers/all-MiniLM-L6-v2","label": "all-MiniLM-L6-v2 (default — fast, CCR reference model)",},{"name": "sentence-transformers/all-mpnet-base-v2","label": "all-mpnet-base-v2 (higher quality, slower)",},{"name": "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2","label": "paraphrase-multilingual-MiniLM-L12-v2 (50+ languages)",},]class EmbeddingBackend(Protocol):name: str8 unmodified lines_cache: dict[str, object] = {}def __init__(self, model_name: str):self.name = model_namedef _model(self):if self.name not in self._cache:from sentence_transformers import SentenceTransformer # lazy: heavy importself._cache[self.name] = SentenceTransformer(self.name)return self._cache[self.name]@property50 unmodified linesreturn outdef get_backend(model_name: str) -> EmbeddingBackend:if model_name == FAKE_MODEL_NAME or os.environ.get("CCR_FAKE_EMBEDDINGS") == "1":return HashEmbeddingBackend()return SentenceTransformerBackend(model_name)@dataclass1 unmodified linesimilarities: np.ndarray # (n_docs, n_items)scores: np.ndarray # (n_docs,) mean over itemsmetadata: dict# Item-set embeddings are tiny and constantly reused (same construct run# against many corpora) — cache them per (model, exact item wording)._item_embedding_cache: dict[tuple[str, str], np.ndarray] = {}12 unmodified linesitems: list[str],backend: EmbeddingBackend,progress_cb: ProgressCb | None = None,) -> CCRResult:"""Compute CCR loadings: cosine(text, item) for every text × item pair."""if not texts:raise ValueError("Corpus contains no non-empty texts.")if not items:1 unmodified linestarted = datetime.now(timezone.utc)item_emb, items_cached = encode_items_cached(backend, items)if progress_cb:progress_cb(0.02)1 unmodified lineif progress_cb:progress_cb(0.02 + 0.93 * frac)doc_emb = backend.encode(texts, progress_cb=doc_progress)# Both matrices are L2-normalized -> cosine similarity is a dot product.sims = doc_emb @ item_emb.T8 unmodified lines"embedding_dim": int(doc_emb.shape[1]),"model_max_seq_length": getattr(backend, "max_seq_length", None),"item_embeddings_from_cache": items_cached,"n_texts": len(texts),"n_items": len(items),"items_sha256_16": items_hash,"similarity": "cosine","score": "mean of per-item cosine similarities","python": sys.version.split()[0],11 unmodified linesif progress_cb:progress_cb(0.97)return CCRResult(similarities=sims, scores=scores, metadata=metadata)12342 unmodified lines7891011121314 unmodified lines2829303132338 unmodified lines4243444546474849505152535455565750 unmodified lines1081091101111121131141151161171181191201211 unmodified line12312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215312 unmodified lines1661671681691701711721731741751761771781791801811 unmodified line1831841851861871881891901 unmodified line1921931941951961971981992002012022032048 unmodified lines21321421521621721821922022122222322411 unmodified lines236237238239"""CCR engine - Contextualized Construct Representations.Method (Atari, Omrani et al.): embed validated questionnaire items and thetexts to be analyzed with a contextual sentence-embedding model, then take2 unmodified linesoverall CCR score.The embedding model is injected behind a small interface so that:* production uses sentence-transformers (local, pinned, reproducible -corpora never leave the machine), and* tests/CI use a deterministic hash-based embedder with no ML dependency."""14 unmodified linesFAKE_MODEL_NAME = "fake-deterministic"class EmbeddingBackend(Protocol):name: str8 unmodified lines_cache: dict[str, object] = {}def __init__(self, model_name: str, revision: str | None = None):self.name = model_nameself.revision = revisiondef _model(self):if self.name not in self._cache:from sentence_transformers import SentenceTransformer # lazy: heavy importkwargs = {"revision": self.revision} if self.revision else {}self._cache[self.name] = SentenceTransformer(self.name, **kwargs)return self._cache[self.name]@property50 unmodified linesreturn outdef get_backend(model_id: str) -> EmbeddingBackend:"""Resolve a REGISTRY model id (or the test fake) to an embedding backend."""if model_id == FAKE_MODEL_NAME or os.environ.get("CCR_FAKE_EMBEDDINGS") == "1":return HashEmbeddingBackend()from . import registry # local import: engine stays importable without yaml depscfg = registry.get_model(model_id)return SentenceTransformerBackend(cfg.provider_model_id, revision=cfg.pinned_revision)@dataclass1 unmodified linesimilarities: np.ndarray # (n_docs, n_items)scores: np.ndarray # (n_docs,) mean over itemsmetadata: dictdoc_embeddings: np.ndarray | None = None # exposed so jobs.py can cache themdef encode_unique(backend: EmbeddingBackend, texts: list[str],progress_cb: ProgressCb | None = None) -> np.ndarray:"""Encode only unique texts, then scatter back to full row order.Duplicate rows are common in social-media corpora; embeddings aredeterministic per text, so encoding each unique text once is a purespeedup with bit-identical output."""unique: dict[str, int] = {}for t in texts:if t not in unique:unique[t] = len(unique)if len(unique) == len(texts):return backend.encode(texts, progress_cb=progress_cb)unique_texts = list(unique.keys())unique_emb = backend.encode(unique_texts, progress_cb=progress_cb)idx = np.fromiter((unique[t] for t in texts), dtype=np.int64, count=len(texts))return unique_emb[idx]# Item-set embeddings are tiny and constantly reused (same construct run# against many corpora) - cache them per (model, exact item wording)._item_embedding_cache: dict[tuple[str, str], np.ndarray] = {}12 unmodified linesitems: list[str],backend: EmbeddingBackend,progress_cb: ProgressCb | None = None,item_prefix: str = "",text_prefix: str = "",doc_embeddings: np.ndarray | None = None,) -> CCRResult:"""Compute CCR loadings: cosine(text, item) for every text × item pair.Prefixes come from the model registry's usage_config - E5-family models require"query: " on BOTH sides for symmetric similarity. Prefixed strings feed theencoder only; raw wording is what gets hashed and exported."""if not texts:raise ValueError("Corpus contains no non-empty texts.")if not items:1 unmodified linestarted = datetime.now(timezone.utc)items_for_encoding = [item_prefix + i for i in items] if item_prefix else itemsitem_emb, items_cached = encode_items_cached(backend, items_for_encoding)if progress_cb:progress_cb(0.02)1 unmodified lineif progress_cb:progress_cb(0.02 + 0.93 * frac)embeddings_from_cache = doc_embeddings is not None and len(doc_embeddings) == len(texts)if embeddings_from_cache:doc_emb = doc_embeddings # precomputed for this exact corpus+model+prefix (jobs.py cache)doc_progress(1.0)else:texts_for_encoding = [text_prefix + t for t in texts] if text_prefix else textsdoc_emb = encode_unique(backend, texts_for_encoding, progress_cb=doc_progress)# Both matrices are L2-normalized -> cosine similarity is a dot product.sims = doc_emb @ item_emb.T8 unmodified lines"embedding_dim": int(doc_emb.shape[1]),"model_max_seq_length": getattr(backend, "max_seq_length", None),"item_embeddings_from_cache": items_cached,"doc_embeddings_from_cache": embeddings_from_cache,"n_texts": len(texts),"n_items": len(items),"items_sha256_16": items_hash,"item_prefix": item_prefix,"text_prefix": text_prefix,"similarity": "cosine","score": "mean of per-item cosine similarities","python": sys.version.split()[0],11 unmodified linesif progress_cb:progress_cb(0.97)return CCRResult(similarities=sims, scores=scores, metadata=metadata, doc_embeddings=doc_emb)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110"""Parse a construct's items from an uploaded CSV/XLSX file.
Design (Deva, 2026-07-11): parse -> preview -> confirm. The file is parsedinto items + reverse flags and returned for the researcher to REVIEW AND EDITbefore saving - never silently imported, because in CCR the item wording ISthe instrument.
Accepted shapes (tolerant, reusing the corpus ingest loaders): * an "item" / "items" / "text" / "statement" / "question" column (case- insensitive), else a single-column file, else the longest-string column; * optional reverse-scoring either as a column ("reverse", "reversed", "reverse_scored", "rev", "r"; truthy = 1/true/yes/y/r) or as a trailing "(R)" / "(rev)" / "(reversed)" marker in the item text (the lab's own spreadsheet convention - packages/construct_library/import_from_xlsx.py); * blank rows dropped, exact duplicates dropped with a warning."""
from __future__ import annotations
import re
import pandas as pd
from .ingest import IngestError, load_corpus
ITEM_COLUMNS = ("item", "items", "text", "statement", "question", "item_text")REVERSE_COLUMNS = ("reverse", "reversed", "reverse_scored", "reverse-scored", "rev", "r")TRUTHY = {"1", "true", "yes", "y", "r", "reverse", "reversed"}REVERSE_MARKER = re.compile(r"\s*\((r|rev|reversed)\)\s*$", re.IGNORECASE)MAX_ITEMS = 200
def parse_construct_file(path: str) -> dict: """Return {items: [{text, reverse_scored}], warnings: [str], source_column: str}.""" try: df, _info = load_corpus(path) except IngestError as exc: raise ValueError(str(exc)) from exc if df.empty: raise ValueError("The file contains no rows.")
lower = {str(c).strip().lower(): c for c in df.columns}
item_col = next((lower[c] for c in ITEM_COLUMNS if c in lower), None) if item_col is None: if len(df.columns) == 1: item_col = df.columns[0] else: # longest average string wins - same heuristic family as corpora def avg_len(col): s = df[col].astype("string").dropna() return s.str.len().mean() if len(s) else 0 item_col = max(df.columns, key=avg_len)
reverse_col = next((lower[c] for c in REVERSE_COLUMNS if c in lower), None) if reverse_col == item_col: reverse_col = None
warnings: list[str] = [] items: list[dict] = [] seen: set[str] = set() n_blank = n_dupes = 0
for _, row in df.iterrows(): raw = row[item_col] text = "" if pd.isna(raw) else str(raw).strip() if not text: n_blank += 1 continue
reverse = False if reverse_col is not None: flag = row[reverse_col] if not pd.isna(flag): s = str(flag).strip().lower() try: # pandas floats an int column containing blanks: 1 -> "1.0" reverse = float(s) != 0 except ValueError: reverse = s in TRUTHY if REVERSE_MARKER.search(text): reverse = True text = REVERSE_MARKER.sub("", text).strip()
if text in seen: n_dupes += 1 continue seen.add(text) items.append({"text": text, "reverse_scored": reverse})
if not items: raise ValueError(f"No usable items found in column '{item_col}'.") if len(items) > MAX_ITEMS: raise ValueError( f"{len(items)} items found; a construct is capped at {MAX_ITEMS}. " "If this file holds multiple scales, split it per construct." )
if n_blank: warnings.append(f"{n_blank} blank row(s) skipped.") if n_dupes: warnings.append(f"{n_dupes} duplicate item(s) skipped.") if reverse_col is None and not any(i["reverse_scored"] for i in items): warnings.append( "No reverse-scoring information found. Mark reverse-scored items by " "appending (R) to the item text, or include a 'reverse' column." ) warnings.append( "Review each item against the original publication before research use - " "the item wording IS the instrument." ) return {"items": items, "warnings": warnings, "source_column": str(item_col)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121"""Construct library loader - seeds the DB from packages/construct_library/constructs/.
Source of truth is the versioned YAML files (spec 0004, design doc §10.1). Rules: * append-only: (construct_id, version) is immutable - same version with changed items is a hard error, never a silent update; * item_hash uses the REFERENCE implementation from validate_constructs.py (loaded by file path) so validator, seeder, and metadata always agree; * verification_status flows to the UI - unverified wording is visibly flagged.
New questionnaires from the lab land as new YAML files; `python packages/construct_library/validate_constructs.py` first, then restart the app (or call sync) to pick them up."""
from __future__ import annotations
import importlib.utilimport jsonimport loggingfrom pathlib import Path
import yamlfrom sqlalchemy.orm import Session
from .models import Construct
logger = logging.getLogger("ccr.constructs")
REPO_ROOT = Path(__file__).resolve().parents[2]CONSTRUCTS_DIR = REPO_ROOT / "packages" / "construct_library" / "constructs"_VALIDATOR_PY = REPO_ROOT / "packages" / "construct_library" / "validate_constructs.py"
def _reference_item_hash(): spec = importlib.util.spec_from_file_location("ccr_construct_validator", _VALIDATOR_PY) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module.item_hash
def load_yaml_constructs() -> list[dict]: files = sorted(CONSTRUCTS_DIR.glob("*.yaml")) out = [] for f in files: data = yaml.safe_load(f.read_text()) data["_file"] = f.name out.append(data) return out
def sync_library(db: Session) -> dict: """Idempotent seed/update of library constructs. Returns a small report.""" item_hash = _reference_item_hash() report = {"inserted": 0, "unchanged": 0, "errors": []}
for c in load_yaml_constructs(): slug, version = c["construct_id"], int(c["version"]) computed_hash = item_hash(c)
existing = ( db.query(Construct) .filter_by(construct_slug=slug, version=version, is_seed=True) .one_or_none() ) if existing: if existing.item_hash != computed_hash: # Append-only violation: same version, different wording. Refuse loudly. report["errors"].append( f"{c['_file']}: items changed under existing version {version} " f"(hash {existing.item_hash[:12]} -> {computed_hash[:12]}). " "Create a NEW version instead of editing this one." ) else: report["unchanged"] += 1 continue
db.add( Construct( name=c["name"], description=c.get("description", ""), reference=c.get("citation", ""), items_json=json.dumps([str(i["text"]) for i in c["items"]]), reverse_flags_json=json.dumps([bool(i.get("reverse_scored", False)) for i in c["items"]]), is_seed=True, construct_slug=slug, version=version, item_hash=computed_hash, verification_status=c.get("verification_status", "needs_verification"), language=c.get("language", "en"), category=c.get("category", ""), ) ) report["inserted"] += 1
db.commit() if report["errors"]: for e in report["errors"]: logger.error("construct library: %s", e) raise RuntimeError( "Construct library append-only violation(s): " + " | ".join(report["errors"]) ) logger.info("construct library sync: %s", report) return report
def construct_snapshot(construct: Construct) -> dict: """Immutable snapshot embedded in every run's metadata (design §10.1).""" items = json.loads(construct.items_json) flags = json.loads(construct.reverse_flags_json or "[]") or [False] * len(items) return { "construct_id": construct.construct_slug or f"custom_{construct.id[:8]}", "version": construct.version or 1, "name": construct.name, "language": construct.language or "en", "items": [ {"text": t, "reverse_scored": bool(f)} for t, f in zip(items, flags) ], "item_hash": construct.item_hash or "", "citation": construct.reference or "", "verification_status": construct.verification_status or "draft", "source_type": "predefined" if construct.is_seed else "user_custom", }123449 unmodified lines545556"""Database setup — SQLite via SQLAlchemy.SQLite is a deliberate choice for this deployment size (single-node, fewconcurrent writers). The models use no SQLite-specific features, so moving49 unmodified linesyield dbfinally:db.close()123449 unmodified lines54555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100"""Database setup - SQLite via SQLAlchemy.SQLite is a deliberate choice for this deployment size (single-node, fewconcurrent writers). The models use no SQLite-specific features, so moving49 unmodified linesyield dbfinally:db.close()def _sqlite_literal(value) -> str:if isinstance(value, bool):return "1" if value else "0"if isinstance(value, (int, float)):return str(value)return "'" + str(value).replace("'", "''") + "'"def auto_migrate_sqlite(target_engine, metadata) -> list[str]:"""Add ORM columns missing from existing SQLite tables (additive only).create_all() creates missing tables but never alters existing ones, so adev DB from last week 500s on this week's new column. This closes that gapfor the additive changes we make; anything non-additive (renames, drops,type changes) waits for Alembic, which replaces this in Phase 2 alongsidePostgres. Columns with scalar defaults get that default; callable defaults(uuid/now) are added nullable and filled by the ORM on new rows."""import loggingfrom sqlalchemy import inspect, textadded: list[str] = []inspector = inspect(target_engine)with target_engine.begin() as conn:for table in metadata.sorted_tables:if table.name not in inspector.get_table_names():continue # create_all handles brand-new tablesexisting = {c["name"] for c in inspector.get_columns(table.name)}for column in table.columns:if column.name in existing:continuecol_type = column.type.compile(target_engine.dialect)ddl = f'ALTER TABLE {table.name} ADD COLUMN "{column.name}" {col_type}'default = getattr(column.default, "arg", None)if default is not None and not callable(default):ddl += f" DEFAULT {_sqlite_literal(default)}"conn.execute(text(ddl))added.append(f"{table.name}.{column.name}")if added:logging.getLogger("ccr.db").warning("auto-migrated columns: %s", ", ".join(added))return added
123429 unmodified lines343536373839407 unmodified lines484950515253545556575859606162636465666768697071727374757677787980818283848586871 unmodified line89909192939495"""Corpus ingestion — tolerant of real-world research files.Researchers upload CSVs exported from Qualtrics, Excel, R, SPSS, andscrapers: BOMs, latin-1 encodings, semicolon/tab delimiters, ragged rows.29 unmodified lines"""Parse CSV/XLSX into a DataFrame.Returns (df, parse_info) where parse_info records the format,encoding, and delimiter actually used — stored with the corpus andechoed into every run's reproducibility metadata."""p = Path(path)7 unmodified lineslast_error: Exception | None = Nonefor encoding in _ENCODINGS:# First attempt: delimiter sniffing (handles ',', ';', '\t', '|').# The python engine is slower but supports sniffing + bad-line skips;# fine at lab scale. Falls back to plain comma parsing for files the# sniffer chokes on (e.g., single-column CSVs).for sep, sep_label in ((None, "sniffed"), (",", ",")):try:df = pd.read_csv(p,encoding=encoding,sep=sep,engine="python",on_bad_lines="skip",)info = {"format": "csv","encoding": encoding,"delimiter": _describe_sep(df, sep_label),}if encoding == "latin-1":info["note"] = ("File was not valid UTF-8; decoded as latin-1. ""Verify non-ASCII characters rendered correctly.")return _validate(df), infoexcept IngestError:raiseexcept Exception as exc: # try next (sep, encoding) combinationlast_error = excraise IngestError(f"Could not parse CSV file: {last_error}")def _describe_sep(df: pd.DataFrame, sep_label: str) -> str:return sep_labeldef _validate(df: pd.DataFrame) -> pd.DataFrame:1 unmodified lineraise IngestError("The file parsed but contains no data rows.")if len(df) > max_rows():raise IngestError(f"File has {len(df):,} rows — above this instance's "f"{max_rows():,}-row limit. Split the corpus or run locally.")df.columns = [str(c) for c in df.columns]123429 unmodified lines343536373839407 unmodified lines484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091 unmodified line111112113114115116117"""Corpus ingestion - tolerant of real-world research files.Researchers upload CSVs exported from Qualtrics, Excel, R, SPSS, andscrapers: BOMs, latin-1 encodings, semicolon/tab delimiters, ragged rows.29 unmodified lines"""Parse CSV/XLSX into a DataFrame.Returns (df, parse_info) where parse_info records the format,encoding, and delimiter actually used - stored with the corpus andechoed into every run's reproducibility metadata."""p = Path(path)7 unmodified lineslast_error: Exception | None = Nonefor encoding in _ENCODINGS:# Delimiter detection restricted to REAL delimiter candidates (, ; tab |).# Unrestricted sniffing famously "detects" spaces in single-column files# of natural-language sentences, exploding the header into word-columns.try:sep = _detect_delimiter(p, encoding)df = pd.read_csv(p,encoding=encoding,sep=sep,engine="python",on_bad_lines="skip",)info = {"format": "csv","encoding": encoding,"delimiter": {"\t": "tab"}.get(sep, sep),}if encoding == "latin-1":info["note"] = ("File was not valid UTF-8; decoded as latin-1. ""Verify non-ASCII characters rendered correctly.")return _validate(df), infoexcept IngestError:raiseexcept Exception as exc: # try next encodinglast_error = excraise IngestError(f"Could not parse CSV file: {last_error}")_DELIMITER_CANDIDATES = (",", ";", "\t", "|")def _detect_delimiter(p: Path, encoding: str) -> str:"""Pick the candidate delimiter most consistent across the first lines.Single-column files (no candidate present) default to ',' - a comma parseof a delimiter-free file yields one column, which is exactly right."""try:with open(p, encoding=encoding, errors="strict") as fh:lines = [line for line, _ in zip(fh, range(20)) if line.strip()]except UnicodeDecodeError:raise ValueError(f"not decodable as {encoding}")if not lines:return ","def score(delim: str) -> tuple[int, int]:counts = [line.count(delim) for line in lines]present = min(counts) > 0consistent = len(set(counts)) == 1return (int(present) + int(present and consistent), counts[0])best = max(_DELIMITER_CANDIDATES, key=score)return best if score(best)[0] > 0 else ","def _validate(df: pd.DataFrame) -> pd.DataFrame:1 unmodified lineraise IngestError("The file parsed but contains no data rows.")if len(df) > max_rows():raise IngestError(f"File has {len(df):,} rows - above this instance's "f"{max_rows():,}-row limit. Split the corpus or run locally.")df.columns = [str(c) for c in df.columns]
1234568 unmodified lines1516171819202122232425262728293031323 unmodified lines36373839404142434445464748495048 unmodified lines991001011021031041053 unmodified lines1091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401412 unmodified lines14414514614714814915015129 unmodified lines181182183184185186187188189190191192193194"""Background job runner.Jobs run on a dedicated single-worker executor — a deliberate right-sizing:embedding is CPU-bound, so running jobs sequentially protects the instance'smemory and keeps per-job throughput predictable, while job state lives inthe DB (queued → running → completed/failed) so the API and UI never depend8 unmodified linesfrom __future__ import annotationsimport jsonimport loggingimport tracebackfrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetime, timezoneimport numpy as npfrom .ccr import get_backend, run_ccrfrom .db import DATA_DIR, SessionLocalfrom .ingest import load_corpusfrom .models import Construct, Corpus, Joblogger = logging.getLogger("ccr.jobs")3 unmodified linesSNIPPET_LEN = 220# Single worker: sequential jobs, bounded memory. See module docstring._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="ccr-job")def submit_job(job_id: str) -> None:_executor.submit(_run_job_logged, job_id)def shutdown_executor() -> None:_executor.shutdown(wait=False, cancel_futures=True)def recover_orphaned_jobs() -> int:48 unmodified linesitems = json.loads(construct.items_json)parse_info = json.loads(corpus.parse_info_json or "{}")df, _ = load_corpus(corpus.path)if job.text_column not in df.columns:raise ValueError(f"Column '{job.text_column}' not found in corpus.")3 unmodified lineswork_df = df.loc[mask].reset_index(drop=True)texts = work_df[job.text_column].astype(str).tolist()def progress(frac: float):_set(db, job, progress=round(float(frac), 3))backend = get_backend(job.model_name)result = run_ccr(texts, items, backend, progress_cb=progress)# Data-quality warnings surfaced to the researcher, not buried in logs.warnings = []if dropped:warnings.append(f"{dropped} empty text row(s) were dropped before analysis.")n_dupes = len(texts) - len(set(texts))if n_dupes:warnings.append(f"{n_dupes} duplicate text(s) detected — each is scored ""independently; deduplicate upstream if unintended.")max_seq = result.metadata.get("model_max_seq_length")if max_seq:char_budget = int(max_seq) * 4 # rough chars-per-token heuristicn_long = sum(1 for t in texts if len(t) > char_budget)if n_long:warnings.append(f"{n_long} text(s) likely exceed the model's {max_seq}-token ""window and were truncated; consider splitting long documents.")if parse_info.get("note"):warnings.append(parse_info["note"])# Export mirrors ccr_wrapper's shape: input columns + per-item# similarity columns + overall score, so it drops into existing2 unmodified linesfor j in range(result.similarities.shape[1]):out[f"sim_item_{j + 1}"] = np.round(result.similarities[:, j], 6)out["ccr_score"] = np.round(result.scores, 6)result_path = RESULTS_DIR / f"{job.id}.csv"out.to_csv(result_path, index=False)scores = result.scoresorder = np.argsort(scores)29 unmodified linesmetadata = {**result.metadata,"job_id": job.id,"corpus_file": corpus.filename,"corpus_parse_info": parse_info,"text_column": job.text_column,"construct": construct.name,"construct_reference": construct.reference,"n_rows_input": int(corpus.n_rows),"n_rows_dropped_empty": dropped,}_set(db,1234568 unmodified lines151617181920212223242526272829303132333435363738394041423 unmodified lines464748495051525354555657585960616263646566676869707172737475767748 unmodified lines1261271281291301311321331341351361371381393 unmodified lines1431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512 unmodified lines25425525625725825926026126229 unmodified lines292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336"""Background job runner.Jobs run on a dedicated single-worker executor - a deliberate right-sizing:embedding is CPU-bound, so running jobs sequentially protects the instance'smemory and keeps per-job throughput predictable, while job state lives inthe DB (queued → running → completed/failed) so the API and UI never depend8 unmodified linesfrom __future__ import annotationsimport hashlibimport jsonimport loggingimport osimport tracebackfrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetime, timezoneimport numpy as npfrom . import registry, warnings_enginefrom .ccr import FAKE_MODEL_NAME, get_backend, run_ccrfrom .construct_lib import construct_snapshotfrom .db import DATA_DIR, SessionLocalfrom .ingest import load_corpusfrom .models import Construct, Corpus, Job, Projectfrom .reproducibility import record_environmentfrom .retention import EMB_CACHE_DIR, remove_corpus_filesfrom . import storagePLATFORM_VERSION = "0.2.0"OUTPUT_SCHEMA_VERSION = "1.0" # bump on ANY export-column change (CLAUDE.md hard rule)logger = logging.getLogger("ccr.jobs")3 unmodified linesSNIPPET_LEN = 220# Single worker: sequential jobs, bounded memory. See module docstring.# Created lazily and re-creatable: a lifespan shutdown (dev reload, test# client closing) must not permanently kill job submission for the process.import threading_executor: ThreadPoolExecutor | None = None_executor_lock = threading.Lock()def _get_executor() -> ThreadPoolExecutor:global _executorwith _executor_lock:if _executor is None:_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="ccr-job")return _executordef submit_job(job_id: str) -> None:_get_executor().submit(_run_job_logged, job_id)def shutdown_executor() -> None:global _executorwith _executor_lock:if _executor is not None:_executor.shutdown(wait=False, cancel_futures=True)_executor = Nonedef recover_orphaned_jobs() -> int:48 unmodified linesitems = json.loads(construct.items_json)parse_info = json.loads(corpus.parse_info_json or "{}")# Materialize the corpus locally (a no-op on the local backend; a# temp download when files live in object storage).local_corpus, corpus_is_temp = storage.fetch_to_local(corpus.path)try:df, _ = load_corpus(str(local_corpus))finally:if corpus_is_temp:local_corpus.unlink(missing_ok=True)if job.text_column not in df.columns:raise ValueError(f"Column '{job.text_column}' not found in corpus.")3 unmodified lineswork_df = df.loc[mask].reset_index(drop=True)texts = work_df[job.text_column].astype(str).tolist()last_progress = -1.0def progress(frac: float):# Throttled: commit only on >=1% movement (or completion) so large# corpora don't turn the progress bar into a DB write hotspot.nonlocal last_progressfrac = round(float(frac), 3)if frac - last_progress >= 0.01 or frac >= 1.0:last_progress = frac_set(db, job, progress=frac)# Model config from the registry (spec 0003); the test fake has none.model_cfg = None if job.model_name == FAKE_MODEL_NAME else registry.get_model(job.model_name)item_prefix = model_cfg.item_prefix if (model_cfg and model_cfg.requires_prefix) else ""text_prefix = model_cfg.text_prefix if (model_cfg and model_cfg.requires_prefix) else ""project = db.get(Project, job.project_id)is_anonymous = not (project and project.owner_user_id)# Corpus-embedding cache: the CCR workflow is many constructs against# the SAME corpus, and ~97% of a run is embedding the documents. Corpora# are immutable after upload, so (corpus, column, model, revision,# prefix) fully determines the embeddings - reusing them is bit-identical.# Disabled for the test fake (unless forced) and skipped for anonymous# runs (their files are removed right after the run anyway).cache_enabled = os.environ.get("CCR_EMB_CACHE", "1") == "1" and (model_cfg is not None or os.environ.get("CCR_EMB_CACHE_FORCE") == "1")cache_path = Nonecached_embeddings = Noneif cache_enabled:key = hashlib.sha256(f"{job.text_column}|{job.model_name}|"f"{model_cfg.revision if model_cfg else 'fake'}|{text_prefix}".encode()).hexdigest()[:20]cache_path = EMB_CACHE_DIR / f"{corpus.id}_{key}.npy"if cache_path.exists():try:candidate = np.load(cache_path)if candidate.shape[0] == len(texts):cached_embeddings = candidateexcept Exception:cache_path.unlink(missing_ok=True) # unreadable cache: recomputebackend = get_backend(job.model_name)result = run_ccr(texts, items, backend,progress_cb=progress, item_prefix=item_prefix, text_prefix=text_prefix,doc_embeddings=cached_embeddings,)if (cache_enabled and cache_path is not None and cached_embeddings is Noneand not is_anonymous and result.doc_embeddings is not None):try:np.save(cache_path, result.doc_embeddings)except Exception:logger.warning("could not write embedding cache %s", cache_path)# Structured data-quality warnings (spec 0001) - objects, never bare strings.W = warnings_engine.warningwarnings: list[dict] = []if dropped:warnings.append(W("EMPTY_ROWS_DROPPED", "info",f"{dropped} empty text row(s) were dropped before analysis.", count=dropped,))n_dupes = len(texts) - len(set(texts))if n_dupes:warnings.append(W("DUPLICATE_TEXTS", "warning",f"{n_dupes} duplicate text(s) detected - each is scored independently; ""deduplicate upstream if unintended.", count=n_dupes,))short = warnings_engine.short_text_warning(texts)if short:warnings.append(short)max_seq = model_cfg.max_seq_length if model_cfg else result.metadata.get("model_max_seq_length")if max_seq:char_budget = int(max_seq) * 4 # rough chars-per-token heuristicn_long = sum(1 for t in texts if len(t) > char_budget)if n_long:warnings.append(W("TEXTS_MAYBE_TRUNCATED", "warning",f"{n_long} text(s) likely exceed the model's {max_seq}-token window and ""were truncated; consider splitting long documents.", count=n_long,))if parse_info.get("note"):warnings.append(W("ENCODING_FALLBACK", "warning", parse_info["note"]))# Language checks: corpus-level detection + model-coverage (spec 0001, design §12).selected_language = (job.language or "en").lower()lang_result, lang_warnings = warnings_engine.detect_corpus_language(texts, selected_language)warnings.extend(lang_warnings)if model_cfg:mlw = warnings_engine.model_language_warning(selected_language, model_cfg.id, model_cfg.supported_languages,model_cfg.language_set_name,)if mlw:warnings.append(mlw)for user_warning in (model_cfg.user_warnings if model_cfg else ()):warnings.append(W("MODEL_NOTE", "info", user_warning))# Export mirrors ccr_wrapper's shape: input columns + per-item# similarity columns + overall score, so it drops into existing2 unmodified linesfor j in range(result.similarities.shape[1]):out[f"sim_item_{j + 1}"] = np.round(result.similarities[:, j], 6)out["ccr_score"] = np.round(result.scores, 6)local_result = RESULTS_DIR / f"{job.id}.csv"out.to_csv(local_result, index=False)result_path = storage.move_local_into_storage("results", f"{job.id}.csv", local_result)scores = result.scoresorder = np.argsort(scores)29 unmodified linesmetadata = {**result.metadata,"job_id": job.id,"platform_version": PLATFORM_VERSION,"output_schema_version": OUTPUT_SCHEMA_VERSION,"corpus_file": corpus.filename,"corpus_parse_info": parse_info,"text_column": job.text_column,"language": lang_result.as_metadata(),"construct": construct.name,"construct_reference": construct.reference,"construct_snapshot": construct_snapshot(construct),"model_registry_id": model_cfg.id if model_cfg else job.model_name,"provider_model_id": model_cfg.provider_model_id if model_cfg else job.model_name,"model_revision": model_cfg.revision if model_cfg else None,"scoring": {"adjustment_strategy": "none", "aggregate": "mean_all_items"},"output_schema": (list(work_df.columns)+ [f"sim_item_{j + 1}" for j in range(result.similarities.shape[1])]+ ["ccr_score"]),"warnings": warnings,"n_rows_input": int(corpus.n_rows),"n_rows_dropped_empty": dropped,}record_environment(metadata) # pins exact package versions for the repro bundle# Retention (PI decision 2026-07-10): anonymous uploads are removed the# moment analysis finishes. The results summary/CSV stay downloadable# until the anonymous project's TTL purge; the raw upload does not.if is_anonymous:remove_corpus_files(corpus)corpus.path = ""metadata["anonymous_corpus_removed"] = Truewarnings.append(W("ANONYMOUS_DATA_REMOVED", "info","The uploaded file was deleted after this analysis (anonymous runs ""keep no raw data). Re-running requires uploading again, or sign in ""to keep datasets.",))summary["warnings"] = warningsmetadata["warnings"] = warnings_set(db,
12345 unmodified lines101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869704 unmodified lines757677787980818283848586879 unmodified lines97989910010110224 unmodified lines12712812913013113213313413513613713813914014114214314414514614722 unmodified lines1701711721731741751761773 unmodified lines18118218318418518618718818919019119219319419519619719819927 unmodified lines2272282292302312322332342352362372382392402412422432442452462472482492502512522532542552561 unmodified line25825926026126226326426526626726 unmodified lines2942952962972982993003013029 unmodified lines312313314315316317"""CCR Platform — FastAPI application.Single deployable: serves the JSON API under /api and the prebuilt Reactdashboard as static files at /. Local-first by design: corpora, embeddings,5 unmodified linesfrom __future__ import annotationsimport jsonfrom contextlib import asynccontextmanagerfrom pathlib import Pathfrom fastapi import Depends, FastAPI, HTTPException, UploadFilefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponse, JSONResponsefrom fastapi.staticfiles import StaticFilesfrom sqlalchemy.orm import Sessionfrom . import jobs as jobs_modulefrom .ccr import AVAILABLE_MODELS, FAKE_MODEL_NAMEfrom .db import DATA_DIR, Base, SessionLocal, engine, get_dbfrom .ingest import IngestError, load_corpus, suggest_text_columnfrom .models import Construct, Corpus, Job, Projectfrom .schemas import (ConstructCreate,ConstructOut,CorpusOut,JobCreate,JobOut,ProjectCreate,ProjectOut,)from .seed_constructs import SEED_CONSTRUCTSMAX_UPLOAD_BYTES = 25 * 1024 * 1024 # sane lab-scale ceiling; raise deliberatelyALLOWED_SUFFIXES = (".csv", ".xlsx", ".xls")@asynccontextmanagerasync def lifespan(_: FastAPI):"""Create tables and seed the construct library once at startup."""Base.metadata.create_all(engine)db = SessionLocal()try:if db.query(Construct).filter_by(is_seed=True).count() == 0:for seed in SEED_CONSTRUCTS:db.add(Construct(name=seed["name"],description=seed["description"],reference=seed["reference"],items_json=json.dumps(seed["items"]),is_seed=True,))db.commit()finally:db.close()jobs_module.recover_orphaned_jobs()yieldjobs_module.shutdown_executor()app = FastAPI(title="CCR Platform", version="0.1.0", lifespan=lifespan)app.add_middleware(CORSMiddleware,allow_origins=["http://localhost:5173", "http://127.0.0.1:5173"], # Vite dev server4 unmodified lines# ---------------------------------------------------------------- helpersdef _construct_out(c: Construct) -> ConstructOut:return ConstructOut(id=c.id,name=c.name,description=c.description,reference=c.reference,items=json.loads(c.items_json),is_seed=c.is_seed,)9 unmodified linescorpus_filename=corpus.filename if corpus else "",text_column=j.text_column,model_name=j.model_name,status=j.status,progress=j.progress,error=j.error,24 unmodified lines@app.get("/api/models")def list_models():return AVAILABLE_MODELS# --------------------------------------------------------------- projects@app.get("/api/projects", response_model=list[ProjectOut])def list_projects(db: Session = Depends(get_db)):return db.query(Project).order_by(Project.created_at.desc()).all()@app.post("/api/projects", response_model=ProjectOut, status_code=201)def create_project(body: ProjectCreate, db: Session = Depends(get_db)):project = Project(name=body.name.strip(), description=body.description.strip())db.add(project)db.commit()return project# ----------------------------------------------------------------- corpora22 unmodified lines@app.post("/api/projects/{project_id}/corpora", response_model=CorpusOut, status_code=201)async def upload_corpus(project_id: str, file: UploadFile, db: Session = Depends(get_db)):_get_or_404(db, Project, project_id)suffix = Path(file.filename or "upload.csv").suffix.lower()if suffix not in ALLOWED_SUFFIXES:3 unmodified linesif len(payload) > MAX_UPLOAD_BYTES:raise HTTPException(413, "File exceeds the 25 MB upload limit.")corpus = Corpus(project_id=project_id, filename=file.filename, path="", n_rows=0, columns_json="[]")dest = DATA_DIR / "corpora" / f"{corpus.id}{suffix}"dest.write_bytes(payload)corpus.path = str(dest)try:df, parse_info = load_corpus(str(dest))except IngestError as exc:dest.unlink(missing_ok=True)raise HTTPException(400, str(exc)) from exccorpus.n_rows = int(len(df))corpus.columns_json = json.dumps(list(df.columns))corpus.parse_info_json = json.dumps(parse_info)27 unmodified linesitems = [i.strip() for i in body.items if i.strip()]if not items:raise HTTPException(400, "Construct needs at least one non-empty item.")construct = Construct(name=body.name.strip(),description=body.description.strip(),reference=body.reference.strip(),items_json=json.dumps(items),is_seed=False,)db.add(construct)db.commit()return _construct_out(construct)# -------------------------------------------------------------------- jobs@app.post("/api/jobs", response_model=JobOut, status_code=201)def create_job(body: JobCreate, db: Session = Depends(get_db)):_get_or_404(db, Project, body.project_id)corpus = _get_or_404(db, Corpus, body.corpus_id)_get_or_404(db, Construct, body.construct_id)if body.text_column not in json.loads(corpus.columns_json):raise HTTPException(400, f"Column '{body.text_column}' not in corpus columns.")allowed = {m["name"] for m in AVAILABLE_MODELS} | {FAKE_MODEL_NAME}if body.model_name not in allowed:raise HTTPException(400, f"Unknown model '{body.model_name}'.")job = Job(project_id=body.project_id,1 unmodified lineconstruct_id=body.construct_id,text_column=body.text_column,model_name=body.model_name,)db.add(job)db.commit()jobs_module.submit_job(job.id)return _job_out(db, job)26 unmodified linesjob = _get_or_404(db, Job, job_id)if job.status != "completed" or not job.result_path:raise HTTPException(409, "Results not available.")return FileResponse(job.result_path, media_type="text/csv", filename=f"ccr_results_{job_id[:8]}.csv")@app.get("/api/jobs/{job_id}/metadata")9 unmodified lines)# ------------------------------------------------------------ static (SPA)STATIC_DIR = Path(__file__).resolve().parent.parent / "static"if STATIC_DIR.exists():12345 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889904 unmodified lines95969798991001011021031041051061071081091101111121131141159 unmodified lines12512612712812913013124 unmodified lines15615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343422 unmodified lines4574584594604614624634644654664674684694703 unmodified lines47447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351427 unmodified lines5425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416421 unmodified line64464564664764864965065165265365465565665765865966066166266366426 unmodified lines6916926936946956966976986997007017027037047057069 unmodified lines716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750"""CCR Platform - FastAPI application.Single deployable: serves the JSON API under /api and the prebuilt Reactdashboard as static files at /. Local-first by design: corpora, embeddings,5 unmodified linesfrom __future__ import annotationsimport jsonimport osfrom contextlib import asynccontextmanagerfrom pathlib import Pathfrom fastapi import Depends, FastAPI, HTTPException, Request, Response, UploadFilefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.middleware.gzip import GZipMiddlewarefrom fastapi.responses import FileResponse, JSONResponse, PlainTextResponsefrom fastapi.staticfiles import StaticFilesfrom sqlalchemy.orm import Sessionfrom . import auth, auth_google, retention, storagefrom . import jobs as jobs_modulefrom . import registryfrom .ccr import FAKE_MODEL_NAMEfrom .construct_files import parse_construct_filefrom .construct_lib import sync_libraryfrom .db import DATA_DIR, Base, SessionLocal, auto_migrate_sqlite, engine, get_dbfrom .ingest import IngestError, load_corpus, suggest_text_columnfrom .models import Construct, Corpus, Job, Project, Userfrom .reproducibility import requirements_text, script_textfrom .schemas import (ConstructCreate,ConstructOut,CorpusOut,JobCreate,JobOut,LoginIn,ProjectCreate,ProjectOut,ProjectPatch,RegisterIn,)MAX_UPLOAD_BYTES = 25 * 1024 * 1024 # sane lab-scale ceiling; raise deliberatelyALLOWED_SUFFIXES = (".csv", ".xlsx", ".xls")# Languages offered in the UI selector; detection may report others (ISO 639-1).SELECTABLE_LANGUAGES = ["en", "es", "fr", "de", "it", "pt", "nl", "ru", "zh", "ja", "ko", "ar", "hi", "tr", "fa",]@asynccontextmanagerasync def lifespan(_: FastAPI):"""Create tables and sync the construct library (YAML source of truth) at startup."""Base.metadata.create_all(engine)auto_migrate_sqlite(engine, Base.metadata) # additive column adds for existing dev DBsregistry.list_models() # fail fast on an invalid models.yamldb = SessionLocal()try:sync_library(db)finally:db.close()jobs_module.recover_orphaned_jobs()retention.start_cleanup() # anonymous-data TTL purge (no-op if CCR_ANON_TTL_HOURS=0)if os.environ.get("CCR_WARM_MODEL") == "1" and os.environ.get("CCR_FAKE_EMBEDDINGS") != "1":import threadingdef _warm():try:from .ccr import get_backendget_backend(registry.default_model().id).encode(["warm up"])except Exception:pass # first real run will load the model insteadthreading.Thread(target=_warm, daemon=True, name="ccr-warmup").start()yieldretention.stop_cleanup()jobs_module.shutdown_executor()app = FastAPI(title="CCR Platform", version="0.1.0", lifespan=lifespan)app.add_middleware(GZipMiddleware, minimum_size=1024) # constructs payload + SPA compress ~4-5xapp.add_middleware(CORSMiddleware,allow_origins=["http://localhost:5173", "http://127.0.0.1:5173"], # Vite dev server4 unmodified lines# ---------------------------------------------------------------- helpersdef _construct_out(c: Construct) -> ConstructOut:items = json.loads(c.items_json)flags = json.loads(c.reverse_flags_json or "[]") or [False] * len(items)return ConstructOut(id=c.id,name=c.name,description=c.description,reference=c.reference,items=items,reverse_scored=flags,is_seed=c.is_seed,version=c.version or 1,verification_status=c.verification_status or "draft",language=c.language or "en",category=c.category or "",item_hash=(c.item_hash or "")[:16],)9 unmodified linescorpus_filename=corpus.filename if corpus else "",text_column=j.text_column,model_name=j.model_name,language=j.language or "en",status=j.status,progress=j.progress,error=j.error,24 unmodified lines@app.get("/api/models")def list_models():"""Model options from the registry (spec 0003) - never hardcoded."""return [{"id": m.id,"label": m.display_name,"default": m.default,"languages": (m.language_set_name or ", ".join(sorted(m.supported_languages)) or "unspecified"),"speed_tier": m.speed_tier,"quality_tier": m.quality_tier,"warnings": list(m.user_warnings),}for m in registry.list_models()]@app.get("/api/languages")def list_languages():return SELECTABLE_LANGUAGES# ------------------------------------------------------------------ accounts# Local email+password accounts (auth.py) - the free interim provider. The# managed swap (Supabase: Google + email/password) replaces token issuance# only; every other endpoint just depends on auth.get_current_user.def _saved_runs_used(db: Session, user_id: str) -> int:return (db.query(Job).join(Project, Job.project_id == Project.id).filter(Project.owner_user_id == user_id, Job.status.in_(("queued", "running", "completed"))).count())def _set_session_cookie(response: Response, user: User) -> None:response.set_cookie(auth.COOKIE_NAME,auth.create_session_token(user.id, user.email, user.name),httponly=True,samesite="lax",secure=auth.cookies_secure(),max_age=30 * 24 * 3600,)@app.get("/api/auth/me")def auth_me(request: Request,db: Session = Depends(get_db),user: dict | None = Depends(auth.get_current_user),):if user:return {"signed_in": True,"name": user["name"],"email": user["email"],"limits": {"max_bytes": MAX_UPLOAD_BYTES, "max_rows": None},"usage": {"saved_runs": _saved_runs_used(db, user["id"]),"max_saved_runs": auth.user_max_saved_runs(),},}return {"signed_in": False,"name": None,"email": None,"google_available": auth_google.configured(),"limits": {"max_bytes": auth.anon_max_bytes(), "max_rows": auth.anon_max_rows()},"usage": {"runs_used_today": auth.runs_used_today(request),"max_runs_per_day": auth.anon_max_runs_per_day(),},}@app.post("/api/auth/register", status_code=201)def register(body: RegisterIn, response: Response, db: Session = Depends(get_db)):email = body.email.strip().lower()if not auth.valid_email(email):raise HTTPException(400, "Please enter a valid email address.")if len(body.password) < auth.MIN_PASSWORD_LEN:raise HTTPException(400, f"Password must be at least {auth.MIN_PASSWORD_LEN} characters.")if db.query(User).filter_by(email=email).first():raise HTTPException(409, "An account with this email already exists. Sign in instead.")user = User(email=email, name=body.name.strip(), password_hash=auth.hash_password(body.password))db.add(user)db.commit()_set_session_cookie(response, user)return {"signed_in": True, "name": user.name, "email": user.email}@app.post("/api/auth/login")def login(body: LoginIn, response: Response, db: Session = Depends(get_db)):email = body.email.strip().lower()user = db.query(User).filter_by(email=email).first()if user is not None and not user.password_hash:raise HTTPException(401, "This account uses Google sign-in - use the Google button.")if user is None or not auth.verify_password(body.password, user.password_hash):raise HTTPException(401, "Incorrect email or password.")_set_session_cookie(response, user)return {"signed_in": True, "name": user.name, "email": user.email}@app.get("/api/auth/google/login")def google_login():"""Start the Google sign-in flow (Supabase PKCE). Plain redirect - thefrontend links here directly, no SDK involved."""if not auth_google.configured():raise HTTPException(503, "Google sign-in is not configured on this instance.")from fastapi.responses import RedirectResponseurl, verifier = auth_google.begin()resp = RedirectResponse(url, status_code=307)resp.set_cookie(auth_google.VERIFIER_COOKIE,auth.sign_payload({"v": verifier}),httponly=True,samesite="lax",secure=auth.cookies_secure(),max_age=auth_google.VERIFIER_TTL_SECONDS,)return resp@app.get("/api/auth/google/callback")def google_callback(request: Request, code: str = "", db: Session = Depends(get_db)):from fastapi.responses import RedirectResponsedef fail(msg: str):return RedirectResponse(f"/?auth_error={msg}", status_code=307)if not auth_google.configured():return fail("google-not-configured")payload = auth.verify_payload(request.cookies.get(auth_google.VERIFIER_COOKIE))if not code or not payload or "v" not in payload:return fail("sign-in-expired-try-again")try:info = auth_google.exchange(code, payload["v"])except ValueError:return fail("google-exchange-failed")user = db.query(User).filter_by(email=info["email"]).first()if user is None:# Google-verified account: no local password (password login is refused# with a pointer to the Google button).user = User(email=info["email"], name=info["name"], password_hash="")db.add(user)db.commit()resp = RedirectResponse("/", status_code=307)resp.delete_cookie(auth_google.VERIFIER_COOKIE)_set_session_cookie(resp, user)return resp@app.post("/api/auth/logout")def logout(response: Response):response.delete_cookie(auth.COOKIE_NAME)return {"signed_in": False}# --------------------------------------------------------------- projectsdef _visible_owners(user: dict | None) -> tuple[str, ...]:"""Anonymous viewers see anonymous projects; signed-in users additionallysee their own. Other users' projects are invisible (and untouchable)."""return ("",) if user is None else ("", user["id"])def _require_project_access(project: Project, user: dict | None) -> None:if project.owner_user_id and (user is None or project.owner_user_id != user["id"]):raise HTTPException(403, "This project belongs to another account.")@app.get("/api/projects", response_model=list[ProjectOut])def list_projects(db: Session = Depends(get_db), user: dict | None = Depends(auth.get_current_user)):"""Projects ordered by last activity (latest run, else creation) - theproject a researcher wants is almost always the one they last worked on."""from sqlalchemy import funcactivity = {pid: (last, count)for pid, last, count in db.query(Job.project_id, func.max(Job.created_at), func.count(Job.id)).group_by(Job.project_id).all()}rows = db.query(Project).filter(Project.owner_user_id.in_(_visible_owners(user))).all()out = []for p in rows:last, count = activity.get(p.id, (None, 0))out.append(ProjectOut(id=p.id,name=p.name,description=p.description,created_at=p.created_at,last_activity_at=last or p.created_at,n_runs=count,archived=bool(p.archived),))out.sort(key=lambda x: x.last_activity_at, reverse=True)return out@app.post("/api/projects", response_model=ProjectOut, status_code=201)def create_project(body: ProjectCreate,db: Session = Depends(get_db),user: dict | None = Depends(auth.get_current_user),):project = Project(name=body.name.strip(),description=body.description.strip(),owner_user_id=user["id"] if user else "", # "" = anonymous (TTL purge applies))db.add(project)db.commit()return ProjectOut(id=project.id,name=project.name,description=project.description,created_at=project.created_at,last_activity_at=project.created_at,n_runs=0,archived=False,)@app.patch("/api/projects/{project_id}", response_model=ProjectOut)def patch_project(project_id: str,body: ProjectPatch,db: Session = Depends(get_db),user: dict | None = Depends(auth.get_current_user),):"""Archive/unarchive - reversible, no data loss. Archived projects collapseinto the sidebar's Archived section and keep all datasets and runs."""project = _get_or_404(db, Project, project_id)_require_project_access(project, user)if body.archived is not None:project.archived = bool(body.archived)db.commit()return ProjectOut(id=project.id,name=project.name,description=project.description,created_at=project.created_at,last_activity_at=project.created_at,n_runs=0,archived=bool(project.archived),)@app.delete("/api/projects/{project_id}", status_code=204)def delete_project(project_id: str,db: Session = Depends(get_db),user: dict | None = Depends(auth.get_current_user),):"""Permanent delete: removes the project, its datasets, runs, uploadedfiles, result files, and cached embeddings. Logged without retaining anyuploaded text (design doc §9)."""import loggingproject = _get_or_404(db, Project, project_id)_require_project_access(project, user)counts = retention.delete_project_cascade(db, project)logging.getLogger("ccr.projects").info("project deleted: id=%s name=%r corpora=%d runs=%d",project_id, project.name, counts["corpora"], counts["runs"],)return Response(status_code=204)# ----------------------------------------------------------------- corpora22 unmodified lines@app.post("/api/projects/{project_id}/corpora", response_model=CorpusOut, status_code=201)async def upload_corpus(project_id: str,file: UploadFile,db: Session = Depends(get_db),user: dict | None = Depends(auth.get_current_user),):project = _get_or_404(db, Project, project_id)_require_project_access(project, user)suffix = Path(file.filename or "upload.csv").suffix.lower()if suffix not in ALLOWED_SUFFIXES:3 unmodified linesif len(payload) > MAX_UPLOAD_BYTES:raise HTTPException(413, "File exceeds the 25 MB upload limit.")# Tier gate (design §5.1): anonymous users get strict caps; signing in# lifts them.if user is None and len(payload) > auth.anon_max_bytes():mb = auth.anon_max_bytes() // (1024 * 1024)raise HTTPException(413,f"Anonymous uploads are limited to {mb} MB. Sign in (top right) to upload larger files.",)corpus = Corpus(project_id=project_id, filename=file.filename, path="", n_rows=0, columns_json="[]")# Parse from a local temp file, then hand the bytes to the storage backend# (local disk by default; S3/R2 when CCR_STORAGE=s3 in production).tmp_dir = DATA_DIR / "tmp"tmp_dir.mkdir(exist_ok=True)tmp = tmp_dir / f"{corpus.id}{suffix}"tmp.write_bytes(payload)try:df, parse_info = load_corpus(str(tmp))except IngestError as exc:tmp.unlink(missing_ok=True)raise HTTPException(400, str(exc)) from excif user is None and len(df) > auth.anon_max_rows():tmp.unlink(missing_ok=True)raise HTTPException(400,f"Anonymous uploads are limited to {auth.anon_max_rows():,} rows "f"(this file has {len(df):,}). Sign in (top right) to upload larger corpora.",)corpus.path = storage.move_local_into_storage("corpora", f"{corpus.id}{suffix}", tmp)corpus.n_rows = int(len(df))corpus.columns_json = json.dumps(list(df.columns))corpus.parse_info_json = json.dumps(parse_info)27 unmodified linesitems = [i.strip() for i in body.items if i.strip()]if not items:raise HTTPException(400, "Construct needs at least one non-empty item.")flags = body.reverse_scored or [False] * len(items)if len(flags) != len(items):raise HTTPException(400, "reverse_scored must have one flag per item.")construct = Construct(name=body.name.strip(),description=body.description.strip(),reference=body.reference.strip(),items_json=json.dumps(items),reverse_flags_json=json.dumps([bool(f) for f in flags]),is_seed=False,verification_status="draft", # user-defined research tools, not validated scaleslanguage=(body.language or "en").lower(),)db.add(construct)db.commit()return _construct_out(construct)@app.post("/api/constructs/parse-file")async def parse_construct_upload(file: UploadFile):"""Parse a CSV/XLSX of scale items into a PREVIEW (nothing is saved).The researcher reviews/edits, then saves via POST /api/constructs."""suffix = Path(file.filename or "items.csv").suffix.lower()if suffix not in ALLOWED_SUFFIXES:raise HTTPException(400, f"Unsupported file type '{suffix}'. Use CSV or XLSX.")payload = await file.read()if len(payload) > 1024 * 1024:raise HTTPException(413, "Item files are capped at 1 MB (a scale is a short list).")tmp_dir = DATA_DIR / "tmp"tmp_dir.mkdir(exist_ok=True)tmp = tmp_dir / f"construct_upload_{os.urandom(6).hex()}{suffix}"tmp.write_bytes(payload)try:parsed = parse_construct_file(str(tmp))except ValueError as exc:raise HTTPException(400, str(exc)) from excfinally:tmp.unlink(missing_ok=True) # item files are never retainedstem = Path(file.filename or "").stem.replace("_", " ").replace("-", " ").strip()parsed["suggested_name"] = stem.title() if stem else ""return parsed# -------------------------------------------------------------------- jobs@app.post("/api/jobs", response_model=JobOut, status_code=201)def create_job(body: JobCreate,request: Request,response: Response,db: Session = Depends(get_db),user: dict | None = Depends(auth.get_current_user),):project = _get_or_404(db, Project, body.project_id)_require_project_access(project, user)corpus = _get_or_404(db, Corpus, body.corpus_id)_get_or_404(db, Construct, body.construct_id)# Anonymous tier: N runs per day, then sign-in (PI decision 2026-07-10).# Cookie counter = a nudge, not a security boundary (recorded in DECISIONS.md).if user is None:used = auth.runs_used_today(request)if used >= auth.anon_max_runs_per_day():raise HTTPException(429,f"Anonymous limit reached ({auth.anon_max_runs_per_day()} runs/day). ""Sign in (top right) to keep running - accounts are free.",)else:# Signed-in tier: saved-run cap instead of deletion (their data, their call).if _saved_runs_used(db, user["id"]) >= auth.user_max_saved_runs():raise HTTPException(409,f"You have {auth.user_max_saved_runs()} saved runs (the maximum). ""Delete a project or old runs to start a new analysis.",)if body.text_column not in json.loads(corpus.columns_json):raise HTTPException(400, f"Column '{body.text_column}' not in corpus columns.")allowed = registry.known_ids() | {FAKE_MODEL_NAME}if body.model_name not in allowed:raise HTTPException(400, f"Unknown model '{body.model_name}'.")language = (body.language or "en").strip().lower()if not (2 <= len(language) <= 8 and language.replace("-", "").isalpha()):raise HTTPException(400, f"Invalid language code '{body.language}'.")# Retention: anonymous uploads are deleted after their analysis, so a# re-run needs a fresh upload (or an account, where data persists).if not corpus.path or not storage.exists(corpus.path):raise HTTPException(410,"This dataset's file was removed after analysis (anonymous uploads are ""not kept). Upload the file again, or sign in to keep datasets.",)job = Job(project_id=body.project_id,1 unmodified lineconstruct_id=body.construct_id,text_column=body.text_column,model_name=body.model_name,language=language,)db.add(job)db.commit()jobs_module.submit_job(job.id)if user is None: # advance the daily counter only after the job is acceptedresponse.set_cookie(auth.RUNS_COOKIE_NAME,auth.run_counter_token(auth.runs_used_today(request) + 1),httponly=True,samesite="lax",secure=auth.cookies_secure(),max_age=24 * 3600,)return _job_out(db, job)26 unmodified linesjob = _get_or_404(db, Job, job_id)if job.status != "completed" or not job.result_path:raise HTTPException(409, "Results not available.")filename = f"ccr_results_{job_id[:8]}.csv"if storage.is_s3(job.result_path):from fastapi.responses import StreamingResponsereturn StreamingResponse(storage.open_stream(job.result_path),media_type="text/csv",headers={"Content-Disposition": f'attachment; filename="{filename}"'},)return FileResponse(job.result_path, media_type="text/csv", filename=filename)@app.get("/api/jobs/{job_id}/metadata")9 unmodified lines)@app.get("/api/jobs/{job_id}/script")def export_script(job_id: str, db: Session = Depends(get_db)):"""Offline-runnable reproduction script generated from run metadata (spec 0002)."""job = _get_or_404(db, Job, job_id)if job.status != "completed":raise HTTPException(409, "Script not available until the run completes.")return PlainTextResponse(script_text(json.loads(job.metadata_json)),media_type="text/x-python",headers={"Content-Disposition": f'attachment; filename="reproduce_analysis_{job_id[:8]}.py"'},)@app.get("/api/jobs/{job_id}/script-requirements")def export_script_requirements(job_id: str, db: Session = Depends(get_db)):job = _get_or_404(db, Job, job_id)if job.status != "completed":raise HTTPException(409, "Requirements not available until the run completes.")return PlainTextResponse(requirements_text(json.loads(job.metadata_json)),media_type="text/plain",headers={"Content-Disposition": f'attachment; filename="requirements-repro_{job_id[:8]}.txt"'},)# ------------------------------------------------------------ static (SPA)STATIC_DIR = Path(__file__).resolve().parent.parent / "static"if STATIC_DIR.exists():
1 unmodified line234567813 unmodified lines22232425262728293031323317 unmodified lines5152535455565758595 unmodified lines656667686970711 unmodified lineIDs are UUID strings (portable across SQLite/Postgres). JSON-ish payloads(column lists, construct items, job metadata/summaries) are stored as JSONtext — they are read-mostly blobs, not queried relationally."""import uuid13 unmodified linesreturn datetime.now(timezone.utc).isoformat(timespec="seconds")class Project(Base):__tablename__ = "projects"id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_uuid)name: Mapped[str] = mapped_column(String(200))description: Mapped[str] = mapped_column(Text, default="")created_at: Mapped[str] = mapped_column(String(32), default=_now)17 unmodified linesid: Mapped[str] = mapped_column(String(32), primary_key=True, default=_uuid)name: Mapped[str] = mapped_column(String(200))description: Mapped[str] = mapped_column(Text, default="")reference: Mapped[str] = mapped_column(Text, default="")items_json: Mapped[str] = mapped_column(Text) # list[str]is_seed: Mapped[bool] = mapped_column(Boolean, default=False)created_at: Mapped[str] = mapped_column(String(32), default=_now)5 unmodified linescorpus_id: Mapped[str] = mapped_column(ForeignKey("corpora.id"))construct_id: Mapped[str] = mapped_column(ForeignKey("constructs.id"))text_column: Mapped[str] = mapped_column(String(200))model_name: Mapped[str] = mapped_column(String(200))status: Mapped[str] = mapped_column(String(20), default="queued")# queued -> running -> completed | failedprogress: Mapped[float] = mapped_column(Float, default=0.0) # 0..11 unmodified line234567813 unmodified lines22232425262728293031323334353637383940414243444517 unmodified lines6364656667686970717273747576777879805 unmodified lines86878889909192931 unmodified lineIDs are UUID strings (portable across SQLite/Postgres). JSON-ish payloads(column lists, construct items, job metadata/summaries) are stored as JSONtext - they are read-mostly blobs, not queried relationally."""import uuid13 unmodified linesreturn datetime.now(timezone.utc).isoformat(timespec="seconds")class User(Base):__tablename__ = "users"id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_uuid)email: Mapped[str] = mapped_column(String(255), unique=True, index=True)name: Mapped[str] = mapped_column(String(120), default="")password_hash: Mapped[str] = mapped_column(Text) # scrypt$salt$digest (auth.py)created_at: Mapped[str] = mapped_column(String(32), default=_now)class Project(Base):__tablename__ = "projects"id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_uuid)name: Mapped[str] = mapped_column(String(200))description: Mapped[str] = mapped_column(Text, default="")archived: Mapped[bool] = mapped_column(Boolean, default=False)owner_user_id: Mapped[str] = mapped_column(String(32), default="") # "" = anonymouscreated_at: Mapped[str] = mapped_column(String(32), default=_now)17 unmodified linesid: Mapped[str] = mapped_column(String(32), primary_key=True, default=_uuid)name: Mapped[str] = mapped_column(String(200))description: Mapped[str] = mapped_column(Text, default="")reference: Mapped[str] = mapped_column(Text, default="") # citationitems_json: Mapped[str] = mapped_column(Text) # list[str]reverse_flags_json: Mapped[str] = mapped_column(Text, default="[]") # list[bool], parallel to itemsis_seed: Mapped[bool] = mapped_column(Boolean, default=False)# Library identity (spec 0004): versioned append-only; hash via reference algorithm.construct_slug: Mapped[str] = mapped_column(String(120), default="")version: Mapped[int] = mapped_column(default=1)item_hash: Mapped[str] = mapped_column(String(64), default="")verification_status: Mapped[str] = mapped_column(String(24), default="draft")# draft | needs_verification | verified | archivedlanguage: Mapped[str] = mapped_column(String(12), default="en")category: Mapped[str] = mapped_column(String(80), default="")created_at: Mapped[str] = mapped_column(String(32), default=_now)5 unmodified linescorpus_id: Mapped[str] = mapped_column(ForeignKey("corpora.id"))construct_id: Mapped[str] = mapped_column(ForeignKey("constructs.id"))text_column: Mapped[str] = mapped_column(String(200))model_name: Mapped[str] = mapped_column(String(200)) # registry id (or test fake)language: Mapped[str] = mapped_column(String(12), default="en") # selected analysis languagestatus: Mapped[str] = mapped_column(String(20), default="queued")# queued -> running -> completed | failedprogress: Mapped[float] = mapped_column(Float, default=0.0) # 0..1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134"""Model registry loader - the app-side reader of packages/model_registry/models.yaml.
Single source of model truth (design doc §13): the UI dropdown, backend validation,prefix handling, language-support warnings, run metadata, and generated reproductionscripts all read the SAME config through this module. No model behavior is hardcodedanywhere else (CLAUDE.md hard rule).
Language sets are resolved through packages/model_registry/language_sets.py, loadedby explicit file path (editable-install wiring arrives with Phase 1 packaging)."""
from __future__ import annotations
import importlib.utilimport osfrom dataclasses import dataclass, fieldfrom functools import lru_cachefrom pathlib import Path
import yaml
REPO_ROOT = Path(__file__).resolve().parents[2]MODELS_YAML = Path(os.environ.get("CCR_MODELS_YAML", REPO_ROOT / "packages" / "model_registry" / "models.yaml"))_LANGUAGE_SETS_PY = REPO_ROOT / "packages" / "model_registry" / "language_sets.py"
def _load_language_sets(): spec = importlib.util.spec_from_file_location("ccr_language_sets", _LANGUAGE_SETS_PY) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
@dataclass(frozen=True)class ModelConfig: id: str provider_model_id: str display_name: str revision: str default: bool supported_languages: frozenset[str] # resolved ISO codes; frozenset() = unknown/any language_set_name: str | None embedding_dimension: int max_seq_length: int quality_tier: str speed_tier: str requires_prefix: bool item_prefix: str text_prefix: str normalize_embeddings: bool lazy_load: bool user_warnings: tuple[str, ...] = field(default_factory=tuple)
@property def pinned_revision(self) -> str | None: """Revision to pass to the model loader; None while unpinned (PIN_ME).""" return None if self.revision in ("PIN_ME", "", None) else self.revision
def supports_language(self, iso_code: str) -> bool: if not self.supported_languages: # unknown coverage - never block/warn on it return True return iso_code.lower() in self.supported_languages
def _parse_model(raw: dict, lang_sets) -> ModelConfig: usage = raw.get("usage_config", {}) ops = raw.get("operational_config", {}) set_name = raw.get("supported_language_set") if set_name: languages = frozenset(lang_sets.resolve(set_name)) else: languages = frozenset(str(c).lower() for c in raw.get("supported_languages", []))
sym = usage.get("symmetric_similarity_prefix") or "" return ModelConfig( id=raw["id"], provider_model_id=raw["provider_model_id"], display_name=raw.get("display_name", raw["id"]), revision=str(raw.get("revision", "PIN_ME")), default=bool(raw.get("default", False)), supported_languages=languages, language_set_name=set_name, embedding_dimension=int(raw["embedding_dimension"]), max_seq_length=int(raw["max_seq_length"]), quality_tier=str(raw.get("quality_tier", "unknown")), speed_tier=str(raw.get("speed_tier", "unknown")), requires_prefix=bool(usage.get("requires_prefix", False)), item_prefix=usage.get("construct_prefix") or sym or "", text_prefix=usage.get("text_prefix") or sym or "", normalize_embeddings=bool(usage.get("normalize_embeddings", True)), lazy_load=bool(ops.get("lazy_load", False)), user_warnings=tuple(raw.get("warnings", []) or []), )
@lru_cache(maxsize=1)def _registry() -> dict[str, ModelConfig]: data = yaml.safe_load(MODELS_YAML.read_text()) lang_sets = _load_language_sets() models = {} for raw in data.get("models", []): cfg = _parse_model(raw, lang_sets) if cfg.requires_prefix and not (cfg.item_prefix and cfg.text_prefix): raise ValueError(f"models.yaml: {cfg.id} requires_prefix but prefixes missing.") models[cfg.id] = cfg defaults = [m for m in models.values() if m.default] if len(defaults) != 1: raise ValueError(f"models.yaml must define exactly one default model, found {len(defaults)}.") return models
def reload() -> None: """Clear the cache (tests / config changes).""" _registry.cache_clear()
def list_models() -> list[ModelConfig]: ordered = sorted(_registry().values(), key=lambda m: (not m.default, m.id)) return ordered
def get_model(model_id: str) -> ModelConfig: reg = _registry() if model_id not in reg: raise KeyError(f"Unknown model id '{model_id}'. Known: {sorted(reg)}") return reg[model_id]
def default_model() -> ModelConfig: return next(m for m in _registry().values() if m.default)
def known_ids() -> set[str]: return set(_registry().keys())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""Reproduction-script generation (spec 0002, design doc §14).
The generated script is built ONLY from the run's stored metadata - never from livestate - so it reproduces what actually ran. It must be runnable outside the platform:input CSV + Python + internet for the (pinned) model download. No platform credentials."""
from __future__ import annotations
import json
def _pinned_requirements(metadata: dict) -> list[str]: """Exact versions of the packages the analysis math depends on.""" from importlib.metadata import PackageNotFoundError, version
pins = [] for pkg in ("sentence-transformers", "torch", "numpy", "pandas"): try: pins.append(f"{pkg}=={version(pkg)}") except PackageNotFoundError: continue return pins
def requirements_text(metadata: dict) -> str: lines = [ "# Reproduction environment for CCR run " + metadata.get("job_id", "?"), "# Install: pip install -r requirements-repro.txt", ] recorded = metadata.get("environment_pins") lines += recorded if recorded else _pinned_requirements(metadata) return "\n".join(lines) + "\n"
def record_environment(metadata: dict) -> dict: """Store pins in metadata at run time so exports match the executing environment.""" metadata["environment_pins"] = _pinned_requirements(metadata) return metadata
def script_text(metadata: dict) -> str: """Standalone Python script reproducing the run's similarities and scores.""" construct = metadata.get("construct_snapshot", {}) items = construct.get("items", []) model_id = metadata.get("model_registry_id", metadata.get("model", "")) provider = metadata.get("provider_model_id", metadata.get("model", "")) revision = metadata.get("model_revision") revision_arg = f", revision={revision!r}" if revision and revision != "PIN_ME" else "" item_prefix = metadata.get("item_prefix", "") text_prefix = metadata.get("text_prefix", "") text_column = metadata.get("text_column", "text") scoring = metadata.get("scoring", {})
items_literal = json.dumps( [{"text": i["text"], "reverse_scored": i.get("reverse_scored", False)} for i in items], indent=4, ensure_ascii=False, )
return f'''#!/usr/bin/env python3"""Reproduce CCR analysis independently of the platform.
run_id: {metadata.get("job_id", "?")}created_at: {metadata.get("started_at", "?")}platform_version: {metadata.get("platform_version", "?")}output_schema_version: {metadata.get("output_schema_version", "1.0")}construct: {construct.get("name", "?")} (v{construct.get("version", "?")}, hash {construct.get("item_hash", "?")[:16]})model: {model_id} -> {provider} (revision: {revision or "unpinned"})scoring: adjustment_strategy={scoring.get("adjustment_strategy", "none")}, aggregate={scoring.get("aggregate", "mean_all_items")}
Usage: pip install -r requirements-repro.txt python reproduce_analysis.py your_corpus.csvOutputs reproduced_results.csv with the same similarity columns as the platform export."""
import sys
import numpy as npimport pandas as pdfrom sentence_transformers import SentenceTransformer
TEXT_COLUMN = {text_column!r}ITEM_PREFIX = {item_prefix!r} # model-required prefix (E5 family); empty = noneTEXT_PREFIX = {text_prefix!r}
ITEMS = {items_literal}
def main(csv_path: str) -> None: df = pd.read_csv(csv_path) texts_all = df[TEXT_COLUMN].astype("string") mask = texts_all.notna() & (texts_all.str.strip() != "") work = df.loc[mask].reset_index(drop=True) # platform drops empty rows the same way texts = work[TEXT_COLUMN].astype(str).tolist()
model = SentenceTransformer({provider!r}{revision_arg}) item_texts = [ITEM_PREFIX + i["text"] for i in ITEMS] doc_texts = [TEXT_PREFIX + t for t in texts]
item_emb = model.encode(item_texts, convert_to_numpy=True, normalize_embeddings=True) doc_emb = model.encode(doc_texts, convert_to_numpy=True, normalize_embeddings=True)
sims = doc_emb @ item_emb.T # normalized -> cosine similarity for j in range(sims.shape[1]): work[f"sim_item_{{j + 1}}"] = np.round(sims[:, j], 6) work["ccr_score"] = np.round(sims.mean(axis=1), 6)
work.to_csv("reproduced_results.csv", index=False) print(f"Wrote reproduced_results.csv ({{len(work)}} rows, {{sims.shape[1]}} items).") print("Compare against the platform export - values should match to ~1e-5.")
if __name__ == "__main__": if len(sys.argv) != 2: raise SystemExit("Usage: python reproduce_analysis.py <corpus.csv>") main(sys.argv[1])'''123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123"""Data retention (PI decision, 2026-07-10: "remove temp data after analysis").
Policy: * ANONYMOUS runs: the uploaded corpus file (and its embedding cache) is deleted the moment the run finishes (jobs.py calls remove_corpus_files). Result summaries/CSVs stick around so the person can download them, then the whole anonymous project is purged after CCR_ANON_TTL_HOURS. * SIGNED-IN runs: nothing is auto-deleted; a saved-run cap applies instead (enforced at job creation in main.py - the user chooses what to delete).
The purge loop runs in a daemon thread (startup + hourly). TTL of 0 disablespurging entirely - the local-dev default, so nobody's dev projects vanishovernight. Deployments set CCR_ANON_TTL_HOURS=24."""
from __future__ import annotations
import loggingimport threadingfrom datetime import datetime, timedelta, timezonefrom pathlib import Path
from sqlalchemy.orm import Session
from . import auth, storagefrom .db import DATA_DIR, SessionLocalfrom .models import Corpus, Job, Project
logger = logging.getLogger("ccr.retention")
EMB_CACHE_DIR = DATA_DIR / "emb_cache"EMB_CACHE_DIR.mkdir(exist_ok=True)
_stop = threading.Event()_thread: threading.Thread | None = None
def remove_corpus_files(corpus: Corpus) -> None: """Delete the uploaded file (whatever backend holds it) and any cached embeddings (always local - caches are derived data).""" storage.delete(corpus.path) for cached in EMB_CACHE_DIR.glob(f"{corpus.id}_*.npy"): cached.unlink(missing_ok=True)
def delete_project_cascade(db: Session, project: Project) -> dict: """Shared cascade used by the DELETE endpoint and the anonymous purge. Removes DB rows plus uploaded, result, and embedding-cache files. Logs counts only - never any uploaded text (design doc §9).""" corpora = db.query(Corpus).filter_by(project_id=project.id).all() jobs = db.query(Job).filter_by(project_id=project.id).all()
for corpus in corpora: remove_corpus_files(corpus) for job in jobs: storage.delete(job.result_path)
for job in jobs: db.delete(job) for corpus in corpora: db.delete(corpus) db.delete(project) db.commit() return {"corpora": len(corpora), "runs": len(jobs)}
def purge_expired_anonymous(db: Session) -> int: """Delete anonymous projects whose last activity is older than the TTL.""" ttl = auth.anon_ttl_hours() if ttl <= 0: return 0 cutoff = (datetime.now(timezone.utc) - timedelta(hours=ttl)).isoformat(timespec="seconds")
purged = 0 candidates = db.query(Project).filter(Project.owner_user_id == "").all() for project in candidates: latest_job = ( db.query(Job.created_at) .filter_by(project_id=project.id) .order_by(Job.created_at.desc()) .first() ) last_activity = max(project.created_at, latest_job[0]) if latest_job else project.created_at if last_activity < cutoff: counts = delete_project_cascade(db, project) purged += 1 logger.info( "purged expired anonymous project id=%s (corpora=%d runs=%d, ttl=%dh)", project.id, counts["corpora"], counts["runs"], ttl, ) return purged
def _loop(interval_seconds: int) -> None: while not _stop.wait(interval_seconds): db = SessionLocal() try: purge_expired_anonymous(db) except Exception: logger.exception("anonymous purge failed; will retry next cycle") finally: db.close()
def start_cleanup(interval_seconds: int = 3600) -> None: """Run one purge now, then hourly in a daemon thread. No-op if TTL is 0.""" global _thread db = SessionLocal() try: purge_expired_anonymous(db) except Exception: logger.exception("startup anonymous purge failed") finally: db.close() if auth.anon_ttl_hours() > 0 and (_thread is None or not _thread.is_alive()): _stop.clear() _thread = threading.Thread(target=_loop, args=(interval_seconds,), daemon=True, name="ccr-retention") _thread.start()
def stop_cleanup() -> None: _stop.set()12 unmodified lines13141516171813 unmodified lines3233343536372 unmodified lines404142434445461 unmodified line484950515253545 unmodified lines60616263646512 unmodified linesname: strdescription: strcreated_at: strclass CorpusOut(BaseModel):13 unmodified linesdescription: str = ""reference: str = ""items: list[str] = Field(min_length=1)class ConstructOut(BaseModel):2 unmodified linesdescription: strreference: stritems: list[str]is_seed: boolclass JobCreate(BaseModel):1 unmodified linecorpus_id: strconstruct_id: strtext_column: strmodel_name: str = "sentence-transformers/all-MiniLM-L6-v2"class JobOut(BaseModel):5 unmodified linescorpus_filename: str = ""text_column: strmodel_name: strstatus: strprogress: floaterror: str12 unmodified lines13141516171819202122232425262728293031323334353613 unmodified lines50515253545556572 unmodified lines606162636465666768697071721 unmodified line74757677787980815 unmodified lines8788899091929312 unmodified linesname: strdescription: strcreated_at: strlast_activity_at: str = "" # latest run creation, else project creationn_runs: int = 0archived: bool = Falseclass ProjectPatch(BaseModel):archived: bool | None = Noneclass RegisterIn(BaseModel):email: str = Field(min_length=3, max_length=255)password: str = Field(min_length=8, max_length=200)name: str = Field(min_length=1, max_length=120)class LoginIn(BaseModel):email: str = Field(min_length=3, max_length=255)password: str = Field(min_length=1, max_length=200)class CorpusOut(BaseModel):13 unmodified linesdescription: str = ""reference: str = ""items: list[str] = Field(min_length=1)reverse_scored: list[bool] | None = None # parallel to items; defaults to all Falselanguage: str = "en"class ConstructOut(BaseModel):2 unmodified linesdescription: strreference: stritems: list[str]reverse_scored: list[bool] = []is_seed: boolversion: int = 1verification_status: str = "draft"language: str = "en"category: str = ""item_hash: str = "" # first 16 hex chars for displayclass JobCreate(BaseModel):1 unmodified linecorpus_id: strconstruct_id: strtext_column: strmodel_name: str = "all-minilm-l6-v2" # registry id (spec 0003)language: str = "en"class JobOut(BaseModel):5 unmodified linescorpus_filename: str = ""text_column: strmodel_name: strlanguage: str = "en"status: strprogress: floaterror: str
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""Seed construct library — psychometrically validated scales.
IMPORTANT: item wordings below are seeded for demonstration. Before anyresearch use, verify each item verbatim against the cited originalpublication (CCR's validity depends on using the validated instrumentas published)."""
SEED_CONSTRUCTS = [ { "name": "Satisfaction with Life", "description": "Global cognitive judgment of one's life satisfaction (SWLS).", "reference": "Diener, E., Emmons, R. A., Larsen, R. J., & Griffin, S. (1985). The Satisfaction with Life Scale. Journal of Personality Assessment, 49(1).", "items": [ "In most ways my life is close to my ideal.", "The conditions of my life are excellent.", "I am satisfied with my life.", "So far I have gotten the important things I want in life.", "If I could live my life over, I would change almost nothing.", ], }, { "name": "Moral Foundations — Care", "description": "Concern with suffering, compassion, and protection of the vulnerable (MFQ Care/Harm foundation).", "reference": "Graham, J., Nosek, B. A., Haidt, J., Iyer, R., Koleva, S., & Ditto, P. H. (2011). Mapping the moral domain. JPSP, 101(2). Verify items against the published MFQ.", "items": [ "Compassion for those who are suffering is the most crucial virtue.", "One of the worst things a person could do is hurt a defenseless animal.", "Whether or not someone suffered emotionally.", "Whether or not someone cared for someone weak or vulnerable.", ], }, { "name": "Moral Foundations — Fairness", "description": "Concern with justice, rights, and equal treatment (MFQ Fairness/Cheating foundation).", "reference": "Graham, J., Nosek, B. A., Haidt, J., Iyer, R., Koleva, S., & Ditto, P. H. (2011). Mapping the moral domain. JPSP, 101(2). Verify items against the published MFQ.", "items": [ "Justice is the most important requirement for a society.", "When the government makes laws, the number one principle should be ensuring that everyone is treated fairly.", "Whether or not some people were treated differently than others.", "Whether or not someone acted unfairly.", ], }, { "name": "Individualism (Horizontal)", "description": "Self-reliance and independence from in-groups (Triandis & Gelfand horizontal individualism).", "reference": "Triandis, H. C., & Gelfand, M. J. (1998). Converging measurement of horizontal and vertical individualism and collectivism. JPSP, 74(1). Verify items against the published scale.", "items": [ "I'd rather depend on myself than others.", "I rely on myself most of the time; I rarely rely on others.", "I often do my own thing.", "My personal identity, independent of others, is very important to me.", ], }, { "name": "Collectivism (Horizontal)", "description": "Interdependence, cooperation, and in-group well-being (Triandis & Gelfand horizontal collectivism).", "reference": "Triandis, H. C., & Gelfand, M. J. (1998). Converging measurement of horizontal and vertical individualism and collectivism. JPSP, 74(1). Verify items against the published scale.", "items": [ "If a coworker gets a prize, I would feel proud.", "The well-being of my coworkers is important to me.", "To me, pleasure is spending time with others.", "I feel good when I cooperate with others.", ], },]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""File storage behind one interface: local disk (default) or S3-compatible.
Production-ready now, enabled by configuration at deploy time (Deva,2026-07-13): the R2/S3 code path ships with the codebase so flipping aproduction instance to object storage is an env change, never a developmenttask. Local dev keeps writing plain files under CCR_DATA_DIR.
Locator scheme (stored in the DB's existing path columns - no migration): * local backend: an absolute filesystem path (exactly as before); * s3 backend: "s3://{key}" inside the configured bucket.Old rows with absolute paths keep working even on an s3-configured instance.
Config (s3 backend): CCR_STORAGE=s3, CCR_S3_ENDPOINT (R2: the accountendpoint URL), CCR_S3_BUCKET, CCR_S3_ACCESS_KEY_ID, CCR_S3_SECRET_ACCESS_KEY.The bucket stays private; downloads stream through the API, so no publicaccess or presigned-URL exposure is required.
Embedding caches deliberately stay on local disk: they are derived data,cheap to recompute, and read with numpy - a cache does not need durability."""
from __future__ import annotations
import osimport tempfilefrom pathlib import Path
from .db import DATA_DIR
S3_PREFIX = "s3://"
_client = None # injectable for tests
def backend() -> str: return os.environ.get("CCR_STORAGE", "local").lower()
def _s3(): global _client if _client is None: import boto3 # lazy: only s3-configured deployments need it
_client = boto3.client( "s3", endpoint_url=os.environ["CCR_S3_ENDPOINT"], aws_access_key_id=os.environ["CCR_S3_ACCESS_KEY_ID"], aws_secret_access_key=os.environ["CCR_S3_SECRET_ACCESS_KEY"], region_name=os.environ.get("CCR_S3_REGION", "auto"), ) return _client
def _bucket() -> str: return os.environ["CCR_S3_BUCKET"]
def is_s3(locator: str) -> bool: return locator.startswith(S3_PREFIX)
# ------------------------------------------------------------------ writedef store_bytes(category: str, name: str, data: bytes) -> str: """Persist bytes under category/name; return the locator to store in the DB.""" key = f"{category}/{name}" if backend() == "s3": _s3().put_object(Bucket=_bucket(), Key=key, Body=data) return S3_PREFIX + key dest = DATA_DIR / category / name dest.parent.mkdir(parents=True, exist_ok=True) dest.write_bytes(data) return str(dest)
def store_file(category: str, name: str, src: Path) -> str: return store_bytes(category, name, Path(src).read_bytes())
# ------------------------------------------------------------------- readdef exists(locator: str) -> bool: if not locator: return False if is_s3(locator): try: _s3().head_object(Bucket=_bucket(), Key=locator[len(S3_PREFIX):]) return True except Exception: return False return Path(locator).exists()
def fetch_to_local(locator: str) -> tuple[Path, bool]: """Return (local_path, is_temporary). Caller unlinks temporary files after use; local-backend paths are returned as-is.""" if is_s3(locator): key = locator[len(S3_PREFIX):] suffix = Path(key).suffix or ".bin" fd, tmp = tempfile.mkstemp(suffix=suffix, prefix="ccr_s3_") os.close(fd) _s3().download_file(_bucket(), key, tmp) return Path(tmp), True return Path(locator), False
def open_stream(locator: str): """Iterator of byte chunks, for streaming downloads through the API.""" if is_s3(locator): body = _s3().get_object(Bucket=_bucket(), Key=locator[len(S3_PREFIX):])["Body"] return iter(lambda: body.read(64 * 1024), b"") fh = open(locator, "rb")
def gen(): with fh: while chunk := fh.read(64 * 1024): yield chunk
return gen()
# ------------------------------------------------------------------ deletedef delete(locator: str) -> None: if not locator: return if is_s3(locator): try: _s3().delete_object(Bucket=_bucket(), Key=locator[len(S3_PREFIX):]) except Exception: pass # deletion is best-effort; the TTL sweep retries implicitly return Path(locator).unlink(missing_ok=True)
def move_local_into_storage(category: str, name: str, local_path: Path) -> str: """Store a locally produced file; the source copy is removed unless it IS the stored destination (local backend writing in place).""" locator = store_file(category, name, local_path) src = Path(local_path) if is_s3(locator) or (src.exists() and str(src.resolve()) != str(Path(locator).resolve())): src.unlink(missing_ok=True) return locator123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151"""Structured data-quality warnings (spec 0001, design doc §12).
Every warning is an object - {code, severity, message, count?, affected_rows_sample?} -never a bare string. Codes are UPPER_SNAKE and stable: downstream notebooks and the UIkey off them. Severity: "info" (status, not a problem) | "warning" (proceed with care).Language detection is corpus-level only; short texts are exactly where detection isunreliable, so uncertainty is reported instead of guessed away.
Deviation from spec 0001 (recorded there): langdetect instead of lingua - pure-Python,~1 MB vs ~100 MB wheels; seeded for determinism. Upgrade path preserved by recordingdetector + version in metadata."""
from __future__ import annotations
from dataclasses import dataclass
MIN_TOKENS_STABLE = 4 # texts below this are flagged TEXT_TOO_SHORTDETECT_MIN_TOKENS = 5 # rows shorter than this are skipped for detectionDETECT_SAMPLE_MAX = 200 # rows sampled for corpus-level detectionDETECT_MIN_ROWS = 20 # fewer detectable rows -> LANGUAGE_UNCERTAINDETECT_CONFIDENCE = 0.70 # majority share below this -> LANGUAGE_UNCERTAINSAMPLE_ROWS_SHOWN = 5
def warning(code: str, severity: str, message: str, **extra) -> dict: return {"code": code, "severity": severity, "message": message, **extra}
# ---------------------------------------------------------------- text QAdef short_text_warning(texts: list[str]) -> dict | None: idx = [i for i, t in enumerate(texts) if len(t.split()) < MIN_TOKENS_STABLE] if not idx: return None return warning( "TEXT_TOO_SHORT", "warning", f"{len(idx)} text(s) contain fewer than {MIN_TOKENS_STABLE} words; " "CCR scores may be unstable for very short texts.", count=len(idx), affected_rows_sample=idx[:SAMPLE_ROWS_SHOWN], )
# ---------------------------------------------------------- language checks@dataclassclass LanguageResult: selected: str detected: str | None confidence: float | None n_rows_sampled: int detector: str detector_version: str
def as_metadata(self) -> dict: return { "selected": self.selected, "detected": self.detected, "confidence": self.confidence, "n_rows_sampled": self.n_rows_sampled, "detector": self.detector, "detector_version": self.detector_version, }
def detect_corpus_language(texts: list[str], selected: str) -> tuple[LanguageResult, list[dict]]: """Corpus-level majority-vote detection on a sample of detectable rows.""" from langdetect import DetectorFactory, detect # lazy import from langdetect.lang_detect_exception import LangDetectException
try: from importlib.metadata import version as _v
detector_version = _v("langdetect") except Exception: detector_version = "unknown"
DetectorFactory.seed = 0 # determinism - same corpus, same result, every run
detectable = [t for t in texts if len(t.split()) >= DETECT_MIN_TOKENS][:DETECT_SAMPLE_MAX] warnings: list[dict] = []
if len(detectable) < DETECT_MIN_ROWS: result = LanguageResult(selected, None, None, len(detectable), "langdetect", detector_version) warnings.append( warning( "LANGUAGE_UNCERTAIN", "info", f"Language could not be determined confidently ({len(detectable)} detectable " f"row(s), need {DETECT_MIN_ROWS}); language checks were skipped.", ) ) return result, warnings
votes: dict[str, int] = {} for t in detectable: try: lang = detect(t) # one detection per row (detect() is the expensive call) except LangDetectException: continue votes[lang] = votes.get(lang, 0) + 1
if not votes: result = LanguageResult(selected, None, None, len(detectable), "langdetect", detector_version) warnings.append( warning("LANGUAGE_UNCERTAIN", "info", "Language detection produced no result; language checks were skipped.") ) return result, warnings
top_lang, top_count = max(votes.items(), key=lambda kv: kv[1]) confidence = round(top_count / sum(votes.values()), 3) result = LanguageResult(selected, top_lang, confidence, len(detectable), "langdetect", detector_version)
if confidence < DETECT_CONFIDENCE: warnings.append( warning( "LANGUAGE_UNCERTAIN", "info", f"Detected language is uncertain (top candidate '{top_lang}' at " f"{confidence:.0%} of sampled rows); interpret language checks with care.", ) ) elif top_lang != selected.lower(): warnings.append( warning( "LANGUAGE_MISMATCH", "warning", f"You selected '{selected}', but the corpus appears to be '{top_lang}' " f"({confidence:.0%} of {len(detectable)} sampled rows).", detected_language=top_lang, selected_language=selected, ) ) return result, warnings
def model_language_warning(selected: str, model_id: str, supported: frozenset[str], language_set_name: str | None) -> dict | None: if not supported or selected.lower() in supported: return None label = f"the '{language_set_name}' language set" if language_set_name else \ f"{sorted(supported)}" return warning( "MODEL_LANGUAGE_UNSUPPORTED", "warning", f"The selected model supports {label}, but you selected '{selected}'. " "Switch to a multilingual model or proceed with caution.", selected_language=selected, model_id=model_id, )6 unmodified lines7896 unmodified linespython-multipart>=0.0.9numpy>=1.26sentence-transformers>=2.66 unmodified lines7891011126 unmodified linespython-multipart>=0.0.9numpy>=1.26sentence-transformers>=2.6pyyaml>=6.0langdetect>=1.0.9boto3>=1.34 # used only when CCR_STORAGE=s3 (Cloudflare R2 / any S3-compatible store)
1:root{--maroon: #7a1f3d;--maroon-dark: #5e1730;--ink: #1d2129;--muted: #667085;--line: #e5e7eb;--bg: #f7f7f8;--card: #ffffff;--ok: #157f3d;--err: #b42318;--accent-soft: #f6ebef}*{box-sizing:border-box}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,sans-serif;color:var(--ink);background:var(--bg);font-size:14.5px;line-height:1.5}.app{display:flex;flex-direction:column;min-height:100vh}.header{background:var(--maroon);color:#fff;padding:14px 28px;display:flex;align-items:baseline;gap:14px}.header h1{font-size:17px;margin:0;font-weight:650;letter-spacing:.2px}.header .sub{font-size:12.5px;opacity:.85}.layout{display:flex;flex:1;min-height:0}.sidebar{width:250px;background:var(--card);border-right:1px solid var(--line);padding:18px 14px;flex-shrink:0}.sidebar h2{font-size:11.5px;text-transform:uppercase;letter-spacing:.7px;color:var(--muted);margin:0 0 10px 4px}.project-item{display:block;width:100%;text-align:left;padding:9px 12px;margin-bottom:4px;border:1px solid transparent;border-radius:8px;background:none;cursor:pointer;font:inherit;color:var(--ink)}.project-item:hover{background:var(--bg)}.project-item.active{background:var(--accent-soft);border-color:var(--maroon);font-weight:600}.project-item .date{display:block;font-size:11.5px;color:var(--muted);font-weight:400}.main{flex:1;padding:22px 28px;overflow-y:auto;min-width:0}.card{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:18px 20px;margin-bottom:16px}.card h3{margin:0 0 4px;font-size:15px}.card .hint{color:var(--muted);font-size:12.5px;margin:0 0 12px}.step-badge{display:inline-flex;align-items:center;justify-content:center;width:21px;height:21px;border-radius:50%;background:var(--maroon);color:#fff;font-size:12px;font-weight:700;margin-right:8px;vertical-align:-3px}button.primary{background:var(--maroon);color:#fff;border:none;padding:9px 18px;border-radius:8px;font:inherit;font-weight:600;cursor:pointer}button.primary:hover{background:var(--maroon-dark)}button.primary:disabled{background:#c9ccd1;cursor:not-allowed}button.ghost{background:none;border:1px solid var(--line);color:var(--ink);padding:8px 14px;border-radius:8px;font:inherit;cursor:pointer}button.ghost:hover{border-color:var(--maroon);color:var(--maroon)}button.linkish{background:none;border:none;color:var(--maroon);font:inherit;cursor:pointer;padding:0;text-decoration:underline}input[type=text],textarea,select{width:100%;padding:8px 10px;border:1px solid var(--line);border-radius:8px;font:inherit;background:#fff;color:var(--ink)}textarea{resize:vertical}label.field{display:block;margin-bottom:10px;font-size:13px;font-weight:600}label.field>*{margin-top:4px;font-weight:400}.row{display:flex;gap:14px;flex-wrap:wrap}.row>.grow{flex:1;min-width:220px}.pill{display:inline-block;padding:2px 10px;border-radius:999px;font-size:11.5px;font-weight:600}.pill.completed{background:#e6f4ea;color:var(--ok)}.pill.running{background:#fff3e0;color:#b45309}.pill.queued{background:#eef2f7;color:var(--muted)}.pill.failed{background:#fdecea;color:var(--err)}.progress-track{background:var(--line);border-radius:999px;height:7px;overflow:hidden}.progress-fill{background:var(--maroon);height:100%;transition:width .4s ease}.warnings{background:#fff8e6;border:1px solid #f2dfa8;color:#7a5b00;border-radius:8px;padding:10px 14px}.error-banner{background:#fdecea;color:var(--err);border:1px solid #f5c6c0;padding:10px 14px;border-radius:8px;margin-bottom:14px;font-size:13px}table.docs{width:100%;border-collapse:collapse;font-size:13px}table.docs th{text-align:left;color:var(--muted);font-size:11.5px;text-transform:uppercase;letter-spacing:.5px;padding:6px 8px;border-bottom:1px solid var(--line)}table.docs td{padding:7px 8px;border-bottom:1px solid var(--bg);vertical-align:top}table.docs td.score{font-variant-numeric:tabular-nums;font-weight:600;white-space:nowrap}.stat-grid{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:4px}.stat{flex:1;min-width:110px;background:var(--bg);border-radius:8px;padding:10px 14px}.stat .v{font-size:20px;font-weight:700;font-variant-numeric:tabular-nums}.stat .k{font-size:11.5px;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}.item-bar-row{display:flex;align-items:center;gap:10px;margin-bottom:7px}.item-bar-label{flex:1;font-size:12.5px;min-width:0}.item-bar-track{flex:1.2;background:var(--bg);border-radius:999px;height:10px}.item-bar-fill{background:var(--maroon);opacity:.85;height:100%;border-radius:999px}.item-bar-val{width:52px;text-align:right;font-variant-numeric:tabular-nums;font-size:12.5px;font-weight:600}.construct-items{margin:8px 0 0;padding-left:20px;color:var(--muted);font-size:12.5px}.construct-items li{margin-bottom:2px}.meta-footer{font-size:12px;color:var(--muted);background:var(--bg);border-radius:8px;padding:10px 14px;margin-top:14px;font-variant-numeric:tabular-nums}.meta-footer code{font-size:11.5px}.muted{color:var(--muted)}.small{font-size:12.5px}.mt{margin-top:12px}1:root{--maroon: #7a1f3d;--maroon-dark: #5e1730;--ink: #1d2129;--muted: #667085;--line: #e5e7eb;--bg: #f7f7f8;--card: #ffffff;--ok: #157f3d;--err: #b42318;--accent-soft: #f6ebef;--control-height: 40px}*{box-sizing:border-box}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,sans-serif;color:var(--ink);background:var(--bg);font-size:14.5px;line-height:1.5}.app{display:flex;flex-direction:column;min-height:100vh}.header{background:var(--maroon);color:#fff;padding:14px 28px;display:flex;align-items:baseline;flex-wrap:wrap;gap:14px}.header h1{flex:0 0 auto;font-size:17px;margin:0;font-weight:650;letter-spacing:.2px;white-space:nowrap}.header .sub{flex:1 1 280px;min-width:0;font-size:12.5px;opacity:.85}.layout{display:flex;flex:1;min-width:0;min-height:0}.sidebar{width:250px;background:var(--card);border-right:1px solid var(--line);padding:18px 14px;flex-shrink:0;display:flex;flex-direction:column;min-height:0}.sidebar h2{font-size:11.5px;text-transform:uppercase;letter-spacing:.7px;color:var(--muted);margin:0 0 10px 4px;display:flex;align-items:center;gap:8px}.sidebar h2 .count{background:var(--bg);border:1px solid var(--line);border-radius:999px;padding:0 8px;font-size:10.5px;letter-spacing:0;color:var(--muted)}.sidebar-filter{width:100%;padding:7px 10px;margin-bottom:10px;border:1px solid var(--line);border-radius:8px;font:inherit;font-size:13px;background:#fff;color:var(--ink)}.sidebar-filter:focus{outline:none;border-color:var(--maroon)}.project-list{flex:1;min-height:0;overflow-y:auto;margin:0 -4px;padding:0 4px 4px}.group-label{font-size:10.5px;text-transform:uppercase;letter-spacing:.6px;color:var(--muted);margin:10px 4px 5px}div:first-child>.group-label{margin-top:2px}.project-item{display:block;width:100%;text-align:left;padding:9px 12px;margin-bottom:5px;border:1px solid transparent;border-radius:8px;background:none;cursor:pointer;font:inherit;color:var(--ink)}.project-item:hover{background:var(--bg)}.project-item.active{background:var(--accent-soft);border-color:var(--maroon);font-weight:600}.project-item .project-name{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.project-item .date{display:block;font-size:11.5px;color:var(--muted);font-weight:400}.project-create{margin-top:12px;padding-top:12px;border-top:1px solid var(--line)}.project-create>button{width:100%}.main{flex:1;padding:22px 28px;overflow-y:auto;min-width:0}.card{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:18px 20px;margin-bottom:16px}.card h3{margin:0 0 4px;font-size:15px}.card .hint{color:var(--muted);font-size:12.5px;margin:0 0 12px}.step-badge{display:inline-flex;align-items:center;justify-content:center;width:21px;height:21px;border-radius:50%;background:var(--maroon);color:#fff;font-size:12px;font-weight:700;margin-right:8px;vertical-align:-3px}button{white-space:nowrap}button.primary{background:var(--maroon);color:#fff;border:none;min-height:var(--control-height);display:inline-flex;align-items:center;justify-content:center;padding:0 18px;border-radius:8px;font:inherit;font-weight:600;cursor:pointer;line-height:1.2}button.primary:hover{background:var(--maroon-dark)}button.primary:disabled{background:#c9ccd1;cursor:not-allowed}a.google-btn{background:var(--maroon);color:#fff;border:none;min-height:var(--control-height);display:flex;align-items:center;justify-content:center;padding:0 18px;border-radius:8px;font:inherit;font-weight:600;cursor:pointer;line-height:1.2;text-decoration:none;width:100%;box-sizing:border-box}a.google-btn:hover{background:var(--maroon-dark)}button.ghost{background:none;border:1px solid var(--line);color:var(--ink);min-height:var(--control-height);display:inline-flex;align-items:center;justify-content:center;padding:0 14px;border-radius:8px;font:inherit;cursor:pointer;line-height:1.2}button.ghost:hover{border-color:var(--maroon);color:var(--maroon)}button.linkish{background:none;border:none;color:var(--maroon);font:inherit;cursor:pointer;padding:0;text-decoration:underline}input[type=text],input[type=email],input[type=password],textarea,select{width:100%;padding:8px 10px;border:1px solid var(--line);border-radius:8px;font:inherit;background:#fff;color:var(--ink)}input[type=text],input[type=email],input[type=password],select{height:var(--control-height)}button:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible{outline:2px solid rgba(122,31,61,.38);outline-offset:2px}input[type=file]{display:block;max-width:100%;margin-top:6px;font-size:13px;color:var(--muted)}input[type=file]::file-selector-button{background:#fff;border:1px solid var(--line);color:var(--ink);padding:7px 14px;border-radius:8px;font:inherit;font-size:13px;cursor:pointer;margin-right:10px}input[type=file]::file-selector-button:hover{border-color:var(--maroon);color:var(--maroon)}.row>button{align-self:flex-end;margin-bottom:1px}textarea{resize:vertical}label.field{display:block;margin-bottom:10px;font-size:13px;font-weight:600}label.field>*{margin-top:4px;font-weight:400}.field-hint{margin-top:0;font-weight:400;color:var(--muted);font-size:12px}.row{display:flex;gap:14px;flex-wrap:wrap}.row>*{min-width:0}.row>.grow{flex:1;min-width:min(220px,100%)}.language-control{min-width:170px}.model-control{min-width:260px}.run-settings{display:grid;grid-template-columns:minmax(160px,230px) minmax(320px,720px) max-content;justify-content:start;gap:14px;align-items:end}.run-settings .field{margin-bottom:0}.run-button{min-width:180px;height:var(--control-height)}.construct-row{display:grid;grid-template-columns:minmax(320px,1120px) max-content;justify-content:start;align-items:end;gap:14px}.results-toolbar{display:flex;align-items:center;justify-content:space-between;gap:14px;margin-bottom:14px;flex-wrap:wrap}.result-actions{justify-content:flex-end}.result-actions a{display:inline-flex;text-decoration:none}.pill{display:inline-block;padding:2px 10px;border-radius:999px;font-size:11.5px;font-weight:600}.pill.completed{background:#e6f4ea;color:var(--ok)}.pill.running{background:#fff3e0;color:#b45309}.pill.queued{background:#eef2f7;color:var(--muted)}.pill.failed{background:#fdecea;color:var(--err)}.progress-track{background:var(--line);border-radius:999px;height:7px;overflow:hidden}.progress-fill{background:var(--maroon);height:100%;transition:width .4s ease}.warnings{background:#fff8e6;border:1px solid #f2dfa8;color:#7a5b00;border-radius:8px;padding:10px 14px}.error-banner{background:#fdecea;color:var(--err);border:1px solid #f5c6c0;padding:10px 14px;border-radius:8px;margin-bottom:14px;font-size:13px}.table-wrap{width:100%;overflow-x:auto}table.docs{width:100%;border-collapse:collapse;font-size:13px}table.docs th{text-align:left;color:var(--muted);font-size:11.5px;text-transform:uppercase;letter-spacing:.5px;padding:6px 8px;border-bottom:1px solid var(--line)}table.docs td{padding:7px 8px;border-bottom:1px solid var(--bg);vertical-align:top;overflow-wrap:anywhere}table.docs td.score{font-variant-numeric:tabular-nums;font-weight:600;white-space:nowrap}.stat-grid{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:4px}.stat{flex:1;min-width:110px;background:var(--bg);border-radius:8px;padding:10px 14px}.stat .v{font-size:20px;font-weight:700;font-variant-numeric:tabular-nums}.stat .k{font-size:11.5px;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}.item-bar-row{display:flex;align-items:center;gap:10px;margin-bottom:7px}.item-bar-label{flex:1;font-size:12.5px;min-width:0;overflow-wrap:anywhere}.item-bar-track{flex:1.2;background:var(--bg);border-radius:999px;height:10px}.item-bar-fill{background:var(--maroon);opacity:.85;height:100%;border-radius:999px}.item-bar-val{width:52px;text-align:right;font-variant-numeric:tabular-nums;font-size:12.5px;font-weight:600}.construct-items{margin:8px 0 0;padding-left:20px;color:var(--muted);font-size:12.5px}.construct-items li{margin-bottom:2px}.meta-footer{font-size:12px;color:var(--muted);background:var(--bg);border-radius:8px;padding:10px 14px;margin-top:14px;font-variant-numeric:tabular-nums}.meta-footer code{font-size:11.5px}.muted{color:var(--muted)}.small{font-size:12.5px}.mt{margin-top:12px}.header-auth{margin-left:auto;display:flex;align-items:center;gap:10px;color:#fff}.header-btn{background:#ffffff1f;color:#fff;border:1px solid rgba(255,255,255,.45);padding:5px 14px;border-radius:7px;font:inherit;font-size:13px;cursor:pointer}.header-btn:hover{background:#ffffff38}.project-header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px;flex-wrap:wrap}.project-title{font-size:17px;font-weight:650;margin-right:10px}button.danger{color:var(--err);border-color:#f0c4be}button.danger:hover{color:var(--err);border-color:var(--err)}button.danger-solid{background:var(--err)}button.danger-solid:hover{background:#93261b}button.danger-solid:disabled{background:#c9ccd1}.picker{position:relative}.picker-display{width:100%;display:flex;align-items:center;gap:10px;padding:8px 12px;border:1px solid var(--line);border-radius:8px;background:#fff;font:inherit;color:var(--ink);cursor:pointer;text-align:left}.picker-display:hover{border-color:var(--maroon)}.picker-display .picker-caret{margin-left:auto;color:var(--muted);font-size:11px}.picker-search{width:100%;padding:8px 12px;border:1px solid var(--maroon);border-radius:8px;font:inherit;background:#fff}.picker-search:focus{outline:none;box-shadow:0 0 0 3px #7a1f3d1f}.picker-panel{position:absolute;top:calc(100% + 6px);left:0;z-index:50;width:100%;max-width:640px;background:var(--card);border:1px solid var(--line);border-radius:10px;box-shadow:0 14px 40px #0000002e;max-height:340px;overflow-y:auto;padding:4px 0 6px}.picker-group{font-size:10.5px;text-transform:uppercase;letter-spacing:.6px;color:var(--muted);padding:8px 12px 3px;position:sticky;top:0;background:var(--card)}.picker-option{display:flex;align-items:baseline;justify-content:space-between;gap:12px;padding:6px 12px;cursor:pointer;font-size:13.5px}.picker-option:hover,.picker-option.active{background:var(--accent-soft)}.picker-option.selected .picker-name{font-weight:650;color:var(--maroon)}.picker-name{min-width:0}.picker-meta{flex-shrink:0;font-size:11.5px;color:var(--muted);white-space:nowrap}.picker-empty{padding:12px;margin:0}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;background:#14161a73;display:flex;align-items:center;justify-content:center;z-index:40;padding:16px}.modal{background:var(--card);border-radius:12px;padding:26px 28px 24px;width:100%;max-width:460px;box-shadow:0 12px 40px #0000002e}.modal h3{margin:0 0 8px;font-size:18px}.modal .hint{color:var(--muted);font-size:13px;line-height:1.5;margin:0 0 4px}.modal form.mt{margin-top:18px}.modal label.field{margin-bottom:16px}.modal label.field:last-of-type{margin-bottom:20px}.modal .row{gap:10px}.modal .row>.primary{flex:1}.modal p.small.muted.mt{margin-top:18px;padding-top:16px;border-top:1px solid var(--line);font-size:12.5px;line-height:1.6}@media (max-width: 820px){body{font-size:14px}.header{padding:12px 16px;align-items:flex-start;gap:2px 12px}.header h1{font-size:16px}.header .sub{flex:1 1 210px;font-size:12px;line-height:1.35}.layout{display:block}.sidebar{width:100%;border-right:0;border-bottom:1px solid var(--line);padding:14px}.project-list{max-height:220px;margin-right:0;flex:none}.project-create{border-top:0}.main{width:100%;padding:16px 14px 28px;overflow:visible}.card{padding:16px;margin-bottom:14px}.row,.run-settings,.construct-row,.results-toolbar,.result-actions{gap:10px}.row,.results-toolbar,.result-actions{flex-direction:column;align-items:stretch}.run-settings,.construct-row{grid-template-columns:1fr}.row>.grow,.construct-row>.grow,.language-control,.model-control{width:100%;min-width:0}.main .row>button,.main .row>a,.main .row>a>button,.results-toolbar>button{align-self:stretch;margin-bottom:0;width:100%}.run-button{width:100%;min-width:0}.stat-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr))}.stat{min-width:0}.item-bar-row{display:grid;grid-template-columns:minmax(0,1fr) 56px;gap:6px 10px}.item-bar-track{grid-column:1 / -1;width:100%}.item-bar-val{width:auto}table.docs{min-width:520px}}@media (max-width: 460px){.header .sub{flex-basis:100%}.stat-grid{grid-template-columns:1fr}}2 unmodified lines345678910112 unmodified lines<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>CCR Platform — Contextualized Construct Representations</title><script type="module" crossorigin src="/assets/index-BUzS6usZ.js"></script><link rel="stylesheet" crossorigin href="/assets/index-C356-0ZT.css"></head><body><div id="root"></div>2 unmodified lines345678910112 unmodified lines<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>CCR Platform - Contextualized Construct Representations</title><script type="module" crossorigin src="/assets/index-DrFcy6bH.js"></script><link rel="stylesheet" crossorigin href="/assets/index-CN_FzJfm.css"></head><body><div id="root"></div>
8 unmodified lines910111213148 unmodified linesfrom pathlib import Pathos.environ["CCR_DATA_DIR"] = tempfile.mkdtemp(prefix="ccr_test_")# Make `app` importable regardless of pytest invocation directory.sys.path.insert(0, str(Path(__file__).resolve().parent.parent))8 unmodified lines910111213141516178 unmodified linesfrom pathlib import Pathos.environ["CCR_DATA_DIR"] = tempfile.mkdtemp(prefix="ccr_test_")# Tests that exercise the anonymous run limit set this themselves; everything# else should not trip over it while running multiple jobs per test.os.environ.setdefault("CCR_ANON_MAX_RUNS_PER_DAY", "1000")# Make `app` importable regardless of pytest invocation directory.sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311"""Accounts (register/login), anonymous run limits, retention (delete-after-analysis + TTL purge), saved-run cap, ownership, and construct file upload."""
import ioimport time
import pytestfrom fastapi.testclient import TestClient
from app.main import app
@pytest.fixture()def client(): with TestClient(app) as c: yield c
def csv_rows(n: int) -> bytes: return ("text\n" + "\n".join(f"sample sentence number {i} here" for i in range(n))).encode()
def upload(client, project_id, name, payload: bytes): return client.post( f"/api/projects/{project_id}/corpora", files={"file": (name, io.BytesIO(payload), "text/csv")}, )
def register(client, email="user@test.edu", name="Test User"): resp = client.post( "/api/auth/register", json={"email": email, "password": "password123", "name": name} ) assert resp.status_code == 201, resp.json() return resp.json()
def run_job(client, project_id, corpus_id, construct_id): return client.post( "/api/jobs", json={ "project_id": project_id, "corpus_id": corpus_id, "construct_id": construct_id, "text_column": "text", "model_name": "fake-deterministic", }, )
def wait_for_job(client, job_id, timeout=10.0): deadline = time.time() + timeout while time.time() < deadline: job = client.get(f"/api/jobs/{job_id}").json() if job["status"] in ("completed", "failed"): return job time.sleep(0.05) raise TimeoutError(job_id)
def any_construct(client): return client.get("/api/constructs").json()[0]
# ---------------------------------------------------------------- accountsdef test_register_login_logout_roundtrip(client): register(client, "roundtrip@test.edu", "Rounder") me = client.get("/api/auth/me").json() assert me["signed_in"] and me["email"] == "roundtrip@test.edu" assert me["usage"]["max_saved_runs"] > 0
client.post("/api/auth/logout") assert client.get("/api/auth/me").json()["signed_in"] is False
resp = client.post( "/api/auth/login", json={"email": "ROUNDTRIP@test.edu", "password": "password123"} ) assert resp.status_code == 200 # email is case-insensitive assert client.get("/api/auth/me").json()["signed_in"] is True
def test_wrong_password_and_duplicate_email(client): register(client, "dupe@test.edu") client.post("/api/auth/logout") resp = client.post("/api/auth/login", json={"email": "dupe@test.edu", "password": "wrongpass1"}) assert resp.status_code == 401 resp = client.post( "/api/auth/register", json={"email": "dupe@test.edu", "password": "password123", "name": "X"} ) assert resp.status_code == 409
def test_register_validation(client): resp = client.post( "/api/auth/register", json={"email": "not-an-email", "password": "password123", "name": "X"} ) assert resp.status_code == 400
# ------------------------------------------------------ anonymous run limitdef test_anonymous_daily_run_limit(client, monkeypatch): monkeypatch.setenv("CCR_ANON_MAX_RUNS_PER_DAY", "2") project = client.post("/api/projects", json={"name": "Limited"}).json() construct = any_construct(client)
for i in range(2): corpus = upload(client, project["id"], f"c{i}.csv", csv_rows(5)).json() resp = run_job(client, project["id"], corpus["id"], construct["id"]) assert resp.status_code == 201, resp.json() wait_for_job(client, resp.json()["id"])
me = client.get("/api/auth/me").json() assert me["usage"]["runs_used_today"] == 2
corpus = upload(client, project["id"], "c3.csv", csv_rows(5)).json() resp = run_job(client, project["id"], corpus["id"], construct["id"]) assert resp.status_code == 429 assert "Sign in" in resp.json()["detail"]
def test_signed_in_users_bypass_run_limit(client, monkeypatch): monkeypatch.setenv("CCR_ANON_MAX_RUNS_PER_DAY", "1") register(client, "runner@test.edu") project = client.post("/api/projects", json={"name": "Unlimited"}).json() corpus = upload(client, project["id"], "c.csv", csv_rows(5)).json() construct = any_construct(client) for _ in range(3): resp = run_job(client, project["id"], corpus["id"], construct["id"]) assert resp.status_code == 201, resp.json() wait_for_job(client, resp.json()["id"])
# ----------------------------------------------------------------- retentiondef test_anonymous_corpus_removed_after_run_and_rerun_gets_410(client): from pathlib import Path
project = client.post("/api/projects", json={"name": "Ephemeral"}).json() corpus = upload(client, project["id"], "c.csv", csv_rows(5)).json() construct = any_construct(client)
resp = run_job(client, project["id"], corpus["id"], construct["id"]) job = wait_for_job(client, resp.json()["id"]) assert job["status"] == "completed"
results = client.get(f"/api/jobs/{job['id']}/results").json() codes = [w["code"] for w in results["summary"]["warnings"]] assert "ANONYMOUS_DATA_REMOVED" in codes assert results["metadata"]["anonymous_corpus_removed"] is True # results are still downloadable; the raw upload is gone assert client.get(f"/api/jobs/{job['id']}/export").status_code == 200
resp = run_job(client, project["id"], corpus["id"], construct["id"]) assert resp.status_code == 410
def test_signed_in_corpus_survives_run(client): register(client, "keeper@test.edu") project = client.post("/api/projects", json={"name": "Kept"}).json() corpus = upload(client, project["id"], "c.csv", csv_rows(5)).json() construct = any_construct(client)
resp = run_job(client, project["id"], corpus["id"], construct["id"]) job = wait_for_job(client, resp.json()["id"]) assert job["status"] == "completed" codes = [w["code"] for w in client.get(f"/api/jobs/{job['id']}/results").json()["summary"]["warnings"]] assert "ANONYMOUS_DATA_REMOVED" not in codes
# re-running the same corpus works: the file is still there resp = run_job(client, project["id"], corpus["id"], construct["id"]) assert resp.status_code == 201
def test_ttl_purge_removes_only_expired_anonymous_projects(client, monkeypatch): from app.db import SessionLocal from app.models import Project from app.retention import purge_expired_anonymous
monkeypatch.setenv("CCR_ANON_TTL_HOURS", "24") old_anon = client.post("/api/projects", json={"name": "OldAnon"}).json() fresh_anon = client.post("/api/projects", json={"name": "FreshAnon"}).json() register(client, "owner@test.edu") owned = client.post("/api/projects", json={"name": "OwnedOld"}).json()
db = SessionLocal() try: db.get(Project, old_anon["id"]).created_at = "2020-01-01T00:00:00+00:00" db.get(Project, owned["id"]).created_at = "2020-01-01T00:00:00+00:00" db.commit() purged = purge_expired_anonymous(db) assert purged == 1 assert db.get(Project, old_anon["id"]) is None assert db.get(Project, fresh_anon["id"]) is not None assert db.get(Project, owned["id"]) is not None # owned data never TTL-purged finally: db.close()
# ------------------------------------------------------------ saved-run capdef test_saved_run_cap_for_signed_in_users(client, monkeypatch): monkeypatch.setenv("CCR_USER_MAX_SAVED_RUNS", "2") register(client, "capped@test.edu") project = client.post("/api/projects", json={"name": "Capped"}).json() corpus = upload(client, project["id"], "c.csv", csv_rows(5)).json() construct = any_construct(client)
for _ in range(2): resp = run_job(client, project["id"], corpus["id"], construct["id"]) assert resp.status_code == 201 wait_for_job(client, resp.json()["id"])
resp = run_job(client, project["id"], corpus["id"], construct["id"]) assert resp.status_code == 409 assert "saved runs" in resp.json()["detail"]
# ---------------------------------------------------------------- ownershipdef test_owned_projects_invisible_and_untouchable_to_others(client): register(client, "alice@test.edu", "Alice") owned = client.post("/api/projects", json={"name": "AlicePrivate"}).json() client.post("/api/auth/logout")
ids = [p["id"] for p in client.get("/api/projects").json()] assert owned["id"] not in ids # invisible to anonymous viewers assert client.patch(f"/api/projects/{owned['id']}", json={"archived": True}).status_code == 403 assert client.delete(f"/api/projects/{owned['id']}").status_code == 403
register(client, "bob@test.edu", "Bob") assert client.patch(f"/api/projects/{owned['id']}", json={"archived": True}).status_code == 403
# ------------------------------------------------- construct file uploaddef test_parse_construct_file_with_reverse_column(client): csv = "item,reverse\nI am satisfied with my life.,0\nI rarely feel content. ,1\n,\nI am satisfied with my life.,0\n" resp = client.post( "/api/constructs/parse-file", files={"file": ("swls_short.csv", io.BytesIO(csv.encode()), "text/csv")}, ) assert resp.status_code == 200, resp.json() body = resp.json() assert body["items"] == [ {"text": "I am satisfied with my life.", "reverse_scored": False}, {"text": "I rarely feel content.", "reverse_scored": True}, ] assert any("blank" in w for w in body["warnings"]) assert any("duplicate" in w for w in body["warnings"]) assert body["suggested_name"] == "Swls Short"
def test_parse_construct_file_with_r_marker_single_column(client): csv = "text\nLife feels meaningful to me\nNothing I do matters (R)\n" resp = client.post( "/api/constructs/parse-file", files={"file": ("meaning.csv", io.BytesIO(csv.encode()), "text/csv")}, ) body = resp.json() assert body["items"][1] == {"text": "Nothing I do matters", "reverse_scored": True}
def test_parse_construct_file_rejects_bad_type_and_empty(client): resp = client.post( "/api/constructs/parse-file", files={"file": ("items.pdf", io.BytesIO(b"x"), "application/pdf")}, ) assert resp.status_code == 400 resp = client.post( "/api/constructs/parse-file", files={"file": ("empty.csv", io.BytesIO(b"item\n"), "text/csv")}, ) assert resp.status_code == 400
# ------------------------------------------------------- perf: dedup encodedef test_encode_unique_matches_full_encode_and_saves_calls(): import numpy as np
from app.ccr import HashEmbeddingBackend, encode_unique
class Counting(HashEmbeddingBackend): def __init__(self): super().__init__() self.n_encoded = 0
def encode(self, texts, progress_cb=None): self.n_encoded += len(texts) return super().encode(texts, progress_cb)
texts = ["alpha beta", "gamma delta", "alpha beta", "alpha beta", "gamma delta"] counting = Counting() deduped = encode_unique(counting, texts) assert counting.n_encoded == 2 # only unique texts hit the encoder full = HashEmbeddingBackend().encode(texts) assert np.allclose(deduped, full) # bit-identical expansion
def test_created_construct_carries_reverse_flags_into_run_metadata(client): created = client.post( "/api/constructs", json={ "name": "Flagged Scale", "items": ["good item", "bad item"], "reverse_scored": [False, True], }, ).json() assert created["reverse_scored"] == [False, True]
project = client.post("/api/projects", json={"name": "FlagRun"}).json() corpus = upload(client, project["id"], "c.csv", csv_rows(5)).json() resp = run_job(client, project["id"], corpus["id"], created["id"]) job = wait_for_job(client, resp.json()["id"]) snapshot = client.get(f"/api/jobs/{job['id']}/results").json()["metadata"]["construct_snapshot"] assert snapshot["items"][1]["reverse_scored"] is True1234567872 unmodified lines8182838485868715 unmodified lines10310410510610710810911011111211311411511646 unmodified lines163164165"""End-to-end API tests: project -> upload -> job -> results -> export.Run against the fake embedding backend (model_name = 'fake-deterministic'),exercising the full pipeline — tolerant upload parsing, the real job queue(worker thread + polling), results summary, warnings, and export shape —without ML dependencies."""72 unmodified linesdef test_seed_constructs_present(client):names = {c["name"] for c in client.get("/api/constructs").json()}assert "Satisfaction with Life" in namesassert "Moral Foundations — Care" in namesdef test_corpus_upload_parses_columns(flow):15 unmodified linesassert summary["n_docs"] == 5 # empty row droppedassert summary["n_dropped_empty"] == 1assert len(summary["item_means"]) == 5 # SWLS has 5 itemsassert any("duplicate" in w for w in summary["warnings"])assert any("empty" in w for w in summary["warnings"])# satisfaction-flavored texts should outrank the bus/printer rowstop_texts = " ".join(d["text"] for d in summary["top_docs"][:2])assert "satisfied" in top_texts or "ideal" in top_textsassert metadata["construct"] == "Satisfaction with Life"assert metadata["model"] == "fake-deterministic"assert metadata["corpus_parse_info"]["format"] == "csv"def test_export_csv_shape(client, flow):46 unmodified lines# bad file typeresp = upload(client, flow["project"]["id"], "evil.exe", b"x")assert resp.status_code == 4001234567872 unmodified lines8182838485868715 unmodified lines10310410510610710810911011111211311411511611711811912012112212312412512646 unmodified lines173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271"""End-to-end API tests: project -> upload -> job -> results -> export.Run against the fake embedding backend (model_name = 'fake-deterministic'),exercising the full pipeline - tolerant upload parsing, the real job queue(worker thread + polling), results summary, warnings, and export shape -without ML dependencies."""72 unmodified linesdef test_seed_constructs_present(client):names = {c["name"] for c in client.get("/api/constructs").json()}assert "Satisfaction with Life" in namesassert "Moral Foundations - Care" in namesdef test_corpus_upload_parses_columns(flow):15 unmodified linesassert summary["n_docs"] == 5 # empty row droppedassert summary["n_dropped_empty"] == 1assert len(summary["item_means"]) == 5 # SWLS has 5 itemscodes = {w["code"] for w in summary["warnings"]} # structured objects (spec 0001)assert "DUPLICATE_TEXTS" in codesassert "EMPTY_ROWS_DROPPED" in codesassert all({"code", "severity", "message"} <= set(w) for w in summary["warnings"])# satisfaction-flavored texts should outrank the bus/printer rowstop_texts = " ".join(d["text"] for d in summary["top_docs"][:2])assert "satisfied" in top_texts or "ideal" in top_textsassert metadata["construct"] == "Satisfaction with Life"assert metadata["model"] == "fake-deterministic"assert metadata["corpus_parse_info"]["format"] == "csv"# spec 0001/0004 metadata additionsassert metadata["output_schema_version"] == "1.0"assert metadata["scoring"]["adjustment_strategy"] == "none"assert metadata["language"]["selected"] == "en"snapshot = metadata["construct_snapshot"]assert snapshot["construct_id"] == "satisfaction_with_life"assert snapshot["item_hash"] and len(snapshot["items"]) == 5assert "ccr_score" in metadata["output_schema"]def test_export_csv_shape(client, flow):46 unmodified lines# bad file typeresp = upload(client, flow["project"]["id"], "evil.exe", b"x")assert resp.status_code == 400# unknown model id (registry-validated now)resp = client.post("/api/jobs",json={"project_id": flow["project"]["id"],"corpus_id": flow["corpus"]["id"],"construct_id": flow["construct"]["id"],"text_column": "text","model_name": "sentence-transformers/all-MiniLM-L6-v2", # provider id, not registry id},)assert resp.status_code == 400def test_projects_carry_activity_and_sort_by_it(client, flow):projects = client.get("/api/projects").json()demo = next(p for p in projects if p["id"] == flow["project"]["id"])assert demo["n_runs"] >= 1assert demo["last_activity_at"] >= demo["created_at"]# the project with runs sorts above a freshly created empty one from earlier testsorder = [p["last_activity_at"] for p in projects]assert order == sorted(order, reverse=True)# --------------------------------------------------- spec 0003: models APIdef test_models_endpoint_from_registry(client):models = client.get("/api/models").json()ids = [m["id"] for m in models]assert "all-minilm-l6-v2" in ids and "e5-large-v2" in ids and "multilingual-e5-base" in idsdefaults = [m for m in models if m["default"]]assert len(defaults) == 1 and defaults[0]["id"] == "all-minilm-l6-v2"assert client.get("/api/languages").json()[0] == "en"# --------------------------------------------------- spec 0004: construct librarydef test_constructs_carry_library_fields(client):swls = next(c for c in client.get("/api/constructs").json()if c["name"] == "Satisfaction with Life")assert swls["verification_status"] == "needs_verification"assert swls["version"] == 1assert len(swls["item_hash"]) == 16assert swls["reverse_scored"] == [False] * 5# --------------------------------------------------- spec 0001: language warningsdef test_language_uncertain_on_tiny_corpus(client, flow):body = client.get(f"/api/jobs/{flow['job']['id']}/results").json()codes = {w["code"] for w in body["summary"]["warnings"]}# 5-row corpus is far below the 20 detectable-row minimumassert "LANGUAGE_UNCERTAIN" in codesassert body["metadata"]["language"]["detected"] is Nonedef test_short_text_and_model_language_warnings(client, flow):csv = "text\n" + "\n".join([f"esta es una frase de prueba número {i} para el corpus" for i in range(25)]+ ["si", "no"] # two very short rows)corpus = upload(client, flow["project"]["id"], "spanish.csv", csv.encode()).json()job = client.post("/api/jobs",json={"project_id": flow["project"]["id"],"corpus_id": corpus["id"],"construct_id": flow["construct"]["id"],"text_column": "text","model_name": "fake-deterministic","language": "es",},).json()job = wait_for_job(client, job["id"])assert job["status"] == "completed", job["error"]body = client.get(f"/api/jobs/{job['id']}/results").json()warnings = {w["code"]: w for w in body["summary"]["warnings"]}assert warnings["TEXT_TOO_SHORT"]["count"] == 2assert warnings["TEXT_TOO_SHORT"]["affected_rows_sample"]assert body["metadata"]["language"]["selected"] == "es"# --------------------------------------------------- spec 0002: script exportdef test_script_export_is_valid_offline_python(client, flow):job_id = flow["job"]["id"]resp = client.get(f"/api/jobs/{job_id}/script")assert resp.status_code == 200source = resp.textcompile(source, "reproduce_analysis.py", "exec") # must be valid Python# embeds the construct items verbatim and never references the platformassert "In most ways my life is close to my ideal." in sourceassert "sim_item_" in source and "ccr_score" in sourceassert "127.0.0.1" not in source and "/api/" not in sourcereqs = client.get(f"/api/jobs/{job_id}/script-requirements")assert reqs.status_code == 200assert "==" in reqs.text # pinned versions, not ranges
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138"""Sign-in tiers (anonymous caps lift on sign-in) and project lifecycle(archive is reversible; delete cascades to files and rows)."""
import ioimport timefrom pathlib import Path
import pytestfrom fastapi.testclient import TestClient
from app.main import app
def upload(client, project_id, name, payload: bytes): return client.post( f"/api/projects/{project_id}/corpora", files={"file": (name, io.BytesIO(payload), "text/csv")}, )
def wait_for_job(client, job_id, timeout=10.0): deadline = time.time() + timeout while time.time() < deadline: job = client.get(f"/api/jobs/{job_id}").json() if job["status"] in ("completed", "failed"): return job time.sleep(0.05) raise TimeoutError(job_id)
@pytest.fixture()def client(): with TestClient(app) as c: yield c
def csv_rows(n: int) -> bytes: return ("text\n" + "\n".join(f"sample sentence number {i} here" for i in range(n))).encode()
# ------------------------------------------------------------------- tiersdef test_anonymous_row_cap_and_signin_lifts_it(client, monkeypatch): monkeypatch.setenv("CCR_ANON_MAX_ROWS", "5") project = client.post("/api/projects", json={"name": "Tiers"}).json()
me = client.get("/api/auth/me").json() assert me["signed_in"] is False and me["limits"]["max_rows"] == 5
resp = upload(client, project["id"], "big.csv", csv_rows(10)) assert resp.status_code == 400 assert "Sign in" in resp.json()["detail"]
resp = client.post( "/api/auth/register", json={"email": "deva@test.edu", "password": "password123", "name": "Deva"}, ) assert resp.status_code == 201 me = client.get("/api/auth/me").json() assert me["signed_in"] is True and me["name"] == "Deva"
resp = upload(client, project["id"], "big.csv", csv_rows(10)) assert resp.status_code == 201, resp.json()
client.post("/api/auth/logout") assert client.get("/api/auth/me").json()["signed_in"] is False
def test_anonymous_size_cap(client, monkeypatch): monkeypatch.setenv("CCR_ANON_MAX_BYTES", "200") project = client.post("/api/projects", json={"name": "SizeCap"}).json() resp = upload(client, project["id"], "big.csv", csv_rows(50)) assert resp.status_code == 413 assert "Sign in" in resp.json()["detail"]
def test_tampered_session_cookie_is_anonymous(client): client.cookies.set("ccr_session", "aGFja2Vy.badsignature") assert client.get("/api/auth/me").json()["signed_in"] is False
# --------------------------------------------------------------- lifecycledef test_archive_toggle_is_reversible(client): project = client.post("/api/projects", json={"name": "Archivable"}).json() assert project["archived"] is False
patched = client.patch(f"/api/projects/{project['id']}", json={"archived": True}).json() assert patched["archived"] is True listed = next(p for p in client.get("/api/projects").json() if p["id"] == project["id"]) assert listed["archived"] is True
patched = client.patch(f"/api/projects/{project['id']}", json={"archived": False}).json() assert patched["archived"] is False
def test_delete_cascades_rows_and_files(client): project = client.post("/api/projects", json={"name": "Doomed"}).json() corpus = upload(client, project["id"], "corpus.csv", csv_rows(6)).json()
constructs = client.get("/api/constructs").json() swls = next(c for c in constructs if c["name"] == "Satisfaction with Life") job = client.post( "/api/jobs", json={ "project_id": project["id"], "corpus_id": corpus["id"], "construct_id": swls["id"], "text_column": "text", "model_name": "fake-deterministic", }, ).json() job = wait_for_job(client, job["id"]) assert job["status"] == "completed"
# capture file paths before deletion results = client.get(f"/api/jobs/{job['id']}/results") assert results.status_code == 200
resp = client.delete(f"/api/projects/{project['id']}") assert resp.status_code == 204
assert client.get(f"/api/jobs/{job['id']}").status_code == 404 assert all(p["id"] != project["id"] for p in client.get("/api/projects").json()) # corpora listing for the deleted project 404s assert client.get(f"/api/projects/{project['id']}/corpora").status_code == 404
def test_delete_removes_files_on_disk(client, tmp_path): import os
data_dir = Path(os.environ["CCR_DATA_DIR"]) project = client.post("/api/projects", json={"name": "FileCheck"}).json() before = set((data_dir / "corpora").glob("*")) upload(client, project["id"], "corpus.csv", csv_rows(6)) created = set((data_dir / "corpora").glob("*")) - before assert len(created) == 1
client.delete(f"/api/projects/{project['id']}") assert not created.pop().exists()123456789101112131415161718192021222324252627282930313233343536373839404142"""Additive SQLite auto-migration: an old-schema DB gains new ORM columnsat startup instead of 500ing (the 'no such column: projects.archived' bug)."""
import sqlite3
from sqlalchemy import create_engine, inspect
from app.db import Base, auto_migrate_sqlitefrom app.models import Project # noqa: F401 - registers tables on Base.metadata
def test_old_schema_gains_missing_columns(tmp_path): db_path = tmp_path / "old.db"
# Simulate a dev DB created before archived/language/etc. existed. conn = sqlite3.connect(db_path) conn.execute( "CREATE TABLE projects (id VARCHAR(32) PRIMARY KEY, name VARCHAR(200), " "description TEXT, created_at VARCHAR(32))" ) conn.execute( "INSERT INTO projects VALUES ('abc123', 'Old Project', '', '2026-07-01T00:00:00')" ) conn.commit() conn.close()
engine = create_engine(f"sqlite:///{db_path}") Base.metadata.create_all(engine) # creates the other, brand-new tables added = auto_migrate_sqlite(engine, Base.metadata)
assert "projects.archived" in added cols = {c["name"] for c in inspect(engine).get_columns("projects")} assert "archived" in cols
# Existing row survives with the default applied, and queries work. conn = sqlite3.connect(db_path) row = conn.execute("SELECT name, archived FROM projects WHERE id='abc123'").fetchone() conn.close() assert row == ("Old Project", 0)
# Second run is a no-op (idempotent). assert auto_migrate_sqlite(engine, Base.metadata) == []1234"""Unit tests for the CCR engine (deterministic fake backend — no torch)."""import numpy as npimport pytest1234"""Unit tests for the CCR engine (deterministic fake backend - no torch)."""import numpy as npimport pytest
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889"""Google sign-in (Supabase PKCE): feature flag, redirect flow, callbackfind-or-create, and password-login guard for Google-only accounts. TheSupabase exchange itself is mocked - no network in tests."""
import pytestfrom fastapi.testclient import TestClient
from app import auth, auth_googlefrom app.main import app
@pytest.fixture()def client(): with TestClient(app) as c: yield c
@pytest.fixture()def google_env(monkeypatch): monkeypatch.setenv("SUPABASE_URL", "https://fakeproj.supabase.co") monkeypatch.setenv("SUPABASE_ANON_KEY", "fake-anon-key") monkeypatch.setenv("CCR_APP_URL", "http://testserver")
def test_unconfigured_instance_hides_and_refuses_google(client): assert client.get("/api/auth/me").json().get("google_available") is False assert client.get("/api/auth/google/login", follow_redirects=False).status_code == 503
def test_login_redirects_to_supabase_with_pkce(client, google_env): me = client.get("/api/auth/me").json() assert me["google_available"] is True
resp = client.get("/api/auth/google/login", follow_redirects=False) assert resp.status_code == 307 loc = resp.headers["location"] assert loc.startswith("https://fakeproj.supabase.co/auth/v1/authorize?") assert "provider=google" in loc assert "code_challenge=" in loc and "code_challenge_method=s256" in loc assert "redirect_to=http%3A%2F%2Ftestserver%2Fapi%2Fauth%2Fgoogle%2Fcallback" in loc assert auth_google.VERIFIER_COOKIE in resp.cookies
def test_callback_creates_user_and_signs_in(client, google_env, monkeypatch): monkeypatch.setattr( auth_google, "exchange", lambda code, verifier: {"email": "pi@lab.edu", "name": "The PI"}, ) client.cookies.set(auth_google.VERIFIER_COOKIE, auth.sign_payload({"v": "verifier123"}))
resp = client.get("/api/auth/google/callback?code=abc", follow_redirects=False) assert resp.status_code == 307 and resp.headers["location"] == "/"
me = client.get("/api/auth/me").json() assert me["signed_in"] is True and me["email"] == "pi@lab.edu" and me["name"] == "The PI"
# second sign-in reuses the same account (no duplicate users) client.cookies.set(auth_google.VERIFIER_COOKIE, auth.sign_payload({"v": "verifier456"})) client.get("/api/auth/google/callback?code=def", follow_redirects=False) from app.db import SessionLocal from app.models import User
db = SessionLocal() try: assert db.query(User).filter_by(email="pi@lab.edu").count() == 1 finally: db.close()
def test_callback_without_verifier_fails_safely(client, google_env): resp = client.get("/api/auth/google/callback?code=abc", follow_redirects=False) assert resp.status_code == 307 assert "auth_error=" in resp.headers["location"]
def test_google_only_account_cannot_password_login(client, google_env, monkeypatch): monkeypatch.setattr( auth_google, "exchange", lambda code, verifier: {"email": "gonly@lab.edu", "name": "G Only"}, ) client.cookies.set(auth_google.VERIFIER_COOKIE, auth.sign_payload({"v": "v1"})) client.get("/api/auth/google/callback?code=abc", follow_redirects=False) client.post("/api/auth/logout")
resp = client.post( "/api/auth/login", json={"email": "gonly@lab.edu", "password": "password123"} ) assert resp.status_code == 401 assert "Google" in resp.json()["detail"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110"""Registry loader + E5 prefix application (spec 0003) and warnings engine units (spec 0001)."""
import numpy as npimport pytest
from app import registryfrom app.ccr import run_ccrfrom app.warnings_engine import ( detect_corpus_language, model_language_warning, short_text_warning,)
class RecordingBackend: """Captures exactly what the engine sends to the encoder."""
name = "recording"
def __init__(self): self.calls: list[list[str]] = []
def encode(self, texts, progress_cb=None): self.calls.append(list(texts)) rng = np.random.default_rng(42) emb = rng.normal(size=(len(texts), 8)) return emb / np.linalg.norm(emb, axis=1, keepdims=True)
# ------------------------------------------------------------------ registrydef test_registry_loads_three_models_with_minilm_default(): models = registry.list_models() ids = [m.id for m in models] assert ids[0] == "all-minilm-l6-v2" # default sorts first assert registry.default_model().id == "all-minilm-l6-v2" assert {"e5-large-v2", "multilingual-e5-base"} <= set(ids)
def test_e5_config_requires_prefix_on_both_sides(): cfg = registry.get_model("e5-large-v2") assert cfg.requires_prefix assert cfg.item_prefix == "query: " and cfg.text_prefix == "query: " assert cfg.max_seq_length == 512 and cfg.embedding_dimension == 1024
def test_multilingual_language_set_resolves_to_real_codes(): cfg = registry.get_model("multilingual-e5-base") assert cfg.language_set_name == "xlm_roberta_100" assert "es" in cfg.supported_languages and "sw" in cfg.supported_languages assert cfg.supports_language("hi") and not cfg.supports_language("xx")
def test_unknown_model_raises(): with pytest.raises(KeyError): registry.get_model("gpt-9000")
# ------------------------------------------------------------------ prefixesdef test_run_ccr_applies_prefixes_to_encoder_input_only(): backend = RecordingBackend() result = run_ccr( ["first text here", "second text here"], ["an item statement"], backend, item_prefix="query: ", text_prefix="query: ", ) item_call, text_call = backend.calls assert item_call == ["query: an item statement"] assert text_call == ["query: first text here", "query: second text here"] # metadata records the prefixes for the reproducibility bundle assert result.metadata["item_prefix"] == "query: " assert result.metadata["text_prefix"] == "query: "
def test_run_ccr_without_prefixes_passes_raw_strings(): backend = RecordingBackend() run_ccr(["a text"], ["an item"], backend) assert backend.calls[0] == ["an item"] and backend.calls[1] == ["a text"]
# ------------------------------------------------------------- warnings unitsdef test_short_text_warning_boundary(): w = short_text_warning(["one two three", "one two three four", "x"]) assert w["count"] == 2 # 3-token and 1-token rows flagged; 4-token row not assert w["affected_rows_sample"] == [0, 2] assert short_text_warning(["four token sentence here"] * 3) is None
def test_language_detection_uncertain_below_min_rows(): result, warnings = detect_corpus_language(["hello there my good friend"] * 5, "en") assert result.detected is None assert warnings[0]["code"] == "LANGUAGE_UNCERTAIN"
def test_language_mismatch_detected_deterministically(): spanish = [f"esta es una frase de prueba número {i} sobre la vida cotidiana" for i in range(30)] result, warnings = detect_corpus_language(spanish, "en") assert result.detected == "es" assert any(w["code"] == "LANGUAGE_MISMATCH" for w in warnings) # determinism: same corpus, same outcome result2, _ = detect_corpus_language(spanish, "en") assert result2.detected == result.detected and result2.confidence == result.confidence
def test_model_language_unsupported_warning(): w = model_language_warning("xx", "multilingual-e5-base", frozenset({"en", "es"}), "demo_set") assert w["code"] == "MODEL_LANGUAGE_UNSUPPORTED" assert model_language_warning("en", "m", frozenset({"en"}), None) is None assert model_language_warning("zz", "m", frozenset(), None) is None # unknown coverage: no warning123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""Storage interface: local backend (default) and S3/R2 backend via a fakeclient - proves production object storage works end to end (upload -> run ->export -> retention delete) without any network or boto3 dependency."""
import ioimport time
import pytestfrom fastapi.testclient import TestClient
from app import storagefrom app.main import app
class FakeS3: """Minimal S3 client: just what storage.py calls."""
def __init__(self): self.objects: dict[str, bytes] = {}
def put_object(self, Bucket, Key, Body): self.objects[Key] = Body if isinstance(Body, bytes) else Body.read()
def head_object(self, Bucket, Key): if Key not in self.objects: raise KeyError(Key) return {"ContentLength": len(self.objects[Key])}
def download_file(self, Bucket, Key, Filename): with open(Filename, "wb") as f: f.write(self.objects[Key])
def get_object(self, Bucket, Key): return {"Body": io.BytesIO(self.objects[Key])}
def delete_object(self, Bucket, Key): self.objects.pop(Key, None)
@pytest.fixture()def s3(monkeypatch): fake = FakeS3() monkeypatch.setenv("CCR_STORAGE", "s3") monkeypatch.setenv("CCR_S3_BUCKET", "ccr-test") monkeypatch.setattr(storage, "_client", fake) yield fake monkeypatch.setattr(storage, "_client", None)
@pytest.fixture()def client(): with TestClient(app) as c: yield c
def csv_rows(n: int) -> bytes: return ("text\n" + "\n".join(f"sample sentence number {i} here" for i in range(n))).encode()
def wait_for_job(client, job_id, timeout=10.0): deadline = time.time() + timeout while time.time() < deadline: job = client.get(f"/api/jobs/{job_id}").json() if job["status"] in ("completed", "failed"): return job time.sleep(0.05) raise TimeoutError(job_id)
# ------------------------------------------------------------------ unitdef test_s3_roundtrip(s3, tmp_path): locator = storage.store_bytes("corpora", "abc.csv", b"text\nhello world row\n") assert locator == "s3://corpora/abc.csv" assert storage.exists(locator)
local, is_temp = storage.fetch_to_local(locator) assert is_temp and local.read_bytes().startswith(b"text") local.unlink()
assert b"".join(storage.open_stream(locator)) == b"text\nhello world row\n" storage.delete(locator) assert not storage.exists(locator) assert s3.objects == {}
def test_local_backend_unchanged(tmp_path): locator = storage.store_bytes("corpora", "local_check.csv", b"data") assert not storage.is_s3(locator) local, is_temp = storage.fetch_to_local(locator) assert not is_temp and local.read_bytes() == b"data" storage.delete(locator) assert not storage.exists(locator)
# ------------------------------------------------------------ end to enddef test_full_flow_on_s3_backend(client, s3): """Signed-in upload -> corpus lands in the bucket -> run materializes a temp copy -> result CSV lands in the bucket -> export streams it -> project delete empties the bucket.""" client.post( "/api/auth/register", json={"email": "s3user@test.edu", "password": "password123", "name": "S3"}, ) project = client.post("/api/projects", json={"name": "S3Flow"}).json() corpus = client.post( f"/api/projects/{project['id']}/corpora", files={"file": ("c.csv", io.BytesIO(csv_rows(6)), "text/csv")}, ).json() assert any(k.startswith("corpora/") for k in s3.objects)
construct = client.get("/api/constructs").json()[0] job = client.post( "/api/jobs", json={ "project_id": project["id"], "corpus_id": corpus["id"], "construct_id": construct["id"], "text_column": "text", "model_name": "fake-deterministic", }, ).json() job = wait_for_job(client, job["id"]) assert job["status"] == "completed" assert any(k.startswith("results/") for k in s3.objects)
export = client.get(f"/api/jobs/{job['id']}/export") assert export.status_code == 200 assert b"ccr_score" in export.content
client.delete(f"/api/projects/{project['id']}") assert s3.objects == {} # cascade emptied the bucket
def test_anonymous_run_deletes_s3_corpus(client, s3): project = client.post("/api/projects", json={"name": "S3Anon"}).json() corpus = client.post( f"/api/projects/{project['id']}/corpora", files={"file": ("c.csv", io.BytesIO(csv_rows(5)), "text/csv")}, ).json() construct = client.get("/api/constructs").json()[0] job = client.post( "/api/jobs", json={ "project_id": project["id"], "corpus_id": corpus["id"], "construct_id": construct["id"], "text_column": "text", "model_name": "fake-deterministic", }, ).json() job = wait_for_job(client, job["id"]) assert job["status"] == "completed" assert not any(k.startswith("corpora/") for k in s3.objects) # upload gone assert any(k.startswith("results/") for k in s3.objects) # results kept for TTL1 unmodified line234567891011121314151617181920219 unmodified lines3132333435362 unmodified lines3940414243444546474849505152535455565758596061626364656667686970717273747576777879808182833 unmodified lines878889909192933 unmodified lines9798991001011021031 unmodified lineimport { api } from "./api.js";import Workspace from "./Workspace.jsx";export default function App() {const [projects, setProjects] = useState([]);const [selectedId, setSelectedId] = useState(null);const [creating, setCreating] = useState(false);const [newName, setNewName] = useState("");const [error, setError] = useState("");const loadProjects = () =>api.listProjects().then(setProjects).catch((e) => setError(e.message));useEffect(() => {loadProjects();}, []);async function createProject(e) {e.preventDefault();if (!newName.trim()) return;9 unmodified lines}const selected = projects.find((p) => p.id === selectedId) || null;return (<div className="app">2 unmodified lines<span className="sub">Contextualized Construct Representations · theory-driven psychological text analysis</span></header><div className="layout"><aside className="sidebar"><h2>Projects</h2>{projects.map((p) => (<buttonkey={p.id}className={"project-item" + (p.id === selectedId ? " active" : "")}onClick={() => setSelectedId(p.id)}>{p.name}<span className="date">{p.created_at.slice(0, 10)}</span></button>))}{creating ? (<form onSubmit={createProject} className="mt"><inputtype="text"autoFocusplaceholder="Project name"value={newName}onChange={(e) => setNewName(e.target.value)}/><div className="row mt"><button className="primary" type="submit">Create</button><button className="ghost" type="button" onClick={() => setCreating(false)}>Cancel</button></div></form>) : (<button className="ghost mt" onClick={() => setCreating(true)}>+ New project</button>)}</aside><main className="main">3 unmodified lines</div>)}{selected ? (<Workspace key={selected.id} project={selected} />) : (<div className="card"><h3>Welcome</h3>3 unmodified linesscore distributions, and a reproducibility record for every run.</p><p className="small muted">Self-contained by design: embeddings run on this server itself — nothird-party AI APIs. Demo instance: storage is ephemeral and may reset;please don't upload sensitive or identifiable data.</p>1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141159 unmodified lines1251261271281291301311321331342 unmodified lines1371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193 unmodified lines3233243253263273283293303313323333343353363373383393 unmodified lines3433443453463473483491 unmodified lineimport { api } from "./api.js";import Workspace from "./Workspace.jsx";function relativeTime(iso) {if (!iso) return "";const then = new Date(iso.endsWith("Z") || iso.includes("+") ? iso : iso + "Z");const mins = Math.max(0, Math.floor((Date.now() - then.getTime()) / 60000));if (mins < 1) return "just now";if (mins < 60) return `${mins}m ago`;const hours = Math.floor(mins / 60);if (hours < 24) return `${hours}h ago`;const days = Math.floor(hours / 24);if (days < 7) return `${days}d ago`;return then.toISOString().slice(0, 10);}function groupProjects(projects) {// Buckets by last activity: Today / This week / Earlier, with archived// projects collapsed into their own group at the bottom. Projects arrive// sorted by last activity (backend), so group order falls out naturally.const now = Date.now();const DAY = 86400000;const groups = { Today: [], "This week": [], Earlier: [], Archived: [] };for (const p of projects) {if (p.archived) {groups.Archived.push(p);continue;}const iso = p.last_activity_at || p.created_at;const t = new Date(iso.endsWith("Z") || iso.includes("+") ? iso : iso + "Z").getTime();const age = now - t;if (age < DAY) groups.Today.push(p);else if (age < 7 * DAY) groups["This week"].push(p);else groups.Earlier.push(p);}return Object.entries(groups).filter(([, items]) => items.length > 0);}export default function App() {const [projects, setProjects] = useState([]);const [selectedId, setSelectedId] = useState(null);const [creating, setCreating] = useState(false);const [newName, setNewName] = useState("");const [filter, setFilter] = useState("");const [error, setError] = useState("");const [auth, setAuth] = useState(null);const [showLogin, setShowLogin] = useState(false);const [authMode, setAuthMode] = useState("signin"); // signin | registerconst [authEmail, setAuthEmail] = useState("");const [authPassword, setAuthPassword] = useState("");const [authName, setAuthName] = useState("");const [authError, setAuthError] = useState("");const [authBusy, setAuthBusy] = useState(false);const loadProjects = () =>api.listProjects().then(setProjects).catch((e) => setError(e.message));const loadAuth = () => api.authMe().then(setAuth).catch(() => {});useEffect(() => {loadProjects();loadAuth();// Surface Google sign-in failures passed back via redirect.const params = new URLSearchParams(window.location.search);const authFail = params.get("auth_error");if (authFail) {setError(`Sign-in problem: ${authFail.replaceAll("-", " ")}.`);window.history.replaceState({}, "", "/");}}, []);async function handleAuthSubmit(e) {e.preventDefault();setAuthError("");setAuthBusy(true);try {if (authMode === "register") {await api.register({ email: authEmail.trim(), password: authPassword, name: authName.trim() });} else {await api.login({ email: authEmail.trim(), password: authPassword });}setShowLogin(false);setAuthEmail("");setAuthPassword("");setAuthName("");await Promise.all([loadAuth(), loadProjects()]); // owned projects appear on sign-in} catch (err) {setAuthError(err.message);} finally {setAuthBusy(false);}}async function handleLogout() {try {await api.logout();await Promise.all([loadAuth(), loadProjects()]);} catch (err) {setError(err.message);}}useEffect(() => {if (projects.length === 0) {setSelectedId(null);return;}if (!selectedId || !projects.some((p) => p.id === selectedId)) {setSelectedId(projects[0].id);}}, [projects, selectedId]);async function createProject(e) {e.preventDefault();if (!newName.trim()) return;9 unmodified lines}const selected = projects.find((p) => p.id === selectedId) || null;const normalizedFilter = filter.trim().toLowerCase();const visibleProjects = projects.filter((p) =>p.name.toLowerCase().includes(normalizedFilter));return (<div className="app">2 unmodified lines<span className="sub">Contextualized Construct Representations · theory-driven psychological text analysis</span><span className="header-auth">{auth?.signed_in ? (<><span className="small">Hi, {auth.name}</span><button className="header-btn" onClick={handleLogout}>Sign out</button></>) : (<button className="header-btn" onClick={() => setShowLogin(true)}>Sign in</button>)}</span></header>{showLogin && (<div className="modal-backdrop" onClick={() => setShowLogin(false)}><div className="modal" onClick={(e) => e.stopPropagation()}><h3>{authMode === "register" ? "Create an account" : "Sign in"}</h3><p className="hint">Accounts are free. Signing in lifts the anonymous limits{auth?.limits?.max_rows? ` (${Math.round(auth.limits.max_bytes / 1048576)} MB / ${auth.limits.max_rows.toLocaleString()} rows per file, ${auth?.usage?.max_runs_per_day ?? 3} runs/day)`: ""}{" "}and keeps your datasets and runs instead of deleting them after analysis.</p>{authError && <p className="small" style={{ color: "var(--danger, #b3261e)" }}>{authError}</p>}{auth?.google_available && (<><a className="primary google-btn" href="/api/auth/google/login">Continue with Google</a><p className="small muted" style={{ textAlign: "center", margin: "8px 0" }}>or use email and password</p></>)}<form onSubmit={handleAuthSubmit} className="mt">{authMode === "register" && (<label className="field">Name<inputtype="text"autoFocusvalue={authName}onChange={(e) => setAuthName(e.target.value)}placeholder="e.g. Mohammad"/></label>)}<label className="field"><inputtype="email"autoFocus={authMode === "signin"}value={authEmail}onChange={(e) => setAuthEmail(e.target.value)}placeholder="you@example.com"/></label><label className="field">Password{authMode === "register" && (<span className="field-hint"> at least 8 characters</span>)}<inputtype="password"value={authPassword}onChange={(e) => setAuthPassword(e.target.value)}/></label><div className="row"><buttonclassName="primary"type="submit"disabled={authBusy ||!authEmail.trim() ||!authPassword ||(authMode === "register" && !authName.trim())}>{authBusy ? "…" : authMode === "register" ? "Create account" : "Sign in"}</button><button className="ghost" type="button" onClick={() => setShowLogin(false)}>Cancel</button></div></form><p className="small muted mt">{authMode === "register" ? (<>Already have an account?{" "}<button className="linkish" onClick={() => { setAuthMode("signin"); setAuthError(""); }}>Sign in</button></>) : (<>New here?{" "}<button className="linkish" onClick={() => { setAuthMode("register"); setAuthError(""); }}>Create a free account</button></>)}{auth?.google_available? " · Forgot your password? Contact the lab admin, or use Google.": " · Google sign-in arrives with lab accounts. Forgot your password? Contact the lab admin."}</p></div></div>)}<div className="layout"><aside className="sidebar"><h2>Projects{projects.length > 0 && <span className="count">{projects.length}</span>}</h2><inputtype="text"className="sidebar-filter"placeholder="Search projects..."value={filter}onChange={(e) => setFilter(e.target.value)}/><div className="project-list">{groupProjects(visibleProjects).map(([groupLabel, items]) => (<div key={groupLabel}><div className="group-label">{groupLabel}</div>{items.map((p) => (<buttonkey={p.id}className={"project-item" + (p.id === selectedId ? " active" : "")}onClick={() => setSelectedId(p.id)}title={p.name}><span className="project-name">{p.name}</span><span className="date">{p.n_runs > 0 ? `${p.n_runs} run${p.n_runs === 1 ? "" : "s"} · ` : ""}{relativeTime(p.last_activity_at || p.created_at)}</span></button>))}</div>))}{filter && visibleProjects.length === 0 && (<p className="small muted">No projects match "{filter}".</p>)}</div><div className="project-create">{creating ? (<form onSubmit={createProject}><inputtype="text"autoFocusplaceholder="Project name"value={newName}onChange={(e) => setNewName(e.target.value)}/><div className="row mt"><button className="primary" type="submit">Create</button><button className="ghost" type="button" onClick={() => setCreating(false)}>Cancel</button></div></form>) : (<button className="ghost" onClick={() => setCreating(true)}>+ New project</button>)}</div></aside><main className="main">3 unmodified lines</div>)}{selected ? (<Workspacekey={selected.id}project={selected}auth={auth}onAuthRefresh={loadAuth}onProjectChanged={loadProjects}onProjectDeleted={() => {setSelectedId(null);loadProjects();}}/>) : (<div className="card"><h3>Welcome</h3>3 unmodified linesscore distributions, and a reproducibility record for every run.</p><p className="small muted">Self-contained by design: embeddings run on this server itself - nothird-party AI APIs. Demo instance: storage is ephemeral and may reset;please don't upload sensitive or identifiable data.</p>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206import { useEffect, useMemo, useRef, useState } from "react";
// Searchable, grouped construct picker. A flat dropdown stops working past// ~15 options; the library is at 99 and growing. Researchers either know the// scale ("GAD-7") or the family ("empathy"), so search matches name, category,// and questionnaire, results group by category, and the last 5 used constructs// stay on top (researchers re-run the same scales constantly).// Keyboard: ArrowUp/Down move, Enter selects, Escape closes.
const RECENT_KEY = "ccr_recent_constructs";const RECENT_MAX = 5;
function readRecent() { try { return JSON.parse(localStorage.getItem(RECENT_KEY) || "[]"); } catch { return []; }}
export function rememberRecent(id) { const next = [id, ...readRecent().filter((x) => x !== id)].slice(0, RECENT_MAX); try { localStorage.setItem(RECENT_KEY, JSON.stringify(next)); } catch { /* storage unavailable: recents simply don't persist */ }}
export default function ConstructPicker({ constructs, value, onChange }) { const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); const [active, setActive] = useState(0); const rootRef = useRef(null); const inputRef = useRef(null); const listRef = useRef(null);
const selected = constructs.find((c) => c.id === value) || null;
const groups = useMemo(() => { const q = query.trim().toLowerCase(); const match = (c) => !q || c.name.toLowerCase().includes(q) || (c.category || "").toLowerCase().includes(q); const filtered = constructs.filter(match);
const out = []; const used = new Set();
const recentIds = readRecent(); const recent = recentIds .map((id) => filtered.find((c) => c.id === id)) .filter(Boolean); if (recent.length) { out.push(["Recently used", recent]); recent.forEach((c) => used.add(c.id)); }
const custom = filtered.filter((c) => !c.is_seed && !used.has(c.id)); if (custom.length) { out.push(["My custom constructs", custom]); custom.forEach((c) => used.add(c.id)); }
const byCategory = new Map(); for (const c of filtered) { if (used.has(c.id)) continue; const cat = c.category || "Other"; if (!byCategory.has(cat)) byCategory.set(cat, []); byCategory.get(cat).push(c); } for (const cat of [...byCategory.keys()].sort((a, b) => a.localeCompare(b))) { out.push([cat, byCategory.get(cat).sort((a, b) => a.name.localeCompare(b.name))]); } return out; }, [constructs, query]);
const flat = useMemo(() => groups.flatMap(([, items]) => items), [groups]);
useEffect(() => setActive(0), [query, open]);
// Close on outside click. useEffect(() => { if (!open) return undefined; const onDown = (e) => { if (rootRef.current && !rootRef.current.contains(e.target)) setOpen(false); }; document.addEventListener("mousedown", onDown); return () => document.removeEventListener("mousedown", onDown); }, [open]);
// Keep the active option scrolled into view. useEffect(() => { const el = listRef.current?.querySelector('[data-active="true"]'); el?.scrollIntoView({ block: "nearest" }); }, [active, open]);
function choose(c) { onChange(c.id); rememberRecent(c.id); setOpen(false); setQuery(""); }
function onKeyDown(e) { if (e.key === "ArrowDown") { e.preventDefault(); setActive((a) => Math.min(a + 1, flat.length - 1)); } else if (e.key === "ArrowUp") { e.preventDefault(); setActive((a) => Math.max(a - 1, 0)); } else if (e.key === "Enter") { e.preventDefault(); if (flat[active]) choose(flat[active]); } else if (e.key === "Escape") { setOpen(false); } }
let index = -1; // running index across groups for keyboard highlight
return ( <div className="picker" ref={rootRef}> {!open ? ( <button type="button" className="picker-display" aria-haspopup="listbox" aria-expanded="false" onClick={() => { setOpen(true); setTimeout(() => inputRef.current?.focus(), 0); }} > {selected ? ( <> <span>{selected.name}</span> <span className="picker-meta"> {selected.items.length} item{selected.items.length === 1 ? "" : "s"} </span> </> ) : ( <span className="muted">Select a construct ({constructs.length} in library)</span> )} <span className="picker-caret" aria-hidden="true">▾</span> </button> ) : ( <> <input ref={inputRef} type="text" role="combobox" aria-expanded="true" aria-autocomplete="list" className="picker-search" placeholder="Search by scale, construct, or category (e.g. empathy, GAD-7)" value={query} onChange={(e) => setQuery(e.target.value)} onKeyDown={onKeyDown} /> <div className="picker-panel" role="listbox" ref={listRef}> {flat.length === 0 && ( <p className="small muted picker-empty"> No constructs match "{query}". Try a scale abbreviation or use + Custom construct. </p> )} {groups.map(([label, items]) => ( <div key={label}> <div className="picker-group">{label}</div> {items.map((c) => { index += 1; const isActive = index === active; return ( <div key={c.id} role="option" aria-selected={c.id === value} data-active={isActive || undefined} className={ "picker-option" + (isActive ? " active" : "") + (c.id === value ? " selected" : "") } onMouseDown={(e) => { e.preventDefault(); choose(c); }} > <span className="picker-name">{c.name}</span> <span className="picker-meta"> {c.category ? `${c.category} · ` : ""} {c.items.length} item{c.items.length === 1 ? "" : "s"} {c.verification_status !== "verified" ? " · unverified" : ""} </span> </div> ); })} </div> ))} </div> </> )} </div> );}24 unmodified lines252627282930313233343536373825 unmodified lines646566676869708 unmodified lines7980818283848524 unmodified lines1101111121131141151161 unmodified line11811912012112212312411 unmodified lines13613713813914014114214314414514614714814915015115215315415515615724 unmodified linesreturn (<><div className="row" style={{ justifyContent: "space-between", marginBottom: 14 }}><button className="ghost" onClick={onBack}>← Back to workspace</button><div className="row"><a href={api.exportUrl(jobId)}><button className="primary">Export results CSV</button></a><a href={api.metadataUrl(jobId)}><button className="ghost">Run metadata (JSON)</button></a>25 unmodified lines<strong className="small">Data-quality notes</strong><ul className="small" style={{ margin: "4px 0 0", paddingLeft: 20 }}>{summary.warnings.map((w, i) => (<li key={i}>{w}</li>))}</ul></div>8 unmodified lines<div className="card"><h3>Per-item mean loadings</h3><p className="hint">Mean similarity of the corpus to each scale item — a face-validity check on whichitems drive the construct signal.</p>{summary.item_means.map((m, i) => (24 unmodified lines</div><div className="meta-footer"><strong>Reproducibility record</strong> — model: <code>{metadata.model}</code> (dim{" "}{metadata.embedding_dim}) · items hash: <code>{metadata.items_sha256_16}</code> ·text column: <code>{metadata.text_column}</code> · run:{" "}{metadata.started_at} → {metadata.finished_at} ({metadata.duration_seconds}s) ·1 unmodified line{metadata.sentence_transformers &&` · sentence-transformers ${metadata.sentence_transformers}`}<div className="mt small">Construct reference: {metadata.construct_reference || "—"}</div></div></>11 unmodified linesfunction DocTable({ docs }) {return (<table className="docs"><thead><tr><th style={{ width: 60 }}>Score</th><th>Text</th></tr></thead><tbody>{docs.map((d) => (<tr key={d.row}><td className="score">{d.score.toFixed(3)}</td><td>{d.text}</td></tr>))}</tbody></table>);}24 unmodified lines252627282930313233343536373839404142434425 unmodified lines707172737475767778798081828 unmodified lines9192939495969724 unmodified lines1221231241251261271281 unmodified line13013113213313413513611 unmodified lines14814915015115215315415515615715815916016116216316416516616716816917017124 unmodified linesreturn (<><div className="results-toolbar"><button className="ghost" onClick={onBack}>← Back to workspace</button><div className="row result-actions"><a href={api.exportUrl(jobId)}><button className="primary">Export results CSV</button></a><a href={api.scriptUrl(jobId)}><button className="ghost">Python script</button></a><a href={api.scriptRequirementsUrl(jobId)}><button className="ghost">requirements.txt</button></a><a href={api.metadataUrl(jobId)}><button className="ghost">Run metadata (JSON)</button></a>25 unmodified lines<strong className="small">Data-quality notes</strong><ul className="small" style={{ margin: "4px 0 0", paddingLeft: 20 }}>{summary.warnings.map((w, i) => (<li key={i}>{typeof w === "string" ? w : (<><code style={{ fontSize: 11 }}>{w.code}</code> - {w.message}</>)}</li>))}</ul></div>8 unmodified lines<div className="card"><h3>Per-item mean loadings</h3><p className="hint">Mean similarity of the corpus to each scale item - a face-validity check on whichitems drive the construct signal.</p>{summary.item_means.map((m, i) => (24 unmodified lines</div><div className="meta-footer"><strong>Reproducibility record</strong> - model: <code>{metadata.model}</code> (dim{" "}{metadata.embedding_dim}) · items hash: <code>{metadata.items_sha256_16}</code> ·text column: <code>{metadata.text_column}</code> · run:{" "}{metadata.started_at} → {metadata.finished_at} ({metadata.duration_seconds}s) ·1 unmodified line{metadata.sentence_transformers &&` · sentence-transformers ${metadata.sentence_transformers}`}<div className="mt small">Construct reference: {metadata.construct_reference || "-"}</div></div></>11 unmodified linesfunction DocTable({ docs }) {return (<div className="table-wrap"><table className="docs"><thead><tr><th style={{ width: 60 }}>Score</th><th>Text</th></tr></thead><tbody>{docs.map((d) => (<tr key={d.row}><td className="score">{d.score.toFixed(3)}</td><td>{d.text}</td></tr>))}</tbody></table></div>);}
123456783 unmodified lines121314151617181920212223246 unmodified lines31323334353637383937 unmodified lines777879808182838423 unmodified lines10810911011111211311411511611711811912013 unmodified lines13413513613713813914010 unmodified lines1511521531541551561579 unmodified lines1671681691701711721732 unmodified lines1761771781791801811821831841851861871881891901914 unmodified lines19619719819920020120220320420520620710 unmodified lines2182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203212 unmodified lines32432532632732832915 unmodified lines345346347348349350351352353354import { useCallback, useEffect, useRef, useState } from "react";import { api } from "./api.js";import ResultsView from "./ResultsView.jsx";export default function Workspace({ project }) {const [corpora, setCorpora] = useState([]);const [constructs, setConstructs] = useState([]);const [models, setModels] = useState([]);3 unmodified linesconst [textColumn, setTextColumn] = useState("");const [constructId, setConstructId] = useState("");const [modelName, setModelName] = useState("");const [uploading, setUploading] = useState(false);const [running, setRunning] = useState(false);const [error, setError] = useState("");const [showNewConstruct, setShowNewConstruct] = useState(false);const [viewJobId, setViewJobId] = useState(null);const fileRef = useRef(null);const refreshJobs = useCallback(() => api.listJobs(project.id).then(setJobs).catch(() => {}),[project.id]6 unmodified lines.models().then((m) => {setModels(m);if (m.length) setModelName(m[0].name);}).catch((e) => setError(e.message));refreshJobs();}, [project.id, refreshJobs]);37 unmodified linesconstruct_id: constructId,text_column: textColumn,model_name: modelName,});await refreshJobs();} catch (err) {setError(err.message);} finally {23 unmodified lines</div>)}{/* Step 1 — corpus */}<div className="card"><h3><span className="step-badge">1</span>Corpus</h3><p className="hint">Upload a CSV or XLSX file, then choose the column containing the text to analyze.</p><div className="row"><div className="grow">13 unmodified lines<label className="field">Corpus<select value={corpusId} onChange={(e) => setCorpusId(e.target.value)}><option value="">— select —</option>{corpora.map((c) => (<option key={c.id} value={c.id}>{c.filename} ({c.n_rows.toLocaleString()} rows)10 unmodified linesonChange={(e) => setTextColumn(e.target.value)}disabled={!corpus}><option value="">— select —</option>{corpus?.columns.map((col) => (<option key={col} value={col}>{col}9 unmodified lines)}</div>{/* Step 2 — construct */}<div className="card"><h3><span className="step-badge">2</span>Construct2 unmodified linesPick a validated scale from the library, or define custom items. CCR scores eachtext by its similarity to these items.</p><div className="row"><div className="grow"><select value={constructId} onChange={(e) => setConstructId(e.target.value)}><option value="">— select construct —</option>{constructs.map((c) => (<option key={c.id} value={c.id}>{c.name} ({c.items.length} items{c.is_seed ? ", library" : ", custom"})</option>))}</select></div><button className="ghost" onClick={() => setShowNewConstruct((s) => !s)}>{showNewConstruct ? "Close" : "+ Custom construct"}4 unmodified lines<><ul className="construct-items">{construct.items.map((item, i) => (<li key={i}>{item}</li>))}</ul>{construct.reference && (<p className="small muted mt">Reference: {construct.reference}</p>)}</>)}10 unmodified lines)}</div>{/* Step 3 — model + run */}<div className="card"><h3><span className="step-badge">3</span>Model & run</h3><p className="hint">Embeddings run locally via sentence-transformers; the model is pinned and recordedin the run metadata for reproducibility.</p><div className="row"><div className="grow"><select value={modelName} onChange={(e) => setModelName(e.target.value)}>{models.map((m) => (<option key={m.name} value={m.name}>{m.label}</option>))}</select></div><button className="primary" disabled={!canRun} onClick={handleRun}>{running ? "Starting…" : "Run CCR analysis"}</button></div></div>{/* Jobs */}{jobs.length > 0 && (<div className="card"><h3>Runs</h3><table className="docs"><thead><tr><th>Started</th><th>Corpus</th><th>Construct</th><th style={{ width: "24%" }}>Status</th><th /></tr></thead><tbody>{jobs.map((j) => (<tr key={j.id}><td className="muted">{(j.started_at || j.created_at).replace("T", " ").slice(0, 16)}</td><td>{j.corpus_filename}</td><td>{j.construct_name}</td><td>{j.status === "running" ? (<div className="progress-track" title={`${Math.round(j.progress * 100)}%`}><divclassName="progress-fill"style={{ width: `${Math.max(3, j.progress * 100)}%` }}/></div>) : (<span className={`pill ${j.status}`}>{j.status}</span>)}{j.status === "failed" && (<div className="small muted" title={j.error}>{j.error.split("\n").pop()}</div>)}</td><td>{j.status === "completed" && (<button className="linkish" onClick={() => setViewJobId(j.id)}>View results</button>)}</td></tr>))}</tbody></table></div>)}</>);}function NewConstructForm({ onCreated, onError }) {const [name, setName] = useState("");const [reference, setReference] = useState("");const [itemsText, setItemsText] = useState("");const [saving, setSaving] = useState(false);async function save(e) {e.preventDefault();const items = itemsText.split("\n").map((s) => s.trim()).filter(Boolean);if (!name.trim() || items.length === 0) {onError("A custom construct needs a name and at least one item (one per line).");return;}setSaving(true);try {const created = await api.createConstruct({ name: name.trim(), reference, items });onCreated(created);} catch (err) {onError(err.message);2 unmodified lines}}return (<form onSubmit={save} className="mt"><div className="row">15 unmodified lines</div></div><label className="field">Scale items — one per line, verbatim from the validated instrument<textarea rows={5} value={itemsText} onChange={(e) => setItemsText(e.target.value)} /></label><button className="primary" type="submit" disabled={saving}>{saving ? "Saving…" : "Save construct"}</button></form>1234567893 unmodified lines1314151617181920212223242526272829303132333435363738394041424344454647486 unmodified lines555657585960616263646537 unmodified lines10310410510610710810911011111223 unmodified lines13613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221313 unmodified lines22722822923023123223310 unmodified lines2442452462472482492509 unmodified lines2602612622632642652662 unmodified lines2692702712722732742752762772782792802814 unmodified lines28628728828929029129229329429529629729829930030130230330430530610 unmodified lines3173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005012 unmodified lines50450550650750850951051115 unmodified lines527528529530531532533534535536537538539540541542543544545546547548549550551552553554555import { useCallback, useEffect, useRef, useState } from "react";import { api } from "./api.js";import ConstructPicker from "./ConstructPicker.jsx";import ResultsView from "./ResultsView.jsx";export default function Workspace({ project, auth, onAuthRefresh, onProjectChanged, onProjectDeleted }) {const [corpora, setCorpora] = useState([]);const [constructs, setConstructs] = useState([]);const [models, setModels] = useState([]);3 unmodified linesconst [textColumn, setTextColumn] = useState("");const [constructId, setConstructId] = useState("");const [modelName, setModelName] = useState("");const [languages, setLanguages] = useState(["en"]);const [language, setLanguage] = useState("en");const [uploading, setUploading] = useState(false);const [running, setRunning] = useState(false);const [error, setError] = useState("");const [showNewConstruct, setShowNewConstruct] = useState(false);const [viewJobId, setViewJobId] = useState(null);const [confirmDelete, setConfirmDelete] = useState(false);const [deleteText, setDeleteText] = useState("");const fileRef = useRef(null);async function toggleArchive() {try {await api.patchProject(project.id, { archived: !project.archived });onProjectChanged?.();} catch (err) {setError(err.message);}}async function handleDelete() {try {await api.deleteProject(project.id);setConfirmDelete(false);onProjectDeleted?.();} catch (err) {setError(err.message);}}const refreshJobs = useCallback(() => api.listJobs(project.id).then(setJobs).catch(() => {}),[project.id]6 unmodified lines.models().then((m) => {setModels(m);const def = m.find((x) => x.default) || m[0];if (def) setModelName(def.id);}).catch((e) => setError(e.message));api.languages().then(setLanguages).catch(() => {});refreshJobs();}, [project.id, refreshJobs]);37 unmodified linesconstruct_id: constructId,text_column: textColumn,model_name: modelName,language,});await refreshJobs();onAuthRefresh?.(); // anonymous run counter changed} catch (err) {setError(err.message);} finally {23 unmodified lines</div>)}{/* Project header + actions */}<div className="project-header"><div><span className="project-title">{project.name}</span>{project.archived && <span className="pill queued">archived</span>}</div><div className="row"><button className="ghost" onClick={toggleArchive}>{project.archived ? "Unarchive" : "Archive"}</button><button className="ghost danger" onClick={() => setConfirmDelete(true)}>Delete</button></div></div>{confirmDelete && (<div className="modal-backdrop" onClick={() => setConfirmDelete(false)}><div className="modal" onClick={(e) => e.stopPropagation()}><h3>Delete "{project.name}"?</h3><p className="hint">This permanently deletes {corpora.length} dataset{corpora.length === 1 ? "" : "s"},{" "}{jobs.length} run{jobs.length === 1 ? "" : "s"}, and all uploaded and result files.This cannot be undone. If you might need it later, use Archive instead.</p><label className="field">Type the project name to confirm<inputtype="text"autoFocusvalue={deleteText}onChange={(e) => setDeleteText(e.target.value)}placeholder={project.name}/></label><div className="row"><buttonclassName="primary danger-solid"disabled={deleteText !== project.name}onClick={handleDelete}>Delete permanently</button><buttonclassName="ghost"onClick={() => {setConfirmDelete(false);setDeleteText("");}}>Cancel</button></div></div></div>)}{/* Step 1 - corpus */}<div className="card"><h3><span className="step-badge">1</span>Corpus</h3><p className="hint">Upload a CSV or XLSX file, then choose the column containing the text to analyze.{auth && !auth.signed_in && auth.limits?.max_rows && (<>{" "}Anonymous limit: {Math.round(auth.limits.max_bytes / 1048576)} MB /{" "}{auth.limits.max_rows.toLocaleString()} rows per file; uploads are deletedafter analysis. Sign in (top right) for larger uploads and to keep your data.</>)}</p><div className="row"><div className="grow">13 unmodified lines<label className="field">Corpus<select value={corpusId} onChange={(e) => setCorpusId(e.target.value)}><option value="">- select -</option>{corpora.map((c) => (<option key={c.id} value={c.id}>{c.filename} ({c.n_rows.toLocaleString()} rows)10 unmodified linesonChange={(e) => setTextColumn(e.target.value)}disabled={!corpus}><option value="">- select -</option>{corpus?.columns.map((col) => (<option key={col} value={col}>{col}9 unmodified lines)}</div>{/* Step 2 - construct */}<div className="card"><h3><span className="step-badge">2</span>Construct2 unmodified linesPick a validated scale from the library, or define custom items. CCR scores eachtext by its similarity to these items.</p><div className="construct-row"><div className="grow"><ConstructPickerconstructs={constructs}value={constructId}onChange={setConstructId}/></div><button className="ghost" onClick={() => setShowNewConstruct((s) => !s)}>{showNewConstruct ? "Close" : "+ Custom construct"}4 unmodified lines<><ul className="construct-items">{construct.items.map((item, i) => (<li key={i}>{item}{construct.reverse_scored?.[i] ? " (reverse-scored)" : ""}</li>))}</ul>{construct.reference && (<p className="small muted mt">Reference: {construct.reference}</p>)}{construct.verification_status !== "verified" && (<p className="small muted">⚠ Item wording not yet verified verbatim against the original publication(status: {construct.verification_status.replace("_", " ")}).</p>)}</>)}10 unmodified lines)}</div>{/* Step 3 - language, model + run */}<div className="card"><h3><span className="step-badge">3</span>Language, model & run</h3><p className="hint">Embeddings run locally via sentence-transformers; model and language are recordedin the run metadata. If the corpus doesn't match the selected language or themodel doesn't support it, you'll get a warning - never a silent result.</p><div className="run-settings"><label className="field language-control">Text language<select value={language} onChange={(e) => setLanguage(e.target.value)}>{languages.map((l) => (<option key={l} value={l}>{l}</option>))}</select></label><label className="field model-control">Embedding model<select value={modelName} onChange={(e) => setModelName(e.target.value)}>{models.map((m) => (<option key={m.id} value={m.id}>{m.label}</option>))}</select></label><button className="primary run-button" disabled={!canRun} onClick={handleRun}>{running ? "Starting…" : "Run CCR analysis"}</button></div>{auth && !auth.signed_in && auth.usage?.max_runs_per_day != null && (<p className="small muted">{Math.min(auth.usage.runs_used_today, auth.usage.max_runs_per_day)} of{" "}{auth.usage.max_runs_per_day} free runs used today{auth.usage.runs_used_today >= auth.usage.max_runs_per_day? " - sign in (top right) to keep running.": "."}</p>)}{auth?.signed_in && auth.usage?.max_saved_runs != null && (<p className="small muted">{auth.usage.saved_runs} of {auth.usage.max_saved_runs} saved runs used.</p>)}{models.find((m) => m.id === modelName)?.warnings?.map((w, i) => (<p key={i} className="small muted">⚠ {w}</p>))}</div>{/* Jobs */}{jobs.length > 0 && (<div className="card"><h3>Runs</h3><div className="table-wrap"><table className="docs"><thead><tr><th>Started</th><th>Corpus</th><th>Construct</th><th>Model</th><th>Lang</th><th style={{ width: "20%" }}>Status</th><th /></tr></thead><tbody>{jobs.map((j) => (<tr key={j.id}><td className="muted">{(j.started_at || j.created_at).replace("T", " ").slice(0, 16)}</td><td>{j.corpus_filename}</td><td>{j.construct_name}</td><td className="muted small">{j.model_name}</td><td className="muted small">{j.language}</td><td>{j.status === "running" ? (<div className="progress-track" title={`${Math.round(j.progress * 100)}%`}><divclassName="progress-fill"style={{ width: `${Math.max(3, j.progress * 100)}%` }}/></div>) : (<span className={`pill ${j.status}`}>{j.status}</span>)}{j.status === "failed" && (<div className="small muted" title={j.error}>{j.error.split("\n").pop()}</div>)}</td><td>{j.status === "completed" && (<button className="linkish" onClick={() => setViewJobId(j.id)}>View results</button>)}</td></tr>))}</tbody></table></div></div>)}</>);}const REVERSE_SUFFIX = /\s*\((r|rev|reversed)\)\s*$/i;function NewConstructForm({ onCreated, onError }) {const [name, setName] = useState("");const [reference, setReference] = useState("");const [itemsText, setItemsText] = useState("");const [saving, setSaving] = useState(false);const [parsing, setParsing] = useState(false);const [parseNotes, setParseNotes] = useState([]);const itemFileRef = useRef(null);// Convention shared with the file parser and the lab's own spreadsheets:// a trailing (R) marks a reverse-scored item.function parseLines() {return itemsText.split("\n").map((s) => s.trim()).filter(Boolean).map((line) => ({text: line.replace(REVERSE_SUFFIX, "").trim(),reverse: REVERSE_SUFFIX.test(line),}));}async function handleItemFile(e) {const file = e.target.files?.[0];if (!file) return;setParsing(true);setParseNotes([]);try {const parsed = await api.parseConstructFile(file);setItemsText(parsed.items.map((i) => (i.reverse_scored ? `${i.text} (R)` : i.text)).join("\n"));if (!name.trim() && parsed.suggested_name) setName(parsed.suggested_name);setParseNotes(parsed.warnings || []);} catch (err) {onError(err.message);} finally {setParsing(false);if (itemFileRef.current) itemFileRef.current.value = "";}}async function save(e) {e.preventDefault();const parsed = parseLines();if (!name.trim() || parsed.length === 0) {onError("A custom construct needs a name and at least one item (one per line).");return;}setSaving(true);try {const created = await api.createConstruct({name: name.trim(),reference,items: parsed.map((i) => i.text),reverse_scored: parsed.map((i) => i.reverse),});onCreated(created);} catch (err) {onError(err.message);2 unmodified lines}}const nReverse = parseLines().filter((i) => i.reverse).length;return (<form onSubmit={save} className="mt"><div className="row">15 unmodified lines</div></div><label className="field">Upload items from CSV/XLSX (optional) - an "item" column, or one item per row;reverse-scored via a "reverse" column or a trailing (R)<inputref={itemFileRef}type="file"accept=".csv,.xlsx,.xls"onChange={handleItemFile}disabled={parsing}/></label>{parsing && <p className="small muted">Parsing…</p>}{parseNotes.map((w, i) => (<p key={i} className="small muted">⚠ {w}</p>))}<label className="field">Scale items - one per line, verbatim from the validated instrument; append (R) tomark a reverse-scored item<textarea rows={6} value={itemsText} onChange={(e) => setItemsText(e.target.value)} /></label>{nReverse > 0 && (<p className="small muted">{nReverse} item(s) marked reverse-scored.</p>)}<button className="primary" type="submit" disabled={saving || parsing}>{saving ? "Saving…" : "Save construct"}</button></form>
24 unmodified lines2526272829303132334 unmodified lines3839404142432 unmodified lines4647484924 unmodified linesexport const api = {health: () => request("/api/health"),models: () => request("/api/models"),listProjects: () => request("/api/projects"),createProject: (body) => request("/api/projects", json("POST", body)),listCorpora: (projectId) => request(`/api/projects/${projectId}/corpora`),uploadCorpus: (projectId, file) => {4 unmodified lineslistConstructs: () => request("/api/constructs"),createConstruct: (body) => request("/api/constructs", json("POST", body)),createJob: (body) => request("/api/jobs", json("POST", body)),listJobs: (projectId) => request(`/api/jobs?project_id=${projectId}`),2 unmodified linesexportUrl: (jobId) => `/api/jobs/${jobId}/export`,metadataUrl: (jobId) => `/api/jobs/${jobId}/metadata`,};24 unmodified lines25262728293031323334353637383940414 unmodified lines46474849505152535455562 unmodified lines59606162636424 unmodified linesexport const api = {health: () => request("/api/health"),models: () => request("/api/models"),languages: () => request("/api/languages"),listProjects: () => request("/api/projects"),createProject: (body) => request("/api/projects", json("POST", body)),patchProject: (projectId, body) => request(`/api/projects/${projectId}`, json("PATCH", body)),deleteProject: (projectId) => fetch(`/api/projects/${projectId}`, { method: "DELETE" }),authMe: () => request("/api/auth/me"),register: (body) => request("/api/auth/register", json("POST", body)),login: (body) => request("/api/auth/login", json("POST", body)),logout: () => request("/api/auth/logout", { method: "POST" }),listCorpora: (projectId) => request(`/api/projects/${projectId}/corpora`),uploadCorpus: (projectId, file) => {4 unmodified lineslistConstructs: () => request("/api/constructs"),createConstruct: (body) => request("/api/constructs", json("POST", body)),parseConstructFile: (file) => {const form = new FormData();form.append("file", file);return request("/api/constructs/parse-file", { method: "POST", body: form });},createJob: (body) => request("/api/jobs", json("POST", body)),listJobs: (projectId) => request(`/api/jobs?project_id=${projectId}`),2 unmodified linesexportUrl: (jobId) => `/api/jobs/${jobId}/export`,metadataUrl: (jobId) => `/api/jobs/${jobId}/metadata`,scriptUrl: (jobId) => `/api/jobs/${jobId}/script`,scriptRequirementsUrl: (jobId) => `/api/jobs/${jobId}/script-requirements`,};
8 unmodified lines9101112131416 unmodified lines3132333435363738394041422 unmodified lines4546474849505152535455565758596061626364656667686970716 unmodified lines7879808182838485868788899091921 unmodified line94959697989910010110210310410510610710810918 unmodified lines1281291301311321331341351361371381395 unmodified lines14514614714814915015111 unmodified lines1631641658 unmodified lines--ok: #157f3d;--err: #b42318;--accent-soft: #f6ebef;}* { box-sizing: border-box; }16 unmodified linespadding: 14px 28px;display: flex;align-items: baseline;gap: 14px;}.header h1 { font-size: 17px; margin: 0; font-weight: 650; letter-spacing: 0.2px; }.header .sub { font-size: 12.5px; opacity: 0.85; }.layout { display: flex; flex: 1; min-height: 0; }/* ---------- sidebar ---------- */.sidebar {2 unmodified linesborder-right: 1px solid var(--line);padding: 18px 14px;flex-shrink: 0;}.sidebar h2 {font-size: 11.5px; text-transform: uppercase; letter-spacing: 0.7px;color: var(--muted); margin: 0 0 10px 4px;}.project-item {display: block; width: 100%; text-align: left;padding: 9px 12px; margin-bottom: 4px;border: 1px solid transparent; border-radius: 8px;background: none; cursor: pointer; font: inherit; color: var(--ink);}.project-item:hover { background: var(--bg); }.project-item.active { background: var(--accent-soft); border-color: var(--maroon); font-weight: 600; }.project-item .date { display: block; font-size: 11.5px; color: var(--muted); font-weight: 400; }/* ---------- main ---------- */.main { flex: 1; padding: 22px 28px; overflow-y: auto; min-width: 0; }.card {background: var(--card); border: 1px solid var(--line);border-radius: 10px; padding: 18px 20px; margin-bottom: 16px;}.card h3 { margin: 0 0 4px; font-size: 15px; }.card .hint { color: var(--muted); font-size: 12.5px; margin: 0 0 12px; }6 unmodified lines}/* ---------- controls ---------- */button.primary {background: var(--maroon); color: #fff; border: none;padding: 9px 18px; border-radius: 8px; font: inherit; font-weight: 600; cursor: pointer;}button.primary:hover { background: var(--maroon-dark); }button.primary:disabled { background: #c9ccd1; cursor: not-allowed; }button.ghost {background: none; border: 1px solid var(--line); color: var(--ink);padding: 8px 14px; border-radius: 8px; font: inherit; cursor: pointer;}button.ghost:hover { border-color: var(--maroon); color: var(--maroon); }button.linkish {1 unmodified linefont: inherit; cursor: pointer; padding: 0; text-decoration: underline;}input[type="text"], textarea, select {width: 100%; padding: 8px 10px; border: 1px solid var(--line);border-radius: 8px; font: inherit; background: #fff; color: var(--ink);}textarea { resize: vertical; }label.field { display: block; margin-bottom: 10px; font-size: 13px; font-weight: 600; }label.field > * { margin-top: 4px; font-weight: 400; }.row { display: flex; gap: 14px; flex-wrap: wrap; }.row > .grow { flex: 1; min-width: 220px; }/* ---------- misc ---------- */.pill {18 unmodified linespadding: 10px 14px; border-radius: 8px; margin-bottom: 14px; font-size: 13px;}table.docs { width: 100%; border-collapse: collapse; font-size: 13px; }table.docs th {text-align: left; color: var(--muted); font-size: 11.5px; text-transform: uppercase;letter-spacing: 0.5px; padding: 6px 8px; border-bottom: 1px solid var(--line);}table.docs td { padding: 7px 8px; border-bottom: 1px solid var(--bg); vertical-align: top; }table.docs td.score { font-variant-numeric: tabular-nums; font-weight: 600; white-space: nowrap; }.stat-grid { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 4px; }5 unmodified lines.stat .k { font-size: 11.5px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px; }.item-bar-row { display: flex; align-items: center; gap: 10px; margin-bottom: 7px; }.item-bar-label { flex: 1; font-size: 12.5px; min-width: 0; }.item-bar-track { flex: 1.2; background: var(--bg); border-radius: 999px; height: 10px; }.item-bar-fill { background: var(--maroon); opacity: 0.85; height: 100%; border-radius: 999px; }.item-bar-val { width: 52px; text-align: right; font-variant-numeric: tabular-nums; font-size: 12.5px; font-weight: 600; }11 unmodified lines.muted { color: var(--muted); }.small { font-size: 12.5px; }.mt { margin-top: 12px; }8 unmodified lines910111213141516 unmodified lines32333435363738394041424344454647484950512 unmodified lines545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171186 unmodified lines1251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601 unmodified line16216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623718 unmodified lines2562572582592602612622632642652662672682692702715 unmodified lines27727827928028128228311 unmodified lines2952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704718 unmodified lines--ok: #157f3d;--err: #b42318;--accent-soft: #f6ebef;--control-height: 40px;}* { box-sizing: border-box; }16 unmodified linespadding: 14px 28px;display: flex;align-items: baseline;flex-wrap: wrap;gap: 14px;}.header h1 {flex: 0 0 auto;font-size: 17px;margin: 0;font-weight: 650;letter-spacing: 0.2px;white-space: nowrap;}.header .sub { flex: 1 1 280px; min-width: 0; font-size: 12.5px; opacity: 0.85; }.layout { display: flex; flex: 1; min-width: 0; min-height: 0; }/* ---------- sidebar ---------- */.sidebar {2 unmodified linesborder-right: 1px solid var(--line);padding: 18px 14px;flex-shrink: 0;display: flex;flex-direction: column;min-height: 0;}.sidebar h2 {font-size: 11.5px; text-transform: uppercase; letter-spacing: 0.7px;color: var(--muted); margin: 0 0 10px 4px;display: flex; align-items: center; gap: 8px;}.sidebar h2 .count {background: var(--bg); border: 1px solid var(--line); border-radius: 999px;padding: 0 8px; font-size: 10.5px; letter-spacing: 0; color: var(--muted);}.sidebar-filter {width: 100%; padding: 7px 10px; margin-bottom: 10px;border: 1px solid var(--line); border-radius: 8px; font: inherit; font-size: 13px;background: #fff; color: var(--ink);}.sidebar-filter:focus { outline: none; border-color: var(--maroon); }.project-list {flex: 1;min-height: 0;overflow-y: auto;margin: 0 -4px;padding: 0 4px 4px;}.group-label {font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.6px;color: var(--muted); margin: 10px 4px 5px;}div:first-child > .group-label { margin-top: 2px; }.project-item {display: block; width: 100%; text-align: left;padding: 9px 12px; margin-bottom: 5px;border: 1px solid transparent; border-radius: 8px;background: none; cursor: pointer; font: inherit; color: var(--ink);}.project-item:hover { background: var(--bg); }.project-item.active { background: var(--accent-soft); border-color: var(--maroon); font-weight: 600; }.project-item .project-name {display: block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}.project-item .date { display: block; font-size: 11.5px; color: var(--muted); font-weight: 400; }.project-create {margin-top: 12px;padding-top: 12px;border-top: 1px solid var(--line);}.project-create > button { width: 100%; }/* ---------- main ---------- */.main { flex: 1; padding: 22px 28px; overflow-y: auto; min-width: 0; }.card {background: var(--card); border: 1px solid var(--line);border-radius: 8px; padding: 18px 20px; margin-bottom: 16px;}.card h3 { margin: 0 0 4px; font-size: 15px; }.card .hint { color: var(--muted); font-size: 12.5px; margin: 0 0 12px; }6 unmodified lines}/* ---------- controls ---------- */button { white-space: nowrap; }button.primary {background: var(--maroon); color: #fff; border: none;min-height: var(--control-height);display: inline-flex;align-items: center;justify-content: center;padding: 0 18px; border-radius: 8px; font: inherit; font-weight: 600; cursor: pointer;line-height: 1.2;}button.primary:hover { background: var(--maroon-dark); }button.primary:disabled { background: #c9ccd1; cursor: not-allowed; }a.google-btn {background: var(--maroon); color: #fff; border: none;min-height: var(--control-height);display: flex; align-items: center; justify-content: center;padding: 0 18px; border-radius: 8px; font: inherit; font-weight: 600;cursor: pointer; line-height: 1.2; text-decoration: none; width: 100%;box-sizing: border-box;}a.google-btn:hover { background: var(--maroon-dark); }button.ghost {background: none; border: 1px solid var(--line); color: var(--ink);min-height: var(--control-height);display: inline-flex;align-items: center;justify-content: center;padding: 0 14px; border-radius: 8px; font: inherit; cursor: pointer;line-height: 1.2;}button.ghost:hover { border-color: var(--maroon); color: var(--maroon); }button.linkish {1 unmodified linefont: inherit; cursor: pointer; padding: 0; text-decoration: underline;}input[type="text"], input[type="email"], input[type="password"], textarea, select {width: 100%; padding: 8px 10px; border: 1px solid var(--line);border-radius: 8px; font: inherit; background: #fff; color: var(--ink);}input[type="text"], input[type="email"], input[type="password"], select { height: var(--control-height); }button:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible {outline: 2px solid rgba(122, 31, 61, 0.38);outline-offset: 2px;}/* File input: block-level with breathing room under its label, and a styledpicker button so it matches the rest of the controls. */input[type="file"] {display: block; max-width: 100%; margin-top: 6px; font-size: 13px; color: var(--muted);}input[type="file"]::file-selector-button {background: #fff; border: 1px solid var(--line); color: var(--ink);padding: 7px 14px; border-radius: 8px; font: inherit; font-size: 13px;cursor: pointer; margin-right: 10px;}input[type="file"]::file-selector-button:hover {border-color: var(--maroon); color: var(--maroon);}/* Buttons inside a row of labeled fields align to the controls' baselineinstead of stretching to the row's full height. */.row > button { align-self: flex-end; margin-bottom: 1px; }textarea { resize: vertical; }label.field { display: block; margin-bottom: 10px; font-size: 13px; font-weight: 600; }label.field > * { margin-top: 4px; font-weight: 400; }.field-hint { margin-top: 0; font-weight: 400; color: var(--muted); font-size: 12px; }.row { display: flex; gap: 14px; flex-wrap: wrap; }.row > * { min-width: 0; }.row > .grow { flex: 1; min-width: min(220px, 100%); }.language-control { min-width: 170px; }.model-control { min-width: 260px; }.run-settings {display: grid;grid-template-columns: minmax(160px, 230px) minmax(320px, 720px) max-content;justify-content: start;gap: 14px;align-items: end;}.run-settings .field { margin-bottom: 0; }.run-button {min-width: 180px;height: var(--control-height);}.construct-row {display: grid;grid-template-columns: minmax(320px, 1120px) max-content;justify-content: start;align-items: end;gap: 14px;}.results-toolbar {display: flex;align-items: center;justify-content: space-between;gap: 14px;margin-bottom: 14px;flex-wrap: wrap;}.result-actions { justify-content: flex-end; }.result-actions a { display: inline-flex; text-decoration: none; }/* ---------- misc ---------- */.pill {18 unmodified linespadding: 10px 14px; border-radius: 8px; margin-bottom: 14px; font-size: 13px;}.table-wrap { width: 100%; overflow-x: auto; }table.docs { width: 100%; border-collapse: collapse; font-size: 13px; }table.docs th {text-align: left; color: var(--muted); font-size: 11.5px; text-transform: uppercase;letter-spacing: 0.5px; padding: 6px 8px; border-bottom: 1px solid var(--line);}table.docs td {padding: 7px 8px; border-bottom: 1px solid var(--bg); vertical-align: top;overflow-wrap: anywhere;}table.docs td.score { font-variant-numeric: tabular-nums; font-weight: 600; white-space: nowrap; }.stat-grid { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 4px; }5 unmodified lines.stat .k { font-size: 11.5px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px; }.item-bar-row { display: flex; align-items: center; gap: 10px; margin-bottom: 7px; }.item-bar-label { flex: 1; font-size: 12.5px; min-width: 0; overflow-wrap: anywhere; }.item-bar-track { flex: 1.2; background: var(--bg); border-radius: 999px; height: 10px; }.item-bar-fill { background: var(--maroon); opacity: 0.85; height: 100%; border-radius: 999px; }.item-bar-val { width: 52px; text-align: right; font-variant-numeric: tabular-nums; font-size: 12.5px; font-weight: 600; }11 unmodified lines.muted { color: var(--muted); }.small { font-size: 12.5px; }.mt { margin-top: 12px; }/* ---------- header auth ---------- */.header-auth {margin-left: auto; display: flex; align-items: center; gap: 10px; color: #fff;}.header-btn {background: rgba(255, 255, 255, 0.12); color: #fff;border: 1px solid rgba(255, 255, 255, 0.45);padding: 5px 14px; border-radius: 7px; font: inherit; font-size: 13px; cursor: pointer;}.header-btn:hover { background: rgba(255, 255, 255, 0.22); }/* ---------- project header + actions ---------- */.project-header {display: flex; align-items: center; justify-content: space-between;gap: 12px; margin-bottom: 14px; flex-wrap: wrap;}.project-title { font-size: 17px; font-weight: 650; margin-right: 10px; }button.danger { color: var(--err); border-color: #f0c4be; }button.danger:hover { color: var(--err); border-color: var(--err); }button.danger-solid { background: var(--err); }button.danger-solid:hover { background: #93261b; }button.danger-solid:disabled { background: #c9ccd1; }/* ---------- construct picker (searchable, grouped) ---------- */.picker { position: relative; }.picker-display {width: 100%; display: flex; align-items: center; gap: 10px;padding: 8px 12px; border: 1px solid var(--line); border-radius: 8px;background: #fff; font: inherit; color: var(--ink); cursor: pointer; text-align: left;}.picker-display:hover { border-color: var(--maroon); }.picker-display .picker-caret { margin-left: auto; color: var(--muted); font-size: 11px; }.picker-search {width: 100%; padding: 8px 12px; border: 1px solid var(--maroon);border-radius: 8px; font: inherit; background: #fff;}.picker-search:focus { outline: none; box-shadow: 0 0 0 3px rgba(122, 31, 61, 0.12); }.picker-panel {position: absolute; top: calc(100% + 6px); left: 0; z-index: 50;width: 100%; max-width: 640px;background: var(--card); border: 1px solid var(--line); border-radius: 10px;box-shadow: 0 14px 40px rgba(0, 0, 0, 0.18);max-height: 340px; overflow-y: auto; padding: 4px 0 6px;}.picker-group {font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.6px;color: var(--muted); padding: 8px 12px 3px; position: sticky; top: 0;background: var(--card);}.picker-option {display: flex; align-items: baseline; justify-content: space-between; gap: 12px;padding: 6px 12px; cursor: pointer; font-size: 13.5px;}.picker-option:hover, .picker-option.active { background: var(--accent-soft); }.picker-option.selected .picker-name { font-weight: 650; color: var(--maroon); }.picker-name { min-width: 0; }.picker-meta { flex-shrink: 0; font-size: 11.5px; color: var(--muted); white-space: nowrap; }.picker-empty { padding: 12px; margin: 0; }/* ---------- modal ---------- */.modal-backdrop {position: fixed; inset: 0; background: rgba(20, 22, 26, 0.45);display: flex; align-items: center; justify-content: center; z-index: 40; padding: 16px;}.modal {background: var(--card); border-radius: 12px; padding: 26px 28px 24px;width: 100%; max-width: 460px; box-shadow: 0 12px 40px rgba(0, 0, 0, 0.18);}.modal h3 { margin: 0 0 8px; font-size: 18px; }/* Auth modal: roomier fields and clearer separation between sections. */.modal .hint { color: var(--muted); font-size: 13px; line-height: 1.5; margin: 0 0 4px; }.modal form.mt { margin-top: 18px; }.modal label.field { margin-bottom: 16px; }.modal label.field:last-of-type { margin-bottom: 20px; }.modal .row { gap: 10px; }.modal .row > .primary { flex: 1; }.modal p.small.muted.mt {margin-top: 18px; padding-top: 16px; border-top: 1px solid var(--line);font-size: 12.5px; line-height: 1.6;}@media (max-width: 820px) {body { font-size: 14px; }.header {padding: 12px 16px;align-items: flex-start;gap: 2px 12px;}.header h1 { font-size: 16px; }.header .sub {flex: 1 1 210px;font-size: 12px;line-height: 1.35;}.layout { display: block; }.sidebar {width: 100%;border-right: 0;border-bottom: 1px solid var(--line);padding: 14px;}.project-list {max-height: 220px;margin-right: 0;flex: none;}.project-create { border-top: 0; }.main {width: 100%;padding: 16px 14px 28px;overflow: visible;}.card {padding: 16px;margin-bottom: 14px;}.row,.run-settings,.construct-row,.results-toolbar,.result-actions {gap: 10px;}.row,.results-toolbar,.result-actions {flex-direction: column;align-items: stretch;}.run-settings,.construct-row {grid-template-columns: 1fr;}.row > .grow,.construct-row > .grow,.language-control,.model-control {width: 100%;min-width: 0;}.main .row > button,.main .row > a,.main .row > a > button,.results-toolbar > button {align-self: stretch;margin-bottom: 0;width: 100%;}.run-button {width: 100%;min-width: 0;}.stat-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); }.stat { min-width: 0; }.item-bar-row {display: grid;grid-template-columns: minmax(0, 1fr) 56px;gap: 6px 10px;}.item-bar-track { grid-column: 1 / -1; width: 100%; }.item-bar-val { width: auto; }table.docs { min-width: 520px; }}@media (max-width: 460px) {.header .sub { flex-basis: 100%; }.stat-grid { grid-template-columns: 1fr; }}
1234567891011# ccr_engine (Phase 1 target - spec 0005)
This package will hold the pure CCR analysis engine: preprocessing, embeddings (via the modelregistry), similarity, scoring/aggregation, warnings, stats, reproducibility artifacts -callable from the web app, worker, tests, CLI, and generated scripts.
Today the engine logic lives in `backend/app/ccr.py` + `backend/app/jobs.py`. Do NOT start theextraction ad hoc: it begins by freezing current behavior with golden evals (strangler step 1,design §7), then moves code behind the `run_ccr_analysis(...)` interface (design §10).
Boundary rule (enforced in review): nothing in this package may import from `backend/app`.123456789101112131415161718192021construct_id: collectivism_horizontalversion: 1name: Collectivism (Horizontal)language: encategory: cultural-orientationdescription: Interdependence, cooperation, and in-group well-being (Triandis & Gelfand horizontal collectivism).citation: "Triandis, H. C., & Gelfand, M. J. (1998). Converging measurement of horizontal and vertical individualism and collectivism. JPSP, 74(1)."verification_status: needs_verificationitems: - item_id: hc_1 text: "If a coworker gets a prize, I would feel proud." reverse_scored: false - item_id: hc_2 text: "The well-being of my coworkers is important to me." reverse_scored: false - item_id: hc_3 text: "To me, pleasure is spending time with others." reverse_scored: false - item_id: hc_4 text: "I feel good when I cooperate with others." reverse_scored: false123456789101112131415161718192021construct_id: individualism_horizontalversion: 1name: Individualism (Horizontal)language: encategory: cultural-orientationdescription: Self-reliance and independence from in-groups (Triandis & Gelfand horizontal individualism).citation: "Triandis, H. C., & Gelfand, M. J. (1998). Converging measurement of horizontal and vertical individualism and collectivism. JPSP, 74(1)."verification_status: needs_verificationitems: - item_id: hi_1 text: "I'd rather depend on myself than others." reverse_scored: false - item_id: hi_2 text: "I rely on myself most of the time; I rarely rely on others." reverse_scored: false - item_id: hi_3 text: "I often do my own thing." reverse_scored: false - item_id: hi_4 text: "My personal identity, independent of others, is very important to me." reverse_scored: false123456789101112131415161718192021construct_id: mfq_careversion: 1name: Moral Foundations - Carelanguage: encategory: moral-foundationsdescription: Concern with suffering, compassion, and protection of the vulnerable (MFQ Care/Harm).citation: "Graham, J., Nosek, B. A., Haidt, J., Iyer, R., Koleva, S., & Ditto, P. H. (2011). Mapping the moral domain. JPSP, 101(2)."verification_status: needs_verificationitems: - item_id: care_1 text: "Compassion for those who are suffering is the most crucial virtue." reverse_scored: false - item_id: care_2 text: "One of the worst things a person could do is hurt a defenseless animal." reverse_scored: false - item_id: care_3 text: "Whether or not someone suffered emotionally." reverse_scored: false - item_id: care_4 text: "Whether or not someone cared for someone weak or vulnerable." reverse_scored: false123456789101112131415161718192021construct_id: mfq_fairnessversion: 1name: Moral Foundations - Fairnesslanguage: encategory: moral-foundationsdescription: Concern with justice, rights, and equal treatment (MFQ Fairness/Cheating).citation: "Graham, J., Nosek, B. A., Haidt, J., Iyer, R., Koleva, S., & Ditto, P. H. (2011). Mapping the moral domain. JPSP, 101(2)."verification_status: needs_verificationitems: - item_id: fair_1 text: "Justice is the most important requirement for a society." reverse_scored: false - item_id: fair_2 text: "When the government makes laws, the number one principle should be ensuring that everyone is treated fairly." reverse_scored: false - item_id: fair_3 text: "Whether or not some people were treated differently than others." reverse_scored: false - item_id: fair_4 text: "Whether or not someone acted unfairly." reverse_scored: false12345678910111213141516171819202122232425# Construct: versioned, append-only. Edits create a NEW version (see registries rule).construct_id: satisfaction_with_lifeversion: 1name: Satisfaction with Lifelanguage: encategory: well-beingdescription: Global cognitive judgment of one's life satisfaction (SWLS).citation: "Diener, E., Emmons, R. A., Larsen, R. J., & Griffin, S. (1985). The Satisfaction with Life Scale. Journal of Personality Assessment, 49(1)."verification_status: needs_verification # verify item wording verbatim against the publicationitems: - item_id: swl_1 text: "In most ways my life is close to my ideal." reverse_scored: false - item_id: swl_2 text: "The conditions of my life are excellent." reverse_scored: false - item_id: swl_3 text: "I am satisfied with my life." reverse_scored: false - item_id: swl_4 text: "So far I have gotten the important things I want in life." reverse_scored: false - item_id: swl_5 text: "If I could live my life over, I would change almost nothing." reverse_scored: false.env.exampleAdded+56
.gitignore+1
DEPLOY.md+36-68
Dockerfile+27-16
MANUAL_TESTING.mdAdded+163
README.md+40-78
backend/app/auth.pyAdded+159
backend/app/auth_google.pyAdded+99
backend/app/ccr.py+57-27
backend/app/construct_files.pyAdded+110
backend/app/construct_lib.pyAdded+121
backend/app/db.py+45-1
backend/app/ingest.py+54-32
backend/app/jobs.py+167-25
backend/app/main.py+473-40
backend/app/models.py+25-3
backend/app/registry.pyAdded+134
backend/app/reproducibility.pyAdded+118
backend/app/retention.pyAdded+123
backend/app/schemas.py+29-1
backend/app/seed_constructs.pyDeleted-66
backend/app/storage.pyAdded+140
backend/app/warnings_engine.pyAdded+151
backend/requirements.txt+3
backend/static/assets/index-BUzS6usZ.jsDeleted
backend/static/assets/index-C356-0ZT.cssDeleted-1
backend/static/assets/index-CN_FzJfm.cssAdded+1
backend/static/assets/index-DrFcy6bH.jsAdded
backend/static/index.html+3-3
backend/tests/conftest.py+3
backend/tests/test_accounts_limits_retention.pyAdded+311
backend/tests/test_api.py+111-5
backend/tests/test_auth_tiers_and_lifecycle.pyAdded+138
backend/tests/test_auto_migration.pyAdded+42
backend/tests/test_ccr.py+1-1
backend/tests/test_google_auth.pyAdded+89
backend/tests/test_registry_and_prefixes.pyAdded+110
backend/tests/test_storage_backends.pyAdded+154
frontend/src/App.jsx+280-34
frontend/src/ConstructPicker.jsxAdded+206
frontend/src/ResultsView.jsx+35-21
frontend/src/Workspace.jsx+278-77
frontend/src/api.js+15
frontend/src/styles.css+317-11
packages/ccr_engine/README.mdAdded+11
packages/construct_library/constructs/collectivism_horizontal.yamlAdded+21
packages/construct_library/constructs/individualism_horizontal.yamlAdded+21
packages/construct_library/constructs/mfq_care.yamlAdded+21
packages/construct_library/constructs/mfq_fairness.yamlAdded+21
packages/construct_library/constructs/satisfaction_with_life.yamlAdded+25