jcbowyer commited on
Commit
824f963
·
0 Parent(s):

Clean HuggingFace deployment without binary files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.dockerignore ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ .venv/
8
+ venv/
9
+ ENV/
10
+ env/
11
+
12
+ # Node
13
+ node_modules/
14
+ npm-debug.log*
15
+ yarn-debug.log*
16
+ yarn-error.log*
17
+ .pnpm-debug.log*
18
+ web_app/dist/
19
+ web_app/node_modules/
20
+ # Vite build output — regenerated by `npm run build` inside the image, so there is
21
+ # no need to ship the (large) committed copy into the build context.
22
+ api/static/
23
+ web_docs/build/
24
+ web_docs/node_modules/
25
+ web_docs/.docusaurus/
26
+
27
+ # Data and cache
28
+ data/
29
+ cache/
30
+ logs/
31
+ output/
32
+ *.db
33
+ *.sqlite
34
+
35
+ # Git
36
+ .git/
37
+ .gitignore
38
+ .github/
39
+
40
+ # IDE
41
+ .vscode/
42
+ .idea/
43
+ *.swp
44
+ *.swo
45
+
46
+ # Documentation (we copy specific dirs)
47
+ docs/
48
+ *.md
49
+ !README.md
50
+
51
+ # Test and development
52
+ tests/
53
+ examples/
54
+ notebooks/
55
+ *.ipynb
56
+
57
+ # Large files
58
+ *.zip
59
+ *.tar.gz
60
+ *.mp4
61
+ *.avi
62
+ *.mov
63
+
64
+ # Environment
65
+ .env
66
+ .env.local
67
+ *.key
68
+ *.pem
69
+
70
+ # OS
71
+ .DS_Store
72
+ Thumbs.db
73
+
74
+ # Build artifacts
75
+ build/
76
+ dist/
77
+ *.egg-info/
78
+
79
+ # Temporary
80
+ tmp/
81
+ temp/
82
+ *.tmp
83
+
84
+ # Scripts we don't need in container
85
+ start-all.sh
86
+ stop-all.sh
87
+ deploy-huggingface.sh
88
+ test-huggingface-build.sh
89
+ migrate-docs.sh
90
+ install.sh
.gitignore ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Vite build output of the React app (web_app). vite.config.ts sets
2
+ # outDir=../api/static with emptyOutDir, so this dir is wiped + regenerated by
3
+ # `npm run build` (= `make dashboard`) and by every Docker/HF/databricks deploy.
4
+ # web_app/public is the real source; do not commit the generated copy. A fresh
5
+ # clone must build before the single-port API serves the SPA (vite dev on :5173
6
+ # does not need it). Both api/main.py and api/app.py guard the mount, so a
7
+ # missing api/static degrades gracefully rather than crashing `serve`.
8
+ /api/static/
9
+
10
+ # Python
11
+ __pycache__/
12
+ *.py[cod]
13
+ *$py.class
14
+ *.so
15
+ .Python
16
+ build/
17
+ develop-eggs/
18
+ dist/
19
+ downloads/
20
+ eggs/
21
+ .eggs/
22
+ lib/
23
+ !web_app/src/lib/
24
+ # Databricks app source dirs named "lib" (otherwise hidden from git + bundle deploy)
25
+ !apps/rag-chat-app/server/lib/
26
+ !apps/rag-chat-app/client/src/lib/
27
+ lib64/
28
+ parts/
29
+ sdist/
30
+ var/
31
+ wheels/
32
+ *.egg-info/
33
+ .installed.cfg
34
+ *.egg
35
+
36
+ # Node.js
37
+ node_modules/
38
+
39
+ # Lighthouse / chrome-launcher on WSL: bogus Windows TEMP can become a single directory name under cwd
40
+ packages/accessibility/src/accessibility/C*
41
+
42
+ # Virtual environments
43
+ venv/
44
+ env/
45
+ ENV/
46
+ .venv
47
+ .venv-dbt
48
+ .venv-intel
49
+
50
+ # IDE
51
+ .vscode/
52
+ .idea/
53
+ *.swp
54
+ *.swo
55
+ *~
56
+ .DS_Store
57
+
58
+ # Environment variables
59
+ .env
60
+ .env.bak.*
61
+ .env.local
62
+ .env.*.local
63
+ .env.production
64
+ .env.development
65
+ .env.test
66
+
67
+ # Terraform (infra/azure)
68
+ **/.terraform/*
69
+ *.tfstate
70
+ *.tfstate.*
71
+ *.tfvars
72
+ !*.tfvars.example
73
+ !subscriptions.auto.tfvars
74
+ crash.log
75
+ crash.*.log
76
+ .terraform.lock.hcl
77
+ override.tf
78
+ override.tf.json
79
+ *_override.tf
80
+ *_override.tf.json
81
+ .terraformrc
82
+ terraform.rc
83
+
84
+ # Credentials and secrets
85
+ credentials.json
86
+ service-account.json
87
+ *_credentials.json
88
+ auth.json
89
+ token.json
90
+ *_token.txt
91
+ *-token.txt
92
+ gcp-*.json
93
+ bigquery-*.json
94
+ .gcp/
95
+
96
+ # Logs (runtime; keep under repo logs/ or data/logs/)
97
+ logs/
98
+ **/logs/
99
+ *.log
100
+ *.log.*
101
+ wget-log
102
+ nohup.out
103
+
104
+ # Wikidata loaders — runtime resume state (historical root default); prefer data/cache/wikidata/
105
+ .wikidata_checkpoint.json
106
+
107
+ # Jupyter Notebook
108
+ .ipynb_checkpoints
109
+ *.ipynb
110
+
111
+ # Exception: Allow Colab tutorial notebooks (must have outputs cleared before commit)
112
+ !packages/scrapers/src/scrapers/youtube/load_youtube_events_colab.ipynb
113
+ !packages/scrapers/src/scrapers/youtube/download_audio_colab.ipynb
114
+ !packages/scrapers/src/scrapers/wikidata/load_jurisdictions_wikidata_colab.ipynb
115
+ !packages/scrapers/src/scrapers/wikidata/wikidata_fips_gnis_extract_colab.ipynb
116
+ !packages/llm/src/llm/governance/02_run_meeting_llm.ipynb
117
+ !notebooks/colab_gpu_diarize.ipynb
118
+ !notebooks/colab_gemma_policy_analysis.ipynb
119
+
120
+ # Data files
121
+ data/
122
+ # These app dirs keep committed SOURCE data; the broad data/ rule above must not swallow them.
123
+ !web_app/src/data/
124
+ !web_app/src/data/**
125
+ !web_app/policy-dashboards/src/data/
126
+ !web_app/policy-dashboards/src/data/**
127
+ .migration_backup/
128
+ *.csv
129
+ # The vendored NTEE seed is package data the loader falls back to (#321).
130
+ !packages/ingestion/src/ingestion/ntee/seed_ntee_codes.csv
131
+ # dbt seeds are source, not data dumps — must be tracked
132
+ !dbt_project/seeds/*.csv
133
+ *.parquet
134
+ *.delta
135
+
136
+ # Delta Lake
137
+ _delta_log/
138
+
139
+ # Testing
140
+ .coverage
141
+ htmlcov/
142
+ .pytest_cache/
143
+ .tox/
144
+ test-results/
145
+
146
+ # Documentation
147
+ docs/_build/
148
+
149
+ # Databricks
150
+ .databricks/
151
+
152
+ # Secrets
153
+ secrets/
154
+ *.key
155
+ *.pem
156
+
157
+ # OS
158
+ Thumbs.db
159
+ # Binary files for Docker build only (not in git)
160
+ web_docs/static/img/communityone_card.png
161
+ data/gold_old/
162
+ data/gold_backup_*/
163
+
164
+ # Security: Cookie files (browser exports for YouTube auth)
165
+ youtube_cookies.txt
166
+ *_cookies.txt
167
+ cookies.txt
168
+ *.cookies
169
+ , psycopg2
170
+ # Claude Code: local state stays out of git; the shared agent files are tracked (AGENTS.md, issue #225)
171
+ .claude/*
172
+ !.claude/agents/
173
+ !.claude/commands/
174
+ !.claude/review-rubric.md
175
+ !.claude/settings.json
176
+
177
+ # transcript-analysis backfill runtime log
178
+ analyze_backlog.out
179
+ analyze_backlog_shard*.out
180
+
181
+ # Parallel shard / harvest / one-off run logs (process stdout, never source)
182
+ shard*.out
183
+ *_harvest.out
184
+ *_run.out
185
+
186
+ # Stray empty file accidentally created by a mistyped `git` command
187
+ /git
188
+
189
+ # VS Code "VSCode Counter" extension output (local code-stats dumps)
190
+ .VSCodeCounter/
191
+
192
+ # Runtime API server log (not source)
193
+ api_server.out
194
+
195
+ # Versioned Postgres release backups (make backup / make restore) — large dumps,
196
+ # stored off-machine on Google Drive, never committed. Keep `open-navigator-backups/`
197
+ # as a real directory (README committed); ignore dump contents. Do not replace it
198
+ # with a symlink to an unmounted Drive path — that breaks local pytest (#612).
199
+ # `.backup-staging` is the local fast-disk scratch dir dumps stream to before copy.
200
+ open-navigator-backups/**
201
+ !open-navigator-backups/
202
+ !open-navigator-backups/README.md
203
+ .backup-staging/
204
+ backups/
205
+ *.dump
206
+ .worktrees/
207
+
208
+ # draw.io export webapp (sparse clone for PNG render)
209
+ diagrams/youtube-api-audit/_build/drawio/
210
+ diagrams/youtube-api-audit/_build/__pycache__/
211
+ .superpowers/
.huggingface/README.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: CommunityOne - Open Navigator
3
+ emoji: 🏛️
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ license: apache-2.0
10
+ tags:
11
+ - civic-engagement
12
+ - policy-tracking
13
+ - government-transparency
14
+ - nonprofit-discovery
15
+ - open-data
16
+ ---
17
+
18
+ # 🏛️ CommunityOne - Open Navigator
19
+
20
+ **Track local governments across the U.S. Monitor 1.8M nonprofits. Amplify your voice.**
21
+
22
+ CommunityOne is a civic engagement platform that helps you discover advocacy opportunities, track policy changes, and connect with organizations working on the causes you care about.
23
+
24
+ ## ✨ Features
25
+
26
+ - **🔍 Unified Search**: Find contacts, meetings, organizations, and causes across the entire United States
27
+ - **📊 Real-time Stats**: Track policy activity across cities, counties, school districts and states
28
+ - **🏢 Nonprofit Discovery**: Explore 1.8M organizations from IRS data enriched with Every.org
29
+ - **📅 Meeting Minutes**: Search 250,000+ government meeting transcripts and agendas
30
+ - **🎯 Geographic Filtering**: Browse by state, county, or city to find local opportunities
31
+ - **🔐 OAuth Login**: Sign in with HuggingFace, GitHub, or Google to save your preferences
32
+
33
+ ## 🚀 Three Services Architecture
34
+
35
+ This deployment runs three integrated services:
36
+
37
+ 1. **📚 Documentation** (Docusaurus) - `/docs/`
38
+ 2. **🖥️ Main Application** (React + Vite) - `/`
39
+ 3. **⚡ API Backend** (FastAPI) - `/api/`
40
+
41
+ All services are reverse-proxied through nginx on port 7860.
42
+
43
+ ## 📖 Quick Start
44
+
45
+ ### Browse Without Login
46
+ - Click "Browse All" to explore data by state
47
+ - Use the search bar to find organizations, contacts, or causes
48
+ - Filter by location using the state/county/city selectors
49
+
50
+ ### Sign In for Personalization
51
+ - Click "Login" in the top right
52
+ - Choose your OAuth provider (HuggingFace, GitHub, or Google)
53
+ - Follow organizations, leaders, and causes you care about
54
+ - Get personalized recommendations
55
+
56
+ ### Explore the API
57
+ - Visit `/redoc` for interactive API documentation
58
+ - Try the search endpoints with state filters
59
+ - Export data in JSON format for your own projects
60
+
61
+ ## 🛠️ Technology Stack
62
+
63
+ - **Frontend**: React 18 + TypeScript + Vite + TailwindCSS + shadcn/ui
64
+ - **Backend**: Python 3.11 + FastAPI + Pydantic
65
+ - **Data**: Delta Lake + Parquet (90GB+ of civic data)
66
+ - **Docs**: Docusaurus v3
67
+ - **Infrastructure**: nginx + supervisor + Docker
68
+
69
+ ## 📊 Data Sources
70
+
71
+ - **IRS BMF**: 1.8M tax-exempt organizations
72
+ - **Every.org**: Nonprofit enrichment (logos, causes, revenue)
73
+ - **Open States**: State legislators and bills (7,300+ officials)
74
+ - **Census**: Jurisdictions and boundaries
75
+ - **CityScrapers**: Local government meetings
76
+ - **OpenCivicData**: Standardized government data
77
+
78
+ ## 🔗 Links
79
+
80
+ - **Repository**: [github.com/getcommunityone/open-navigator](https://github.com/getcommunityone/open-navigator)
81
+ - **Documentation**: Click "📚 Browse Documentation" on the homepage
82
+ - **API Docs**: `/redoc` endpoint
83
+ - **Website**: [www.communityone.com](https://www.communityone.com)
84
+
85
+ ## 📝 License
86
+
87
+ Apache License 2.0 - Free for commercial and non-commercial use
88
+
89
+ ## 🤝 Contributing
90
+
91
+ We welcome contributions! See CONTRIBUTING.md in the repository for guidelines.
92
+
93
+ ## 💬 Support
94
+
95
+ - **Issues**: [GitHub Issues](https://github.com/getcommunityone/open-navigator/issues)
96
+ - **Discussions**: [GitHub Discussions](https://github.com/getcommunityone/open-navigator/discussions)
97
+ - **Email**: johnbowyer@communityone.com
98
+
99
+ ---
100
+
101
+ Built with ❤️ for civic engagement and government transparency.
.huggingface/nginx.conf ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ worker_processes auto;
2
+ pid /tmp/nginx.pid;
3
+
4
+ events {
5
+ worker_connections 1024;
6
+ }
7
+
8
+ http {
9
+ include /etc/nginx/mime.types;
10
+ default_type application/octet-stream;
11
+
12
+ # Logging
13
+ access_log /app/logs/nginx-access.log;
14
+ error_log /app/logs/nginx-error.log;
15
+
16
+ # Performance
17
+ sendfile on;
18
+ tcp_nopush on;
19
+ tcp_nodelay on;
20
+ keepalive_timeout 65;
21
+ types_hash_max_size 2048;
22
+ client_max_body_size 50M;
23
+
24
+ # Compression
25
+ gzip on;
26
+ gzip_vary on;
27
+ gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
28
+
29
+ upstream fastapi_backend {
30
+ server 127.0.0.1:8000;
31
+ }
32
+
33
+ server {
34
+ listen 7860;
35
+ server_name _;
36
+
37
+ # Force HTTPS - HSTS header tells browsers to ALWAYS use HTTPS
38
+ add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
39
+
40
+ # Additional security headers
41
+ add_header X-Content-Type-Options "nosniff" always;
42
+ add_header X-Frame-Options "SAMEORIGIN" always;
43
+ add_header X-XSS-Protection "1; mode=block" always;
44
+
45
+ # Documentation - serve static files built by Docusaurus
46
+ # Use root instead of alias to avoid path issues
47
+ location /docs {
48
+ root /app/static;
49
+ try_files $uri $uri/index.html $uri.html /docs/index.html;
50
+
51
+ # Cache static assets - shorter for easier updates
52
+ location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
53
+ expires 1d;
54
+ add_header Cache-Control "public, max-age=86400";
55
+ }
56
+ }
57
+
58
+ # API backend at /api/
59
+ location /api/ {
60
+ proxy_pass http://fastapi_backend/api/;
61
+ proxy_http_version 1.1;
62
+ proxy_set_header Upgrade $http_upgrade;
63
+ proxy_set_header Connection 'upgrade';
64
+ proxy_set_header Host $host;
65
+ proxy_cache_bypass $http_upgrade;
66
+ proxy_set_header X-Real-IP $remote_addr;
67
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
68
+ proxy_set_header X-Forwarded-Proto $scheme;
69
+ proxy_read_timeout 300s;
70
+ proxy_connect_timeout 75s;
71
+ }
72
+
73
+ # API docs: the app serves its Swagger UI at /api/docs itself (api/main.py sets
74
+ # docs_url=None and adds a custom /api/docs route), so pass the path through (#281).
75
+ location = /api/docs {
76
+ proxy_pass http://fastapi_backend/api/docs;
77
+ proxy_http_version 1.1;
78
+ proxy_set_header Host $host;
79
+ proxy_set_header X-Real-IP $remote_addr;
80
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
81
+ proxy_set_header X-Forwarded-Proto $scheme;
82
+ }
83
+
84
+ # API OpenAPI schema - support both /api/openapi.json and /openapi.json
85
+ location ~ ^/(api/)?(openapi\.json|redoc) {
86
+ proxy_pass http://fastapi_backend/$2;
87
+ proxy_http_version 1.1;
88
+ proxy_set_header Host $host;
89
+ proxy_set_header X-Real-IP $remote_addr;
90
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
91
+ proxy_set_header X-Forwarded-Proto $scheme;
92
+ }
93
+
94
+ # SEO: robots.txt (do not reuse sitemap MIME — crawlers expect text/plain)
95
+ location = /robots.txt {
96
+ root /app/static/frontend;
97
+ default_type text/plain;
98
+ add_header Cache-Control "public, max-age=3600";
99
+ try_files $uri =404;
100
+ }
101
+
102
+ # SEO: XML sitemaps (single Content-Type — avoid duplicate text/xml + application/xml)
103
+ location ~ ^/sitemap.*\.xml$ {
104
+ root /app/static/frontend;
105
+ default_type application/xml;
106
+ add_header Cache-Control "public, max-age=3600";
107
+ try_files $uri =404;
108
+ }
109
+
110
+ # Frontend assets - shorter cache for easier updates
111
+ location /assets/ {
112
+ alias /app/static/frontend/assets/;
113
+ expires 1d;
114
+ add_header Cache-Control "public, max-age=86400";
115
+ }
116
+
117
+ # Favicon — proxy to FastAPI so missing binary .ico can fall back to SVG/PNG
118
+ location = /favicon.ico {
119
+ proxy_pass http://fastapi_backend/favicon.ico;
120
+ proxy_http_version 1.1;
121
+ proxy_set_header Host $host;
122
+ proxy_set_header X-Real-IP $remote_addr;
123
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
124
+ proxy_set_header X-Forwarded-Proto $scheme;
125
+ }
126
+
127
+ # Main frontend app at root
128
+ location / {
129
+ root /app/static/frontend;
130
+ try_files $uri $uri/ /index.html;
131
+
132
+ # NEVER cache index.html - force browser to check for new version
133
+ location = /index.html {
134
+ add_header Cache-Control "no-cache, no-store, must-revalidate";
135
+ add_header Pragma "no-cache";
136
+ add_header Expires "0";
137
+ }
138
+
139
+ # Service worker files are never cached (#913, #918). The app is a PWA: a phone keeps serving the old
140
+ # site from its cache until it sees a new sw.js. This rule must stay INSIDE `location /` and BEFORE
141
+ # the static-file rule below: nginx tries the nested regex rules of the matched prefix first, in
142
+ # order, so a server-level rule never sees /sw.js.
143
+ location ~ ^/(sw\.js|registerSW\.js|workbox-[^/]+\.js|manifest\.webmanifest)$ {
144
+ add_header Cache-Control "no-cache, no-store, must-revalidate";
145
+ try_files $uri =404;
146
+ }
147
+
148
+ # Cache hashed assets (immutable) but shorter time for easier updates
149
+ location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
150
+ expires 1d;
151
+ add_header Cache-Control "public, max-age=86400";
152
+ }
153
+ }
154
+
155
+ # Health check endpoint
156
+ location /health {
157
+ access_log off;
158
+ return 200 "OK";
159
+ add_header Content-Type text/plain;
160
+ }
161
+ }
162
+ }
.huggingface/restore_lfs_static.sh ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Replace served Git LFS pointer files with their real objects (#911).
3
+ #
4
+ # The Space image is built from a context that holds LFS files as pointers, so the web build
5
+ # copies 130-byte pointer text into the served static directories. At container start this
6
+ # script finds every such pointer under the given static roots, looks up which repository
7
+ # file has the same object id, downloads that file from the Space's own repository and puts
8
+ # it in place only when its SHA-256 equals the pointer's oid. Anything it cannot fetch or
9
+ # verify is left as it was and named in the output. It never exits non-zero.
10
+ #
11
+ # restore_lfs_static.sh <repo_root> <static_root> [<static_root>...]
12
+ #
13
+ # Environment: SPACE_ID (set by Hugging Face), HF_TOKEN (optional, private Spaces),
14
+ # LFS_RESOLVE_BASE (optional override of the download base, used by the test).
15
+
16
+ SPEC='version https://git-lfs.github.com/spec/v1'
17
+ repo_root=${1:-}
18
+ shift || true
19
+ base=${LFS_RESOLVE_BASE:-}
20
+ if [ -z "$base" ] && [ -n "${SPACE_ID:-}" ]; then
21
+ base="https://huggingface.co/spaces/${SPACE_ID}/resolve/main"
22
+ fi
23
+ if [ -z "$repo_root" ] || [ "$#" -eq 0 ] || [ -z "$base" ]; then
24
+ echo "restore_lfs_static: nothing to do (need a repo root, a static root, and SPACE_ID or LFS_RESOLVE_BASE)"
25
+ exit 0
26
+ fi
27
+
28
+ # Print the oid of a file when it is an LFS pointer; print nothing otherwise.
29
+ pointer_oid() {
30
+ local f=$1 size
31
+ size=$(wc -c <"$f" 2>/dev/null) || return 0
32
+ [ "$size" -lt 1024 ] || return 0
33
+ [ "$(head -n 1 "$f" 2>/dev/null)" = "$SPEC" ] || return 0
34
+ sed -n 's/^oid sha256:\([0-9a-f]\{64\}\)$/\1/p' "$f" | head -n 1
35
+ }
36
+
37
+ # oid -> repository path, from the pointer files the image was built with.
38
+ map=$(mktemp)
39
+ trap 'rm -f "$map"' EXIT
40
+ while IFS= read -r -d '' f; do
41
+ oid=$(pointer_oid "$f")
42
+ [ -n "$oid" ] && printf '%s %s\n' "$oid" "${f#"$repo_root"/}" >>"$map"
43
+ done < <(find "$repo_root/web_app/public" "$repo_root/web_docs/static" -type f -size -2 -print0 2>/dev/null)
44
+
45
+ restored=0
46
+ failed=0
47
+ for root in "$@"; do
48
+ [ -d "$root" ] || continue
49
+ while IFS= read -r -d '' f; do
50
+ oid=$(pointer_oid "$f")
51
+ [ -n "$oid" ] || continue
52
+ path=$(grep -m 1 "^$oid " "$map" | cut -d' ' -f2-)
53
+ if [ -z "$path" ]; then
54
+ echo "restore_lfs_static: no repository file for $f"
55
+ failed=$((failed + 1))
56
+ continue
57
+ fi
58
+ tmp="$f.lfs-tmp"
59
+ auth=()
60
+ [ -n "${HF_TOKEN:-}" ] && auth=(-H "Authorization: Bearer ${HF_TOKEN}")
61
+ if curl -fsSL --max-time 120 "${auth[@]}" -o "$tmp" "$base/$path" \
62
+ && [ "$(sha256sum "$tmp" | cut -d' ' -f1)" = "$oid" ]; then
63
+ mv -f "$tmp" "$f"
64
+ restored=$((restored + 1))
65
+ else
66
+ rm -f "$tmp"
67
+ echo "restore_lfs_static: could not restore $f (from $path)"
68
+ failed=$((failed + 1))
69
+ fi
70
+ done < <(find "$root" -type f -size -2 -print0 2>/dev/null)
71
+ done
72
+ echo "restore_lfs_static: restored $restored file(s), $failed not restored"
73
+ exit 0
.huggingface/start.sh ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+
4
+ echo "🚀 Starting CommunityOne on Hugging Face Spaces..."
5
+ echo "📊 Three services architecture:"
6
+ echo " 1. Documentation (Docusaurus) - Port 3000"
7
+ echo " 2. Main Application (React + Vite) - Port 5173"
8
+ echo " 3. API Backend (FastAPI) - Port 8000"
9
+ echo " 4. Nginx Reverse Proxy - Port 7860 (HF Spaces public port)"
10
+ echo ""
11
+
12
+ # DEBUG: Check environment variable
13
+ echo "🔍 Environment Check:"
14
+ echo " HF_SPACES = ${HF_SPACES:-NOT SET}"
15
+ if [ "$HF_SPACES" = "1" ]; then
16
+ echo " ✅ HF_SPACES is correctly set to 1"
17
+ else
18
+ echo " ❌ WARNING: HF_SPACES is not set to 1"
19
+ echo " Setting HF_SPACES=1 now..."
20
+ export HF_SPACES=1
21
+ fi
22
+ echo ""
23
+
24
+ # Create required directories
25
+ mkdir -p /app/logs /app/data /var/log/supervisor
26
+
27
+ # Verify static files exist
28
+ echo "📁 Verifying static files..."
29
+ if [ -d "/app/static/docs" ]; then
30
+ echo "✅ Documentation static files found"
31
+ ls -lh /app/static/docs/ | head -5
32
+ else
33
+ echo "❌ ERROR: Documentation static files missing at /app/static/docs"
34
+ exit 1
35
+ fi
36
+
37
+ if [ -d "/app/static/frontend" ]; then
38
+ echo "✅ Frontend static files found"
39
+ ls -lh /app/static/frontend/ | head -5
40
+ else
41
+ echo "❌ ERROR: Frontend static files missing at /app/static/frontend"
42
+ exit 1
43
+ fi
44
+
45
+ # Install serve for static file hosting (if not already installed)
46
+ if ! command -v serve &> /dev/null; then
47
+ echo "📦 Installing serve for static file hosting..."
48
+ npm install -g serve
49
+ fi
50
+
51
+ # Test nginx configuration
52
+ echo "🔧 Testing nginx configuration..."
53
+ nginx -t
54
+
55
+ # Initialize database if needed
56
+ echo "💾 Initializing database..."
57
+ python -c "from api.database import init_db; init_db()" || echo "⚠️ Database init skipped"
58
+
59
+ # Served files that are still Git LFS pointers are swapped for the real files (#911). This runs
60
+ # beside the services so it never delays or fails the start.
61
+ if [ -x /app/restore_lfs_static.sh ]; then
62
+ /app/restore_lfs_static.sh /app /app/static/frontend /app/static/docs /app/api/static > /app/logs/restore_lfs_static.log 2>&1 &
63
+ fi
64
+
65
+ # Start all services with supervisor
66
+ echo "🎬 Starting all services with supervisor..."
67
+ exec /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf
.huggingface/supervisord.conf ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [supervisord]
2
+ nodaemon=true
3
+ logfile=/dev/stdout
4
+ logfile_maxbytes=0
5
+ pidfile=/tmp/supervisord.pid
6
+ user=root
7
+
8
+ [program:nginx]
9
+ command=/usr/sbin/nginx -g "daemon off;"
10
+ autostart=true
11
+ autorestart=true
12
+ stdout_logfile=/dev/stdout
13
+ stdout_logfile_maxbytes=0
14
+ stderr_logfile=/dev/stderr
15
+ stderr_logfile_maxbytes=0
16
+ priority=10
17
+
18
+ [program:fastapi]
19
+ command=uvicorn api.main:app --host 0.0.0.0 --port 8000 --log-level info --proxy-headers
20
+ directory=/app
21
+ autostart=true
22
+ autorestart=true
23
+ stdout_logfile=/dev/stdout
24
+ stdout_logfile_maxbytes=0
25
+ stderr_logfile=/dev/stderr
26
+ stderr_logfile_maxbytes=0
27
+ environment=PYTHONUNBUFFERED="1",HF_SPACES="1"
28
+ priority=20
AGENTS.md ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AGENTS.md
2
+
3
+ Rules for every coding agent working in this repository (Claude Code, Codex, Cursor, Copilot and others), and for
4
+ people too. `CLAUDE.md` imports this file. Read `CLAUDE.md` as well: it holds the architecture, data, UX,
5
+ documentation and commit rules, and they apply to every agent.
6
+
7
+ ## Issues first: log the work before you start
8
+
9
+ Every change starts from a GitHub issue, and agents open it themselves. Don't wait to be asked.
10
+
11
+ 1. **Search open issues first.** If one already covers the work, use it. If not, open one before the first commit.
12
+ 2. **Title:** `<type>(<scope>): <what changes>`, in the Conventional Commit style used for commits
13
+ (for example `fix(census): Connecticut counties render blank on the county map`).
14
+ 3. **Labels:** `bug`, `enhancement`, `documentation`, or the feedback labels (`ux-friction`, `copy/content`,
15
+ `feature-request`, `validated`). Follow-ups get `action-item`.
16
+ 4. **One issue, one pull request.** A larger story is split into issues, and each PR closes one.
17
+
18
+ ## What an issue says
19
+
20
+ Write all four parts, as headings, before the first commit. The template is `.github/ISSUE_TEMPLATE/work-item.md`.
21
+
22
+ **Planned work opens with an Attributes table.** When the work belongs to the quarter's plan (a PI epic and its user
23
+ stories, filed as parent issues and sub-issues), the issue starts with a table that names its `Epic` and `User story`
24
+ as markdown links to their issues, plus `PI · Sprint` and `Points` where the plan gives them. A story links its epic and
25
+ says "this issue" for itself. A task, bug or follow-up under a story links both. The pull request repeats the table, so
26
+ a reader can go from any change to the story and the epic it serves. Examples: the CORE epic #235, its story #242,
27
+ and that story's pull request #253.
28
+
29
+ - **Problem:** what is wrong or missing, and who it affects, with the evidence linked (a failing test, a log line,
30
+ a screenshot, a feedback issue).
31
+ - **Done when:** one line per check a test or reviewer will make.
32
+ - **Contract:** every name a test or another layer will use that isn't in the repository yet. For an API, that's
33
+ the path, parameters and response fields. For data, it's the dbt model or table, its grain (one row per what), its
34
+ typed columns, its primary key and its foreign keys (see `CLAUDE.md`, "Data Pipeline Standards"). For the UI, it's
35
+ the route and the URL parameters it reads.
36
+ - **Read first:** the files to change, and the rules and docs that govern them.
37
+
38
+ If a name has to change later, add a dated line to the issue. Never rewrite the original text: it records what was
39
+ asked.
40
+
41
+ ## Log what you find, as you go
42
+
43
+ - **Follow-ups become issues, not notes.** Anything out of scope that you notice (a bug, a missing test, a stale doc)
44
+ gets its own issue, labelled `action-item`, with the four parts and the evidence. Link it from your PR. Never leave
45
+ it only in a TODO comment or a line of PR text.
46
+ - **Failures become issues.** When CI, a data load or a run fails for a reason your change doesn't fix, open a
47
+ `bug` issue with the failing command, the error line and where it ran. Then carry on with your own work.
48
+ - **Feedback becomes issues.** A reviewer's or user's feedback gets one issue per concrete item (as #137 to #151
49
+ were), each linked to the feedback issue it came from.
50
+ - **Decisions are written down.** A choice and its reason go in a page under `web_docs/docs/development/`, linked
51
+ from the issue. Never leave a decision only in an issue or PR thread.
52
+
53
+ ## Docs with the change
54
+
55
+ If a change alters behavior, contracts, operator UI, or data grain, the **same PR** updates or adds the governed
56
+ page under `web_docs/docs/`. Name that page in the issue **Done when** and in the PR body.
57
+
58
+ Keep publishing new designs and plans under `web_docs/docs/development/` (Working notes). **Archive is for
59
+ pages that are wrong or misleading** (wrong paths, superseded product story) — not for every doc whose issue
60
+ already shipped. If you find a wrong page mid-work: fix it, `git mv` it into `web_docs/docs/development/archive/`,
61
+ or open an `action-item` when the rewrite is out of scope. Do not leave “TODO: fix docs” only in the PR.
62
+
63
+ Lifecycle: [Development docs hygiene](web_docs/docs/development/development-docs-hygiene-design.md).
64
+
65
+ ## Branches and pull requests
66
+
67
+ - **Branch:** `<type>/<issue>-<slug>`, for example `fix/71-ct-county-map`. The type is a Conventional Commit type
68
+ (`feat`, `fix`, `docs`, `chore`, `refactor`, `test`, `perf`, `ci`, `build`, `revert`), then the issue number, then
69
+ a lowercase slug of at most 40 characters. Branches a tool names (`dependabot/*`, `renovate/*`) stay as they are.
70
+ - **Pull request:** the description says `Closes #<issue>` (or `Refs #<issue>` for one part of a larger issue), so
71
+ merging closes it.
72
+ - **The `PR conventions` check** (`.github/scripts/pr_conventions.py`) enforces both on every pull request opened from
73
+ November 14, 2026. It also checks that the linked issue has the four parts, each with text under it (the
74
+ template's guidance is in comments, so an unfilled template fails). It runs when the PR changes, not when the
75
+ issue does: after fixing the issue, re-run the check from the PR's Checks tab.
76
+ - **Open and review with the two prompts.** `/create-pr` (`.claude/commands/create-pr.md`) checks the branch, opens
77
+ the PR and reviews it. `/pr-review` (`.claude/commands/pr-review.md`) reviews any PR against
78
+ `.claude/review-rubric.md` and writes `pull_requests/pr-<n>-review.md`. The review is committed to the PR's branch.
79
+ Agents without slash commands read those files and follow the same steps. Every PR gets a review before it merges.
80
+ - **An agent merges its own PR when it's ready, without waiting to be told** (standing rule, #758; same practice as
81
+ health-transformation-lab-nlp #497). Ready means every required check is green on the latest commit, there is no
82
+ merge conflict, and `pull_requests/pr-<n>-review.md` finds nothing blocking (`verdict:` is `approve` or
83
+ `approve-with-nits`, not `request-changes`). Squash-merge with admin when GitHub blocks self-approval
84
+ (`gh pr merge <n> --squash --admin`; `enforce_admins` is off on `main`). These still wait for the owner to say
85
+ "merge":
86
+ - a PR that starts a run on limited or paid compute (GPU / Colab, WhisperX diarization, paid LLM endpoints);
87
+ - one that publishes outside this repo (Hugging Face, production deploy, the public docs site beyond a normal merge);
88
+ - one that deletes data, warehouse tables or branches, or changes these agent rules;
89
+ - one the owner has said to hold.
90
+
91
+ Before merging, check open PRs and recent commits on `main` for the same work. If another session already did it,
92
+ close yours and say so. Enforcing that the review file exists in CI is #648.
93
+ - Everything in `CLAUDE.md`, "Branch & PR Workflow" still applies: never push to `main`, never force-push, required
94
+ checks green before merge.
95
+
96
+ ## Privacy and data ethics
97
+
98
+ Citizens' privacy comes first. Every agent follows these rules, the minimum the law requires and the standard we hold
99
+ ourselves to. The reasons and the laws behind them:
100
+ [Privacy and data ethics](web_docs/docs/development/privacy-and-data-ethics.md) (#1080). When a rule and a task
101
+ conflict, the rule wins: stop and ask the owner.
102
+
103
+ - **Public role or private person.** Officials, staff acting in their role, and organizations are public. Their
104
+ official contact details, votes and statements may be stored and shown. A private resident who spoke at a meeting is
105
+ shown only as the record shows them, with the name shortened to "First L.". We never enrich a private person with a
106
+ home address, workplace, church, school, family, social accounts or personal email, from any source (brokers,
107
+ people-search sites, scraping or AI). See [People in meetings](web_docs/docs/development/people-claim-and-privacy.md).
108
+ - **Sensitive data is never tied to a private person.** That covers health conditions, religion, race or ethnicity,
109
+ immigration status, sexual orientation, disability, criminal history, finances and precise home location. We aren't
110
+ a HIPAA covered entity, but health details are treated as protected: a speaker who mentions an illness is not tagged
111
+ with it. Aggregates with no one identifiable are fine.
112
+ - **Minors and students.** Never name, quote or tag a child or student identified in a meeting or document (school
113
+ board meetings, FERPA). No accounts under 13 (COPPA).
114
+ - **AI tagging and extraction.** Prompts and classifiers (Gemini, Jev, Claude) may tag what was said, the topic,
115
+ stance and outcome. They may not infer a person's sensitive traits, motives or identity beyond the record. Speaker
116
+ names stay "First L." in served data.
117
+ - **Scraping.** Fetch public pages only:
118
+ - Never log in, bypass a paywall or CAPTCHA, or disguise who we are (no spoofed browser identity or rotating
119
+ proxies to get past a block).
120
+ - Honour robots.txt and the site's terms. A 403 or 429 means stop or back off, not retry harder.
121
+ - Identify as `open-navigator` and keep requests slow.
122
+ - Where terms forbid automated collection, cite or link instead of scraping (as with job boards, #1019).
123
+ - **Contact.** Never email, text or call a private person who hasn't asked us to. Officials are contacted only at
124
+ their official address, by the owner, never automatically. Any bulk email follows CAN-SPAM: who it's from, why,
125
+ and how to opt out.
126
+ - **Our users' data.** Collect only what a feature needs, and say why. Keep it no longer than needed (a looked-up
127
+ address is used, not stored), never sell or share it, and delete it on request. Never log emails, tokens, exact
128
+ locations or chat text with an identity attached.
129
+ - **Correction and removal.** Anyone shown on the site can ask to correct, hide or remove how we show them (#1064).
130
+ A removal request is honoured even without full verification when the risk to them is plausible.
131
+ - **Third-party sources.** Don't reference CareQuest (CareQuest Institute) or use its data, polls, charts or wording
132
+ anywhere in the product, code, comments, docs, issues, PRs or commits. Build our own maps and charts from our meeting
133
+ and bill data.
134
+ - **Blocking in review.** A PR that adds private personal data, ties sensitive data to a person, names a minor,
135
+ scrapes against a site's terms or contacts people unasked is 🔴 Blocking (`.claude/review-rubric.md`).
136
+
137
+ ## Context for models and agents
138
+
139
+ Anything a model reads (a prompt, a transcript, a tool result, this repository) is context, and it's engineered like
140
+ code. The six principles and where each applies: [Context engineering](web_docs/docs/development/context-engineering.md).
141
+
142
+ - **Send the least that answers the question.** Split at units of meaning (caption segments, sections), and load
143
+ detail with a tool when it's needed rather than up front.
144
+ - **Read the governed layer.** Models and the API read `public` (or Unity Catalog), never `bronze` or `gold` directly;
145
+ access rules belong to the data, not to a prompt.
146
+ - **Carry the source forward.** Every derived row, quote or answer keeps the ID and link of the record it came from.
147
+ - **Say how current it is.** A table a model or the site reads has a freshness target and a last-updated date.
148
+ - **Version and test it.** Prompts, output schemas and tool definitions live in git with a version that changes when
149
+ they do, and are checked against known answers, not by asking another model whether the result looks right.
150
+
151
+ ## GPU and paid compute
152
+
153
+ GPU steps (WhisperX diarization, local Gemma generation; #262, #297) run on paid or shared machines. The decision and
154
+ its reasons: [GPU compute decisions](web_docs/docs/development/gpu-compute-decisions.md) (#357).
155
+
156
+ - **GPU runs go to the owner's Colab, never the Kaggle account.** The Kaggle GPU pool is kept for
157
+ health-transformation-lab-nlp's competition work. The Colab compute units are one subscription shared with that
158
+ project, so one project's run can leave the other short.
159
+ - **A paid GPU run starts only on the owner's explicit yes** for that run, given in the session that starts it; "do
160
+ what you recommend" doesn't.
161
+ - **Read usage before and after every GPU run** (its `gpu_run` rows, `packages/llm/src/llm/usage/gpu.py`, and the
162
+ compute units Colab shows) and put the cost in the run's issue or PR.
163
+ - **Recorded outputs and CPU come first.** Re-run a question on outputs already saved, or on CPU, before asking for a
164
+ GPU; a GPU run is for what they can't answer.
CITATIONS.md ADDED
The diff for this file is too large to render. See raw diff
 
CLAUDE.md ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Monorepo Architecture & Rules — Open Navigator
2
+
3
+ @AGENTS.md
4
+
5
+ The rules above (in `AGENTS.md`) apply to every agent: every change starts from a logged issue, and every
6
+ branch and pull request names it. This file adds the architecture, data, UX, documentation and commit rules.
7
+
8
+ ## Tech Stack
9
+ - **Backend:** FastAPI (Python 3.11+)
10
+ - **Data:** dbt Core + SQL (PostgreSQL — local warehouse on `localhost:5433`)
11
+ - **Frontend:** React (Vite, TypeScript); Docusaurus for documentation
12
+ - **Tooling:** **uv** for Python dependency management & the workspace (NOT Poetry); Ruff for lint/format; Node.js for the frontend
13
+
14
+ ## Repository Layout
15
+ - `api/`: FastAPI application — entry points `api/main.py` / `api/app.py`, route handlers in `api/routes/`, Pydantic models in `api/models.py`.
16
+ - `web_app/`: React + Vite + TypeScript app (port 5173).
17
+ - `web_docs/`: Docusaurus documentation site (port 3000).
18
+ - `dbt_project/`: dbt models, macros, and `schema.yml` files. Standalone uv project (its protobuf/pathspec pins conflict with the main resolution). Medallion: `bronze → staging → intermediate → marts`.
19
+ - `packages/`: internal shared Python libraries — the **uv workspace** (`packages/*`): `core`, `core-lib`, `datamodels`, `ingestion`, `scrapers`, `llm`, `agents`, `accessibility`. This is the destination for the `scripts/ → packages/` refactor.
20
+ - `scripts/`: **LEGACY** top-level scripts being ported into `packages/`. Do not add new code here — port instead (see Refactor Workflow).
21
+
22
+ > Note: `apps/` (FastAPI, web) and `services/` are planned for a later migration phase per `pyproject.toml`; today the API lives in `api/` and the web app in `web_app/`.
23
+
24
+ ## Where New Code Goes — `scripts/` Is Being Retired (CRITICAL)
25
+ - **`scripts/` is frozen.** We are actively retiring the top-level `scripts/` tree into `packages/`. Treat it as legacy: read it, port from it, but **never add to it**.
26
+ - **All new Python features go in `packages/`** as a proper importable library module (under the relevant `packages/<lib>/src/<lib>/…`), with a real module path, not a loose top-level script.
27
+ - **New runnable entry points** belong in a package as a CLI module invoked with `python -m <lib>.<module>` (argparse `main()` + `if __name__ == "__main__"`), **not** as a new file in `scripts/`.
28
+ - **Do not even suggest** creating a new `scripts/` file or a "`scripts/`-style runner." If a one-off runner is needed, propose it as a package CLI module instead.
29
+ - When a task would naturally extend a `scripts/` file, port the needed piece into the appropriate package first, then build on the package version. Route such work to the `python-packages-specialist` sub-agent, which enforces this rule.
30
+
31
+ ## Running Locally — Three Services
32
+ 1. **Documentation** (Docusaurus) — port 3000
33
+ 2. **Main Application** (React + Vite) — port 5173
34
+ 3. **API Backend** (FastAPI) — port 8001
35
+ - Launch command: `./start-all.sh`
36
+
37
+ ## Explicit Development Guidelines
38
+ - **CRITICAL:** Never refactor a shared Python library in `packages/` without running its tests first. A library change can ripple into both the API (`api/`) and the ingestion/dbt-adjacent loaders — run `pytest` for the touched package **and** its dependents before committing.
39
+ - **Do not read large raw or mock data files directly** (e.g. `analyze.log`, parquet dumps, `data/cache/` contents). Refer to schemas, the Pydantic models in `packages/datamodels`, or dbt `schema.yml` / TypeScript type definitions instead.
40
+ - **When refactoring dbt models, always verify downstream dependencies via the dbt DAG** (`dbt ls --select <model>+`, or the docs graph) before changing them.
41
+ - New Python belongs in `packages/` as a proper library — never extend `scripts/` in place.
42
+
43
+ ## Refactor Workflow
44
+ - **Roadmap / Manager memory:** `web_docs/docs/development/cleanup-roadmap.md` — the living backlog + status for the `scripts/ → packages/` library refactor. Read it before starting cleanup work.
45
+ - **Specialist sub-agents** (in `.claude/agents/`): route scoped work to `python-packages-specialist` (Python libraries in `packages/`; enforces prefer-packages / never-add-to-`scripts/`), `data-dbt-specialist` (dbt/SQL), `api-specialist` (FastAPI), or `frontend-specialist` (React/Docusaurus). Cross-layer tasks get split across them.
46
+
47
+ ## Data Pipeline Standards (CRITICAL)
48
+ - **Transformations:** ALWAYS use **dbt**. No Python for SQL logic or JSONB extraction.
49
+ - **Python:** Use only for ingestion (API calls, scraping), ML, or orchestration.
50
+ - **Naming:**
51
+ - `state_code` (2-letter) vs `state` (full name). Include BOTH.
52
+ - `website_url` is the primary web column name.
53
+ - **Do NOT use dimensional `dim_`/`fact_` (dimension/fact) names** — do not recommend or apply star-schema dim/fact naming to models or tables. Name models by the entity they represent (e.g. `jurisdictions`, `event_*`).
54
+ - **Keys:** ALWAYS define an explicit primary key, and foreign keys for every relationship, on tables/models exposed in the `public` schema (declare via dbt constraints / `schema.yml` so they are enforced in Postgres).
55
+ - **Scripts:** Data loading scripts in `scripts/datasources/` must start with `load_`.
56
+
57
+ ## No Fabricated Data (CRITICAL)
58
+ - **NEVER display fabricated, dummy, placeholder, mocked, or hard-coded "example" numbers or data to the user** — not in the UI, API responses, charts, docs, or summaries. Every figure shown must trace to a real value from the warehouse/source.
59
+ - This applies especially to **financial and civic figures** (budgets, dollar amounts, contributions, "Follow the money" / "Money Moves" lenses, vote counts, statistics). A made-up dollar amount is worse than showing nothing.
60
+ - **If real data is missing, empty, or not yet ingested, show an explicit empty/unavailable state** (e.g. "No data available", a disabled card, `null`/`—`) — do **not** invent stand-in numbers to fill the gap or make a demo "look complete."
61
+ - Do **not** seed components, fixtures-as-defaults, or fallback constants with realistic-looking numbers. Test fixtures stay in tests; never let them leak into a served code path.
62
+ - When unsure whether a value is real, **treat it as unavailable** and surface the gap rather than guessing.
63
+
64
+ ## Database Access
65
+ - **Host:** `localhost:5433` (ALREADY RUNNING — do not suggest new Docker PG instances).
66
+ - **Databases:** `open_navigator` (primary) and `openstates` (source).
67
+ - **API Access:** Use the `public` schema in `open_navigator`. Avoid direct `bronze` access.
68
+ - **Keys:** Every table/model exposed in `public` MUST declare an explicit primary key and foreign keys for all relationships (enforced via dbt constraints / `schema.yml`).
69
+ - **CAUTION:** Never delete or suggest deleting `data/cache/`.
70
+
71
+ ## Documentation Rules (Docusaurus)
72
+ - **MANDATORY:** ALL docs go in `web_docs/docs/` subdirectories.
73
+ - **Formatting:** kebab-case filenames, YAML frontmatter included, lowercase only.
74
+ - **Root:** No `.md` files in root except `README`, `LICENSE`, `CONTRIBUTING`, and the agent rule files
75
+ `AGENTS.md` and `CLAUDE.md`.
76
+
77
+ ## Frontend UX — Scope Label Must Match the Active Filter (MANDATORY, SITE-WIDE)
78
+ This rule governs every scoped/browse/list/search surface in `web_app/` — not just Browse Causes.
79
+
80
+ - **The visible scope label is the single source of truth for what the data is filtered to, and it MUST match the active filter exactly.** Whatever filter is in effect, the label next to the page/section title states it precisely:
81
+ - National / no geo filter → show **`National`** (or no place qualifier), never a stale city/state.
82
+ - State filter → show the **state** (e.g. `Browse Causes · Alabama` / `All of AL`).
83
+ - City / jurisdiction filter → show the **city/jurisdiction** (e.g. `Browse Causes · Tuscaloosa`).
84
+ - Same idea for non-geo dimensions (topic, cause, date range, entity type, source): the label names the actual scope in effect.
85
+ - **Label and data move together — atomically.** Changing the filter must update the label, the underlying query, and the rendered results in lockstep. A label that says one scope while the data reflects another (or vice-versa) is a bug. The label is never decorative: it always corresponds to a real, applied filter (see No Fabricated Data — don't show a "Tuscaloosa" chip over national data).
86
+ - **Filters carry over across navigation.** A scope the user picks travels to every page where it applies (Browse Topics/Causes/Questions, Search, decision/meeting lists, maps…). Never silently drop or reset a filter on navigation; if a destination genuinely can't honor it (data isn't at that grain), surface that explicitly rather than pretending it applied.
87
+ - **Carry scope via the URL** (e.g. `?state=AL&city=Tuscaloosa`, `?scope=national`) so it survives refresh / deep-link / back-button and is the authority both the label and the API query read from. The entry point appends the params; the destination reads them (`useSearchParams`) and renders the matching label.
88
+ - **Let the user see and change the active scope in place** — e.g. the `📍 Tuscaloosa` / `All of AL` toggle — and broaden up the hierarchy (city → state → national) without losing context.
89
+ - **Canonical reference:** `web_app/src/pages/BrowseTopics.tsx` and `BrowseCauses.tsx` — read `?state=&city=`, render the scope label + a one-click broaden control, and forward the scope into `DecisionCardList` and the API. New scoped surfaces must follow this pattern.
90
+
91
+ ## Frontend UX — Show the Match Evidence on Filtered Tiles (MANDATORY, SITE-WIDE)
92
+ When a result tile/card is shown **because of a topic, keyword, cause, question, or any other content filter**, the tile MUST show the evidence for *why it matched* — a real quote/passage from the underlying record — not just a title, badge, and date. A user looking at "36 results for 'fluoride'" must be able to see *where* fluoride appears in each result without clicking in.
93
+
94
+ - **Show the matched passage, quoted.** Surface the actual text from the transcript, decision statement, summary, agenda/minutes, or bill that contains the filter term. It must be a verbatim excerpt of the real record — never paraphrased, summarized, or fabricated (see No Fabricated Data).
95
+ - **Highlight the matched terms.** The matched keyword(s) within the excerpt are visibly marked so the association is unmistakable (the convention here is server-side `ts_headline(... StartSel=<mark>, StopSel=</mark>)` → the `highlightSnippet()` helper renders `<mark>` segments React-escaped, never `dangerouslySetInnerHTML`).
96
+ - **Backend produces the evidence; the tile renders it.** The search/filter SQL emits the highlighted snippet (e.g. `ts_headline` over the searchable text), returned in the result's `description`. The card component renders it under the title (e.g. `StoryCard`'s `excerpt`, clamped so it can't blow out tile height). Every result *type* the filter can return (meetings, transcripts/documents, decisions, bills, …) carries its own snippet.
97
+ - **No filter term in the record ⇒ it should not be a result.** If you cannot produce a real matched passage for a tile under an active content filter, that is a signal the match is spurious (or matched only on metadata) — surface *that* honestly; do not invent a quote to justify the tile.
98
+ - **Plain browse (no content filter) is exempt.** With no topic/keyword filter in effect there's nothing to "highlight"; a contextual lead-in (e.g. the start of the decision statement) is fine. The requirement applies whenever a content filter is what produced the result set.
99
+ - **Canonical reference:** `api/routes/search_postgres.py` (`ts_headline` snippet → `SearchResult.description` for the meeting, document, and decision legs) feeding `web_app/src/pages/UnifiedSearch.tsx` (`toStoryCard` / `toTranscriptCard` → `StoryCard.excerpt` via `highlightSnippet`). New filtered surfaces must follow this pattern.
100
+
101
+ ## Code Style
102
+ - **Python:** Type hints, PEP 8, `pathlib`.
103
+ - **React:** Functional components, TypeScript interfaces, Tailwind CSS.
104
+ - **dbt:** Use Medallion architecture (`bronze -> staging -> intermediate -> marts`).
105
+
106
+ ## Git Commit Standards (MANDATORY)
107
+ - **ALWAYS** use [Conventional Commits](https://www.conventionalcommits.org/) for ALL commit messages.
108
+ - Format: `<type>(<scope>): <description>`
109
+ - Types: `feat`, `fix`, `chore`, `docs`, `refactor`, `test`, `perf`, `ci`, `build`, `revert`
110
+ - Examples:
111
+ - `feat(api): add jurisdiction search endpoint`
112
+ - `fix(bronze): handle missing state_code in census loader`
113
+ - `chore(deps): upgrade loguru to 0.7.3`
114
+ - `docs(web_docs): add FastAPI deployment guide`
115
+
116
+ ## Branch & PR Workflow (MANDATORY)
117
+ - **NEVER push directly to `main`.** `main` is branch-protected on GitHub (`getcommunityone/open-navigator`): direct pushes are rejected. All changes land via pull request.
118
+ - **Every change goes through a PR.** Branch off the latest `main`, commit there, push the branch, and open a PR against `main`:
119
+ ```bash
120
+ git checkout main && git pull
121
+ git checkout -b <type>/<issue>-<slug> # e.g. feat/137-money-game-income (AGENTS.md: issue first)
122
+ # ... commit work (Conventional Commits) ...
123
+ git push -u origin <type>/<issue>-<slug>
124
+ gh pr create --base main
125
+ ```
126
+ - **A PR must be green before merge.** Required CI checks (Frontend Build, Documentation Build, Backend Tests, API Types) must pass; resolve all conversations. The Docker Build Test is **not** required (it self-skips when no Docker files change).
127
+ - **Agents merge when ready** (`AGENTS.md` standing rule #758). After `/create-pr` / `/pr-review`, if required CI is green, there is no conflict, and `pull_requests/pr-<n>-review.md` has no blocking findings, squash-merge without waiting for the owner to say "merge". Use `gh pr merge <n> --squash --admin` while branch protection requires a human approval GitHub forbids the author from giving. Exceptions that still wait for the owner: paid/GPU compute, publish outside the repo, destructive data or rule changes, or an explicit hold. When a second human reviewer exists, keep the written review and prefer their approval before merge.
128
+ - **Never rewrite or force-push shared history** (`main`, or any branch with an open PR). A parallel session may be committing alongside you: stage only your own files, and verify your work landed via `git log` rather than amending.
129
+ - **Agents/automation** must follow the same flow — branch + PR, never a direct push to `main`.
130
+
131
+ ## Git Commit Standards (MANDATORY)
132
+
133
+ ### Simple Python Scripts & Packages → Loguru
134
+ Use `loguru` for all standalone scripts and simple Python packages:
135
+ ```python
136
+ from loguru import logger
137
+
138
+ logger.info("Loading data from {}", source)
139
+ logger.success("Loaded {:,} rows", count)
140
+ logger.warning("Missing field: {}", field)
141
+ logger.error("Failed to connect: {}", err)
142
+ ```
143
+ - Import only `from loguru import logger` — no manual handler setup needed for scripts.
144
+ - Use `logger.success()` to signal a completed step.
145
+ - For scripts that write log files, follow the pattern in `scripts/load_bronze.py` (sink to timestamped file + `scripts/utils/log_sync.py` for upload).
146
+
147
+ ### FastAPI → OpenTelemetry
148
+ Use OpenTelemetry for all FastAPI services:
149
+ ```python
150
+ from opentelemetry import trace
151
+ from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
152
+
153
+ FastAPIInstrumentor.instrument_app(app)
154
+ tracer = trace.get_tracer(__name__)
155
+
156
+ with tracer.start_as_current_span("operation-name") as span:
157
+ span.set_attribute("key", value)
158
+ ```
159
+ - Instrument at app startup via `FastAPIInstrumentor`.
160
+ - Use spans for discrete operations (DB queries, external calls, enrichment steps).
161
+ - Export to OTLP collector; fall back to console exporter in development.
162
+
163
+ ### React → OpenTelemetry
164
+ Use OpenTelemetry for frontend observability:
165
+ ```typescript
166
+ import { trace } from '@opentelemetry/api';
167
+
168
+ const tracer = trace.getTracer('open-navigator-frontend');
169
+ const span = tracer.startSpan('fetch-jurisdictions');
170
+ // ... operation ...
171
+ span.end();
172
+ ```
173
+ - Initialize the Web SDK once in `src/instrumentation.ts`, imported at the app entry point.
174
+ - Use `@opentelemetry/sdk-trace-web` + `@opentelemetry/exporter-trace-otlp-http`.
175
+ - Instrument route changes and key user interactions (search, filter, data load).
176
+
177
+ ## Calendar Years — Storage vs Serialization
178
+ The rule splits by layer; do not conflate them:
179
+ - **SQL storage (columns):** a bare calendar year is an **`integer`** (`smallint` is fine) — never `text`/`varchar`/`double precision`/`numeric`. Integer keeps range filters (`WHERE year >= 2020`) and numeric sort correct. **Bronze** may keep the source-native type for raw fidelity, but **cast to `integer` by the staging layer** so intermediate/marts/`public` are uniform.
180
+ - **Real dates:** when you have a full date, use a `date`/`timestamp` column — not a year column.
181
+ - **JSON / API / manifests (the wire):** serialize a bare year as a **string** (e.g. `"year": "2026"`), not a number — JSON numbers get locale-formatted (e.g. `2,024`) by UI clients. Convert at the JSON boundary: `str(y)` in Python, `::text` in SQL/`jsonb_build_object`. A real `DATE`/`TIMESTAMP` already serializes as an ISO string, so this exception does not apply to it.
182
+ - **`calendar_year_label()`** (`scripts/utils/calendar_year_util.py`) is the canonical Python helper for the wire/string form — it normalizes any value to a clean 4-digit string or `None`. Use it at serialization / serving-table boundaries, **not** to define an integer storage column. Bronze raw loaders that land source-native `VARCHAR(4)` years via this helper are fine (raw fidelity); staging still casts to `integer`.
183
+ - Internal paths may still use numeric years for folders; convert with `str(y)` at the JSON boundary.
184
+ - Migration: `python scripts/discovery/fix_scraped_meetings_manifest_years.py` (see `--dry-run`).
CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ ## Our Standards
8
+
9
+ Examples of behavior that contributes to creating a positive environment include:
10
+
11
+ * Using welcoming and inclusive language
12
+ * Being respectful of differing viewpoints and experiences
13
+ * Gracefully accepting constructive criticism
14
+ * Focusing on what is best for the community
15
+ * Showing empathy towards other community members
16
+
17
+ Examples of unacceptable behavior by participants include:
18
+
19
+ * The use of sexualized language or imagery and unwelcome sexual attention or advances
20
+ * Trolling, insulting/derogatory comments, and personal or political attacks
21
+ * Public or private harassment
22
+ * Publishing others' private information, such as a physical or electronic address, without explicit permission
23
+ * Other conduct which could reasonably be considered inappropriate in a professional setting
24
+
25
+ ## Our Responsibilities
26
+
27
+ Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
28
+
29
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
30
+
31
+ ## Scope
32
+
33
+ This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
34
+
35
+ ## Enforcement
36
+
37
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at johnbowyer@communityone.com or by [opening an issue on GitHub](https://github.com/getcommunityone/open-navigator/issues). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
38
+
39
+ Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
40
+
41
+ ## Attribution
42
+
43
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
44
+
45
+ For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq
46
+
47
+ [homepage]: https://www.contributor-covenant.org
CONTRIBUTING.md ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to CommunityOne Open Navigator
2
+
3
+ Thank you for your interest in contributing to the CommunityOne Open Navigator project!!
4
+
5
+ ## How to Contribute
6
+
7
+ ### Reporting Bugs
8
+
9
+ If you find a bug, please open an issue with:
10
+ - A clear description of the problem
11
+ - Steps to reproduce
12
+ - Expected vs actual behavior
13
+ - Your environment (OS, Python version, etc.)
14
+
15
+ ### Suggesting Features
16
+
17
+ Feature requests are welcome! Please:
18
+ - Check if the feature has already been requested
19
+ - Clearly describe the feature and its use case
20
+ - Explain how it would benefit advocacy groups
21
+
22
+ ### Development Setup
23
+
24
+ Follow the [Quick Start Guide](web_docs/docs/quickstart.md) to get the three
25
+ services running locally. Pick the path for your OS:
26
+
27
+ - **macOS / Linux:** `./install.sh`, then `./start-all.sh` (see
28
+ [Option 1](web_docs/docs/quickstart.md#option-1-start-everything-at-once-recommended)).
29
+ - **Windows:** `.\install.ps1`, then `.\start-all.ps1` (see
30
+ [Option 4: Windows (PowerShell)](web_docs/docs/quickstart.md#option-4-windows-powershell)).
31
+
32
+ > **Heads-up — don't run `uv sync` to install the backend.** The root
33
+ > `pyproject.toml` is a uv *workspace*; `uv sync` installs only the `packages/*`
34
+ > libraries and skips the top-level `requirements.txt`, so the dev tools
35
+ > (`pytest`/`black`/`ruff`) and runtime deps like `yt-dlp` go missing. Install with
36
+ > `install.sh` / `install.ps1` / `pip install -r requirements.txt` instead.
37
+
38
+ ### Code Contributions
39
+
40
+ > **Developing on Windows?** The `Makefile` / `install.sh` flow is Unix-oriented — see [Developing on Windows](web_docs/docs/development/developing-on-windows.md) for `uv`-workspace setup and test-running notes.
41
+
42
+ 1. **Fork the repository**
43
+ 2. **Create a feature branch**
44
+ ```bash
45
+ git checkout -b feature/your-feature-name
46
+ ```
47
+
48
+ 3. **Make your changes**
49
+ - Follow the existing code style
50
+ - Add tests for new functionality
51
+ - Update documentation as needed
52
+
53
+ 4. **Run tests**
54
+ ```bash
55
+ pytest
56
+ black .
57
+ ruff check .
58
+ ```
59
+
60
+ 5. **Commit your changes**
61
+ ```bash
62
+ git commit -m "Add feature: description"
63
+ ```
64
+
65
+ 6. **Push and create a pull request**
66
+ ```bash
67
+ git push origin feature/your-feature-name
68
+ ```
69
+
70
+ ## Code Style
71
+
72
+ - Follow PEP 8 guidelines
73
+ - Use type hints
74
+ - Write docstrings for all public functions
75
+ - Keep functions focused and single-purpose
76
+ - Use meaningful variable names
77
+
78
+ ## Code of Conduct
79
+
80
+ This project values respectful, inclusive collaboration. We align with the principles of:
81
+ - **Open States Code of Conduct**: https://docs.openstates.org/code-of-conduct/
82
+ - Be respectful and professional
83
+ - Welcome diverse perspectives
84
+ - Focus on what's best for the community
85
+ - Show empathy towards other contributors
86
+
87
+ ## Contributing to Upstream Projects
88
+
89
+ We use data and patterns from several open source civic tech projects. When contributing scraper patterns or improvements back to upstream projects like **OpenStates**, please:
90
+
91
+ 1. **Follow their standards**: https://github.com/openstates/openstates-scrapers
92
+ 2. **Reference their documentation**: https://docs.openstates.org/contributing/local-database/
93
+ 3. **Respect their Code of Conduct**: https://docs.openstates.org/code-of-conduct/
94
+ 4. **Test locally** before submitting pull requests
95
+ 5. **Document data sources** used in scraper development
96
+
97
+ ## Testing
98
+
99
+ All new features should include tests. Run the test suite with:
100
+
101
+ ```bash
102
+ pytest tests/ -v
103
+ ```
104
+
105
+ ## Documentation
106
+
107
+ Update relevant documentation when:
108
+ - Adding new features
109
+ - Changing API endpoints
110
+ - Modifying configuration options
111
+ - Adding new dependencies
112
+
113
+ ## Questions?
114
+
115
+ Open an issue or reach out to the maintainers.
116
+
117
+ Thank you for helping improve oral health advocacy! 🦷
Dockerfile ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+ # Multi-stage build for Hugging Face Spaces
3
+ # Runs all three apps: Docusaurus docs, React frontend, FastAPI backend
4
+
5
+ FROM node:20-slim AS docs-builder
6
+ WORKDIR /build
7
+
8
+ # Set baseUrl to /docs/ for HuggingFace deployment # Docs are served at nginx /docs/ location
9
+ # routeBasePath: '/' in docusaurus.config.ts prevents /docs/docs/ nesting
10
+ ENV DOCUSAURUS_BASE_URL=/docs/
11
+
12
+ COPY web_docs/package*.json ./
13
+ RUN npm config set fetch-retry-mintimeout 20000 && \
14
+ npm config set fetch-retry-maxtimeout 120000 && \
15
+ npm ci --prefer-offline --no-audit || npm install --prefer-offline --no-audit
16
+
17
+ # Add cache-busting argument to force rebuild when needed
18
+ ARG CACHE_BUST=2026-04-27-12-00-fix-double-docs-prefix
19
+
20
+ COPY web_docs/ ./
21
+
22
+ # Verify environment variable is set and build
23
+ RUN echo "Building Docusaurus with DOCUSAURUS_BASE_URL=$DOCUSAURUS_BASE_URL" && \
24
+ echo "Cache bust: 2026-04-27-12-00-fix-double-docs-prefix" && \
25
+ npm run build && \
26
+ echo "Verifying baseUrl in build output..." && \
27
+ { grep -r "baseUrl" build/ | head -5 || true; }
28
+
29
+ FROM python:3.11-slim
30
+
31
+ # Install system dependencies, nginx, and Node.js for frontend build
32
+ RUN apt-get update && apt-get install -y \
33
+ build-essential \
34
+ curl \
35
+ git \
36
+ tesseract-ocr \
37
+ nginx \
38
+ supervisor \
39
+ && curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
40
+ && apt-get install -y nodejs \
41
+ && rm -rf /var/lib/apt/lists/*
42
+
43
+ WORKDIR /app
44
+
45
+ # Pre-install CPU-only torch/torchvision in their own cache-stable layer (no
46
+ # requirements.txt dependency). sentence-transformers pulls torch transitively;
47
+ # without this, pip drags in the ~2.5GB CUDA wheel — pure waste on a CPU-only HF
48
+ # Space. Installing it here means an edit to requirements.txt (e.g. a transformers
49
+ # pin bump) reuses this cached layer instead of redownloading the whole ML stack.
50
+ RUN --mount=type=cache,target=/root/.cache/pip \
51
+ pip install torch==2.8.0 torchvision==0.23.0 \
52
+ --index-url https://download.pytorch.org/whl/cpu
53
+
54
+ # Copy Python requirements and install. torch/torchvision are already satisfied
55
+ # above, so this layer only (re)installs the lighter packages on a pin change.
56
+ # The BuildKit cache mount persists pip's wheel cache (keeps the layer slim like
57
+ # --no-cache-dir did, while still caching downloads for local rebuilds).
58
+ COPY requirements.txt .
59
+ RUN --mount=type=cache,target=/root/.cache/pip \
60
+ pip install -r requirements.txt
61
+
62
+ # OPTIMIZATION: Copy frontend package files first for better caching
63
+ COPY web_app/package*.json /app/web_app/
64
+ RUN cd /app/web_app && npm ci
65
+
66
+ # Copy application code (now npm ci layer is cached)
67
+ COPY . .
68
+
69
+ # Install ALL workspace packages so they import as top-level modules at runtime
70
+ # (--no-deps keeps the dependency closure unchanged — their third-party deps are
71
+ # pinned in requirements.txt). The API eagerly imports agents, ingestion and llm
72
+ # in api/main.py / routes, and lazily imports scrapers; installing the whole set
73
+ # avoids a startup ModuleNotFoundError when any package imports a sibling package.
74
+ RUN pip install --no-cache-dir --no-deps \
75
+ ./packages/core ./packages/core-lib ./packages/datamodels ./packages/agents \
76
+ ./packages/scrapers ./packages/ingestion ./packages/llm \
77
+ ./packages/accessibility ./packages/hosting
78
+
79
+ # Copy built static files from docs stage
80
+ COPY --from=docs-builder /build/build /app/static/docs
81
+
82
+ # Build frontend (npm_modules already cached from above)
83
+ # Set production environment variables for Vite
84
+ ENV VITE_CANONICAL_DOMAIN=www.communityone.com
85
+ ENV VITE_API_URL=/api
86
+ # Cache bust: 2026-04-29-remove-axios
87
+ ARG CACHE_BUST_FRONTEND=2026-04-29-remove-axios
88
+ RUN cd /app/web_app && echo "Frontend build cache bust: $CACHE_BUST_FRONTEND" && npm run build
89
+
90
+ # Frontend is already built to /app/api/static/ via vite.config.ts
91
+ # Create frontend directory in /app/static for nginx
92
+ RUN mkdir -p /app/static/frontend && \
93
+ ls -la /app/api/static/ && \
94
+ cp -r /app/api/static/* /app/static/frontend/
95
+
96
+ # Create necessary directories
97
+ RUN mkdir -p /app/logs /app/data /var/log/supervisor
98
+
99
+ # Copy Hugging Face specific configs
100
+ COPY .huggingface/nginx.conf /etc/nginx/nginx.conf
101
+ COPY .huggingface/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
102
+ COPY .huggingface/start.sh /app/start.sh
103
+ COPY .huggingface/restore_lfs_static.sh /app/restore_lfs_static.sh
104
+ RUN chmod +x /app/start.sh /app/restore_lfs_static.sh
105
+
106
+ # Expose port 7860 (Hugging Face Spaces default)
107
+ EXPOSE 7860
108
+
109
+ # Set environment variables
110
+ ENV PYTHONUNBUFFERED=1
111
+ ENV LOG_LEVEL=INFO
112
+ ENV HF_SPACES=1
113
+
114
+ # Use supervisor to run all services
115
+ CMD ["/app/start.sh"]
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Support. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Community One
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
Makefile ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .PHONY: help install install-web_app install-docs build-web_app build-docs clean test run dev dev-web_app dev-docs start-all stop-all dev-full docker-up docker-down deploy-databricks grants-refresh setup-backup-drive backup-preflight backup backup-public backup-neon restore restore-public restore-neon azure-init azure-plan azure-apply azure-fmt
2
+
3
+ # Azure subscriptions Terraform (infra/azure). Creds load from infra/azure/.env (ARM_*),
4
+ # never committed. Override dir with AZURE_TF_DIR if needed.
5
+ AZURE_TF_DIR ?= infra/azure
6
+
7
+ help:
8
+ @echo "🦷 Open Navigator - Makefile Commands"
9
+ @echo "===================================================="
10
+ @echo ""
11
+ @echo "🚀 Quick Start:"
12
+ @echo " make start-all - Start ALL services (API + Dashboard + Docs) with tmux"
13
+ @echo " make stop-all - Stop all running services"
14
+ @echo ""
15
+ @echo "🐍 Python Backend:"
16
+ @echo " make install - Install Python dependencies in .venv"
17
+ @echo " make dev - Start backend with auto-reload"
18
+ @echo " make run - Start backend (production)"
19
+ @echo ""
20
+ @echo "⚛️ React Dashboard:"
21
+ @echo " make install-web_app - Install dashboard npm dependencies"
22
+ @echo " make build-web_app - Build React dashboard for production"
23
+ @echo " make dev-web_app - Start dashboard dev server"
24
+ @echo ""
25
+ @echo "📚 Documentation Site:"
26
+ @echo " make install-docs - Install Docusaurus dependencies"
27
+ @echo " make build-docs - Build documentation for production"
28
+ @echo " make dev-docs - Start documentation dev server"
29
+ @echo ""
30
+ @echo "☁️ Deployment:"
31
+ @echo " make deploy-databricks - Deploy to Databricks Apps"
32
+ @echo ""
33
+ @echo "🐳 Docker:"
34
+ @echo " make docker-up - Start Docker containers"
35
+ @echo " make docker-down - Stop Docker containers"
36
+ @echo ""
37
+ @echo "🧪 Testing:"
38
+ @echo " make test - Run test suite"
39
+ @echo " make clean - Remove build artifacts"
40
+ @echo ""
41
+ @echo "💰 Data Refresh:"
42
+ @echo " make grants-refresh - Refresh Grants.gov opportunities (incremental upsert)"
43
+ @echo ""
44
+ @echo "🏷️ Releases & Backups (semver, see web_docs Quick Start):"
45
+ @echo " make setup-backup-drive - Mount Google Drive (I:) and link open-navigator-backups"
46
+ @echo " make backup VERSION=v1.5.0 - Dump full open_navigator + openstates, push to Drive"
47
+ @echo " make backup-neon VERSION=v1.5.0 - Dump the Neon serving DB (civic only, NO user PII) [recommended]"
48
+ @echo " make backup-public VERSION=v1.5.0 - Dump the local public schema, personal user tables excluded"
49
+ @echo " make restore VERSION=v1.5.0 - Restore a full backup (dev only)"
50
+ @echo " make restore-neon VERSION=v1.5.0 - Restore Neon snapshot into local '$(NEON_RESTORE_DB)' (dev only)"
51
+ @echo " make restore-public VERSION=v1.5.0 - Restore the public schema (dev only; needs gold present)"
52
+ @echo ""
53
+ @echo "☁️ Azure subscriptions (Terraform, infra/azure — creds from infra/azure/.env):"
54
+ @echo " make azure-init - terraform init"
55
+ @echo " make azure-fmt - terraform fmt + validate"
56
+ @echo " make azure-plan - terraform plan"
57
+ @echo " make azure-apply - terraform apply"
58
+ @echo ""
59
+
60
+ # --- Azure subscriptions Terraform ------------------------------------------------
61
+ # Each target sources infra/azure/.env so ARM_* creds reach terraform without ever
62
+ # living in a .tf/.tfvars file. Fails loudly if .env is missing.
63
+ define _azure_tf
64
+ @command -v terraform >/dev/null 2>&1 || { echo "❌ terraform not installed (https://developer.hashicorp.com/terraform/install)"; exit 1; }
65
+ @test -f "$(AZURE_TF_DIR)/.env" || { echo "❌ $(AZURE_TF_DIR)/.env missing — copy $(AZURE_TF_DIR)/.env.example and fill in ARM_* creds"; exit 1; }
66
+ @set -a && . "$(AZURE_TF_DIR)/.env" && set +a && cd "$(AZURE_TF_DIR)" && terraform $(1)
67
+ endef
68
+
69
+ azure-init:
70
+ $(call _azure_tf,init)
71
+
72
+ azure-fmt:
73
+ $(call _azure_tf,fmt -recursive)
74
+ $(call _azure_tf,validate)
75
+
76
+ azure-plan:
77
+ $(call _azure_tf,plan)
78
+
79
+ azure-apply:
80
+ $(call _azure_tf,apply)
81
+
82
+ install:
83
+ @echo "📦 Creating virtual environment and installing dependencies..."
84
+ @chmod +x install.sh
85
+ @./install.sh
86
+
87
+ install-web_app:
88
+ @echo "📦 Installing dashboard dependencies..."
89
+ @cd web_app && npm install
90
+ @echo "✅ Dashboard dependencies installed!"
91
+
92
+ install-docs:
93
+ @echo "📦 Installing documentation dependencies..."
94
+ @cd web_docs && npm install
95
+ @echo "✅ Documentation dependencies installed!"
96
+
97
+ build-web_app:
98
+ @echo "🔨 Building React dashboard..."
99
+ @cd web_app && npm run build
100
+ @echo "✅ Dashboard built to api/static/"
101
+
102
+ build-docs:
103
+ @echo "🔨 Building documentation site..."
104
+ @cd web_docs && npm run build
105
+ @echo "✅ Documentation built to web_docs/build/"
106
+
107
+ clean:
108
+ @echo "🧹 Cleaning up..."
109
+ @rm -rf .venv venv
110
+ @rm -rf web_app/node_modules web_app/dist
111
+ @rm -rf web_docs/node_modules web_docs/build web_docs/.docusaurus
112
+ @rm -rf api/static
113
+ @rm -rf __pycache__
114
+ @find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
115
+ @find . -type f -name "*.pyc" -delete
116
+ @find . -type f -name "*.pyo" -delete
117
+ @rm -rf .pytest_cache
118
+ @rm -rf .coverage
119
+ @rm -rf htmlcov
120
+ @rm -rf dist
121
+ @rm -rf build
122
+ @rm -rf *.egg-info
123
+ @rm -rf logs/*.pid logs/*.log
124
+ @echo "✅ Cleanup complete"
125
+
126
+ test:
127
+ @echo "🧪 Running tests..."
128
+ @. .venv/bin/activate && pytest tests/ -v
129
+
130
+ run: build-web_app
131
+ @echo "🚀 Starting application (production mode)..."
132
+ @. .venv/bin/activate && uvicorn api.app:app --host 0.0.0.0 --port 8000
133
+
134
+ dev:
135
+ @echo "🔧 Starting backend with auto-reload..."
136
+ @echo "📡 Backend running at http://localhost:8000"
137
+ @. .venv/bin/activate && uvicorn api.app:app --reload
138
+
139
+ dev-web_app:
140
+ @echo "⚛️ Starting dashboard dev server..."
141
+ @echo "📡 Dashboard running at http://localhost:5173"
142
+ @cd web_app && npm run dev
143
+
144
+ dev-docs:
145
+ @echo "📚 Starting documentation dev server..."
146
+ @echo "📡 Documentation running at http://localhost:3000"
147
+ @cd web_docs && npm start
148
+
149
+ start-all:
150
+ @echo "🚀 Starting all services with tmux..."
151
+ @chmod +x start-all.sh
152
+ @./start-all.sh
153
+
154
+ stop-all:
155
+ @echo "🛑 Stopping all services..."
156
+ @chmod +x stop-all.sh
157
+ @./stop-all.sh
158
+
159
+ dev-full:
160
+ @echo "🚀 Use 'make start-all' for better experience with tmux!"
161
+ @echo ""
162
+ @echo "Starting backend and web_app (manual)..."
163
+ @echo "📡 Backend: http://localhost:8000"
164
+ @echo "📡 Dashboard: http://localhost:5173"
165
+ @echo "📡 Docs: http://localhost:3000 (run 'make dev-docs' in another terminal)"
166
+ @echo ""
167
+ @. .venv/bin/activate && uvicorn api.app:app --reload & \
168
+ cd web_app && npm run dev
169
+
170
+ deploy-databricks:
171
+ @echo "☁️ Deploying to Databricks Apps..."
172
+ @chmod +x scripts/deploy-databricks-app.sh
173
+ @./scripts/deploy-databricks-app.sh
174
+
175
+ docker-up:
176
+ @echo "Starting Docker containers..."
177
+ @docker-compose up -d
178
+ @echo "✓ Containers started"
179
+ @echo " API: http://localhost:8000"
180
+ @echo " Docs: http://localhost:8000/docs"
181
+
182
+ docker-down:
183
+ @echo "Stopping Docker containers..."
184
+ @docker-compose down
185
+ @echo "✓ Containers stopped"
186
+
187
+ example:
188
+ @echo "Running example workflow..."
189
+ @. .venv/bin/activate && python examples/example_workflow.py
190
+
191
+ heatmap:
192
+ @echo "Generating example heatmap..."
193
+ @. .venv/bin/activate && python main.py generate-heatmap --output example_heatmap.html
194
+ @echo "✓ Heatmap saved to example_heatmap.html"
195
+
196
+ init:
197
+ @echo "Initializing system..."
198
+ @. .venv/bin/activate && python main.py init
199
+
200
+ status:
201
+ @echo "Checking system status..."
202
+ @. .venv/bin/activate && python main.py status
203
+
204
+ format:
205
+ @echo "Formatting code..."
206
+ @. .venv/bin/activate && black .
207
+ @. .venv/bin/activate && ruff check . --fix
208
+ @echo "✓ Code formatted"
209
+
210
+ lint:
211
+ @echo "Linting code..."
212
+ @. .venv/bin/activate && ruff check .
213
+ @. .venv/bin/activate && mypy agents/ pipeline/ visualization/ api/
214
+
215
+ # Incremental refresh of Grants.gov federal opportunities -> public.grant_opportunity.
216
+ # Bronze upserts by opportunity_id (no --truncate), then the dbt mart merges
217
+ # incrementally (delete+insert on the PK). Safe to run on a schedule/cron.
218
+ # DSN defaults to local dev; export DATABASE_URL/NEON_DATABASE_URL_DEV to override.
219
+ grants-refresh:
220
+ @echo "💰 Refreshing Grants.gov opportunities (incremental)..."
221
+ @: $${DATABASE_URL:=postgresql://postgres:password@localhost:5433/open_navigator}; \
222
+ export DATABASE_URL NEON_DATABASE_URL_DEV=$${NEON_DATABASE_URL_DEV:-$$DATABASE_URL}; \
223
+ . .venv/bin/activate && python -m ingestion.grants_gov.bronze
224
+ @cd dbt_project && .venv_dbt/bin/dbt run --select stg_grants_gov__opportunity grant_opportunity
225
+ @echo "✅ grant_opportunity refreshed"
226
+
227
+ # --- Releases & Data Versioning -------------------------------------------------
228
+ # Tie a semantic-version release tag to a Postgres backup of the warehouse so the
229
+ # code at a tag can be reproduced against the exact data it shipped with.
230
+ # See web_docs/docs/quickstart.md (Releases & Data Versioning) for the full flow.
231
+ #
232
+ # make backup VERSION=v1.5.0 # dump both DBs (version-stamped) into the Drive folder
233
+ # make restore VERSION=v1.5.0 # restore that version's dumps from the Drive folder (DEV ONLY)
234
+ #
235
+ # BACKUP_DIR is a WSL symlink that points at the Google Drive for Desktop folder on
236
+ # Windows (open-navigator-backups -> /mnt/i/My Drive/open-navigator-backups). Writing
237
+ # there means Google Drive auto-syncs the dumps off-machine — no rclone needed.
238
+ #
239
+ # pg_dump streams to a LOCAL staging dir first (BACKUP_STAGING, on fast ext4), then the
240
+ # finished file is copied into the Drive folder. This sidesteps a known DriveFS-over-WSL
241
+ # failure mode where large sequential writes straight into the virtual I: drive stall.
242
+ # One-time setup is documented in web_docs/docs/quickstart.md.
243
+ # Override any of these via env. Defaults match the local dev warehouse (localhost:5433).
244
+ PG_HOST ?= localhost
245
+ PG_PORT ?= 5433
246
+ PG_USER ?= postgres
247
+ PGPASSWORD ?= password
248
+ BACKUP_DIR ?= open-navigator-backups
249
+ BACKUP_STAGING ?= .backup-staging
250
+ # Local DB to restore a Neon serving snapshot into (NEVER prod; localhost only).
251
+ NEON_RESTORE_DB ?= open_navigator_serving
252
+ # Personal / app-owned tables in public.* that must NEVER land in a shared snapshot.
253
+ # Mirrors RUNTIME_OWNED in packages/hosting/src/hosting/neon/sync_public_to_neon.py — the
254
+ # same set the Neon serving DB already excludes (user accounts, OAuth state, social graph,
255
+ # feed prefs). backup-public strips these so no personal user data leaves the machine.
256
+ PII_EXCLUDE_TABLES ?= user contact_oauth_state social_follows user_lens_prefs user_locations user_signal_prefs meeting_document_gap_cache job_application_link contact_submission stance_response
257
+ # Postgres client tools. `pg_dump` must be >= the server it dumps (Neon is PG 17), and
258
+ # `pg_restore` >= the dump's archive format — a mismatched major aborts the dump. We
259
+ # AUTO-SELECT the newest client installed under /usr/lib/postgresql/*/bin, so PG 17 is used
260
+ # even when PATH still points at PG 16; this is empty (→ PATH) on other platforms. Override
261
+ # explicitly with PG_BIN=/usr/lib/postgresql/17/bin/ (or PG_BIN= to force PATH).
262
+ PG_BIN ?= $(shell ls -d /usr/lib/postgresql/*/bin/ 2>/dev/null | sort -V | tail -1)
263
+ PG_DUMP ?= $(PG_BIN)pg_dump
264
+ PG_RESTORE ?= $(PG_BIN)pg_restore
265
+ PG_CREATEDB ?= $(PG_BIN)createdb
266
+
267
+ # Google Drive backup folder one-time setup. Default drive letter I: (override DRIVE_LETTER=H).
268
+ DRIVE_LETTER ?= I
269
+
270
+ setup-backup-drive:
271
+ @set -e; \
272
+ letter="$(DRIVE_LETTER)"; \
273
+ lc=$$(printf '%s' "$$letter" | tr '[:upper:]' '[:lower:]'); \
274
+ root="/mnt/$$lc"; \
275
+ drive="$$letter:"; \
276
+ target="$$root/My Drive/open-navigator-backups"; \
277
+ echo "📁 Setting up backup folder on $$drive ($$root)..."; \
278
+ sudo mkdir -p "$$root"; \
279
+ if ! mountpoint -q "$$root" 2>/dev/null; then \
280
+ sudo mount -t drvfs "$$drive" "$$root"; \
281
+ fi; \
282
+ if grep -qE '^H:[[:space:]]+/mnt/h[[:space:]]' /etc/fstab 2>/dev/null; then \
283
+ echo "🔄 Removing stale H: entry from /etc/fstab..."; \
284
+ sudo sed -i '/^H:[[:space:]]\+\/mnt\/h[[:space:]]/d' /etc/fstab; \
285
+ fi; \
286
+ if ! grep -qE "^$$letter:[[:space:]]+$$root[[:space:]]" /etc/fstab 2>/dev/null; then \
287
+ echo "$$drive $$root drvfs defaults 0 0" | sudo tee -a /etc/fstab; \
288
+ fi; \
289
+ mkdir -p "$$target"; \
290
+ ln -sfn "$$target" open-navigator-backups; \
291
+ test -d open-navigator-backups/ && echo "✅ Drive backup folder ready at open-navigator-backups → $$target"
292
+
293
+ # Verify the Drive folder is reachable, and if not, diagnose *why* and print the exact
294
+ # fix. Most common cause: the WSL symlink exists but the Drive letter never got mounted
295
+ # (e.g. after a WSL restart with no /etc/fstab entry) — see web_docs/docs/quickstart.md.
296
+ backup-preflight:
297
+ @test -d "$(BACKUP_DIR)/" && exit 0; \
298
+ echo "❌ $(BACKUP_DIR) does not resolve to a directory."; \
299
+ if [ -L "$(BACKUP_DIR)" ]; then \
300
+ tgt=$$(readlink "$(BACKUP_DIR)"); \
301
+ root=$$(printf '%s' "$$tgt" | grep -oE '^/mnt/[a-z]+'); \
302
+ letter=$$(printf '%s' "$$root" | sed -E 's:^/mnt/::' | tr a-z A-Z); \
303
+ echo " Symlink → $$tgt"; \
304
+ if [ -n "$$root" ] && ! mountpoint -q "$$root" 2>/dev/null; then \
305
+ echo " Drive letter $$letter: is not mounted in WSL. Mount it once (needs sudo password):"; \
306
+ echo " sudo mkdir -p $$root && sudo mount -t drvfs '$$letter:' $$root"; \
307
+ echo " echo '$$letter: $$root drvfs defaults 0 0' | sudo tee -a /etc/fstab # persist across WSL restarts"; \
308
+ echo " (Google Drive for Desktop must be running on Windows so $$letter: exists.)"; \
309
+ else \
310
+ echo " Mount is present but the folder is missing. Create it: mkdir -p \"$$tgt\""; \
311
+ fi; \
312
+ else \
313
+ echo " Symlink '$(BACKUP_DIR)' is missing. See web_docs/docs/quickstart.md (Google Drive folder one-time setup)."; \
314
+ fi; \
315
+ exit 1
316
+
317
+ backup:
318
+ @test -n "$(VERSION)" || { echo "❌ VERSION required, e.g. make backup VERSION=v1.5.0"; exit 1; }
319
+ @$(MAKE) --no-print-directory backup-preflight
320
+ @set -e; stamp=$$(date +%Y%m%d); sha=$$(git rev-parse --short HEAD 2>/dev/null || echo nogit); \
321
+ stage="$(BACKUP_STAGING)/$(VERSION)"; case "$(VERSION)" in v[0-9]*) sub=releases;; *) sub=snapshots;; esac; dir="$(BACKUP_DIR)/$$sub/$(VERSION)"; \
322
+ mkdir -p "$$stage" "$$dir"; \
323
+ on="open_navigator_$(VERSION)_$${stamp}_$${sha}.dump"; \
324
+ os="openstates_$(VERSION)_$${stamp}_$${sha}.dump"; \
325
+ echo "📦 Dumping open_navigator + openstates at $(VERSION) ($$stamp, $$sha) to local staging..."; \
326
+ PGPASSWORD=$(PGPASSWORD) $(PG_DUMP) -h $(PG_HOST) -p $(PG_PORT) -U $(PG_USER) -Fc open_navigator -f "$$stage/$$on"; \
327
+ PGPASSWORD=$(PGPASSWORD) $(PG_DUMP) -h $(PG_HOST) -p $(PG_PORT) -U $(PG_USER) -Fc openstates -f "$$stage/$$os"; \
328
+ echo "📤 Copying dumps into the Drive folder ($$dir/)..."; \
329
+ cp "$$stage/$$on" "$$dir/$$on" && cp "$$stage/$$os" "$$dir/$$os"; \
330
+ rm -rf "$$stage"; \
331
+ echo "✅ Dumps in $$dir/ — Google Drive for Desktop will sync them off-machine automatically."
332
+
333
+ restore:
334
+ @test -n "$(VERSION)" || { echo "❌ VERSION required, e.g. make restore VERSION=v1.5.0"; exit 1; }
335
+ @$(MAKE) --no-print-directory backup-preflight
336
+ @echo "⚠️ Restoring $(VERSION) into LOCAL dev warehouse ($(PG_HOST):$(PG_PORT)) — never run against prod."
337
+ @dir=$$(ls -d "$(BACKUP_DIR)"/releases/$(VERSION) "$(BACKUP_DIR)"/snapshots/$(VERSION) 2>/dev/null | head -1); test -n "$$dir" || dir="$(BACKUP_DIR)/snapshots/$(VERSION)"; \
338
+ on=$$(ls "$$dir"/open_navigator_$(VERSION)_*.dump 2>/dev/null | head -1); \
339
+ os=$$(ls "$$dir"/openstates_$(VERSION)_*.dump 2>/dev/null | head -1); \
340
+ test -n "$$on" -a -n "$$os" || { echo "❌ Could not find $(VERSION) dumps in $$dir/"; exit 1; }; \
341
+ echo "♻️ Restoring open_navigator from $$on..."; \
342
+ PGPASSWORD=$(PGPASSWORD) $(PG_RESTORE) -h $(PG_HOST) -p $(PG_PORT) -U $(PG_USER) -d open_navigator --clean --if-exists "$$on"; \
343
+ echo "♻️ Restoring openstates from $$os..."; \
344
+ PGPASSWORD=$(PGPASSWORD) $(PG_RESTORE) -h $(PG_HOST) -p $(PG_PORT) -U $(PG_USER) -d openstates --clean --if-exists "$$os"; \
345
+ echo "✅ Restored $(VERSION)"
346
+
347
+ # Public-only backup: dumps ONLY the `public` serving schema of open_navigator, stored as
348
+ # its own dump file separate from the bronze/gold/private warehouse. Tiny vs the ~170GB DB.
349
+ # The personal/app-owned tables (PII_EXCLUDE_TABLES — user accounts, OAuth state, social
350
+ # graph, feed prefs) are EXCLUDED, so no personal user data leaves the machine; the dump
351
+ # is the civic serving layer only (views + event_documents).
352
+ # A `--schema=public` dump does NOT include the extensions (pg_trgm, btree_gin, …) that
353
+ # live in `public`, so it never DROPs them on restore — gold's indexes are safe.
354
+ # Caveat: the public views are defined over `gold`, so restoring them needs `gold`
355
+ # present (restore the full/private warehouse first, or restore onto your existing one).
356
+ backup-public:
357
+ @test -n "$(VERSION)" || { echo "❌ VERSION required, e.g. make backup-public VERSION=v1.5.0"; exit 1; }
358
+ @$(MAKE) --no-print-directory backup-preflight
359
+ @set -e; stamp=$$(date +%Y%m%d); sha=$$(git rev-parse --short HEAD 2>/dev/null || echo nogit); \
360
+ stage="$(BACKUP_STAGING)/$(VERSION)"; case "$(VERSION)" in v[0-9]*) sub=releases;; *) sub=snapshots;; esac; dir="$(BACKUP_DIR)/$$sub/$(VERSION)"; \
361
+ mkdir -p "$$stage" "$$dir"; \
362
+ f="open_navigator_public_$(VERSION)_$${stamp}_$${sha}.dump"; \
363
+ excl=""; for t in $(PII_EXCLUDE_TABLES); do excl="$$excl --exclude-table=public.$$t"; done; \
364
+ echo "📦 Dumping open_navigator schema 'public' (civic only — personal user tables excluded) at $(VERSION)..."; \
365
+ PGPASSWORD=$(PGPASSWORD) $(PG_DUMP) -h $(PG_HOST) -p $(PG_PORT) -U $(PG_USER) -Fc --no-owner --no-privileges --schema=public $$excl open_navigator -f "$$stage/$$f"; \
366
+ echo "📤 Copying dump into the Drive folder ($$dir/)..."; \
367
+ cp "$$stage/$$f" "$$dir/$$f"; \
368
+ rm -rf "$$stage"; \
369
+ echo "✅ Public-only dump (no personal user data) in $$dir/$$f — Google Drive will sync it off-machine."
370
+
371
+ # Neon serving backup (recommended for a PII-free public snapshot): dumps the PRODUCTION
372
+ # Neon serving DB from NEON_DATABASE_URL in .env. That DB is civic-only by construction —
373
+ # sync_public_to_neon.py NEVER mirrors the user/auth/social/feed tables — and its serving
374
+ # objects are real materialized tables (not views over gold), so the dump is standalone
375
+ # AND contains no personal user data. pg_dump is READ-ONLY, so it is safe against prod.
376
+ # We strip Neon's `-pooler` host suffix because pg_dump needs the direct (session) endpoint.
377
+ # `--no-owner --no-privileges` drops Neon's role/grants so the dump restores cleanly under
378
+ # the LOCAL `$(PG_USER)` user (restore-neon also passes --role=$(PG_USER)).
379
+ backup-neon:
380
+ @test -n "$(VERSION)" || { echo "❌ VERSION required, e.g. make backup-neon VERSION=v1.5.0"; exit 1; }
381
+ @$(MAKE) --no-print-directory backup-preflight
382
+ @set -e; url=$$(grep -E '^NEON_DATABASE_URL=' .env 2>/dev/null | head -1 | cut -d= -f2- | tr -d '"' | tr -d "'"); \
383
+ test -n "$$url" || { echo "❌ NEON_DATABASE_URL not found in .env (the prod serving DB)."; exit 1; }; \
384
+ url=$$(printf '%s' "$$url" | sed 's/-pooler//'); \
385
+ stamp=$$(date +%Y%m%d); sha=$$(git rev-parse --short HEAD 2>/dev/null || echo nogit); \
386
+ stage="$(BACKUP_STAGING)/$(VERSION)"; case "$(VERSION)" in v[0-9]*) sub=releases;; *) sub=snapshots;; esac; dir="$(BACKUP_DIR)/$$sub/$(VERSION)"; \
387
+ mkdir -p "$$stage" "$$dir"; \
388
+ f="neon_serving_$(VERSION)_$${stamp}_$${sha}.dump"; \
389
+ echo "📦 Dumping Neon serving DB (civic only — no personal user data) at $(VERSION) to local staging..."; \
390
+ $(PG_DUMP) --no-owner --no-privileges -Fc "$$url" -f "$$stage/$$f"; \
391
+ echo "📤 Copying dump into the Drive folder ($$dir/)..."; \
392
+ cp "$$stage/$$f" "$$dir/$$f"; \
393
+ rm -rf "$$stage"; \
394
+ echo "✅ Neon serving dump (no PII) in $$dir/$$f — Google Drive will sync it off-machine."
395
+
396
+ # Restore a Neon serving snapshot into a SEPARATE LOCAL database (default
397
+ # open_navigator_serving on localhost:5433). Never touches prod and never the main
398
+ # open_navigator warehouse. Point the API at it (NEON_DATABASE_URL_DEV) for a PII-free
399
+ # local serving instance.
400
+ restore-neon:
401
+ @test -n "$(VERSION)" || { echo "❌ VERSION required, e.g. make restore-neon VERSION=v1.5.0"; exit 1; }
402
+ @$(MAKE) --no-print-directory backup-preflight
403
+ @echo "⚠️ Restoring Neon serving $(VERSION) into LOCAL db '$(NEON_RESTORE_DB)' ($(PG_HOST):$(PG_PORT)) — never prod."
404
+ @dir=$$(ls -d "$(BACKUP_DIR)"/releases/$(VERSION) "$(BACKUP_DIR)"/snapshots/$(VERSION) 2>/dev/null | head -1); test -n "$$dir" || dir="$(BACKUP_DIR)/snapshots/$(VERSION)"; \
405
+ f=$$(ls "$$dir"/neon_serving_$(VERSION)_*.dump 2>/dev/null | head -1); \
406
+ test -n "$$f" || { echo "❌ Could not find $(VERSION) Neon dump in $$dir/ (run: make backup-neon VERSION=$(VERSION))"; exit 1; }; \
407
+ PGPASSWORD=$(PGPASSWORD) $(PG_CREATEDB) -h $(PG_HOST) -p $(PG_PORT) -U $(PG_USER) $(NEON_RESTORE_DB) 2>/dev/null || true; \
408
+ echo "♻️ Restoring $$f into $(NEON_RESTORE_DB)..."; \
409
+ PGPASSWORD=$(PGPASSWORD) $(PG_RESTORE) -h $(PG_HOST) -p $(PG_PORT) -U $(PG_USER) -d $(NEON_RESTORE_DB) --no-owner --no-privileges --role=$(PG_USER) --clean --if-exists "$$f"; \
410
+ echo "✅ Restored Neon serving $(VERSION) into local '$(NEON_RESTORE_DB)' (owned by $(PG_USER))"
411
+
412
+ restore-public:
413
+ @test -n "$(VERSION)" || { echo "❌ VERSION required, e.g. make restore-public VERSION=v1.5.0"; exit 1; }
414
+ @$(MAKE) --no-print-directory backup-preflight
415
+ @echo "⚠️ Restoring $(VERSION) PUBLIC schema into LOCAL dev warehouse ($(PG_HOST):$(PG_PORT)) — never run against prod."
416
+ @echo " Note: public serving views reference 'gold'; restore the full backup first if gold is absent."
417
+ @dir=$$(ls -d "$(BACKUP_DIR)"/releases/$(VERSION) "$(BACKUP_DIR)"/snapshots/$(VERSION) 2>/dev/null | head -1); test -n "$$dir" || dir="$(BACKUP_DIR)/snapshots/$(VERSION)"; \
418
+ f=$$(ls "$$dir"/open_navigator_public_$(VERSION)_*.dump 2>/dev/null | head -1); \
419
+ test -n "$$f" || { echo "❌ Could not find $(VERSION) public dump in $$dir/ (run: make backup-public VERSION=$(VERSION))"; exit 1; }; \
420
+ echo "♻️ Restoring open_navigator (public schema only) from $$f..."; \
421
+ PGPASSWORD=$(PGPASSWORD) $(PG_RESTORE) -h $(PG_HOST) -p $(PG_PORT) -U $(PG_USER) -d open_navigator --schema=public --clean --if-exists "$$f"; \
422
+ echo "✅ Restored $(VERSION) public schema"
README.md ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Open Navigator
3
+ emoji: 🏛️
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ license: apache-2.0
10
+ ---
11
+
12
+ # Open Navigator
13
+ **See what your local government decided, with the record to prove it.**
14
+
15
+ **The goal: one map for every community.** The U.S. has 91,438 local governments (U.S. Census Bureau, 2025), and
16
+ each publishes its agendas, minutes, videos and budgets its own way. Open Navigator, the open-source engine behind
17
+ [CommunityOne](https://www.communityone.com) (a 501(c)(3) nonprofit), reads those public records, plus nonprofit
18
+ filings and Census data, and shows what was decided, where, and the passage from the record that says so. Nothing on
19
+ the site is a made-up number: when data is missing, it says so.
20
+
21
+ **Coverage today:** 1,926,908 nonprofits, 153,235 meetings and events, 34,289 government officials and 4,495 decisions extracted by AI, from [/api/stats](https://www.communityone.com/api/stats) (snapshot dated June 5, 2026, read November 14, 2026). Jurisdiction counts are left out until that endpoint reports them correctly ([#291](https://github.com/getcommunityone/open-navigator/issues/291)).
22
+
23
+ **Live:** [communityone.com](https://www.communityone.com) · [docs](https://www.communityone.com/docs) ·
24
+ [API](https://www.communityone.com/api) · Apache 2.0
25
+
26
+ <a href="web_docs/docs/pitch/full-text-and-notes.md"><img src="web_docs/static/img/deck-cover.png" alt="Local decisions shape daily life. Most people never see them." width="480"></a>
27
+
28
+ | For | Go to |
29
+ |---|---|
30
+ | **Executives and funders** (12 slides, 10 minutes) | [read the pitch with speaker notes](web_docs/docs/pitch/full-text-and-notes.md) · [slides](https://www.communityone.com/docs/deck/) ([source](web_docs/static/deck/index.html): download and open in a browser) |
31
+ | **Residents** | [the app](https://www.communityone.com) · [guide for citizens](web_docs/docs/for-citizens.md) |
32
+ | **Advocates and nonprofit leaders** | [guide for advocates](web_docs/docs/for-advocates.md) · [accountability strategy](web_docs/docs/guides/accountability-strategy.md) |
33
+ | **Researchers and data analysts** | [data sources](web_docs/docs/data-sources/overview.md) · [data model](web_docs/docs/data-sources/data-model-erd.md) · [citations](CITATIONS.md) |
34
+ | **Developers and data engineers** | [code walkthrough](web_docs/docs/development/code-walkthrough.md) · [quick start](web_docs/docs/quickstart.md) · [architecture](web_docs/docs/architecture.md) · [how we work](AGENTS.md) |
35
+ | **Data platform and DataOps engineers** | [DataOps walkthrough](web_docs/docs/development/dataops-walkthrough.md): retries, recovery, data quality, AI observability, two real incidents, and what isn't built yet |
36
+ | **Students** | [learning path](web_docs/docs/for-students.md): statistics, SQL and window functions, data modeling, dbt, master data management, logistic regression, clustering, embeddings, LLMs, Databricks, MLOps, GitHub Actions, AWS, Azure, security and secrets, ontologies, data contracts and data products, each with a code walkthrough |
37
+
38
+ **This quarter: data center accountability** (planned, not built yet). Residents ask what's being built near them,
39
+ who approved it, what it does to their bill and whether the jobs are real. The plan, October to December 2026:
40
+ [epic #236](https://github.com/getcommunityone/open-navigator/issues/236).
41
+
42
+ <details>
43
+ <summary><b>The six stories</b></summary>
44
+
45
+ - Job promises, on the record: [jobs split by phase](https://github.com/getcommunityone/open-navigator/issues/246) ·
46
+ [promise attributed to a speaker](https://github.com/getcommunityone/open-navigator/issues/247) ·
47
+ [live application links](https://github.com/getcommunityone/open-navigator/issues/248)
48
+ - The pipeline near me: [proposed sites near me](https://github.com/getcommunityone/open-navigator/issues/249) ·
49
+ [site matched to a coming agenda](https://github.com/getcommunityone/open-navigator/issues/250) ·
50
+ [alerts ranked by local concern](https://github.com/getcommunityone/open-navigator/issues/251)
51
+
52
+ They build on the meeting citations in the [CORE epic](https://github.com/getcommunityone/open-navigator/issues/235).
53
+ </details>
54
+
55
+ Each role has more below. Click to open.
56
+
57
+ <details>
58
+ <summary><b>Executives and funders</b>: the pitch in ten minutes</summary>
59
+
60
+ The [slideshow](https://www.communityone.com/docs/deck/) covers who it is for, the problem, what it does, the story
61
+ lenses, the policy model, how the pipeline works, the trust rules, what is open, this quarter's data center work,
62
+ an honest status, and the ask.
63
+ Press **N** for speaker notes, **S** for the speaker view. The [full text and notes](web_docs/docs/pitch/full-text-and-notes.md)
64
+ has every slide's words, for reading on a phone or searching.
65
+
66
+ Where it stands: live and useful, and still uneven. Meeting analysis is deep in a few states and thin elsewhere, and
67
+ it is a small nonprofit project with one maintainer. Data, review and pilot communities help most. Contact:
68
+ johnbowyer@communityone.com.
69
+
70
+ To edit the deck, change a slide in `web_docs/deck/slides/` and run `node web_docs/scripts/build-deck.mjs`.
71
+ </details>
72
+
73
+ <details>
74
+ <summary><b>Residents</b>: what did my city or school board decide?</summary>
75
+
76
+ - Search a topic at [communityone.com](https://www.communityone.com), pick your state or city, and open any result to
77
+ see the passage from the record it came from.
78
+ - Set up **Close to Home** for a feed of the places and issues you choose.
79
+ - Story lenses point to what is worth a look: **Contested** (split votes), **Money Moves** (contracts, grants, budget
80
+ changes), **Raised Eyebrows** (unusual patterns, for a person to review), **Moving Fast** and **Watch Next** (votes
81
+ coming up, where you can still speak).
82
+ - More: [guide for citizens](web_docs/docs/for-citizens.md), [community resources](web_docs/docs/citizens/community-resources.md),
83
+ [voter registration](web_docs/docs/citizens/voter-registration.md).
84
+ </details>
85
+
86
+ <details>
87
+ <summary><b>Advocates and nonprofit leaders</b>: where is my issue moving?</summary>
88
+
89
+ - **Policy questions** follow one issue across places: each vote links to the question behind it and the arguments
90
+ made for and against it.
91
+ - **Money and talk** puts budgets and spending next to what officials said in meetings.
92
+ - **Nonprofits**: IRS filings (Form 990) by place and cause.
93
+ - More: [guide for advocates](web_docs/docs/for-advocates.md), [accountability strategy](web_docs/docs/guides/accountability-strategy.md),
94
+ [legislative tracking](web_docs/docs/guides/legislative-tracking.md), [case study: Tuscaloosa](web_docs/docs/case-studies/tuscaloosa-complete.md).
95
+ </details>
96
+
97
+ <details>
98
+ <summary><b>Researchers and data analysts</b>: what does the record say, at scale?</summary>
99
+
100
+ - **Open datasets** on Hugging Face: [publishing guide](web_docs/docs/guides/huggingface-publishing.md).
101
+ - **Data model**: [entity diagram](web_docs/docs/data-sources/data-model-erd.md), [marts](web_docs/docs/data-sources/marts-erd.md),
102
+ [data contracts](web_docs/docs/development/data-contracts.md).
103
+ - **Sources and licences**: [data sources overview](web_docs/docs/data-sources/overview.md), [CITATIONS.md](CITATIONS.md).
104
+ Meeting data follows the Council Data Project's model; places use Open Civic Data IDs.
105
+ - **AI assistants**: an MCP server lets Claude and other assistants query the data. [MCP guide](web_docs/docs/integrations/mcp-server.md).
106
+ </details>
107
+
108
+ <details>
109
+ <summary><b>Students</b>: learn AI and data engineering from a real system</summary>
110
+
111
+ **Start with the [learning path](web_docs/docs/for-students.md):** each topic gives the idea in plain words, the code to
112
+ read, why it's built that way, and something to try. Topics don't depend on each other.
113
+
114
+ | Topic | Learn it from |
115
+ |---|---|
116
+ | Basic statistics | Median vs mean, p90, outliers and minimum sample sizes in [minutes publish lag](dbt_project/models/marts/jurisdiction_minutes_publish_lag.sql) |
117
+ | SQL and window functions | `row_number`, `lag`, `ntile`, recursive CTEs in [int_civic__item_signals.sql](dbt_project/models/intermediate/int_civic__item_signals.sql) |
118
+ | Data modeling | Grain, keys and a many-to-many bridge in [mdm_bridge_person_jurisdiction.sql](dbt_project/models/marts/mdm_bridge_person_jurisdiction.sql) |
119
+ | dbt and medallion layers | [dbt_project/models/](dbt_project/models): bronze → staging → intermediate → marts, with tests and seeds |
120
+ | Master data management | Golden records and entity resolution with Splink in [mdm/linker.py](packages/ingestion/src/ingestion/mdm/linker.py) |
121
+ | Logistic regression | Log-odds and the logistic function, as Splink uses them in [mdm/settings.py](packages/ingestion/src/ingestion/mdm/settings.py); a trained example is a good first issue ([#373](https://github.com/getcommunityone/open-navigator/issues/373)) |
122
+ | Clustering | HDBSCAN with a noise bucket in [cluster.py](packages/llm/src/llm/policy_questions/cluster.py) |
123
+ | Embeddings and RAG | [encoder.py](packages/llm/src/llm/policy_questions/encoder.py) and the [RAG chat app](apps/rag-chat-app) |
124
+ | LLMs | Extraction, grounding against minutes, LLM-as-judge: [meeting_gap_analysis.py](packages/llm/src/llm/gemini/meeting_gap_analysis.py) |
125
+ | Databricks | Asset bundles (DABs) with dev/free/prod targets, `ai_query` batch inference in dbt: [agent-analysis-sync](apps/agent-analysis-sync) |
126
+ | MLOps and LLMOps | Per-call usage and cost records: [llm/usage](packages/llm/src/llm/usage) |
127
+ | GitHub Actions | [.github/workflows](.github/workflows): CI, a custom PR check, deploys, on-demand GPU |
128
+ | AWS | Sharded Lambda scans and public S3 reads without credentials: [lambda_handler.py](packages/accessibility/src/accessibility/lambda_handler.py) |
129
+ | Azure | Terraform for subscriptions, budgets and a Databricks workspace: [infra/azure](infra/azure) |
130
+ | Security and secrets | OIDC sign-in with no stored secret, service principals, where secrets live, and an app-security fix ([#361](https://github.com/getcommunityone/open-navigator/pull/361)) |
131
+ | Ontologies | NTEE closure table, CAP topics, Policy Frames, COFOG: [int_tags__closure.sql](dbt_project/models/intermediate/int_tags__closure.sql), [seeds](dbt_project/seeds) |
132
+ | Data contracts and products | ODCS contracts and an ODPS product: [dbt_project/contracts](dbt_project/contracts) |
133
+
134
+ </details>
135
+
136
+ <details>
137
+ <summary><b>Data platform and DataOps engineers</b>: how the pipelines fail, recover and get checked</summary>
138
+
139
+ **Start with the [DataOps walkthrough](web_docs/docs/development/dataops-walkthrough.md):** each capability with what
140
+ it does, the code, why it's built that way and how to see it run.
141
+
142
+ | Capability | In short | Code |
143
+ |---|---|---|
144
+ | Failure detection and retry | Errors classified by cause: retry transient ones with backoff and jitter, stop at a quota wall, rotate off an overloaded model | [HTTP client](packages/core-lib/src/core_lib/http/client.py) · [Gemini client](packages/llm/src/llm/gemini/genai_text_client.py) |
145
+ | Stuck-run recovery | Batch runs with no activity are cancelled and their units marked failed for a rerun | [batch_job_status.py](api/batch_jobs/batch_job_status.py) |
146
+ | Safe, repeatable reruns | A second run changes nothing; a file is deleted only if it's byte-identical | [transcript_cache_paths.py](packages/llm/src/llm/gemini/transcript_cache_paths.py) |
147
+ | Data quality and contracts | dbt tests, coverage-bias models, enforced model contracts, ODCS contracts in CI, `null` instead of a made-up number | [dbt tests](dbt_project/tests) · [odcs.py](packages/datamodels/models/odcs.py) |
148
+ | AI in production | Every model call recorded (tokens, attempts, latency); output validated; summaries checked against official minutes; human exclusions | [usage](packages/llm/src/llm/usage) · [gap analysis](packages/llm/src/llm/gemini/meeting_gap_analysis.py) |
149
+ | Observability | OpenTelemetry spans from the browser through the API | [telemetry.py](api/telemetry.py) · [api.ts](web_app/src/lib/api.ts) |
150
+ | Standards | Issue-first rule enforced in CI, one review rubric for every PR, decisions written down | [AGENTS.md](AGENTS.md) · [pr_conventions.py](.github/scripts/pr_conventions.py) |
151
+
152
+ **Two real incidents (November 2026):** a cache cleanup that never converged
153
+ ([#347](https://github.com/getcommunityone/open-navigator/pull/347),
154
+ [#215](https://github.com/getcommunityone/open-navigator/pull/215)), and sign-in down on Neon's pooled endpoint
155
+ ([#368](https://github.com/getcommunityone/open-navigator/pull/368)).
156
+
157
+ **Not built yet:** paging an on-call person, telling a table's users when its refresh fails, learned anomaly detection,
158
+ AI root-cause assessment, and health checks for each database connection.
159
+
160
+ </details>
161
+
162
+ <details>
163
+ <summary><b>Developers and data engineers</b>: run it, change it</summary>
164
+
165
+ **Start with the [code walkthrough](web_docs/docs/development/code-walkthrough.md):** twelve steps in run order, from
166
+ finding governments' websites to the page in the app, each with its code, command and output, plus a table of where to
167
+ change things.
168
+
169
+ **Stack.** FastAPI (`api/`), React + Vite + TypeScript (`web_app/`), Docusaurus (`web_docs/`), dbt on PostgreSQL
170
+ (`dbt_project/`: bronze → staging → intermediate → marts), shared Python libraries in `packages/` (a uv workspace).
171
+ `scripts/` is legacy and frozen: new Python goes in `packages/`. Rules: [CLAUDE.md](CLAUDE.md) and [AGENTS.md](AGENTS.md).
172
+
173
+ **Run it locally** (API on 8001, app on 5173, docs on 3000):
174
+
175
+ ```bash
176
+ git clone https://github.com/getcommunityone/open-navigator.git && cd open-navigator
177
+ ./install.sh # Python backend (.venv + .env); on Windows: .\install.ps1
178
+ cd web_app && npm install && cd ..
179
+ cd web_docs && npm install && cd ..
180
+ ./start-all.sh # on Windows: .\start-all.ps1
181
+ ```
182
+
183
+ Don't use `uv sync` for the backend: the root `pyproject.toml` is a workspace and skips `requirements.txt`. Full setup,
184
+ including restoring a warehouse snapshot: [quick start](web_docs/docs/quickstart.md).
185
+
186
+ **Data pipeline.** Python only for ingestion, AI extraction and orchestration; every SQL transformation is dbt.
187
+
188
+ ```bash
189
+ cd dbt_project && dbt run && dbt test
190
+ ```
191
+
192
+ More: [dbt strategy](web_docs/docs/development/dbt-etl-strategy.md), [entity resolution](web_docs/docs/development/bronze-to-production-merge.md),
193
+ [dbt project](dbt_project/README.md), [refactor roadmap](web_docs/docs/development/cleanup-roadmap.md).
194
+
195
+ **Deploy.** [Hugging Face Spaces](web_docs/docs/deployment/huggingface-spaces.md) (this README's front matter configures
196
+ the Space), [Databricks Apps](web_docs/docs/deployment/databricks-apps.md), or `docker-compose up -d`.
197
+
198
+ **AI and agents.** Gemini reads meeting transcripts and extracts decisions, quotes and amounts; Jev screens
199
+ transcripts first. Coding agents (Claude Code and others) follow [AGENTS.md](AGENTS.md). Long agent sessions get
200
+ *compacted*: when a conversation outgrows the model's context window, older turns are replaced by a summary and exact
201
+ details can be lost. So anything that matters goes into an issue, a PR or a docs page, never only the chat, and a
202
+ summary is never used as evidence. More: [how Open Navigator uses AI](web_docs/docs/development/ai-overview.md)
203
+ (including [compaction](web_docs/docs/development/ai-overview.md#compaction)) and
204
+ [context engineering](web_docs/docs/development/context-engineering.md).
205
+
206
+ **Test.** `pytest` for the backend; CI also builds the app and the docs and checks the slideshow is up to date.
207
+
208
+ **Contribute.** Every change starts from a GitHub issue with four parts (Problem, Done when, Contract, Read first),
209
+ on a branch `<type>/<issue>-<slug>`, through a pull request that closes it. See [AGENTS.md](AGENTS.md) and
210
+ [CONTRIBUTING.md](CONTRIBUTING.md).
211
+ </details>
212
+
213
+ ---
214
+
215
+ Sources: U.S. Census Bureau, [Government Organization Summary Report: 2022 & 2025](https://www.census.gov/library/publications/2026/econ/govtorg2225.html).
216
+ Datasets and research used here: [CITATIONS.md](CITATIONS.md) (including MeetingBank, Hu et al., ACL 2023).
217
+ All generated content should be reviewed by a person before use in advocacy.
218
+ Issues: [github.com/getcommunityone/open-navigator/issues](https://github.com/getcommunityone/open-navigator/issues) ·
219
+ johnbowyer@communityone.com · Apache 2.0, see [LICENSE](LICENSE).
README_HF.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: CommunityOne - Open Navigator
3
+ emoji: 🏛️
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ license: apache-2.0
10
+ tags:
11
+ - civic-engagement
12
+ - policy-tracking
13
+ - government-transparency
14
+ - nonprofit-discovery
15
+ - open-data
16
+ ---
17
+
18
+ # 🏛️ CommunityOne - Open Navigator
19
+
20
+ **Track local governments across the U.S. Monitor 1.8M nonprofits. Amplify your voice.**
21
+
22
+ CommunityOne is a civic engagement platform that helps you discover advocacy opportunities, track policy changes, and connect with organizations working on the causes you care about.
23
+
24
+ ## ✨ Features
25
+
26
+ - **🔍 Unified Search**: Find contacts, meetings, organizations, and causes across the entire United States
27
+ - **📊 Real-time Stats**: Track policy activity across cities, counties, school districts and states
28
+ - **🏢 Nonprofit Discovery**: Explore 1.8M organizations from IRS data enriched with Every.org
29
+ - **📅 Meeting Minutes**: Search 250,000+ government meeting transcripts and agendas
30
+ - **🎯 Geographic Filtering**: Browse by state, county, or city to find local opportunities
31
+ - **🔐 OAuth Login**: Sign in with HuggingFace, GitHub, or Google to save your preferences
32
+
33
+ ## 🚀 Three Services Architecture
34
+
35
+ This deployment runs three integrated services:
36
+
37
+ 1. **📚 Documentation** (Docusaurus) - `/docs/`
38
+ 2. **🖥️ Main Application** (React + Vite) - `/`
39
+ 3. **⚡ API Backend** (FastAPI) - `/api/`
40
+
41
+ All services are reverse-proxied through nginx on port 7860.
42
+
43
+ ## 📖 Quick Start
44
+
45
+ ### Browse Without Login
46
+ - Click "Browse All" to explore data by state
47
+ - Use the search bar to find organizations, contacts, or causes
48
+ - Filter by location using the state/county/city selectors
49
+
50
+ ### Sign In for Personalization
51
+ - Click "Login" in the top right
52
+ - Choose your OAuth provider (HuggingFace, GitHub, or Google)
53
+ - Follow organizations, leaders, and causes you care about
54
+ - Get personalized recommendations
55
+
56
+ ### Explore the API
57
+ - Visit `/redoc` for interactive API documentation
58
+ - Try the search endpoints with state filters
59
+ - Export data in JSON format for your own projects
60
+
61
+ ## 🛠️ Technology Stack
62
+
63
+ - **Frontend**: React 18 + TypeScript + Vite + TailwindCSS + shadcn/ui
64
+ - **Backend**: Python 3.11 + FastAPI + Pydantic
65
+ - **Data**: Delta Lake + Parquet (90GB+ of civic data)
66
+ - **Docs**: Docusaurus v3
67
+ - **Infrastructure**: nginx + supervisor + Docker
68
+
69
+ ## 📊 Data Sources
70
+
71
+ - **IRS BMF**: 1.8M tax-exempt organizations
72
+ - **Every.org**: Nonprofit enrichment (logos, causes, revenue)
73
+ - **Open States**: State legislators and bills (7,300+ officials)
74
+ - **Census**: Jurisdictions and boundaries
75
+ - **CityScrapers**: Local government meetings
76
+ - **OpenCivicData**: Standardized government data
77
+
78
+ ## 🔗 Links
79
+
80
+ - **Repository**: [github.com/getcommunityone/open-navigator](https://github.com/getcommunityone/open-navigator)
81
+ - **Documentation**: Click "📚 Browse Documentation" on the homepage
82
+ - **API Docs**: `/redoc` endpoint
83
+ - **Website**: [www.communityone.com](https://www.communityone.com)
84
+
85
+ ## 📝 License
86
+
87
+ Apache License 2.0 - Free for commercial and non-commercial use
88
+
89
+ ## 🤝 Contributing
90
+
91
+ We welcome contributions! See CONTRIBUTING.md in the repository for guidelines.
92
+
93
+ ## 💬 Support
94
+
95
+ - **Issues**: [GitHub Issues](https://github.com/getcommunityone/open-navigator/issues)
96
+ - **Discussions**: [GitHub Discussions](https://github.com/getcommunityone/open-navigator/discussions)
97
+ - **Email**: johnbowyer@communityone.com
98
+
99
+ ---
100
+
101
+ Built with ❤️ for civic engagement and government transparency.
SECURITY.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ Use this section to tell people about which versions of your project are
6
+ currently being supported with security updates.
7
+
8
+ | Version | Supported |
9
+ | ------- | ------------------ |
10
+ | 5.1.x | :white_check_mark: |
11
+ | 5.0.x | :x: |
12
+ | 4.0.x | :white_check_mark: |
13
+ | < 4.0 | :x: |
14
+
15
+ ## Reporting a Vulnerability
16
+
17
+ Use this section to tell people how to report a vulnerability.
18
+
19
+ Tell them where to go, how often they can expect to get an update on a
20
+ reported vulnerability, what to expect if the vulnerability is accepted or
21
+ declined, etc.
api/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """API module for the CommunityOne Open Navigator system.
2
+
3
+ Import the app from its own module (``from api.main import app``, or ``uvicorn api.main:app``). This file imports
4
+ nothing, so loading one module such as ``api.database`` doesn't build the whole app (#261).
5
+ """
api/app.py ADDED
@@ -0,0 +1,801 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI application optimized for Databricks Apps deployment.
3
+ Serves React frontend and provides REST API for agent interactions.
4
+ """
5
+ from typing import List, Dict, Any, Optional
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+ from fastapi import FastAPI, HTTPException, Query, BackgroundTasks
9
+ from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
10
+ from fastapi.staticfiles import StaticFiles
11
+ from fastapi.middleware.cors import CORSMiddleware
12
+ from fastapi.middleware.gzip import GZipMiddleware
13
+
14
+ from api.static_cache import CachedStaticFiles
15
+ from pydantic import BaseModel, Field
16
+ from loguru import logger
17
+ import os
18
+
19
+ from agents.orchestrator import OrchestratorAgent
20
+ from ingestion.delta_lake import DeltaLakePipeline
21
+ from config import settings
22
+
23
+ # Initialize FastAPI app
24
+ app = FastAPI(
25
+ title="Open Navigator",
26
+ description="AI-powered advocacy opportunity finder",
27
+ version="2.0.0",
28
+ docs_url="/api/docs",
29
+ redoc_url="/api/redoc",
30
+ openapi_url="/api/openapi.json"
31
+ )
32
+
33
+ # Add CORS middleware. Origins come from an explicit env-driven allowlist
34
+ # (api/origins.py), never "*": with allow_credentials=True, Starlette reflects
35
+ # the caller's Origin, so "*" would trust every site on the internet.
36
+ from api.origins import allowed_origins
37
+
38
+ app.add_middleware(
39
+ CORSMiddleware,
40
+ allow_origins=list(allowed_origins()),
41
+ allow_credentials=True,
42
+ allow_methods=["*"],
43
+ allow_headers=["*"],
44
+ )
45
+
46
+ # Compress responses (notably the large /data JSON marts — county_metrics is
47
+ # ~2.6MB, jurisdiction_mapping_quality ~6.6MB; both compress ~5-10x).
48
+ app.add_middleware(GZipMiddleware, minimum_size=1000)
49
+
50
+ # Initialize components
51
+ orchestrator = OrchestratorAgent()
52
+ pipeline = DeltaLakePipeline()
53
+
54
+ # Pydantic models
55
+ class WorkflowRequest(BaseModel):
56
+ """Request to start a new analysis workflow."""
57
+ targets: List[Dict[str, str]]
58
+ topics: Optional[List[str]] = None
59
+
60
+ class OpportunityFilter(BaseModel):
61
+ """Filter criteria for advocacy opportunities."""
62
+ state: Optional[str] = None
63
+ topic: Optional[str] = None
64
+ urgency: Optional[str] = None
65
+ min_confidence: Optional[float] = 0.7
66
+
67
+
68
+ # API Routes
69
+ @app.get("/api/health")
70
+ async def health_check():
71
+ """Health check endpoint."""
72
+ return {"status": "healthy", "timestamp": datetime.utcnow().isoformat()}
73
+
74
+
75
+ @app.get("/api/dashboard")
76
+ async def get_dashboard_stats():
77
+ """Get dashboard statistics and recent opportunities."""
78
+ try:
79
+ # Query Delta Lake for stats
80
+ stats = await pipeline.get_dashboard_stats()
81
+ return stats
82
+ except Exception as e:
83
+ logger.error(f"Dashboard stats error: {e}")
84
+ raise HTTPException(status_code=500, detail=str(e))
85
+
86
+
87
+ @app.get("/api/opportunities")
88
+ async def get_opportunities(
89
+ state: Optional[str] = Query(None),
90
+ topic: Optional[str] = Query(None),
91
+ urgency: Optional[str] = Query(None),
92
+ limit: int = Query(100, le=1000)
93
+ ):
94
+ """Get advocacy opportunities with optional filters."""
95
+ try:
96
+ opportunities = await pipeline.query_opportunities(
97
+ state=state,
98
+ topic=topic,
99
+ urgency=urgency,
100
+ limit=limit
101
+ )
102
+ return {"opportunities": opportunities, "count": len(opportunities)}
103
+ except Exception as e:
104
+ logger.error(f"Query opportunities error: {e}")
105
+ raise HTTPException(status_code=500, detail=str(e))
106
+
107
+
108
+ @app.get("/api/documents")
109
+ async def get_documents(
110
+ search: Optional[str] = Query(None),
111
+ page: int = Query(1, ge=1),
112
+ limit: int = Query(20, le=100)
113
+ ):
114
+ """Get analyzed documents with pagination."""
115
+ try:
116
+ offset = (page - 1) * limit
117
+ documents = await pipeline.query_documents(
118
+ search=search,
119
+ limit=limit,
120
+ offset=offset
121
+ )
122
+ total = await pipeline.count_documents(search=search)
123
+ return {
124
+ "documents": documents,
125
+ "page": page,
126
+ "limit": limit,
127
+ "total": total,
128
+ "total_pages": (total + limit - 1) // limit
129
+ }
130
+ except Exception as e:
131
+ logger.error(f"Query documents error: {e}")
132
+ raise HTTPException(status_code=500, detail=str(e))
133
+
134
+
135
+ @app.get("/api/search/")
136
+ async def search_all(
137
+ q: str = Query(..., min_length=1, description="Search query"),
138
+ types: Optional[str] = Query("contacts,organizations,causes", description="Comma-separated types to search"),
139
+ state: Optional[str] = Query(None, description="Filter by state code (e.g. MA, AL)"),
140
+ limit: int = Query(10, ge=1, le=100),
141
+ page: int = Query(1, ge=1),
142
+ ntee_code: Optional[str] = Query(None, description="NTEE category code")
143
+ ):
144
+ """
145
+ Unified search across contacts, organizations, causes, and jurisdictions.
146
+ Returns results grouped by type with pagination.
147
+ """
148
+ try:
149
+ offset = (page - 1) * limit
150
+ search_types = [t.strip() for t in types.split(',') if t.strip()]
151
+
152
+ # Initialize results structure
153
+ results = {
154
+ "contacts": [],
155
+ "organizations": [],
156
+ "causes": [],
157
+ "meetings": [],
158
+ "jurisdictions": []
159
+ }
160
+
161
+ # Search logic (placeholder - implement actual search)
162
+ # For now, return mock results for demonstration
163
+ if "contacts" in search_types:
164
+ results["contacts"] = [
165
+ {
166
+ "type": "contact",
167
+ "title": f"Sample Contact matching '{q}'",
168
+ "subtitle": "Government Official",
169
+ "description": "Contact information for local official",
170
+ "url": "/contact/1",
171
+ "score": 0.9,
172
+ "metadata": {"state": state or "MA"}
173
+ }
174
+ ]
175
+
176
+ if "organizations" in search_types:
177
+ results["organizations"] = [
178
+ {
179
+ "type": "organization",
180
+ "title": f"Sample Organization matching '{q}'",
181
+ "subtitle": "Nonprofit Organization",
182
+ "description": "Community health organization",
183
+ "url": "/org/1",
184
+ "score": 0.85,
185
+ "metadata": {"state": state or "MA", "ntee": ntee_code}
186
+ }
187
+ ]
188
+
189
+ if "causes" in search_types:
190
+ results["causes"] = [
191
+ {
192
+ "type": "cause",
193
+ "title": f"Sample Cause matching '{q}'",
194
+ "subtitle": "Health & Wellness",
195
+ "description": "Advocacy for community health",
196
+ "url": "/cause/1",
197
+ "score": 0.8,
198
+ "metadata": {}
199
+ }
200
+ ]
201
+
202
+ # Calculate total results
203
+ total_results = sum(len(v) for v in results.values())
204
+ total_pages = max(1, (total_results + limit - 1) // limit)
205
+
206
+ return {
207
+ "query": q,
208
+ "total_results": total_results,
209
+ "results": results,
210
+ "pagination": {
211
+ "page": page,
212
+ "limit": limit,
213
+ "offset": offset,
214
+ "total_pages": total_pages,
215
+ "has_next": page < total_pages,
216
+ "has_prev": page > 1
217
+ },
218
+ "filters": {
219
+ "state": state,
220
+ "ntee_code": ntee_code,
221
+ "types": search_types
222
+ }
223
+ }
224
+ except Exception as e:
225
+ logger.error(f"Search error: {e}")
226
+ raise HTTPException(status_code=500, detail=str(e))
227
+
228
+
229
+ @app.post("/api/workflow/start")
230
+ async def start_workflow(request: WorkflowRequest, background_tasks: BackgroundTasks):
231
+ """Start a new analysis workflow."""
232
+ try:
233
+ workflow_id = f"workflow_{datetime.utcnow().timestamp()}"
234
+
235
+ # Start workflow in background
236
+ background_tasks.add_task(
237
+ orchestrator.execute_pipeline,
238
+ workflow_id=workflow_id,
239
+ targets=request.targets,
240
+ topics=request.topics
241
+ )
242
+
243
+ return {
244
+ "workflow_id": workflow_id,
245
+ "status": "started",
246
+ "message": "Workflow started successfully"
247
+ }
248
+ except Exception as e:
249
+ logger.error(f"Workflow start error: {e}")
250
+ raise HTTPException(status_code=500, detail=str(e))
251
+
252
+
253
+ @app.get("/api/workflow/{workflow_id}/status")
254
+ async def get_workflow_status(workflow_id: str):
255
+ """Get status of a running workflow."""
256
+ try:
257
+ status = await orchestrator.get_workflow_status(workflow_id)
258
+ return status
259
+ except Exception as e:
260
+ logger.error(f"Workflow status error: {e}")
261
+ raise HTTPException(status_code=404, detail="Workflow not found")
262
+
263
+
264
+ @app.post("/api/advocacy/email/{opportunity_id}")
265
+ async def generate_advocacy_email(opportunity_id: str):
266
+ """Generate advocacy email for an opportunity."""
267
+ try:
268
+ opportunity = await pipeline.get_opportunity(opportunity_id)
269
+ if not opportunity:
270
+ raise HTTPException(status_code=404, detail="Opportunity not found")
271
+
272
+ email_content = await orchestrator.generate_advocacy_email(opportunity)
273
+ return {"content": email_content}
274
+ except Exception as e:
275
+ logger.error(f"Generate email error: {e}")
276
+ raise HTTPException(status_code=500, detail=str(e))
277
+
278
+
279
+ @app.get("/api/settings")
280
+ async def get_settings():
281
+ """Get current system settings."""
282
+ return {
283
+ "target_states": settings.target_states or [],
284
+ "policy_topics": settings.policy_topics,
285
+ "min_confidence": 0.7,
286
+ "email_notifications": False,
287
+ "notification_email": ""
288
+ }
289
+
290
+
291
+ @app.put("/api/settings")
292
+ async def update_settings(new_settings: Dict[str, Any]):
293
+ """Update system settings."""
294
+ try:
295
+ # In production, this would update configuration in Unity Catalog
296
+ logger.info(f"Settings update requested: {new_settings}")
297
+ return {"message": "Settings updated successfully"}
298
+ except Exception as e:
299
+ logger.error(f"Settings update error: {e}")
300
+ raise HTTPException(status_code=500, detail=str(e))
301
+
302
+
303
+ @app.get("/api/agents/status")
304
+ async def get_agents_status():
305
+ """Get status of all agents."""
306
+ try:
307
+ return {
308
+ "agents": [
309
+ {"name": "Scraper", "status": "active", "uptime": "24h"},
310
+ {"name": "Classifier", "status": "active", "uptime": "24h"},
311
+ {"name": "Sentiment Analyzer", "status": "active", "uptime": "24h"},
312
+ {"name": "Advocacy Writer", "status": "active", "uptime": "24h"}
313
+ ]
314
+ }
315
+ except Exception as e:
316
+ logger.error(f"Agent status error: {e}")
317
+ raise HTTPException(status_code=500, detail=str(e))
318
+
319
+
320
+ @app.get("/api/nonprofits")
321
+ async def search_nonprofits(
322
+ location: str = Query("Tuscaloosa, AL", description="City, State format"),
323
+ keyword: Optional[str] = Query(None, description="Service keyword (e.g., 'dental', 'health')"),
324
+ state: Optional[str] = Query(None, description="2-letter state code (e.g., 'AL')"),
325
+ ntee_code: Optional[str] = Query(None, description="NTEE code (e.g., 'E' for health)"),
326
+ source: Optional[str] = Query(None, description="Data source: 'propublica', 'everyorg', 'all'")
327
+ ):
328
+ """
329
+ Search for nonprofits using free open data APIs.
330
+
331
+ Integrates data from:
332
+ - ProPublica Nonprofit Explorer (financial data, NTEE codes)
333
+ - Every.org (mission statements, logos)
334
+ - IRS TEOS (official tax-exempt status)
335
+
336
+ Example: /api/nonprofits?location=Tuscaloosa,AL&keyword=dental&ntee_code=E
337
+ """
338
+ try:
339
+ from scrapers.irs.nonprofit_discovery import NonprofitDiscovery
340
+
341
+ discovery = NonprofitDiscovery()
342
+ results = []
343
+
344
+ # Parse location for state/city
345
+ location_parts = location.split(',')
346
+ city = location_parts[0].strip() if len(location_parts) > 0 else None
347
+ state_from_location = location_parts[1].strip() if len(location_parts) > 1 else None
348
+ state_code = state or state_from_location or "AL"
349
+
350
+ # Determine which sources to query
351
+ sources_to_query = ['propublica', 'everyorg'] if source == 'all' or not source else [source]
352
+
353
+ # Query ProPublica
354
+ if 'propublica' in sources_to_query:
355
+ try:
356
+ propublica_results = discovery.search_propublica(
357
+ state=state_code,
358
+ city=city,
359
+ ntee_code=ntee_code
360
+ )
361
+ results.extend(propublica_results)
362
+ logger.info(f"ProPublica: Found {len(propublica_results)} organizations")
363
+ except Exception as e:
364
+ logger.warning(f"ProPublica search failed: {e}")
365
+
366
+ # Query Every.org
367
+ if 'everyorg' in sources_to_query:
368
+ try:
369
+ causes = []
370
+ if keyword:
371
+ # Map keywords to causes
372
+ keyword_lower = keyword.lower()
373
+ if 'health' in keyword_lower or 'dental' in keyword_lower or 'medical' in keyword_lower:
374
+ causes.append('health')
375
+ if 'education' in keyword_lower or 'school' in keyword_lower:
376
+ causes.append('education')
377
+
378
+ everyorg_results = discovery.search_everyorg(
379
+ location=location,
380
+ causes=causes if causes else None
381
+ )
382
+ results.extend(everyorg_results)
383
+ logger.info(f"Every.org: Found {len(everyorg_results)} organizations")
384
+ except Exception as e:
385
+ logger.warning(f"Every.org search failed: {e}")
386
+
387
+ # Filter by keyword if provided
388
+ if keyword and results:
389
+ keyword_lower = keyword.lower()
390
+ filtered_results = []
391
+ for org in results:
392
+ # Search in name, description, mission, ntee_description
393
+ searchable_text = ' '.join([
394
+ str(org.get('name', '')),
395
+ str(org.get('description', '')),
396
+ str(org.get('mission', '')),
397
+ str(org.get('ntee_description', ''))
398
+ ]).lower()
399
+
400
+ if keyword_lower in searchable_text:
401
+ filtered_results.append(org)
402
+
403
+ results = filtered_results
404
+
405
+ return {
406
+ "location": location,
407
+ "keyword": keyword,
408
+ "state": state_code,
409
+ "ntee_code": ntee_code,
410
+ "count": len(results),
411
+ "nonprofits": results,
412
+ "data_sources": {
413
+ "propublica": "https://projects.propublica.org/nonprofits/api",
414
+ "everyorg": "https://www.every.org/nonprofit-api",
415
+ "irs_teos": "https://www.irs.gov/charities-non-profits/tax-exempt-organization-search-bulk-data-downloads"
416
+ }
417
+ }
418
+
419
+ except Exception as e:
420
+ logger.error(f"Nonprofit search error: {e}")
421
+ raise HTTPException(status_code=500, detail=str(e))
422
+
423
+
424
+ @app.get("/api/nonprofits/compensation")
425
+ async def nonprofit_compensation(
426
+ ein: Optional[str] = Query(None, description="Exact EIN — a single org's people"),
427
+ state: Optional[str] = Query(None, description="2-letter state code or full name"),
428
+ person: Optional[str] = Query(None, description="Case-insensitive person-name search"),
429
+ min_comp: Optional[int] = Query(None, description="Minimum reportable comp from the org"),
430
+ limit: int = Query(25, ge=1, le=200),
431
+ offset: int = Query(0, ge=0),
432
+ sort: str = Query("comp-desc", description="comp-desc | comp-asc | name-asc"),
433
+ ):
434
+ """
435
+ Person-level executive/board compensation from the GivingTuesday 990 datamarts
436
+ (Form 990 Part VII-A + Schedule J detail), joined to organization context.
437
+
438
+ Examples:
439
+ /api/nonprofits/compensation?ein=530196605 (one org's people)
440
+ /api/nonprofits/compensation?state=NY&min_comp=500000 (top earners in NY)
441
+ /api/nonprofits/compensation?person=smith&sort=comp-desc
442
+ """
443
+ from api.routes import search_postgres
444
+ try:
445
+ records = await search_postgres.get_nonprofit_compensation_pg(
446
+ ein=ein, state=state, person=person, min_comp=min_comp,
447
+ limit=limit, offset=offset, sort=sort,
448
+ )
449
+ return {"count": len(records), "results": records}
450
+ except Exception as e:
451
+ logger.error(f"Compensation endpoint error: {e}")
452
+ raise HTTPException(status_code=500, detail=str(e))
453
+
454
+
455
+ @app.get("/api/data/status")
456
+ async def get_data_status():
457
+ """
458
+ Get status of all reference data ingestions.
459
+
460
+ Returns counts and last update times for:
461
+ - Census jurisdictions
462
+ - NCES school districts
463
+ - Nonprofit organizations
464
+ - Meeting datasets (MeetingBank, LocalView, etc.)
465
+
466
+ Every count is a real warehouse value (see
467
+ ``stats_neon.fetch_national_reference_counts``) or ``null`` when it can't be
468
+ computed — never a hard-coded estimate (CLAUDE.md, "No Fabricated Data").
469
+ """
470
+ try:
471
+ from api.routes.stats_neon import fetch_national_reference_counts
472
+
473
+ counts = await fetch_national_reference_counts()
474
+ last_updated = counts.get("last_updated")
475
+
476
+ def _entry(path: str, count: Optional[int]) -> Dict[str, Any]:
477
+ return {
478
+ "path": path,
479
+ "status": "available" if count is not None else "unavailable",
480
+ "count": count,
481
+ "last_updated": last_updated if count is not None else None,
482
+ }
483
+
484
+ aggregate = "public.jurisdiction_state_aggregate (national)"
485
+ # Per-source meeting counts are not modeled in `public`; unavailable, not guessed.
486
+ unavailable_meetings = {"status": "unavailable", "count": None}
487
+ return {
488
+ "census_jurisdictions": _entry(aggregate, counts["jurisdictions"]),
489
+ "nces_school_districts": _entry(aggregate, counts["school_districts"]),
490
+ "nonprofits": _entry(aggregate, counts["nonprofits"]),
491
+ "meeting_datasets": {
492
+ "meetingbank": dict(unavailable_meetings),
493
+ "city_scrapers": dict(unavailable_meetings),
494
+ "open_states": dict(unavailable_meetings),
495
+ },
496
+ }
497
+
498
+ except Exception as e:
499
+ logger.error(f"Data status error: {e}")
500
+ raise HTTPException(status_code=500, detail=str(e))
501
+
502
+
503
+ @app.post("/api/data/ingest/census")
504
+ async def ingest_census_data(background_tasks: BackgroundTasks):
505
+ """
506
+ Trigger Census Bureau jurisdiction data ingestion.
507
+
508
+ Downloads and processes:
509
+ - 3,144 counties
510
+ - 19,500+ municipalities
511
+ - 36,000+ townships
512
+ - 13,000+ school districts
513
+
514
+ This is a long-running operation that runs in the background.
515
+ """
516
+ try:
517
+ def run_census_ingestion():
518
+ from scripts.discovery.census_ingestion import CensusGovernmentIngestion
519
+ import asyncio
520
+
521
+ logger.info("Starting Census data ingestion...")
522
+ ingestor = CensusGovernmentIngestion()
523
+
524
+ # Run async ingestion
525
+ loop = asyncio.new_event_loop()
526
+ asyncio.set_event_loop(loop)
527
+ result = loop.run_until_complete(ingestor.ingest_all_jurisdictions())
528
+ loop.close()
529
+
530
+ logger.success(f"Census ingestion complete: {result}")
531
+
532
+ background_tasks.add_task(run_census_ingestion)
533
+
534
+ return {
535
+ "message": "Census data ingestion started",
536
+ "status": "processing",
537
+ "check_status": "/api/data/status"
538
+ }
539
+
540
+ except Exception as e:
541
+ logger.error(f"Census ingestion error: {e}")
542
+ raise HTTPException(status_code=500, detail=str(e))
543
+
544
+
545
+ @app.post("/api/data/ingest/nces")
546
+ async def ingest_nces_data(background_tasks: BackgroundTasks):
547
+ """
548
+ Trigger NCES school district data ingestion.
549
+
550
+ Downloads and processes 13,000+ school districts with:
551
+ - District names and addresses
552
+ - Contact information
553
+ - NCES IDs
554
+ - Enrollment data
555
+ """
556
+ try:
557
+ def run_nces_ingestion():
558
+ from scripts.discovery.nces_ingestion import NCESSchoolDistrictIngestion
559
+ import asyncio
560
+
561
+ logger.info("Starting NCES data ingestion...")
562
+ ingestor = NCESSchoolDistrictIngestion()
563
+
564
+ # Run async ingestion
565
+ loop = asyncio.new_event_loop()
566
+ asyncio.set_event_loop(loop)
567
+ result = loop.run_until_complete(ingestor.download_and_process())
568
+ loop.close()
569
+
570
+ logger.success(f"NCES ingestion complete: {result}")
571
+
572
+ background_tasks.add_task(run_nces_ingestion)
573
+
574
+ return {
575
+ "message": "NCES data ingestion started",
576
+ "status": "processing",
577
+ "check_status": "/api/data/status"
578
+ }
579
+
580
+ except Exception as e:
581
+ logger.error(f"NCES ingestion error: {e}")
582
+ raise HTTPException(status_code=500, detail=str(e))
583
+
584
+
585
+ @app.post("/api/data/ingest/nonprofits")
586
+ async def ingest_nonprofits(
587
+ state: str = Query(..., description="2-letter state code"),
588
+ ntee_codes: Optional[List[str]] = Query(None, description="NTEE codes to ingest"),
589
+ background_tasks: BackgroundTasks = None
590
+ ):
591
+ """
592
+ Trigger nonprofit data ingestion for a specific state.
593
+
594
+ Bulk downloads nonprofit data from ProPublica API and caches locally.
595
+
596
+ Example: POST /api/data/ingest/nonprofits?state=AL&ntee_codes=E&ntee_codes=E20
597
+ """
598
+ try:
599
+ from scrapers.irs.nonprofit_discovery import NonprofitDiscovery
600
+
601
+ discovery = NonprofitDiscovery()
602
+ ntee_list = ntee_codes or ["E"] # Default to health
603
+
604
+ total_orgs = 0
605
+ for ntee_code in ntee_list:
606
+ orgs = discovery.search_propublica(state=state, ntee_code=ntee_code)
607
+ total_orgs += len(orgs)
608
+ logger.info(f"Cached {len(orgs)} nonprofits for {state}/{ntee_code}")
609
+
610
+ return {
611
+ "message": f"Nonprofit data ingestion complete for {state}",
612
+ "state": state,
613
+ "ntee_codes": ntee_list,
614
+ "organizations_cached": total_orgs,
615
+ "cache_location": "data/cache/nonprofits"
616
+ }
617
+
618
+ except Exception as e:
619
+ logger.error(f"Nonprofit ingestion error: {e}")
620
+ raise HTTPException(status_code=500, detail=str(e))
621
+
622
+
623
+ @app.get("/api/jurisdictions")
624
+ async def get_jurisdictions(
625
+ state: Optional[str] = Query(None, description="2-letter state code"),
626
+ type: Optional[str] = Query(None, description="Type: county, municipality, township"),
627
+ limit: int = Query(100, le=1000)
628
+ ):
629
+ """
630
+ Query ingested Census jurisdiction data.
631
+
632
+ Returns government entities with FIPS codes, coordinates, and population.
633
+ """
634
+ try:
635
+ # This would query the Delta Lake census tables
636
+ # For now, return sample data
637
+ return {
638
+ "message": "Query census jurisdiction data from Delta Lake",
639
+ "filters": {"state": state, "type": type},
640
+ "limit": limit,
641
+ "note": "Requires Census data ingestion first (POST /api/data/ingest/census)",
642
+ "example_data": [
643
+ {
644
+ "name": "Tuscaloosa County",
645
+ "state": "AL",
646
+ "type": "county",
647
+ "fips": "01125",
648
+ "population": "209355"
649
+ }
650
+ ]
651
+ }
652
+
653
+ except Exception as e:
654
+ logger.error(f"Jurisdiction query error: {e}")
655
+ raise HTTPException(status_code=500, detail=str(e))
656
+
657
+
658
+ @app.get("/api/school-districts")
659
+ async def get_school_districts(
660
+ state: Optional[str] = Query(None, description="2-letter state code"),
661
+ limit: int = Query(100, le=1000)
662
+ ):
663
+ """
664
+ Query ingested NCES school district data.
665
+
666
+ Returns school districts with contact information and enrollment.
667
+ """
668
+ try:
669
+ # This would query the Delta Lake NCES tables
670
+ return {
671
+ "message": "Query NCES school district data from Delta Lake",
672
+ "filters": {"state": state},
673
+ "limit": limit,
674
+ "note": "Requires NCES data ingestion first (POST /api/data/ingest/nces)",
675
+ "example_data": [
676
+ {
677
+ "name": "Tuscaloosa City Schools",
678
+ "state": "AL",
679
+ "nces_id": "0100123",
680
+ "phone": "(205) 759-3500",
681
+ "website": "https://www.tusc.k12.al.us/"
682
+ }
683
+ ]
684
+ }
685
+
686
+ except Exception as e:
687
+ logger.error(f"School district query error: {e}")
688
+ raise HTTPException(status_code=500, detail=str(e))
689
+
690
+
691
+ # Batch job dashboard (caption/analyze pipelines)
692
+ from api.routes import batch_jobs as batch_jobs_routes
693
+
694
+ app.include_router(batch_jobs_routes.router, prefix="/api")
695
+
696
+ # Prod deployment jobs (database → Neon prod, web → HuggingFace)
697
+ from api.routes import deployments as deployments_routes
698
+
699
+ app.include_router(deployments_routes.router, prefix="/api")
700
+
701
+ # Data-center job claims by phase (#246): GET /api/data-centers/job-claims
702
+ from api.routes import data_centers as data_centers_routes
703
+ from api.routes import data_center_comments as data_center_comments_routes
704
+ from api.routes import data_center_drill as data_center_drill_routes
705
+
706
+ app.include_router(data_centers_routes.router, prefix="/api")
707
+ app.include_router(data_center_comments_routes.router, prefix="/api")
708
+ app.include_router(data_center_drill_routes.router, prefix="/api")
709
+ # Data-center job-application links (#248): public list + admin screen.
710
+ from api.routes import application_links as application_links_routes
711
+
712
+ app.include_router(application_links_routes.public_router, prefix="/api")
713
+ app.include_router(application_links_routes.admin_router, prefix="/api")
714
+ from api.routes import meeting_kind_reviews as meeting_kind_reviews_routes
715
+
716
+ app.include_router(meeting_kind_reviews_routes.admin_router, prefix="/api")
717
+ # Official profile claims + pending edits (#1062). Router prefix is "/people".
718
+ from api.routes import person_claims as person_claims_routes
719
+
720
+ app.include_router(person_claims_routes.router, prefix="/api")
721
+
722
+ # Serve React frontend
723
+ static_dir = Path(__file__).parent / "static"
724
+ if static_dir.exists():
725
+ # Mount static files (JS, CSS, images)
726
+ app.mount("/assets", StaticFiles(directory=static_dir / "assets"), name="assets")
727
+
728
+ # Public /data tree, served the same paths as Vite dev. Covers the ACS
729
+ # map/scorecard marts (/data/census-map), the per-state ZCTA (ZIP) tiles
730
+ # (/data/zctas — the lowest drilldown tier), and the jurisdiction-quality
731
+ # snapshot. Mounting only /data/census-map left the others 404ing.
732
+ web_app_public = Path(__file__).parent.parent / "web_app" / "public"
733
+ data_dir = web_app_public / "data"
734
+ if data_dir.is_dir():
735
+ app.mount("/data", CachedStaticFiles(directory=data_dir), name="public_data")
736
+ else:
737
+ logger.warning(f"Public data bundle missing (expected {data_dir})")
738
+
739
+ # Serve index.html for all non-API routes (SPA routing)
740
+ @app.get("/{full_path:path}")
741
+ async def serve_react_app(full_path: str):
742
+ """Serve a real static file if one exists, else the React app (SPA routing).
743
+
744
+ Top-level public assets (e.g. /pdf/*, /communityone_logo.svg,
745
+ /robots.txt, /wikimedia/*) live in static_dir but are not under the
746
+ mounted /assets or /data trees. Without this file check they fall through
747
+ to index.html, so the browser loads the SPA into e.g. an <iframe
748
+ src="/pdf/..."> and React Router renders the NotFound (404) page instead
749
+ of the file. Vite's dev server serves these from public/ at the root, so
750
+ the gap only shows in production.
751
+ """
752
+ if full_path.startswith("api/"):
753
+ raise HTTPException(status_code=404, detail="API endpoint not found")
754
+
755
+ # Serve a concrete static file when the path resolves to one inside
756
+ # static_dir (path-traversal guarded via relative_to).
757
+ if full_path:
758
+ candidate = (static_dir / full_path).resolve()
759
+ try:
760
+ candidate.relative_to(static_dir.resolve())
761
+ except ValueError:
762
+ candidate = None
763
+ if candidate is not None and candidate.is_file():
764
+ return FileResponse(candidate)
765
+
766
+ index_file = static_dir / "index.html"
767
+ if index_file.exists():
768
+ return FileResponse(index_file)
769
+ else:
770
+ raise HTTPException(status_code=404, detail="Frontend not built")
771
+
772
+
773
+ @app.on_event("startup")
774
+ async def startup_event():
775
+ """Initialize system on startup."""
776
+ logger.info("Starting CommunityOne Open Navigator application...")
777
+
778
+ # Initialize Delta Lake if not exists
779
+ try:
780
+ await pipeline.initialize_tables()
781
+ logger.info("Delta Lake tables initialized")
782
+ except Exception as e:
783
+ logger.warning(f"Delta Lake initialization skipped: {e}")
784
+
785
+ logger.info("Application started successfully")
786
+
787
+
788
+ @app.on_event("shutdown")
789
+ async def shutdown_event():
790
+ """Cleanup on shutdown."""
791
+ logger.info("Shutting down application...")
792
+
793
+
794
+ if __name__ == "__main__":
795
+ import uvicorn
796
+ uvicorn.run(
797
+ "api.app:app",
798
+ host="0.0.0.0",
799
+ port=8001,
800
+ reload=True
801
+ )
api/auth.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Authentication utilities - JWT tokens, password hashing, OAuth helpers
3
+ """
4
+ import os
5
+ import secrets
6
+ from datetime import datetime, timedelta
7
+ from typing import Optional, Dict, Any
8
+ from dotenv import load_dotenv
9
+
10
+ import jwt
11
+ from jwt import InvalidTokenError
12
+ from passlib.context import CryptContext
13
+ from fastapi import HTTPException, status, Depends
14
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
15
+ from sqlalchemy.orm import Session
16
+
17
+ from api.database import get_db
18
+ from api.models import User
19
+
20
+ # Load environment variables
21
+ load_dotenv()
22
+
23
+ # Security configuration
24
+ _jwt_secret = os.getenv("JWT_SECRET_KEY")
25
+ if not _jwt_secret:
26
+ if os.getenv("HF_SPACES") == "1":
27
+ raise RuntimeError(
28
+ "JWT_SECRET_KEY must be set in HuggingFace Space secrets; "
29
+ "an ephemeral key invalidates all tokens on every restart."
30
+ )
31
+ print(
32
+ "WARNING: JWT_SECRET_KEY not set; using an ephemeral key. "
33
+ "Tokens will not survive a restart. Set JWT_SECRET_KEY for stable sessions."
34
+ )
35
+ _jwt_secret = secrets.token_urlsafe(32)
36
+ SECRET_KEY = _jwt_secret
37
+ ALGORITHM = "HS256"
38
+ ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 7 days
39
+
40
+ # Password hashing
41
+ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
42
+
43
+ # HTTP Bearer token scheme
44
+ security = HTTPBearer(auto_error=False)
45
+
46
+
47
+ def hash_password(password: str) -> str:
48
+ """Hash a password using bcrypt"""
49
+ return pwd_context.hash(password)
50
+
51
+
52
+ def verify_password(plain_password: str, hashed_password: str) -> bool:
53
+ """Verify a password against its hash"""
54
+ return pwd_context.verify(plain_password, hashed_password)
55
+
56
+
57
+ def create_access_token(data: Dict[str, Any], expires_delta: Optional[timedelta] = None) -> str:
58
+ """
59
+ Create a JWT access token
60
+
61
+ Args:
62
+ data: Payload to encode (usually {"sub": user_id})
63
+ expires_delta: Optional custom expiration time
64
+
65
+ Returns:
66
+ JWT token string
67
+ """
68
+ to_encode = data.copy()
69
+
70
+ if expires_delta:
71
+ expire = datetime.utcnow() + expires_delta
72
+ else:
73
+ expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
74
+
75
+ to_encode.update({"exp": expire})
76
+ encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
77
+ return encoded_jwt
78
+
79
+
80
+ def decode_access_token(token: str) -> Dict[str, Any]:
81
+ """
82
+ Decode and validate a JWT token
83
+
84
+ Args:
85
+ token: JWT token string
86
+
87
+ Returns:
88
+ Decoded payload
89
+
90
+ Raises:
91
+ HTTPException: If token is invalid or expired
92
+ """
93
+ try:
94
+ payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
95
+ return payload
96
+ except InvalidTokenError:
97
+ raise HTTPException(
98
+ status_code=status.HTTP_401_UNAUTHORIZED,
99
+ detail="Could not validate credentials",
100
+ headers={"WWW-Authenticate": "Bearer"},
101
+ )
102
+
103
+
104
+ def get_current_user(
105
+ credentials: HTTPAuthorizationCredentials = Depends(security),
106
+ db: Session = Depends(get_db)
107
+ ) -> Optional[User]:
108
+ """
109
+ Get current authenticated user from JWT token
110
+
111
+ Usage:
112
+ @app.get("/protected")
113
+ def protected_route(user: User = Depends(get_current_user)):
114
+ return {"message": f"Hello {user.email}"}
115
+
116
+ Returns:
117
+ User object if authenticated, None if optional auth
118
+ """
119
+ if not credentials:
120
+ return None
121
+
122
+ token = credentials.credentials
123
+ payload = decode_access_token(token)
124
+
125
+ user_id: int = payload.get("sub")
126
+ if user_id is None:
127
+ raise HTTPException(
128
+ status_code=status.HTTP_401_UNAUTHORIZED,
129
+ detail="Invalid authentication credentials"
130
+ )
131
+
132
+ user = db.query(User).filter(User.user_id == user_id).first()
133
+ if user is None:
134
+ raise HTTPException(
135
+ status_code=status.HTTP_401_UNAUTHORIZED,
136
+ detail="User not found"
137
+ )
138
+
139
+ # Update last login
140
+ user.last_login = datetime.utcnow()
141
+ db.commit()
142
+
143
+ return user
144
+
145
+
146
+ def require_auth(user: User = Depends(get_current_user)) -> User:
147
+ """
148
+ Require authentication (raises 401 if not authenticated)
149
+
150
+ Usage:
151
+ @app.get("/protected")
152
+ def protected_route(user: User = Depends(require_auth)):
153
+ return {"message": f"Hello {user.email}"}
154
+ """
155
+ if user is None:
156
+ raise HTTPException(
157
+ status_code=status.HTTP_401_UNAUTHORIZED,
158
+ detail="Authentication required",
159
+ headers={"WWW-Authenticate": "Bearer"},
160
+ )
161
+ return user
162
+
163
+
164
+ def admin_emails() -> set[str]:
165
+ """Emails granted admin, from the ADMIN_EMAILS env var (comma-separated).
166
+
167
+ Read at call time (not import) so it can be changed without touching code.
168
+ Comparison is case-insensitive and whitespace-trimmed.
169
+ """
170
+ raw = os.getenv("ADMIN_EMAILS", "")
171
+ return {email.strip().lower() for email in raw.split(",") if email.strip()}
172
+
173
+
174
+ def is_admin_email(email: Optional[str]) -> bool:
175
+ """True if `email` is in the ADMIN_EMAILS allowlist. Used to (de)provision
176
+ `User.is_admin` on every OAuth login so admin status tracks the env."""
177
+ return bool(email) and email.strip().lower() in admin_emails()
178
+
179
+
180
+ def require_admin(user: User = Depends(require_auth)) -> User:
181
+ """
182
+ Require an authenticated admin (401 if anonymous, 403 if non-admin).
183
+
184
+ ``ADMIN_EMAILS`` is authoritative at request time: the persisted
185
+ ``is_admin`` flag alone is not trusted, so dropping an email from the env
186
+ (and restarting) revokes access immediately — without waiting for the
187
+ user's 7-day JWT to expire or for them to log in again.
188
+
189
+ Gate for the control-plane endpoints (pipeline launch/stop, prod deploys):
190
+ @router.post("/launch", dependencies=[Depends(require_admin)])
191
+ """
192
+ if not (getattr(user, "is_admin", False) and is_admin_email(user.email)):
193
+ raise HTTPException(
194
+ status_code=status.HTTP_403_FORBIDDEN,
195
+ detail="Admin privileges required",
196
+ )
197
+ return user
198
+
199
+
200
+ def generate_state_token() -> str:
201
+ """Generate a secure random state token for OAuth CSRF protection"""
202
+ return secrets.token_urlsafe(32)
api/batch_jobs/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """YouTube batch-job orchestration (dashboard/db/status). API-serving; moved out of packages/scrapers/src/scrapers/youtube."""
api/batch_jobs/batch_job_dashboard.py ADDED
@@ -0,0 +1,1104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Build static HTML for batch job status (optional; primary UI is React).
4
+
5
+ React app: Data explorer → Batch jobs (`/data-explorer/batch-jobs`) via `GET /api/batch-jobs`.
6
+
7
+ Usage (repo root):
8
+ .venv/bin/python packages/scrapers/src/scrapers/youtube/batch_job_dashboard.py --build
9
+ .venv/bin/python packages/scrapers/src/scrapers/youtube/batch_job_dashboard.py --build --open
10
+ .venv/bin/python packages/scrapers/src/scrapers/youtube/batch_job_dashboard.py --serve
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import json
17
+ import sys
18
+ import webbrowser
19
+ from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
20
+ from pathlib import Path
21
+ from typing import Any, Dict, List, Literal
22
+
23
+ VideoPayloadMode = Literal["none", "failed_only", "running", "all"]
24
+
25
+ _FAILED_VIDEO_STATUSES = frozenset(
26
+ {
27
+ "fail",
28
+ "failed",
29
+ "tombstoned",
30
+ "empty",
31
+ "rate_limit",
32
+ "error",
33
+ }
34
+ )
35
+
36
+
37
+ def _is_failed_video_status(status: str) -> bool:
38
+ s = (status or "").strip().lower()
39
+ if not s or s in ("ok", "pending", "skipped", "noop"):
40
+ return False
41
+ if s in _FAILED_VIDEO_STATUSES:
42
+ return True
43
+ return s != "ok"
44
+
45
+
46
+ def slim_jurisdiction_videos(
47
+ j: Dict[str, Any],
48
+ *,
49
+ video_mode: VideoPayloadMode,
50
+ ) -> Dict[str, Any]:
51
+ """Drop per-video rows when counts in ``stats`` are enough for the table."""
52
+ if video_mode == "all":
53
+ return j
54
+ out = dict(j)
55
+ status = (out.get("status") or "").strip().lower()
56
+ if video_mode == "running" and (
57
+ status == "running" or (out.get("current_video_id") or "").strip()
58
+ ):
59
+ return out
60
+ videos = list(out.get("videos") or [])
61
+ if video_mode == "failed_only":
62
+ out["videos"] = [v for v in videos if _is_failed_video_status(v.get("status", ""))]
63
+ else:
64
+ out["videos"] = []
65
+ return out
66
+
67
+
68
+ def slim_batch_dict(
69
+ batch: Dict[str, Any],
70
+ *,
71
+ video_mode: VideoPayloadMode,
72
+ ) -> Dict[str, Any]:
73
+ out = dict(batch)
74
+ jurs = batch.get("jurisdictions") or []
75
+ if not jurs:
76
+ return out
77
+ batch_running = (batch.get("status") or "").lower() == "running"
78
+ mode: VideoPayloadMode = video_mode
79
+ if video_mode == "running" and not batch_running:
80
+ mode = "failed_only"
81
+ out["jurisdictions"] = [
82
+ slim_jurisdiction_videos(j, video_mode=mode) if isinstance(j, dict) else j
83
+ for j in jurs
84
+ ]
85
+ return out
86
+
87
+
88
+ def _totals_from_batch_summaries(batches: List[Dict[str, Any]]) -> Dict[str, Any]:
89
+ totals = {
90
+ "batches": 0,
91
+ "running": 0,
92
+ "states": 0,
93
+ "states_planned": 0,
94
+ "states_started": 0,
95
+ "states_completed": 0,
96
+ "processed_jurisdictions": 0,
97
+ "failed_jurisdictions": 0,
98
+ "remaining_jurisdictions": 0,
99
+ "videos_ok": 0,
100
+ "videos_fail": 0,
101
+ "videos_attempted": 0,
102
+ "files_transcripts": 0,
103
+ "files_transcripts_disk": 0,
104
+ "transcript_hours": 0.0,
105
+ "bronze_download_rows": 0,
106
+ "files_analysis": 0,
107
+ "files_reports": 0,
108
+ "files_analysis_recent": 0,
109
+ "files_reports_recent": 0,
110
+ }
111
+ planned_states: set[str] = set()
112
+ started_states: set[str] = set()
113
+ completed_states: set[str] = set()
114
+ transcript_seconds = 0.0
115
+
116
+ from api.batch_jobs.batch_job_status import config_state_codes
117
+
118
+ for d in batches:
119
+ totals["batches"] += 1
120
+ if d.get("status") == "running":
121
+ totals["running"] += 1
122
+ s = d.get("summary") or {}
123
+ for st in config_state_codes(d.get("config") or {}):
124
+ planned_states.add(st)
125
+ for st in s.get("states_started_codes") or []:
126
+ started_states.add(str(st).upper())
127
+ for st in s.get("states_completed_codes") or []:
128
+ completed_states.add(str(st).upper())
129
+ totals["processed_jurisdictions"] += int(s.get("processed_jurisdictions") or 0)
130
+ totals["failed_jurisdictions"] += int(s.get("failed_jurisdictions") or 0)
131
+ totals["remaining_jurisdictions"] += int(s.get("remaining_jurisdictions") or 0)
132
+ totals["videos_ok"] += int(s.get("videos_ok") or 0)
133
+ totals["videos_fail"] += int(s.get("videos_fail") or 0)
134
+ attempted = int(s.get("videos_attempted") or s.get("files_processed") or 0)
135
+ if not attempted:
136
+ attempted = (
137
+ int(s.get("videos_ok") or 0)
138
+ + int(s.get("videos_fail") or 0)
139
+ + int(s.get("videos_tombstoned") or 0)
140
+ + int(s.get("videos_empty") or 0)
141
+ + int(s.get("videos_rate_limit") or 0)
142
+ )
143
+ totals["videos_attempted"] += attempted
144
+ totals["files_transcripts"] += int(s.get("files_transcripts") or 0)
145
+ totals["files_transcripts_disk"] += int(s.get("files_transcripts_disk") or 0)
146
+ totals["bronze_download_rows"] += int(s.get("bronze_download_rows") or 0)
147
+ totals["files_analysis"] += int(s.get("files_analysis") or 0)
148
+ totals["files_reports"] += int(s.get("files_reports") or 0)
149
+ totals["files_analysis_recent"] += int(s.get("files_analysis_recent") or 0)
150
+ totals["files_reports_recent"] += int(s.get("files_reports_recent") or 0)
151
+ transcript_seconds += float(s.get("transcript_seconds") or 0)
152
+
153
+ totals["states_planned"] = len(planned_states)
154
+ totals["states_started"] = len(started_states)
155
+ totals["states_completed"] = len(completed_states)
156
+ totals["states"] = totals["states_planned"]
157
+ totals["transcript_hours"] = round(transcript_seconds / 3600.0, 2)
158
+ return totals
159
+
160
+
161
+ def _max_iso_timestamp(best: str, candidate: str) -> str:
162
+ raw = (candidate or "").strip()
163
+ if raw and (not best or raw > best):
164
+ return raw
165
+ return best
166
+
167
+
168
+ def pipeline_activity_at_from_batches(batches: List[Dict[str, Any]]) -> str:
169
+ """
170
+ Latest jurisdiction/video progress timestamp (not batch ``updated_at`` sync metadata).
171
+
172
+ Includes ``summary.current_video_started_at`` (same clock as the Current file card) when
173
+ the slim running snapshot has no jurisdiction rows.
174
+ """
175
+ best = ""
176
+ for b in batches:
177
+ jurs = b.get("jurisdictions") or []
178
+ for j in jurs:
179
+ if not isinstance(j, dict):
180
+ continue
181
+ for key in (
182
+ "updated_at",
183
+ "current_video_started_at",
184
+ "finished_at",
185
+ "started_at",
186
+ ):
187
+ best = _max_iso_timestamp(best, j.get(key) or "")
188
+ for v in j.get("videos") or []:
189
+ if isinstance(v, dict):
190
+ best = _max_iso_timestamp(best, v.get("finished_at") or "")
191
+ summary = b.get("summary") or {}
192
+ if isinstance(summary, dict):
193
+ for key in (
194
+ "current_video_started_at",
195
+ "current_jurisdiction_finished_at",
196
+ ):
197
+ best = _max_iso_timestamp(best, summary.get(key) or "")
198
+ for key in ("finished_at", "started_at"):
199
+ best = _max_iso_timestamp(best, b.get(key) or "")
200
+ return best
201
+
202
+
203
+ def build_dashboard_summary(*, limit: int = 30, cohort: str | None = None) -> Dict[str, Any]:
204
+ """Fast path: batch list + totals from ``summary`` JSON only (no payload parse)."""
205
+ import datetime as _dt
206
+ import os
207
+
208
+ use_db = os.getenv("BATCH_JOBS_USE_DB", "1").strip().lower() not in (
209
+ "0",
210
+ "false",
211
+ "no",
212
+ "off",
213
+ )
214
+ batches: List[Dict[str, Any]] = []
215
+ source = "files"
216
+ sql_totals: Dict[str, Any] | None = None
217
+
218
+ if use_db:
219
+ try:
220
+ from api.batch_jobs.batch_job_db import (
221
+ aggregate_dashboard_totals_from_db,
222
+ list_batch_job_meta_from_db,
223
+ running_batch_activity_from_db,
224
+ )
225
+
226
+ # Totals first: it reaps stale ``running`` rows, so the meta read
227
+ # below sees the corrected per-batch statuses in this same snapshot.
228
+ reaped_totals = aggregate_dashboard_totals_from_db(limit=limit)
229
+ batches = list_batch_job_meta_from_db(limit=limit)
230
+ if batches:
231
+ source = "database"
232
+ sql_totals = reaped_totals
233
+ running = running_batch_activity_from_db()
234
+ if running:
235
+ for b in batches:
236
+ if b.get("batch_id") == running.get("batch_id"):
237
+ b["jurisdictions"] = running.get("jurisdictions") or []
238
+ break
239
+ except Exception:
240
+ batches = []
241
+
242
+ if not batches:
243
+ jobs = list_batches(limit=limit)
244
+ batches = [
245
+ {
246
+ "batch_id": j.batch_id,
247
+ "step": j.step,
248
+ "status": j.status,
249
+ "started_at": j.started_at,
250
+ "updated_at": j.updated_at,
251
+ "finished_at": j.finished_at,
252
+ "config": dict(j.config or {}),
253
+ "summary": dict(j.summary or {}),
254
+ "jurisdictions": [],
255
+ }
256
+ for j in jobs
257
+ ]
258
+ source = "files"
259
+
260
+ totals = _totals_from_batch_summaries(batches)
261
+ if sql_totals:
262
+ totals.update(
263
+ {
264
+ k: sql_totals[k]
265
+ for k in (
266
+ "batches",
267
+ "running",
268
+ "processed_jurisdictions",
269
+ "failed_jurisdictions",
270
+ "remaining_jurisdictions",
271
+ "videos_ok",
272
+ "videos_fail",
273
+ "files_transcripts",
274
+ "files_transcripts_disk",
275
+ "bronze_download_rows",
276
+ "files_analysis",
277
+ "files_reports",
278
+ "files_analysis_recent",
279
+ "files_reports_recent",
280
+ "files_analysis_errors_recent",
281
+ "files_reports_errors_recent",
282
+ "last_transcript_at",
283
+ "last_analysis_at",
284
+ "last_report_at",
285
+ "transcript_hours",
286
+ )
287
+ if k in sql_totals
288
+ }
289
+ )
290
+ last_activity = pipeline_activity_at_from_batches(batches)
291
+ if not last_activity and sql_totals.get("last_activity_at"):
292
+ last_activity = sql_totals["last_activity_at"]
293
+ else:
294
+ last_activity = pipeline_activity_at_from_batches(batches)
295
+ stage_report: Dict[str, Any] = {"states": [], "rows": []}
296
+ if use_db:
297
+ from api.batch_jobs.batch_job_db import dashboard_stage_report
298
+
299
+ stage_report = dashboard_stage_report(cohort=cohort)
300
+ now = _dt.datetime.now(_dt.timezone.utc)
301
+ return {
302
+ "generated_at": now.isoformat(),
303
+ "last_activity_at": last_activity,
304
+ "totals": totals,
305
+ "batches": batches,
306
+ "stage_report": stage_report,
307
+ "source": source,
308
+ "detail": "summary",
309
+ }
310
+
311
+
312
+ def build_batch_state_jurisdictions(*, batch_id: str, state_code: str) -> List[Dict[str, Any]]:
313
+ """
314
+ Slim jurisdiction rows for one state (no per-video arrays).
315
+
316
+ Uses JSONB extraction for finished batches; single-state plan merge for running.
317
+ """
318
+ from api.batch_jobs.batch_job_db import (
319
+ list_jurisdiction_rows_from_db,
320
+ load_batch_job_from_db,
321
+ )
322
+ from api.batch_jobs.batch_job_status import (
323
+ apply_batch_lifecycle,
324
+ expand_batch_job_plan,
325
+ fetch_batch_plan_jurisdictions_cached,
326
+ needs_plan_expand,
327
+ )
328
+
329
+ st = (state_code or "").strip().upper()
330
+ if not st:
331
+ return []
332
+
333
+ job = load_batch_job_from_db(batch_id)
334
+ if not job:
335
+ return []
336
+
337
+ status = (job.status or "").lower()
338
+ if status == "running" and needs_plan_expand(job):
339
+ rr = job.config.get("round_robin") if job.config else None
340
+ if rr is None:
341
+ rr = True
342
+ plan = fetch_batch_plan_jurisdictions_cached([st], round_robin=bool(rr))
343
+ expand_batch_job_plan(job, plan=plan)
344
+ apply_batch_lifecycle(job)
345
+ full = job.to_dict()
346
+ return [
347
+ slim_jurisdiction_videos(j, video_mode="none")
348
+ for j in full.get("jurisdictions") or []
349
+ if (j.get("state_code") or "").upper() == st
350
+ ]
351
+
352
+ rows = list_jurisdiction_rows_from_db(batch_id, st)
353
+ if rows:
354
+ return rows
355
+
356
+ apply_batch_lifecycle(job)
357
+ full = job.to_dict()
358
+ return [
359
+ slim_jurisdiction_videos(j, video_mode="none")
360
+ for j in full.get("jurisdictions") or []
361
+ if (j.get("state_code") or "").upper() == st
362
+ ]
363
+
364
+ _REPO_ROOT = Path(__file__).resolve().parents[3]
365
+ if str(_REPO_ROOT) not in sys.path:
366
+ sys.path.insert(0, str(_REPO_ROOT))
367
+
368
+ from api.batch_jobs.batch_job_status import (
369
+ _REPO_ROOT,
370
+ BatchJob,
371
+ _recompute_summary,
372
+ apply_batch_lifecycle,
373
+ count_policy_files_for_jurisdiction,
374
+ expand_batch_job_plan,
375
+ jobs_dir,
376
+ latest_dashboard_activity_at,
377
+ list_batches,
378
+ )
379
+
380
+ _DASHBOARD_NAME = "dashboard.html"
381
+ _POLICY_CACHE = _REPO_ROOT / "data" / "cache" / "gemini_transcript_policy"
382
+
383
+
384
+ def _fmt_duration(seconds: Any) -> str:
385
+ if seconds is None:
386
+ return "—"
387
+ try:
388
+ total = int(float(seconds))
389
+ except (TypeError, ValueError):
390
+ return "—"
391
+ if total < 60:
392
+ return f"{total}s"
393
+ m, s = divmod(total, 60)
394
+ if m < 60:
395
+ return f"{m}m {s}s"
396
+ h, m = divmod(m, 60)
397
+ return f"{h}h {m}m"
398
+
399
+
400
+ def _enrich_file_counts(job: BatchJob) -> BatchJob:
401
+ from api.batch_jobs.batch_job_status import policy_disk_file_counts
402
+
403
+ for j in job.jurisdictions:
404
+ scanned = count_policy_files_for_jurisdiction(
405
+ _POLICY_CACHE,
406
+ state_code=j.state_code,
407
+ jurisdiction_id=j.jurisdiction_id,
408
+ )
409
+ j.file_counts = dict(j.file_counts or {})
410
+ j.file_counts.update(policy_disk_file_counts(scanned))
411
+ return job
412
+
413
+
414
+ def _aggregate_jobs(
415
+ jobs: List[BatchJob],
416
+ *,
417
+ enrich_transcript_from_bronze: bool = False,
418
+ cohort: str | None = None,
419
+ ) -> Dict[str, Any]:
420
+ batches: List[Dict[str, Any]] = []
421
+ totals = {
422
+ "batches": 0,
423
+ "running": 0,
424
+ "states": 0,
425
+ "states_planned": 0,
426
+ "states_started": 0,
427
+ "states_completed": 0,
428
+ "processed_jurisdictions": 0,
429
+ "failed_jurisdictions": 0,
430
+ "remaining_jurisdictions": 0,
431
+ "videos_ok": 0,
432
+ "videos_fail": 0,
433
+ "videos_attempted": 0,
434
+ "files_transcripts": 0,
435
+ "files_transcripts_disk": 0,
436
+ "transcript_hours": 0.0,
437
+ "bronze_download_rows": 0,
438
+ "files_analysis": 0,
439
+ "files_reports": 0,
440
+ "files_analysis_recent": 0,
441
+ "files_reports_recent": 0,
442
+ }
443
+ planned_states: set[str] = set()
444
+ started_states: set[str] = set()
445
+ completed_states: set[str] = set()
446
+ transcript_seconds = 0.0
447
+
448
+ bronze_conn = None
449
+ if enrich_transcript_from_bronze:
450
+ try:
451
+ from api.batch_jobs.batch_job_db import (
452
+ enrich_transcript_seconds_from_bronze,
453
+ get_db_connection,
454
+ )
455
+
456
+ bronze_conn = get_db_connection()
457
+ except Exception:
458
+ bronze_conn = None
459
+
460
+ try:
461
+ from api.batch_jobs.batch_job_status import (
462
+ _batch_plan_cache_key,
463
+ _recompute_summary,
464
+ config_state_codes,
465
+ expand_batch_job_plan,
466
+ fetch_batch_plan_jurisdictions_cached,
467
+ needs_plan_expand,
468
+ normalize_batch_job_jurisdictions,
469
+ persist_batch_job,
470
+ )
471
+
472
+ plan_by_states: Dict[str, list] = {}
473
+
474
+ import logging
475
+
476
+ _log = logging.getLogger(__name__)
477
+
478
+ for job in jobs:
479
+ try:
480
+ status_before = job.status
481
+ if needs_plan_expand(job):
482
+ states = config_state_codes(job.config or {})
483
+ rr = job.config.get("round_robin") if job.config else None
484
+ if rr is None:
485
+ rr = True
486
+ plan_key = _batch_plan_cache_key(states, round_robin=bool(rr))
487
+ if plan_key and plan_key not in plan_by_states:
488
+ # Plan expansion is per running batch config, not the dashboard
489
+ # cohort scope; stage_report applies cohort filtering separately.
490
+ plan_by_states[plan_key] = fetch_batch_plan_jurisdictions_cached(
491
+ states, round_robin=bool(rr)
492
+ )
493
+ expand_batch_job_plan(
494
+ job, plan=plan_by_states.get(plan_key) if plan_key else None
495
+ )
496
+ if (job.status or "").lower() == "running":
497
+ normalize_batch_job_jurisdictions(job)
498
+ apply_batch_lifecycle(job)
499
+ _recompute_summary(job)
500
+ if status_before != job.status:
501
+ try:
502
+ persist_batch_job(job)
503
+ except Exception as exc:
504
+ _log.warning(
505
+ "persist batch %s failed: %s", job.batch_id, exc
506
+ )
507
+ if bronze_conn is not None:
508
+ try:
509
+ enrich_transcript_seconds_from_bronze(bronze_conn, job)
510
+ except Exception:
511
+ pass
512
+ d = job.to_dict()
513
+ except Exception as exc:
514
+ _log.exception("batch %s skipped in dashboard: %s", job.batch_id, exc)
515
+ d = job.to_dict()
516
+ batches.append(d)
517
+ s = d.get("summary") or {}
518
+ totals["batches"] += 1
519
+ if d.get("status") == "running":
520
+ totals["running"] += 1
521
+ for st in config_state_codes(job.config or {}):
522
+ planned_states.add(st)
523
+ for st in s.get("states_started_codes") or []:
524
+ started_states.add(str(st).upper())
525
+ for st in s.get("states_completed_codes") or []:
526
+ completed_states.add(str(st).upper())
527
+ totals["processed_jurisdictions"] += int(s.get("processed_jurisdictions") or 0)
528
+ totals["failed_jurisdictions"] += int(s.get("failed_jurisdictions") or 0)
529
+ totals["remaining_jurisdictions"] += int(s.get("remaining_jurisdictions") or 0)
530
+ totals["videos_ok"] += int(s.get("videos_ok") or 0)
531
+ totals["videos_fail"] += int(s.get("videos_fail") or 0)
532
+ attempted = int(s.get("videos_attempted") or s.get("files_processed") or 0)
533
+ if not attempted:
534
+ attempted = (
535
+ int(s.get("videos_ok") or 0)
536
+ + int(s.get("videos_fail") or 0)
537
+ + int(s.get("videos_tombstoned") or 0)
538
+ + int(s.get("videos_empty") or 0)
539
+ + int(s.get("videos_rate_limit") or 0)
540
+ )
541
+ totals["videos_attempted"] += attempted
542
+ totals["files_transcripts"] += int(s.get("files_transcripts") or 0)
543
+ totals["files_transcripts_disk"] += int(s.get("files_transcripts_disk") or 0)
544
+ totals["bronze_download_rows"] += int(s.get("bronze_download_rows") or 0)
545
+ totals["files_analysis"] += int(s.get("files_analysis") or 0)
546
+ totals["files_reports"] += int(s.get("files_reports") or 0)
547
+ totals["files_analysis_recent"] += int(s.get("files_analysis_recent") or 0)
548
+ totals["files_reports_recent"] += int(s.get("files_reports_recent") or 0)
549
+ transcript_seconds += float(s.get("transcript_seconds") or 0)
550
+ finally:
551
+ if bronze_conn is not None:
552
+ try:
553
+ bronze_conn.close()
554
+ except Exception:
555
+ pass
556
+
557
+ totals["states_planned"] = len(planned_states)
558
+ totals["states_started"] = len(started_states)
559
+ totals["states_completed"] = len(completed_states)
560
+ totals["states"] = totals["states_planned"]
561
+ totals["transcript_hours"] = round(transcript_seconds / 3600.0, 2)
562
+
563
+ import datetime as _dt
564
+
565
+ from api.batch_jobs.batch_job_db import dashboard_stage_report
566
+
567
+ now = _dt.datetime.now(_dt.timezone.utc)
568
+ return {
569
+ "generated_at": now.isoformat(),
570
+ "last_activity_at": latest_dashboard_activity_at(jobs),
571
+ "totals": totals,
572
+ "batches": batches,
573
+ "stage_report": dashboard_stage_report(cohort=cohort),
574
+ "source": "database",
575
+ "detail": "full",
576
+ }
577
+
578
+
579
+ def _override_recent_counts_from_events(payload: Dict[str, Any]) -> None:
580
+ """
581
+ Replace the batch-scoped disk-scan counters with the live per-event bronze
582
+ stamps (migration 083): the 24h throughput, the all-time pipeline totals (so
583
+ progress % is de-duplicated and current), and the per-step "ago" timestamps.
584
+ Best-effort: leaves the disk-scan values in place if the DB/columns are missing.
585
+ """
586
+ totals = payload.get("totals")
587
+ if not isinstance(totals, dict):
588
+ return
589
+ try:
590
+ from api.batch_jobs.batch_job_db import (
591
+ get_db_connection,
592
+ policy_event_counts_24h,
593
+ )
594
+
595
+ with get_db_connection() as conn:
596
+ counts = policy_event_counts_24h(conn)
597
+ totals["files_analysis_recent"] = int(counts.get("analysis") or 0)
598
+ totals["files_reports_recent"] = int(counts.get("reports") or 0)
599
+ totals["files_analysis_errors_recent"] = int(counts.get("analysis_errors") or 0)
600
+ totals["files_reports_errors_recent"] = int(counts.get("reports_errors") or 0)
601
+ transcripts_total = int(counts.get("transcripts_total") or 0)
602
+ analysis_total = int(counts.get("analysis_total") or 0)
603
+ reports_total = int(counts.get("reports_total") or 0)
604
+ if transcripts_total > 0:
605
+ totals["files_transcripts_disk"] = transcripts_total
606
+ if analysis_total > 0:
607
+ totals["files_analysis"] = analysis_total
608
+ if reports_total > 0:
609
+ totals["files_reports"] = reports_total
610
+ totals["last_transcript_at"] = counts.get("last_transcript_at") or ""
611
+ totals["last_analysis_at"] = counts.get("last_analysis_at") or ""
612
+ totals["last_report_at"] = counts.get("last_report_at") or ""
613
+ except Exception as exc:
614
+ import logging
615
+
616
+ logging.getLogger(__name__).debug(
617
+ "recent-event count override skipped: %s", exc
618
+ )
619
+
620
+
621
+ def build_dashboard_data(
622
+ *,
623
+ refresh_files: bool = False,
624
+ enrich_bronze: bool = True,
625
+ enrich_bronze_only_running: bool = False,
626
+ batch_limit: int = 25,
627
+ video_mode: VideoPayloadMode = "running",
628
+ cohort: str | None = None,
629
+ ) -> Dict[str, Any]:
630
+ """
631
+ Build dashboard payload. Prefer Postgres (``bronze.youtube_batch_job_runs``);
632
+ fall back to JSON files under ``data/cache/batch_jobs/``.
633
+
634
+ ``refresh_files`` scans the policy cache on disk (slow). By default transcript
635
+ counts come from ``bronze.bronze_event_youtube`` when ``enrich_bronze`` is true.
636
+ """
637
+ import os
638
+
639
+ use_db = os.getenv("BATCH_JOBS_USE_DB", "1").strip().lower() not in (
640
+ "0",
641
+ "false",
642
+ "no",
643
+ "off",
644
+ )
645
+
646
+ if use_db:
647
+ try:
648
+ from api.batch_jobs.batch_job_db import (
649
+ enrich_jobs_from_bronze,
650
+ list_batch_jobs_from_db,
651
+ sync_json_batches_to_db,
652
+ )
653
+
654
+ jobs = list_batch_jobs_from_db(limit=batch_limit)
655
+ if not jobs:
656
+ sync_json_batches_to_db(limit=batch_limit)
657
+ jobs = list_batch_jobs_from_db(limit=batch_limit)
658
+ if jobs:
659
+ if enrich_bronze:
660
+ enrich_jobs_from_bronze(
661
+ jobs,
662
+ only_running_jurisdictions=True,
663
+ enrich_disk=False,
664
+ )
665
+ elif refresh_files:
666
+ for job in jobs:
667
+ _enrich_file_counts(job)
668
+ payload = _aggregate_jobs(
669
+ jobs,
670
+ enrich_transcript_from_bronze=enrich_bronze,
671
+ cohort=cohort,
672
+ )
673
+ _override_recent_counts_from_events(payload)
674
+ if video_mode != "all":
675
+ payload["batches"] = [
676
+ slim_batch_dict(b, video_mode=video_mode)
677
+ for b in payload.get("batches") or []
678
+ ]
679
+ payload["detail"] = "full"
680
+ return payload
681
+ except Exception as exc:
682
+ import logging
683
+
684
+ logging.getLogger(__name__).warning(
685
+ "batch dashboard DB read failed, using JSON files: %s", exc
686
+ )
687
+
688
+ jobs = list_batches(limit=batch_limit)
689
+ if refresh_files:
690
+ for job in jobs:
691
+ _enrich_file_counts(job)
692
+ elif enrich_bronze:
693
+ try:
694
+ from api.batch_jobs.batch_job_db import enrich_jobs_from_bronze
695
+
696
+ enrich_jobs_from_bronze(jobs)
697
+ except Exception:
698
+ pass
699
+ payload = _aggregate_jobs(
700
+ jobs, enrich_transcript_from_bronze=enrich_bronze, cohort=cohort
701
+ )
702
+ payload["source"] = "files"
703
+ if video_mode != "all":
704
+ payload["batches"] = [
705
+ slim_batch_dict(b, video_mode=video_mode) for b in payload.get("batches") or []
706
+ ]
707
+ payload["detail"] = "full"
708
+ return payload
709
+
710
+
711
+ def render_html(payload: Dict[str, Any]) -> str:
712
+ data_json = json.dumps(payload, ensure_ascii=False)
713
+ return f"""<!DOCTYPE html>
714
+ <html lang="en">
715
+ <head>
716
+ <meta charset="utf-8" />
717
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
718
+ <title>Batch job status</title>
719
+ <style>
720
+ :root {{
721
+ --bg: #0f1419;
722
+ --panel: #1a2332;
723
+ --border: #2d3a4f;
724
+ --text: #e7ecf3;
725
+ --muted: #8b9cb3;
726
+ --accent: #3d8bfd;
727
+ --ok: #3dd68c;
728
+ --fail: #f07178;
729
+ --warn: #e7b86a;
730
+ --run: #7eb6ff;
731
+ }}
732
+ * {{ box-sizing: border-box; }}
733
+ body {{
734
+ margin: 0;
735
+ font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
736
+ background: var(--bg);
737
+ color: var(--text);
738
+ line-height: 1.45;
739
+ }}
740
+ header {{
741
+ padding: 1.25rem 1.5rem;
742
+ border-bottom: 1px solid var(--border);
743
+ display: flex;
744
+ flex-wrap: wrap;
745
+ gap: 1rem;
746
+ align-items: baseline;
747
+ justify-content: space-between;
748
+ }}
749
+ h1 {{ margin: 0; font-size: 1.35rem; font-weight: 600; }}
750
+ .meta {{ color: var(--muted); font-size: 0.85rem; }}
751
+ main {{ display: grid; grid-template-columns: 280px 1fr; min-height: calc(100vh - 72px); }}
752
+ @media (max-width: 900px) {{
753
+ main {{ grid-template-columns: 1fr; }}
754
+ }}
755
+ aside {{
756
+ border-right: 1px solid var(--border);
757
+ padding: 1rem;
758
+ overflow: auto;
759
+ }}
760
+ section {{ padding: 1rem 1.25rem; overflow: auto; }}
761
+ .cards {{
762
+ display: grid;
763
+ grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
764
+ gap: 0.65rem;
765
+ margin-bottom: 1.25rem;
766
+ }}
767
+ .card {{
768
+ background: var(--panel);
769
+ border: 1px solid var(--border);
770
+ border-radius: 8px;
771
+ padding: 0.75rem 0.85rem;
772
+ }}
773
+ .card .label {{ color: var(--muted); font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.04em; }}
774
+ .card .value {{ font-size: 1.35rem; font-weight: 600; margin-top: 0.15rem; }}
775
+ .batch-list {{ list-style: none; padding: 0; margin: 0; }}
776
+ .batch-list li {{
777
+ margin-bottom: 0.35rem;
778
+ }}
779
+ .batch-list button {{
780
+ width: 100%;
781
+ text-align: left;
782
+ background: transparent;
783
+ border: 1px solid transparent;
784
+ color: var(--text);
785
+ padding: 0.55rem 0.65rem;
786
+ border-radius: 6px;
787
+ cursor: pointer;
788
+ font-size: 0.88rem;
789
+ }}
790
+ .batch-list button:hover {{ background: var(--panel); }}
791
+ .batch-list button.active {{
792
+ background: var(--panel);
793
+ border-color: var(--accent);
794
+ }}
795
+ .badge {{
796
+ display: inline-block;
797
+ font-size: 0.68rem;
798
+ padding: 0.1rem 0.4rem;
799
+ border-radius: 4px;
800
+ margin-left: 0.35rem;
801
+ vertical-align: middle;
802
+ }}
803
+ .badge.running {{ background: #1e3a5f; color: var(--run); }}
804
+ .badge.completed {{ background: #1a3d2e; color: var(--ok); }}
805
+ .badge.failed {{ background: #3d2226; color: var(--fail); }}
806
+ table {{
807
+ width: 100%;
808
+ border-collapse: collapse;
809
+ font-size: 0.86rem;
810
+ }}
811
+ th, td {{
812
+ text-align: left;
813
+ padding: 0.5rem 0.6rem;
814
+ border-bottom: 1px solid var(--border);
815
+ }}
816
+ th {{ color: var(--muted); font-weight: 500; font-size: 0.75rem; text-transform: uppercase; }}
817
+ tr.j-row {{ cursor: pointer; }}
818
+ tr.j-row:hover {{ background: rgba(61, 139, 253, 0.08); }}
819
+ tr.j-row.selected {{ background: rgba(61, 139, 253, 0.15); }}
820
+ .status-ok {{ color: var(--ok); }}
821
+ .status-fail {{ color: var(--fail); }}
822
+ .status-running {{ color: var(--run); }}
823
+ .detail-panel {{
824
+ margin-top: 1rem;
825
+ background: var(--panel);
826
+ border: 1px solid var(--border);
827
+ border-radius: 8px;
828
+ padding: 1rem;
829
+ }}
830
+ .detail-panel h3 {{ margin: 0 0 0.75rem; font-size: 1rem; }}
831
+ .empty {{ color: var(--muted); padding: 2rem; text-align: center; }}
832
+ .bar-wrap {{
833
+ height: 8px;
834
+ background: var(--border);
835
+ border-radius: 4px;
836
+ overflow: hidden;
837
+ margin-top: 0.5rem;
838
+ }}
839
+ .bar-fill {{ height: 100%; background: var(--accent); }}
840
+ a {{ color: var(--accent); }}
841
+ </style>
842
+ </head>
843
+ <body>
844
+ <header>
845
+ <div>
846
+ <h1>Batch job status</h1>
847
+ <div class="meta" id="generated-meta"></div>
848
+ </div>
849
+ <div class="meta">Refresh: re-run <code>batch_job_dashboard.py --build</code></div>
850
+ </header>
851
+ <main>
852
+ <aside>
853
+ <div class="cards" id="global-cards"></div>
854
+ <ul class="batch-list" id="batch-list"></ul>
855
+ </aside>
856
+ <section>
857
+ <div id="batch-detail" class="empty">Select a batch</div>
858
+ <div id="jurisdiction-detail"></div>
859
+ </section>
860
+ </main>
861
+ <script>
862
+ const DATA = {data_json};
863
+ const fmtDur = (s) => {{
864
+ if (s == null || s === '') return '—';
865
+ const t = Math.max(0, Math.floor(Number(s)));
866
+ if (t < 60) return t + 's';
867
+ const m = Math.floor(t / 60);
868
+ const r = t % 60;
869
+ if (m < 60) return m + 'm ' + r + 's';
870
+ const h = Math.floor(m / 60);
871
+ return h + 'h ' + (m % 60) + 'm';
872
+ }};
873
+ let selectedBatchId = null;
874
+ let selectedJurisdictionId = null;
875
+
876
+ function renderGlobalCards() {{
877
+ const t = DATA.totals;
878
+ const cards = [
879
+ ['Batches', t.batches],
880
+ ['Running', t.running],
881
+ ['Jurisdictions done', t.processed_jurisdictions],
882
+ ['Jurisdictions failed', t.failed_jurisdictions],
883
+ ['Remaining', t.remaining_jurisdictions],
884
+ ['Videos OK', t.videos_ok],
885
+ ['Videos failed', t.videos_fail],
886
+ ['Videos attempted (batch)', t.videos_attempted],
887
+ ['Transcripts on disk', t.files_transcripts_disk],
888
+ ['Bronze download rows', t.bronze_download_rows],
889
+ ['Analysis on disk', t.files_analysis],
890
+ ['Reports on disk', t.files_reports],
891
+ ['Analysis (24h)', t.files_analysis_recent],
892
+ ['Reports (24h)', t.files_reports_recent],
893
+ ];
894
+ document.getElementById('global-cards').innerHTML = cards.map(([l,v]) =>
895
+ `<div class="card"><div class="label">${{l}}</div><div class="value">${{v}}</div></div>`
896
+ ).join('');
897
+ document.getElementById('generated-meta').textContent =
898
+ 'Generated ' + (DATA.generated_at || '').replace('T', ' ').slice(0, 19) + ' UTC';
899
+ }}
900
+
901
+ function statusClass(st) {{
902
+ if (st === 'completed') return 'status-ok';
903
+ if (st === 'failed') return 'status-fail';
904
+ if (st === 'running') return 'status-running';
905
+ return '';
906
+ }}
907
+
908
+ function renderBatchList() {{
909
+ const ul = document.getElementById('batch-list');
910
+ ul.innerHTML = DATA.batches.map(b => {{
911
+ const s = b.summary || {{}};
912
+ const pct = s.total_jurisdictions
913
+ ? Math.round(100 * (s.processed_jurisdictions || 0) / s.total_jurisdictions)
914
+ : 0;
915
+ return `<li>
916
+ <button type="button" data-id="${{b.batch_id}}" class="${{selectedBatchId === b.batch_id ? 'active' : ''}}">
917
+ <div><strong>${{b.step}}</strong>
918
+ <span class="badge ${{b.status}}">${{b.status}}</span></div>
919
+ <div class="meta">${{b.batch_id}}</div>
920
+ <div class="meta">${{s.processed_jurisdictions || 0}}/${{s.total_jurisdictions || '?'}} jurisdictions · ${{pct}}%</div>
921
+ </button>
922
+ </li>`;
923
+ }}).join('');
924
+ ul.querySelectorAll('button').forEach(btn => {{
925
+ btn.addEventListener('click', () => selectBatch(btn.dataset.id));
926
+ }});
927
+ if (!selectedBatchId && DATA.batches.length) selectBatch(DATA.batches[0].batch_id);
928
+ }}
929
+
930
+ function selectBatch(id) {{
931
+ selectedBatchId = id;
932
+ selectedJurisdictionId = null;
933
+ renderBatchList();
934
+ renderBatchDetail();
935
+ document.getElementById('jurisdiction-detail').innerHTML = '';
936
+ }}
937
+
938
+ function renderBatchDetail() {{
939
+ const el = document.getElementById('batch-detail');
940
+ const b = DATA.batches.find(x => x.batch_id === selectedBatchId);
941
+ if (!b) {{ el.innerHTML = '<div class="empty">No batch selected</div>'; return; }}
942
+ const s = b.summary || {{}};
943
+ const cfg = b.config || {{}};
944
+ const pct = s.total_jurisdictions
945
+ ? Math.round(100 * (s.processed_jurisdictions || 0) / s.total_jurisdictions)
946
+ : 0;
947
+ const jurs = b.jurisdictions || [];
948
+ el.innerHTML = `
949
+ <h2 style="margin:0 0 0.5rem;font-size:1.15rem">${{b.step}} <span class="badge ${{b.status}}">${{b.status}}</span></h2>
950
+ <div class="meta">${{b.batch_id}} · started ${{b.started_at || '—'}}</div>
951
+ <div class="cards" style="margin-top:1rem">
952
+ <div class="card"><div class="label">Processed</div><div class="value">${{s.processed_jurisdictions || 0}} / ${{s.total_jurisdictions || '?'}}</div></div>
953
+ <div class="card"><div class="label">Success</div><div class="value status-ok">${{s.success_jurisdictions || 0}}</div></div>
954
+ <div class="card"><div class="label">Failed</div><div class="value status-fail">${{s.failed_jurisdictions || 0}}</div></div>
955
+ <div class="card"><div class="label">Remaining</div><div class="value">${{s.remaining_jurisdictions || 0}}</div></div>
956
+ <div class="card"><div class="label">Elapsed</div><div class="value">${{fmtDur(s.elapsed_seconds)}}</div></div>
957
+ <div class="card"><div class="label">ETA</div><div class="value">${{fmtDur(s.eta_seconds)}}</div></div>
958
+ <div class="card"><div class="label">Videos OK</div><div class="value">${{s.videos_ok || 0}}</div></div>
959
+ <div class="card"><div class="label">Videos fail</div><div class="value">${{s.videos_fail || 0}}</div></div>
960
+ </div>
961
+ <div class="bar-wrap"><div class="bar-fill" style="width:${{pct}}%"></div></div>
962
+ <p class="meta" style="margin-top:0.75rem">States: ${{(cfg.states || []).join(', ') || '—'}} · N=${{cfg.n || '—'}} · delay=${{cfg.delay || '—'}}s · source=${{cfg.transcript_source || '—'}}</p>
963
+ <h3 style="margin:1.25rem 0 0.5rem;font-size:0.95rem">Jurisdictions (${{jurs.length}})</h3>
964
+ <table>
965
+ <thead><tr>
966
+ <th>State</th><th>Jurisdiction</th><th>Status</th><th>Videos</th><th>Files</th><th>Time</th>
967
+ </tr></thead>
968
+ <tbody id="juris-table-body"></tbody>
969
+ </table>
970
+ `;
971
+ const tbody = document.getElementById('juris-table-body');
972
+ tbody.innerHTML = jurs.map(j => {{
973
+ const st = j.stats || {{}};
974
+ const fc = j.file_counts || {{}};
975
+ const vids = (st.ok || 0) + (st.fail || 0) + (st.tombstoned || 0);
976
+ return `<tr class="j-row ${{selectedJurisdictionId === j.jurisdiction_id ? 'selected' : ''}}" data-jid="${{j.jurisdiction_id}}">
977
+ <td>${{j.state_code}}</td>
978
+ <td><strong>${{j.jurisdiction_name || j.jurisdiction_id}}</strong><br><span class="meta">${{j.jurisdiction_id}}</span></td>
979
+ <td class="${{statusClass(j.status)}}">${{j.status}}${{j.exit_code ? ' (' + j.exit_code + ')' : ''}}</td>
980
+ <td>ok ${{st.ok || 0}} · fail ${{st.fail || 0}} · tomb ${{st.tombstoned || 0}}${{vids ? '' : ''}}</td>
981
+ <td>T ${{fc.transcripts || 0}} · A ${{fc.analysis || 0}} · R ${{fc.reports || 0}}</td>
982
+ <td>${{fmtDur(j.elapsed_seconds)}}</td>
983
+ </tr>`;
984
+ }}).join('');
985
+ tbody.querySelectorAll('.j-row').forEach(row => {{
986
+ row.addEventListener('click', () => selectJurisdiction(b, row.dataset.jid));
987
+ }});
988
+ }}
989
+
990
+ function selectJurisdiction(batch, jid) {{
991
+ selectedJurisdictionId = jid;
992
+ renderBatchDetail();
993
+ const j = (batch.jurisdictions || []).find(x => x.jurisdiction_id === jid);
994
+ const panel = document.getElementById('jurisdiction-detail');
995
+ if (!j) {{ panel.innerHTML = ''; return; }}
996
+ const videos = j.videos || [];
997
+ panel.innerHTML = `
998
+ <div class="detail-panel">
999
+ <h3>${{j.jurisdiction_name || j.jurisdiction_id}} — videos (${{videos.length}})</h3>
1000
+ <table>
1001
+ <thead><tr><th>Video</th><th>Title</th><th>Status</th><th>Source</th><th>Error</th></tr></thead>
1002
+ <tbody>
1003
+ ${{videos.length ? videos.map(v => `
1004
+ <tr>
1005
+ <td><a href="https://www.youtube.com/watch?v=${{v.video_id}}" target="_blank" rel="noopener">${{v.video_id}}</a></td>
1006
+ <td>${{escapeHtml(v.title || '')}}</td>
1007
+ <td class="${{v.status === 'ok' ? 'status-ok' : 'status-fail'}}">${{v.status}}</td>
1008
+ <td>${{v.transcript_source || '—'}}</td>
1009
+ <td class="meta">${{escapeHtml(v.error || '')}}</td>
1010
+ </tr>`).join('') : '<tr><td colspan="5" class="meta">No per-video log (re-run with --batch-id)</td></tr>'}}
1011
+ </tbody>
1012
+ </table>
1013
+ <p class="meta" style="margin-top:0.75rem">Stats: ${{JSON.stringify(j.stats || {{}})}}</p>
1014
+ </div>
1015
+ `;
1016
+ }}
1017
+
1018
+ function escapeHtml(s) {{
1019
+ return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
1020
+ }}
1021
+
1022
+ renderGlobalCards();
1023
+ renderBatchList();
1024
+ </script>
1025
+ </body>
1026
+ </html>
1027
+ """
1028
+
1029
+
1030
+ def write_dashboard(*, refresh_files: bool = True) -> Path:
1031
+ out_dir = jobs_dir()
1032
+ out_dir.mkdir(parents=True, exist_ok=True)
1033
+ payload = build_dashboard_data(refresh_files=refresh_files)
1034
+ out_path = out_dir / _DASHBOARD_NAME
1035
+ out_path.write_text(render_html(payload), encoding="utf-8")
1036
+ return out_path
1037
+
1038
+
1039
+ def serve_dashboard(port: int = 8765) -> None:
1040
+ root = jobs_dir()
1041
+ root.mkdir(parents=True, exist_ok=True)
1042
+ handler = SimpleHTTPRequestHandler
1043
+ original = handler.directory
1044
+
1045
+ class _Handler(SimpleHTTPRequestHandler):
1046
+ def __init__(self, *args, **kwargs):
1047
+ super().__init__(*args, directory=str(root), **kwargs)
1048
+
1049
+ server = ThreadingHTTPServer(("127.0.0.1", port), _Handler)
1050
+ url = f"http://127.0.0.1:{port}/{_DASHBOARD_NAME}"
1051
+ print(f"Serving {root} at {url}")
1052
+ print("Ctrl+C to stop")
1053
+ try:
1054
+ webbrowser.open(url)
1055
+ except Exception:
1056
+ pass
1057
+ try:
1058
+ server.serve_forever()
1059
+ except KeyboardInterrupt:
1060
+ print("\nStopped.")
1061
+
1062
+
1063
+ def main() -> int:
1064
+ parser = argparse.ArgumentParser(description=__doc__)
1065
+ parser.add_argument("--build", action="store_true", help="Write dashboard.html")
1066
+ parser.add_argument("--open", action="store_true", help="Open dashboard in browser after build")
1067
+ parser.add_argument("--serve", action="store_true", help="Serve jobs dir and open dashboard")
1068
+ parser.add_argument("--port", type=int, default=8765)
1069
+ parser.add_argument(
1070
+ "--no-refresh-files",
1071
+ action="store_true",
1072
+ help="Skip scanning policy cache for file counts (faster)",
1073
+ )
1074
+ parser.add_argument(
1075
+ "--json",
1076
+ action="store_true",
1077
+ help="Print dashboard JSON to stdout (for Vite dev fallback / debugging)",
1078
+ )
1079
+ args = parser.parse_args()
1080
+
1081
+ if args.json:
1082
+ payload = build_dashboard_data(refresh_files=not args.no_refresh_files)
1083
+ json.dump(payload, sys.stdout, ensure_ascii=False)
1084
+ sys.stdout.write("\n")
1085
+ return 0
1086
+
1087
+ if args.serve:
1088
+ write_dashboard(refresh_files=not args.no_refresh_files)
1089
+ serve_dashboard(port=args.port)
1090
+ return 0
1091
+
1092
+ if args.build or not (args.build or args.serve):
1093
+ path = write_dashboard(refresh_files=not args.no_refresh_files)
1094
+ print(path)
1095
+ if args.open:
1096
+ webbrowser.open(path.as_uri())
1097
+ return 0
1098
+
1099
+ parser.print_help()
1100
+ return 1
1101
+
1102
+
1103
+ if __name__ == "__main__":
1104
+ raise SystemExit(main())
api/batch_jobs/batch_job_db.py ADDED
@@ -0,0 +1,1576 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Postgres persistence for YouTube pipeline batch jobs (real-time dashboard).
3
+
4
+ Table: ``bronze.youtube_batch_job_runs`` (migration 073).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import logging
11
+ import os
12
+ from datetime import datetime, timezone
13
+ from pathlib import Path
14
+ from typing import Any, Dict, List, Optional
15
+
16
+ from psycopg2.extras import Json, RealDictCursor
17
+
18
+ from api.batch_jobs.batch_job_status import BatchJob, BatchJobStore, list_batches
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ _ENSURED = False
23
+
24
+
25
+ def _use_db() -> bool:
26
+ return os.getenv("BATCH_JOBS_USE_DB", "1").strip().lower() not in (
27
+ "0",
28
+ "false",
29
+ "no",
30
+ "off",
31
+ )
32
+
33
+
34
+ def get_db_connection():
35
+ import psycopg2
36
+
37
+ from core_lib.db import resolve_target_database_url
38
+
39
+ url = resolve_target_database_url()
40
+ for bad in ("&channel_binding=require", "channel_binding=require&", "channel_binding=require"):
41
+ url = url.replace(bad, "")
42
+ url = url.replace("&&", "&").rstrip("?&")
43
+ return psycopg2.connect(
44
+ url,
45
+ connect_timeout=int(os.getenv("PGCONNECT_TIMEOUT", "10")),
46
+ options=os.getenv("PGOPTIONS", "-c statement_timeout=60000"),
47
+ )
48
+
49
+
50
+ def ensure_batch_job_tables(conn: Any) -> None:
51
+ global _ENSURED
52
+ if _ENSURED:
53
+ return
54
+ cur = conn.cursor()
55
+ try:
56
+ cur.execute(
57
+ """
58
+ CREATE TABLE IF NOT EXISTS bronze.youtube_batch_job_runs (
59
+ batch_id VARCHAR(128) PRIMARY KEY,
60
+ step VARCHAR(32) NOT NULL,
61
+ status VARCHAR(32) NOT NULL,
62
+ started_at TIMESTAMPTZ,
63
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
64
+ finished_at TIMESTAMPTZ,
65
+ config JSONB NOT NULL DEFAULT '{}',
66
+ summary JSONB NOT NULL DEFAULT '{}',
67
+ payload JSONB NOT NULL
68
+ )
69
+ """
70
+ )
71
+ cur.execute(
72
+ """
73
+ CREATE INDEX IF NOT EXISTS idx_youtube_batch_job_runs_updated
74
+ ON bronze.youtube_batch_job_runs (updated_at DESC)
75
+ """
76
+ )
77
+ cur.execute(
78
+ """
79
+ CREATE INDEX IF NOT EXISTS idx_youtube_batch_job_runs_running
80
+ ON bronze.youtube_batch_job_runs (status)
81
+ WHERE status = 'running'
82
+ """
83
+ )
84
+ finally:
85
+ cur.close()
86
+ conn.commit()
87
+ _ENSURED = True
88
+
89
+
90
+ def upsert_batch_job(conn: Any, job: BatchJob) -> None:
91
+ ensure_batch_job_tables(conn)
92
+ payload = job.to_dict()
93
+ cur = conn.cursor()
94
+ try:
95
+ cur.execute(
96
+ """
97
+ INSERT INTO bronze.youtube_batch_job_runs (
98
+ batch_id, step, status, started_at, updated_at, finished_at,
99
+ config, summary, payload
100
+ ) VALUES (
101
+ %(batch_id)s, %(step)s, %(status)s,
102
+ %(started_at)s::timestamptz, %(updated_at)s::timestamptz,
103
+ NULLIF(%(finished_at)s, '')::timestamptz,
104
+ %(config)s, %(summary)s, %(payload)s
105
+ )
106
+ ON CONFLICT (batch_id) DO UPDATE SET
107
+ step = EXCLUDED.step,
108
+ status = EXCLUDED.status,
109
+ started_at = EXCLUDED.started_at,
110
+ updated_at = EXCLUDED.updated_at,
111
+ finished_at = EXCLUDED.finished_at,
112
+ config = EXCLUDED.config,
113
+ summary = EXCLUDED.summary,
114
+ payload = EXCLUDED.payload
115
+ """,
116
+ {
117
+ "batch_id": job.batch_id,
118
+ "step": job.step,
119
+ "status": job.status,
120
+ "started_at": job.started_at or None,
121
+ "updated_at": job.updated_at,
122
+ "finished_at": job.finished_at or "",
123
+ "config": Json(job.config or {}),
124
+ "summary": Json(job.summary or {}),
125
+ "payload": Json(payload),
126
+ },
127
+ )
128
+ finally:
129
+ cur.close()
130
+ conn.commit()
131
+
132
+
133
+ def sync_batch_job_to_db(job: BatchJob) -> None:
134
+ if not _use_db():
135
+ return
136
+ try:
137
+ with get_db_connection() as conn:
138
+ upsert_batch_job(conn, job)
139
+ except Exception as exc:
140
+ logger.warning("batch job DB sync failed for %s: %s", job.batch_id, exc)
141
+
142
+
143
+ def list_batch_jobs_from_db(*, limit: int = 100) -> List[BatchJob]:
144
+ with get_db_connection() as conn:
145
+ ensure_batch_job_tables(conn)
146
+ with conn.cursor(cursor_factory=RealDictCursor) as cur:
147
+ cur.execute(
148
+ """
149
+ SELECT payload
150
+ FROM bronze.youtube_batch_job_runs
151
+ ORDER BY updated_at DESC NULLS LAST
152
+ LIMIT %s
153
+ """,
154
+ (limit,),
155
+ )
156
+ rows = cur.fetchall()
157
+ jobs: List[BatchJob] = []
158
+ for row in rows:
159
+ payload = row["payload"]
160
+ if isinstance(payload, str):
161
+ payload = json.loads(payload)
162
+ jobs.append(BatchJob.from_dict(payload))
163
+ return jobs
164
+
165
+
166
+ def reap_stale_running_batches(*, limit: int = 30) -> int:
167
+ """Cancel ``running`` batch rows whose recorded activity has gone stale.
168
+
169
+ The dashboard counts ``status = 'running'`` rows, but a row stays ``running``
170
+ after its worker dies or starts skipping already-done work — the per-job
171
+ stale-cancel (``apply_batch_lifecycle`` → ``_maybe_stale_cancel_batch``,
172
+ BATCH_JOB_INACTIVITY_SECONDS, default 3600s) only fires when a job is
173
+ otherwise touched, which never happens for an abandoned run. Sweeping it here,
174
+ on the dashboard read path, keeps ``totals.running`` honest instead of pinning
175
+ it at a phantom count. Returns the number of rows whose status changed.
176
+ """
177
+ if not _use_db():
178
+ return 0
179
+ # Lazy import: batch_job_status imports this module, so import its lifecycle
180
+ # helpers at call time to avoid a circular import at module load.
181
+ from api.batch_jobs.batch_job_status import apply_batch_lifecycle, persist_batch_job
182
+
183
+ reaped = 0
184
+ try:
185
+ with get_db_connection() as conn:
186
+ ensure_batch_job_tables(conn)
187
+ with conn.cursor(cursor_factory=RealDictCursor) as cur:
188
+ cur.execute(
189
+ """
190
+ SELECT payload
191
+ FROM bronze.youtube_batch_job_runs
192
+ WHERE status = 'running'
193
+ ORDER BY updated_at DESC NULLS LAST
194
+ LIMIT %s
195
+ """,
196
+ (limit,),
197
+ )
198
+ rows = cur.fetchall()
199
+ for row in rows:
200
+ payload = row["payload"]
201
+ if isinstance(payload, str):
202
+ payload = json.loads(payload)
203
+ job = BatchJob.from_dict(payload)
204
+ if apply_batch_lifecycle(job):
205
+ persist_batch_job(job) # writes cancelled/completed status back
206
+ reaped += 1
207
+ except Exception as exc:
208
+ logger.warning("stale batch reap failed: %s", exc)
209
+ return reaped
210
+
211
+
212
+ def cancel_running_batches(
213
+ *,
214
+ reason: str = "operator Stop all",
215
+ step: str | None = None,
216
+ limit: int = 50,
217
+ ) -> int:
218
+ """Force-cancel ``running`` batch rows (used by dashboard Stop all).
219
+
220
+ Stop kills launch PIDs tracked in ``launch.json``, but orphan / already-dead
221
+ workers leave ``youtube_batch_job_runs.status = 'running'``, which keeps
222
+ ``totals.running > 0`` and disables **Run all** (#742). Returns how many
223
+ rows were cancelled.
224
+ """
225
+ if not _use_db():
226
+ return 0
227
+ from api.batch_jobs.batch_job_status import persist_batch_job
228
+
229
+ cancelled = 0
230
+ step_l = (step or "").strip().lower() or None
231
+ try:
232
+ with get_db_connection() as conn:
233
+ ensure_batch_job_tables(conn)
234
+ with conn.cursor(cursor_factory=RealDictCursor) as cur:
235
+ cur.execute(
236
+ """
237
+ SELECT payload
238
+ FROM bronze.youtube_batch_job_runs
239
+ WHERE status = 'running'
240
+ ORDER BY updated_at DESC NULLS LAST
241
+ LIMIT %s
242
+ """,
243
+ (limit,),
244
+ )
245
+ rows = cur.fetchall()
246
+ finished = datetime.now(timezone.utc).isoformat()
247
+ for row in rows:
248
+ payload = row["payload"]
249
+ if isinstance(payload, str):
250
+ payload = json.loads(payload)
251
+ job = BatchJob.from_dict(payload)
252
+ if (job.status or "").lower() != "running":
253
+ continue
254
+ if step_l and (job.step or "").lower() != step_l:
255
+ continue
256
+ job.status = "cancelled"
257
+ job.finished_at = finished
258
+ cfg = dict(job.config or {})
259
+ cfg["stop_all_reason"] = reason
260
+ job.config = cfg
261
+ for j in job.jurisdictions:
262
+ if (j.status or "").lower() == "running":
263
+ j.status = "failed"
264
+ j.exit_code = -1
265
+ j.finished_at = finished
266
+ j.updated_at = finished
267
+ j.current_video_id = ""
268
+ j.current_video_title = ""
269
+ j.current_video_started_at = ""
270
+ persist_batch_job(job)
271
+ cancelled += 1
272
+ except Exception as exc:
273
+ logger.warning("cancel running batches failed: %s", exc)
274
+ return cancelled
275
+
276
+
277
+ def policy_event_counts_24h(conn: Any) -> Dict[str, Any]:
278
+ """
279
+ Pipeline counts from the per-event bronze stamps (migration 083):
280
+
281
+ - ``analysis`` / ``reports`` / ``*_errors`` — events in the last 24h.
282
+ - ``*_total`` — all-time count of transcripts/analyses/reports (one live,
283
+ de-duplicated source for the "on disk" cards and progress %, instead of
284
+ summing per-batch disk scans, which double-counts transcripts across
285
+ overlapping batches and goes stale for analysis/reports).
286
+ - ``last_*_at`` — most recent stamp per step; drives the "ago" cards and,
287
+ unlike the batch ``updated_at`` clock, reflects standalone analyze runs.
288
+
289
+ Returns zeros/empty strings if the columns do not exist yet (migration not
290
+ applied), so the dashboard falls back to the batch-summary counters.
291
+ """
292
+ out: Dict[str, Any] = {
293
+ "analysis": 0,
294
+ "reports": 0,
295
+ "analysis_errors": 0,
296
+ "reports_errors": 0,
297
+ "transcripts_total": 0,
298
+ "analysis_total": 0,
299
+ "reports_total": 0,
300
+ "last_transcript_at": "",
301
+ "last_analysis_at": "",
302
+ "last_report_at": "",
303
+ }
304
+ try:
305
+ with conn.cursor() as cur:
306
+ cur.execute(
307
+ """
308
+ SELECT
309
+ COUNT(*) FILTER (
310
+ WHERE policy_analysis_at >= now() - interval '24 hours'
311
+ )::int AS analysis,
312
+ COUNT(*) FILTER (
313
+ WHERE policy_report_at >= now() - interval '24 hours'
314
+ )::int AS reports,
315
+ COUNT(*) FILTER (
316
+ WHERE policy_analysis_error IS NOT NULL
317
+ AND last_updated >= now() - interval '24 hours'
318
+ )::int AS analysis_errors,
319
+ COUNT(*) FILTER (
320
+ WHERE policy_report_error IS NOT NULL
321
+ AND last_updated >= now() - interval '24 hours'
322
+ )::int AS reports_errors,
323
+ COUNT(*) FILTER (WHERE transcript_download_at IS NOT NULL)::int
324
+ AS transcripts_total,
325
+ COUNT(*) FILTER (WHERE policy_analysis_at IS NOT NULL)::int
326
+ AS analysis_total,
327
+ COUNT(*) FILTER (WHERE policy_report_at IS NOT NULL)::int
328
+ AS reports_total,
329
+ MAX(transcript_download_at) AS last_transcript_at,
330
+ MAX(policy_analysis_at) AS last_analysis_at,
331
+ MAX(policy_report_at) AS last_report_at
332
+ FROM bronze.bronze_event_youtube
333
+ """
334
+ )
335
+ row = cur.fetchone()
336
+ if row:
337
+ out["analysis"] = int(row[0] or 0)
338
+ out["reports"] = int(row[1] or 0)
339
+ out["analysis_errors"] = int(row[2] or 0)
340
+ out["reports_errors"] = int(row[3] or 0)
341
+ out["transcripts_total"] = int(row[4] or 0)
342
+ out["analysis_total"] = int(row[5] or 0)
343
+ out["reports_total"] = int(row[6] or 0)
344
+ out["last_transcript_at"] = row[7].isoformat() if row[7] is not None else ""
345
+ out["last_analysis_at"] = row[8].isoformat() if row[8] is not None else ""
346
+ out["last_report_at"] = row[9].isoformat() if row[9] is not None else ""
347
+ except Exception as exc:
348
+ # Columns missing (pre-083) or transient DB error — degrade to zeros so the
349
+ # dashboard falls back to the disk-scan counters.
350
+ conn.rollback()
351
+ logger.debug("policy_event_counts_24h unavailable: %s", exc)
352
+ return out
353
+
354
+
355
+ # Pipeline stages, in funnel order. Each (scope, stage) pair is one report row,
356
+ # so adding a metric is a field and adding a dimension (state, later jurisdiction)
357
+ # is more rows — not more columns.
358
+ # Seven funnel stages (#755). Light stamps use policy_analysis_* / policy_report_*;
359
+ # full stamps use policy_*_full_*. Legacy ``analyses``/``reports`` aliases map to light.
360
+ PIPELINE_STAGES = (
361
+ "discover",
362
+ "videos",
363
+ "transcripts",
364
+ "analyses_light",
365
+ "reports_light",
366
+ "analyses_full",
367
+ "reports_full",
368
+ )
369
+
370
+
371
+ def _stage_report_filters(
372
+ cohort: str | None, conn: Any
373
+ ) -> tuple[Optional[List[str]], Optional[List[str]]]:
374
+ """Return ``(jurisdiction_ids, state_codes)`` filters for a launch cohort.
375
+
376
+ - ``data_centers``: jurisdiction_id ∈ DC site-belt ∪ meeting-mention set
377
+ - ``priority``: state_code ∈ priority launch states
378
+ - ``all`` / unset: no filter (full warehouse)
379
+ """
380
+ cohort_norm = (cohort or "").strip().lower() or None
381
+ if cohort_norm == "data_centers":
382
+ from api.batch_jobs.cohorts import data_center_jurisdiction_ids
383
+
384
+ dc_ids = data_center_jurisdiction_ids(conn)
385
+ return (list(dc_ids) if dc_ids else [], None)
386
+ if cohort_norm == "priority":
387
+ from api.batch_jobs.cohorts import PRIORITY_STATE_CODES
388
+
389
+ return (None, list(PRIORITY_STATE_CODES))
390
+ return (None, None)
391
+
392
+
393
+ def _stage_report_jid_filter(cohort: str | None, conn: Any) -> Optional[List[str]]:
394
+ """Deprecated wrapper — prefer ``_stage_report_filters``."""
395
+ jids, _states = _stage_report_filters(cohort, conn)
396
+ return jids
397
+
398
+
399
+ def _stage_timing(conn: Any) -> Dict[str, Any]:
400
+ """Per-stage cadence: median seconds between recent completions (~throughput
401
+ per file) and the most recent output file path. Column names are fixed (not
402
+ user input), so the f-string is safe. Empty on pre-083 DBs.
403
+
404
+ ``avg_seconds`` is the median gap between *completed* rows, so it freezes
405
+ during a stall — no new row means no new gap, and gaps >= 1h are filtered
406
+ out anyway. To keep ``/hr`` and ETA honest, we also return:
407
+
408
+ - ``stale_seconds``: the open trailing gap (``now() - last_at``), i.e. how
409
+ long we have already been waiting for the next completion.
410
+ - ``effective_seconds``: ``max(avg_seconds, stale_seconds)`` — once the next
411
+ file is overdue, the best estimate of the current per-file pace is at
412
+ least how long we have waited. It degrades while stalled and snaps back to
413
+ ``avg_seconds`` the moment a file lands. Consumers showing a live rate for
414
+ an idle (not-running) stage should ignore ``stale_seconds``.
415
+ """
416
+
417
+ def _one(
418
+ ts_col: str, path_col: str, table: str = "bronze.bronze_event_youtube"
419
+ ) -> Dict[str, Any]:
420
+ out: Dict[str, Any] = {
421
+ "avg_seconds": None,
422
+ "last_path": "",
423
+ "last_at": "",
424
+ "stale_seconds": None,
425
+ "effective_seconds": None,
426
+ }
427
+ try:
428
+ with conn.cursor() as cur:
429
+ cur.execute(
430
+ f"""
431
+ WITH recent AS (
432
+ SELECT {ts_col} AS ts, {path_col} AS path
433
+ FROM {table}
434
+ WHERE {ts_col} IS NOT NULL
435
+ ORDER BY {ts_col} DESC LIMIT 150
436
+ ),
437
+ gaps AS (
438
+ SELECT EXTRACT(EPOCH FROM (ts - LAG(ts) OVER (ORDER BY ts))) AS gap
439
+ FROM recent
440
+ ),
441
+ latest AS (
442
+ SELECT ts, path FROM recent ORDER BY ts DESC LIMIT 1
443
+ )
444
+ SELECT
445
+ (SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY gap)
446
+ FROM gaps WHERE gap > 0 AND gap < 3600) AS med_gap,
447
+ (SELECT path FROM latest) AS last_path,
448
+ (SELECT ts FROM latest) AS last_at,
449
+ EXTRACT(EPOCH FROM (now() - (SELECT ts FROM latest))) AS stale_seconds
450
+ """
451
+ )
452
+ row = cur.fetchone()
453
+ if row:
454
+ out["avg_seconds"] = round(float(row[0]), 1) if row[0] is not None else None
455
+ out["last_path"] = str(row[1] or "")
456
+ out["last_at"] = row[2].isoformat() if row[2] is not None else ""
457
+ out["stale_seconds"] = (
458
+ round(float(row[3]), 1) if row[3] is not None else None
459
+ )
460
+ avg = out["avg_seconds"]
461
+ stale = out["stale_seconds"]
462
+ if avg is not None:
463
+ out["effective_seconds"] = (
464
+ round(max(avg, stale), 1) if stale is not None else avg
465
+ )
466
+ except Exception:
467
+ conn.rollback()
468
+ return out
469
+
470
+ # Videos ▶ Run is catalog: upserts bump ``last_updated`` with --skip-transcripts.
471
+ # Timing must follow that clock (and caption stamps when present), not only
472
+ # ``transcript_download_at``, or Last activity freezes during catalog (#757).
473
+ vids = _one(
474
+ "CASE"
475
+ " WHEN last_updated IS NULL THEN transcript_download_at"
476
+ " WHEN transcript_download_at IS NULL THEN last_updated"
477
+ " ELSE GREATEST(last_updated, transcript_download_at)"
478
+ " END",
479
+ "COALESCE(NULLIF(transcript_file_path, ''), NULLIF(title, ''), video_id)",
480
+ )
481
+ # Transcripts cadence/last-file come from bronze_event_youtube_transcript (where the
482
+ # backfill actually writes), not the YouTube download stamp — otherwise the
483
+ # dashboard reads "stalled · 0/hr · last file <days ago>" while a DB-only
484
+ # backfill is inserting fine. video_id stands in for the missing file path.
485
+ transcripts = _one(
486
+ "COALESCE(last_updated, created_at)",
487
+ "video_id",
488
+ table="bronze.bronze_event_youtube_transcript",
489
+ )
490
+ light_a = _one("policy_analysis_at", "policy_analysis_path")
491
+ light_r = _one("policy_report_at", "policy_report_path")
492
+ full_a = _one("policy_analysis_full_at", "policy_analysis_full_path")
493
+ full_r = _one("policy_report_full_at", "policy_report_full_path")
494
+ return {
495
+ "videos": vids,
496
+ "transcripts": transcripts,
497
+ "analyses_light": light_a,
498
+ "reports_light": light_r,
499
+ "analyses_full": full_a,
500
+ "reports_full": full_r,
501
+ # Back-compat keys for older UI clients.
502
+ "analyses": light_a,
503
+ "reports": light_r,
504
+ }
505
+
506
+
507
+ def discover_last_at_sql(conn: Any) -> str:
508
+ """Per-row SQL for Discover's Last activity on the scraped-jurisdiction tables (#770).
509
+
510
+ ``GREATEST(discovered_at, channel_checked_at)`` when both tables have
511
+ ``channel_checked_at`` (stamped for each jurisdiction a Discover run tries),
512
+ else ``discovered_at``. Read-only: the column is added by the writers, never here.
513
+ """
514
+ try:
515
+ with conn.cursor() as cur:
516
+ cur.execute(
517
+ """
518
+ SELECT COUNT(*)
519
+ FROM information_schema.columns
520
+ WHERE table_schema = 'bronze'
521
+ AND table_name IN ('bronze_jurisdictions_counties_scraped',
522
+ 'bronze_jurisdictions_municipalities_scraped')
523
+ AND column_name = 'channel_checked_at'
524
+ """
525
+ )
526
+ row = cur.fetchone()
527
+ if row and int(row[0]) == 2:
528
+ return "GREATEST(discovered_at, channel_checked_at)"
529
+ except Exception as exc:
530
+ conn.rollback()
531
+ logger.debug("discover_last_at_sql: column lookup failed: %s", exc)
532
+ return "discovered_at"
533
+
534
+
535
+ def pipeline_stage_report(conn: Any, *, cohort: str | None = None) -> Dict[str, Any]:
536
+ """
537
+ Long-format per-state pipeline coverage from the bronze per-event stamps.
538
+
539
+ Returns ``{"states": [...], "rows": [{scope, stage, done, total, failed,
540
+ last_at}, ...]}`` where ``scope`` is a 2-letter state code or ``"ALL"`` (the
541
+ national rollup). All four stages are derived from one ``GROUP BY state_code``
542
+ over ``bronze_event_youtube`` so per-state and overall numbers are consistent
543
+ and live (covering standalone/parallel analyze runs). Empty on pre-083 DBs.
544
+
545
+ When ``cohort="data_centers"``, counts are limited to DC jurisdictions.
546
+ When ``cohort="priority"``, counts are limited to the priority launch states.
547
+ """
548
+ out: Dict[str, Any] = {"states": [], "rows": []}
549
+
550
+ def _iso(v: Any) -> str:
551
+ return v.isoformat() if v is not None else ""
552
+
553
+ def _max_iso(a: str, b: str) -> str:
554
+ return a if a >= b else b
555
+
556
+ jid_filter, state_filter = _stage_report_filters(cohort, conn)
557
+ if jid_filter is not None and not jid_filter:
558
+ return out
559
+ if state_filter is not None and not state_filter:
560
+ return out
561
+
562
+ jf_a: Optional[List[str]] = jid_filter
563
+ jf_b: Optional[List[str]] = jid_filter
564
+ sf_a: Optional[List[str]] = state_filter
565
+ sf_b: Optional[List[str]] = state_filter
566
+
567
+ try:
568
+ with conn.cursor() as cur:
569
+ cur.execute(
570
+ """
571
+ SELECT
572
+ COALESCE(NULLIF(state_code, ''), '??') AS st,
573
+ COUNT(*) FILTER (WHERE transcript_download_at IS NOT NULL)::int AS vids_ok,
574
+ COUNT(*) FILTER (WHERE transcript_file_error IS NOT NULL)::int AS vids_fail,
575
+ COUNT(*) FILTER (WHERE policy_analysis_at IS NOT NULL)::int AS analyses_light,
576
+ COUNT(*) FILTER (WHERE policy_analysis_error IS NOT NULL)::int AS analysis_light_err,
577
+ COUNT(*) FILTER (WHERE policy_report_at IS NOT NULL)::int AS reports_light,
578
+ COUNT(*) FILTER (WHERE policy_report_error IS NOT NULL)::int AS report_light_err,
579
+ COUNT(*) FILTER (WHERE policy_analysis_full_at IS NOT NULL)::int AS analyses_full,
580
+ COUNT(*) FILTER (WHERE policy_analysis_full_error IS NOT NULL)::int AS analysis_full_err,
581
+ COUNT(*) FILTER (WHERE policy_report_full_at IS NOT NULL)::int AS reports_full,
582
+ COUNT(*) FILTER (WHERE policy_report_full_error IS NOT NULL)::int AS report_full_err,
583
+ -- Catalog bumps last_updated; captions stamp transcript_download_at.
584
+ -- Videos Last activity must move for either (#757 / #761).
585
+ MAX(
586
+ CASE
587
+ WHEN last_updated IS NULL THEN transcript_download_at
588
+ WHEN transcript_download_at IS NULL THEN last_updated
589
+ ELSE GREATEST(last_updated, transcript_download_at)
590
+ END
591
+ ) AS last_video,
592
+ MAX(policy_analysis_at) AS last_analysis_light,
593
+ MAX(policy_report_at) AS last_report_light,
594
+ MAX(policy_analysis_full_at) AS last_analysis_full,
595
+ MAX(policy_report_full_at) AS last_report_full
596
+ FROM bronze.bronze_event_youtube y
597
+ WHERE (%s::text[] IS NULL OR y.jurisdiction_id = ANY(%s))
598
+ AND (%s::text[] IS NULL OR y.state_code = ANY(%s))
599
+ GROUP BY 1
600
+ """,
601
+ (jf_a, jf_b, sf_a, sf_b),
602
+ )
603
+ db_rows = cur.fetchall()
604
+ except Exception as exc:
605
+ # Pre-114 DBs lack full_* columns — retry light-only query.
606
+ conn.rollback()
607
+ logger.debug("pipeline_stage_report full columns unavailable, falling back: %s", exc)
608
+ try:
609
+ with conn.cursor() as cur:
610
+ cur.execute(
611
+ """
612
+ SELECT
613
+ COALESCE(NULLIF(state_code, ''), '??') AS st,
614
+ COUNT(*) FILTER (WHERE transcript_download_at IS NOT NULL)::int AS vids_ok,
615
+ COUNT(*) FILTER (WHERE transcript_file_error IS NOT NULL)::int AS vids_fail,
616
+ COUNT(*) FILTER (WHERE policy_analysis_at IS NOT NULL)::int AS analyses_light,
617
+ COUNT(*) FILTER (WHERE policy_analysis_error IS NOT NULL)::int AS analysis_light_err,
618
+ COUNT(*) FILTER (WHERE policy_report_at IS NOT NULL)::int AS reports_light,
619
+ COUNT(*) FILTER (WHERE policy_report_error IS NOT NULL)::int AS report_light_err,
620
+ 0::int AS analyses_full,
621
+ 0::int AS analysis_full_err,
622
+ 0::int AS reports_full,
623
+ 0::int AS report_full_err,
624
+ MAX(
625
+ CASE
626
+ WHEN last_updated IS NULL THEN transcript_download_at
627
+ WHEN transcript_download_at IS NULL THEN last_updated
628
+ ELSE GREATEST(last_updated, transcript_download_at)
629
+ END
630
+ ) AS last_video,
631
+ MAX(policy_analysis_at) AS last_analysis_light,
632
+ MAX(policy_report_at) AS last_report_light,
633
+ NULL::timestamp AS last_analysis_full,
634
+ NULL::timestamp AS last_report_full
635
+ FROM bronze.bronze_event_youtube y
636
+ WHERE (%s::text[] IS NULL OR y.jurisdiction_id = ANY(%s))
637
+ AND (%s::text[] IS NULL OR y.state_code = ANY(%s))
638
+ GROUP BY 1
639
+ """,
640
+ (jf_a, jf_b, sf_a, sf_b),
641
+ )
642
+ db_rows = cur.fetchall()
643
+ except Exception as exc2:
644
+ conn.rollback()
645
+ logger.debug("pipeline_stage_report unavailable: %s", exc2)
646
+ return out
647
+
648
+ # Stage 0 (channel discovery) lives in the scraped-jurisdiction tables, not in
649
+ # bronze_event_youtube: per state, how many jurisdictions have a YouTube channel
650
+ # found (done) out of all scraped (total); failed = still missing a channel.
651
+ # Grouped by entity (counties vs municipalities) so the Discover cell can split
652
+ # the combined coverage; the per-entity rows sum back to the combined total.
653
+ DISCOVER_ENTITIES = ("counties", "municipalities")
654
+ discover_by_state: Dict[str, Dict[str, Any]] = {}
655
+ # Last activity: when a channel was found, or when a Discover run last tried the
656
+ # jurisdiction, whichever is later (#770). ``activity`` is SQL from discover_last_at_sql.
657
+ activity = discover_last_at_sql(conn)
658
+ try:
659
+ with conn.cursor() as cur:
660
+ if jid_filter is not None:
661
+ cur.execute(
662
+ f"""
663
+ SELECT j.state_code AS st, s.entity,
664
+ COUNT(*)::int AS total,
665
+ COUNT(*) FILTER (
666
+ WHERE COALESCE(NULLIF(s.youtube_channel_id, ''),
667
+ NULLIF(s.youtube_channel_url, '')) IS NOT NULL
668
+ )::int AS done,
669
+ MAX(s.activity_at) AS last_at
670
+ FROM (
671
+ SELECT usps, geoid, youtube_channel_id, youtube_channel_url,
672
+ {activity} AS activity_at, 'counties' AS entity
673
+ FROM bronze.bronze_jurisdictions_counties_scraped
674
+ UNION ALL
675
+ SELECT usps, geoid, youtube_channel_id, youtube_channel_url,
676
+ {activity} AS activity_at, 'municipalities' AS entity
677
+ FROM bronze.bronze_jurisdictions_municipalities_scraped
678
+ ) s
679
+ JOIN intermediate.int_jurisdictions j
680
+ ON j.geoid = s.geoid AND j.state_code = s.usps
681
+ WHERE COALESCE(s.usps, '') <> ''
682
+ AND j.jurisdiction_id = ANY(%s)
683
+ AND (%s::text[] IS NULL OR j.state_code = ANY(%s))
684
+ GROUP BY j.state_code, s.entity
685
+ """,
686
+ (jid_filter, sf_a, sf_b),
687
+ )
688
+ else:
689
+ cur.execute(
690
+ f"""
691
+ SELECT usps AS st, entity,
692
+ COUNT(*)::int AS total,
693
+ COUNT(*) FILTER (
694
+ WHERE COALESCE(NULLIF(youtube_channel_id, ''),
695
+ NULLIF(youtube_channel_url, '')) IS NOT NULL
696
+ )::int AS done,
697
+ MAX(activity_at) AS last_at
698
+ FROM (
699
+ SELECT usps, youtube_channel_id, youtube_channel_url,
700
+ {activity} AS activity_at, 'counties' AS entity
701
+ FROM bronze.bronze_jurisdictions_counties_scraped
702
+ UNION ALL
703
+ SELECT usps, youtube_channel_id, youtube_channel_url,
704
+ {activity} AS activity_at, 'municipalities' AS entity
705
+ FROM bronze.bronze_jurisdictions_municipalities_scraped
706
+ ) j
707
+ WHERE COALESCE(usps, '') <> ''
708
+ AND (%s::text[] IS NULL OR usps = ANY(%s))
709
+ GROUP BY usps, entity
710
+ """,
711
+ (sf_a, sf_b),
712
+ )
713
+ for st, entity, total, done, last_at in cur.fetchall():
714
+ rec = discover_by_state.setdefault(
715
+ str(st), {"total": 0, "done": 0, "last_at": "", "breakdown": {}}
716
+ )
717
+ rec["total"] += int(total)
718
+ rec["done"] += int(done)
719
+ rec["last_at"] = _max_iso(rec["last_at"], _iso(last_at))
720
+ rec["breakdown"][str(entity)] = {
721
+ "entity": str(entity), "total": int(total), "done": int(done),
722
+ }
723
+ except Exception:
724
+ conn.rollback() # scraped tables absent — discover stage degrades to zeros
725
+
726
+ # Transcript coverage for the *YouTube pipeline* only: same population as the
727
+ # Videos stage (bronze_event_youtube rows we attempted captions for). Using
728
+ # int_events_union here inflated Data centers (and other filters) to include
729
+ # LocalView/CivicSearch candidates (~142k) while Videos stayed ~13k (#683).
730
+ # total = attempted downloads; done = those with a landed transcript row.
731
+ tx_by_state: Dict[str, Dict[str, Any]] = {}
732
+ tx_unknown_total = 0
733
+ tx_unknown_done = 0
734
+ try:
735
+ with conn.cursor() as cur:
736
+ cur.execute(
737
+ """
738
+ SELECT
739
+ COALESCE(NULLIF(y.state_code, ''), '??') AS st,
740
+ COUNT(*)::int AS total,
741
+ COUNT(t.video_id)::int AS done,
742
+ MAX(COALESCE(t.last_updated, t.created_at)) AS last_at
743
+ FROM bronze.bronze_event_youtube y
744
+ LEFT JOIN bronze.bronze_event_youtube_transcript t
745
+ ON t.video_id = y.video_id
746
+ WHERE (y.transcript_download_at IS NOT NULL
747
+ OR y.transcript_file_error IS NOT NULL)
748
+ AND (%s::text[] IS NULL OR y.jurisdiction_id = ANY(%s))
749
+ AND (%s::text[] IS NULL OR y.state_code = ANY(%s))
750
+ GROUP BY 1
751
+ """,
752
+ (jf_a, jf_b, sf_a, sf_b),
753
+ )
754
+ for st, total, done, last_at in cur.fetchall():
755
+ if str(st) == "??":
756
+ tx_unknown_total += int(total)
757
+ tx_unknown_done += int(done)
758
+ else:
759
+ tx_by_state[str(st)] = {
760
+ "done": int(done), "total": int(total), "last_at": _iso(last_at),
761
+ }
762
+ except Exception:
763
+ conn.rollback() # transcript table absent — coverage degrades to zeros
764
+
765
+ def _discover_row(scope: str, disc: Optional[Dict[str, Any]]) -> Dict[str, Any]:
766
+ d = disc or {"total": 0, "done": 0, "last_at": "", "breakdown": {}}
767
+ bd = d.get("breakdown") or {}
768
+ breakdown = [
769
+ {
770
+ "entity": e,
771
+ "done": int(bd[e]["done"]),
772
+ "total": int(bd[e]["total"]),
773
+ "failed": max(0, int(bd[e]["total"]) - int(bd[e]["done"])),
774
+ }
775
+ for e in DISCOVER_ENTITIES
776
+ if e in bd
777
+ ]
778
+ return {
779
+ "scope": scope, "stage": "discover", "done": d["done"], "total": d["total"],
780
+ "failed": max(0, d["total"] - d["done"]), "last_at": d["last_at"],
781
+ "breakdown": breakdown,
782
+ }
783
+
784
+ def _stage_rows(
785
+ scope: str,
786
+ rec: Dict[str, Any],
787
+ disc: Optional[Dict[str, Any]],
788
+ tx: Dict[str, Any],
789
+ ) -> List[Dict[str, Any]]:
790
+ ok = int(rec["vids_ok"])
791
+ fail = int(rec["vids_fail"])
792
+ attempted = ok + fail
793
+ lv = rec["last_video"]
794
+ la_l = rec["last_analysis_light"]
795
+ lr_l = rec["last_report_light"]
796
+ la_f = rec["last_analysis_full"]
797
+ lr_f = rec["last_report_full"]
798
+ # videos: YouTube download stamps (ok / attempted). transcripts: landed
799
+ # rows over that same attempted set. Light + full analysis are both
800
+ # warehouse coverage over transcripts (#755 / #766). Reports are
801
+ # denominated by their matching analysis tier. Full analysis must NOT
802
+ # use light as its denominator: pre-split deep Part 1 rows were moved
803
+ # onto full stamps without a light stamp (#766), which would otherwise
804
+ # show Analysis full at ~100% while light is a few percent.
805
+ tx_done = int(tx.get("done", 0))
806
+ tx_total = max(int(tx.get("total", 0)), tx_done)
807
+ tx_last = tx.get("last_at") or ""
808
+ analyses_light = int(rec["analyses_light"])
809
+ reports_light = int(rec["reports_light"])
810
+ analyses_full = int(rec["analyses_full"])
811
+ reports_full = int(rec["reports_full"])
812
+ return [
813
+ _discover_row(scope, disc),
814
+ {"scope": scope, "stage": "videos", "done": ok, "total": attempted,
815
+ "failed": fail, "last_at": lv},
816
+ {"scope": scope, "stage": "transcripts", "done": tx_done, "total": tx_total,
817
+ "failed": fail, "last_at": tx_last or lv},
818
+ {"scope": scope, "stage": "analyses_light", "done": analyses_light,
819
+ "total": max(tx_done, analyses_light),
820
+ "failed": int(rec["analysis_light_err"]), "last_at": la_l},
821
+ {"scope": scope, "stage": "reports_light", "done": reports_light,
822
+ "total": max(analyses_light, reports_light),
823
+ "failed": int(rec["report_light_err"]), "last_at": lr_l},
824
+ {"scope": scope, "stage": "analyses_full", "done": analyses_full,
825
+ "total": max(tx_done, analyses_full),
826
+ "failed": int(rec["analysis_full_err"]), "last_at": la_f},
827
+ {"scope": scope, "stage": "reports_full", "done": reports_full,
828
+ "total": max(analyses_full, reports_full),
829
+ "failed": int(rec["report_full_err"]), "last_at": lr_f},
830
+ ]
831
+
832
+ cols = (
833
+ "st", "vids_ok", "vids_fail",
834
+ "analyses_light", "analysis_light_err", "reports_light", "report_light_err",
835
+ "analyses_full", "analysis_full_err", "reports_full", "report_full_err",
836
+ "last_video", "last_analysis_light", "last_report_light",
837
+ "last_analysis_full", "last_report_full",
838
+ )
839
+ yt_by_state: Dict[str, Dict[str, Any]] = {}
840
+ for r in db_rows:
841
+ rec = dict(zip(cols, r))
842
+ for tk in (
843
+ "last_video",
844
+ "last_analysis_light",
845
+ "last_report_light",
846
+ "last_analysis_full",
847
+ "last_report_full",
848
+ ):
849
+ rec[tk] = _iso(rec[tk])
850
+ yt_by_state[str(rec["st"])] = rec
851
+
852
+ _zero_rec = {
853
+ "vids_ok": 0, "vids_fail": 0,
854
+ "analyses_light": 0, "analysis_light_err": 0,
855
+ "reports_light": 0, "report_light_err": 0,
856
+ "analyses_full": 0, "analysis_full_err": 0,
857
+ "reports_full": 0, "report_full_err": 0,
858
+ "last_video": "", "last_analysis_light": "", "last_report_light": "",
859
+ "last_analysis_full": "", "last_report_full": "",
860
+ }
861
+
862
+ rows: List[Dict[str, Any]] = []
863
+ states: List[str] = []
864
+ totals = {
865
+ k: 0
866
+ for k in (
867
+ "vids_ok", "vids_fail",
868
+ "analyses_light", "analysis_light_err",
869
+ "reports_light", "report_light_err",
870
+ "analyses_full", "analysis_full_err",
871
+ "reports_full", "report_full_err",
872
+ )
873
+ }
874
+ last = {
875
+ "last_video": "",
876
+ "last_analysis_light": "",
877
+ "last_report_light": "",
878
+ "last_analysis_full": "",
879
+ "last_report_full": "",
880
+ }
881
+ tx_totals = {"done": 0, "total": 0, "last_at": ""}
882
+
883
+ # Surface every state that has entered the pipeline (any attempted YouTube
884
+ # video) OR that has at least one landed transcript — the latter covers
885
+ # LocalView/union states with no bronze_event_youtube rows.
886
+ candidate_states = {
887
+ st for st, rec in yt_by_state.items()
888
+ if int(rec["vids_ok"]) + int(rec["vids_fail"]) > 0
889
+ } | {
890
+ st for st, tx in tx_by_state.items()
891
+ if int(tx.get("done", 0)) > 0 or int(tx.get("total", 0)) > 0
892
+ }
893
+ candidate_states.discard("??")
894
+
895
+ for st in sorted(candidate_states):
896
+ rec = yt_by_state.get(st, dict(_zero_rec))
897
+ tx = tx_by_state.get(st, {"done": 0, "total": 0, "last_at": ""})
898
+ for nk in totals:
899
+ totals[nk] += int(rec[nk])
900
+ for tk in last:
901
+ last[tk] = _max_iso(last[tk], rec[tk])
902
+ tx_totals["done"] += int(tx.get("done", 0))
903
+ tx_totals["total"] += int(tx.get("total", 0))
904
+ tx_totals["last_at"] = _max_iso(tx_totals["last_at"], tx.get("last_at") or "")
905
+ states.append(st)
906
+ rows.extend(_stage_rows(st, rec, discover_by_state.get(st), tx))
907
+
908
+ disc_all: Dict[str, Any] = {"total": 0, "done": 0, "last_at": "", "breakdown": {}}
909
+ for st in states:
910
+ d = discover_by_state.get(st)
911
+ if d:
912
+ disc_all["total"] += d["total"]
913
+ disc_all["done"] += d["done"]
914
+ disc_all["last_at"] = _max_iso(disc_all["last_at"], d["last_at"])
915
+ for e, b in (d.get("breakdown") or {}).items():
916
+ agg = disc_all["breakdown"].setdefault(
917
+ e, {"entity": e, "total": 0, "done": 0}
918
+ )
919
+ agg["total"] += int(b["total"])
920
+ agg["done"] += int(b["done"])
921
+ # Stateless candidates (CivicSearch school meetings etc. carry no state_code)
922
+ # have no per-state row; fold their coverage into the ALL transcripts numbers
923
+ # so the headline reflects the whole candidate set.
924
+ tx_totals["total"] += tx_unknown_total
925
+ tx_totals["done"] += tx_unknown_done
926
+ rows = _stage_rows("ALL", {**totals, **last}, disc_all, tx_totals) + rows
927
+ out["states"] = sorted(states)
928
+ out["rows"] = rows
929
+ out["timing"] = _stage_timing(conn)
930
+ return out
931
+
932
+
933
+ def dashboard_stage_report(*, cohort: str | None = None) -> Dict[str, Any]:
934
+ """Open a connection and return the per-state pipeline report (empty on error)."""
935
+ try:
936
+ with get_db_connection() as conn:
937
+ ensure_batch_job_tables(conn)
938
+ return pipeline_stage_report(conn, cohort=cohort)
939
+ except Exception as exc:
940
+ logger.debug("dashboard_stage_report unavailable: %s", exc)
941
+ return {"states": [], "rows": []}
942
+
943
+
944
+ def aggregate_dashboard_totals_from_db(*, limit: int = 30) -> Dict[str, Any]:
945
+ """Sum numeric fields from ``summary`` JSONB across recent batches (no payload)."""
946
+ # Reap abandoned ``running`` rows first so the ``running`` count below (and any
947
+ # per-batch meta read for the same dashboard tick) reflects real liveness.
948
+ reap_stale_running_batches(limit=limit)
949
+ with get_db_connection() as conn:
950
+ ensure_batch_job_tables(conn)
951
+ with conn.cursor(cursor_factory=RealDictCursor) as cur:
952
+ cur.execute(
953
+ """
954
+ WITH recent AS (
955
+ SELECT status, config, summary, updated_at
956
+ FROM bronze.youtube_batch_job_runs
957
+ ORDER BY updated_at DESC NULLS LAST
958
+ LIMIT %s
959
+ )
960
+ SELECT
961
+ COUNT(*)::int AS batches,
962
+ COUNT(*) FILTER (WHERE status = 'running')::int AS running,
963
+ COALESCE(SUM((summary->>'processed_jurisdictions')::int), 0)
964
+ AS processed_jurisdictions,
965
+ COALESCE(SUM((summary->>'failed_jurisdictions')::int), 0)
966
+ AS failed_jurisdictions,
967
+ COALESCE(SUM((summary->>'remaining_jurisdictions')::int), 0)
968
+ AS remaining_jurisdictions,
969
+ COALESCE(SUM((summary->>'videos_ok')::int), 0) AS videos_ok,
970
+ COALESCE(SUM((summary->>'videos_fail')::int), 0) AS videos_fail,
971
+ COALESCE(SUM((summary->>'files_transcripts')::int), 0)
972
+ AS files_transcripts,
973
+ COALESCE(SUM((summary->>'files_transcripts_disk')::int), 0)
974
+ AS files_transcripts_disk,
975
+ COALESCE(SUM((summary->>'bronze_download_rows')::int), 0)
976
+ AS bronze_download_rows,
977
+ COALESCE(SUM((summary->>'files_analysis')::int), 0) AS files_analysis,
978
+ COALESCE(SUM((summary->>'files_reports')::int), 0) AS files_reports,
979
+ COALESCE(SUM((summary->>'transcript_seconds')::float), 0)
980
+ AS transcript_seconds,
981
+ MAX(updated_at) AS last_updated
982
+ FROM recent
983
+ """,
984
+ (limit,),
985
+ )
986
+ row = cur.fetchone() or {}
987
+ recent_events = policy_event_counts_24h(conn)
988
+ totals = {
989
+ "batches": int(row.get("batches") or 0),
990
+ "running": int(row.get("running") or 0),
991
+ "states": 0,
992
+ "states_planned": 0,
993
+ "states_started": 0,
994
+ "states_completed": 0,
995
+ "processed_jurisdictions": int(row.get("processed_jurisdictions") or 0),
996
+ "failed_jurisdictions": int(row.get("failed_jurisdictions") or 0),
997
+ "remaining_jurisdictions": int(row.get("remaining_jurisdictions") or 0),
998
+ "videos_ok": int(row.get("videos_ok") or 0),
999
+ "videos_fail": int(row.get("videos_fail") or 0),
1000
+ "videos_attempted": 0,
1001
+ "files_transcripts": int(row.get("files_transcripts") or 0),
1002
+ "files_transcripts_disk": int(row.get("files_transcripts_disk") or 0),
1003
+ "transcript_hours": round(float(row.get("transcript_seconds") or 0) / 3600.0, 2),
1004
+ "bronze_download_rows": int(row.get("bronze_download_rows") or 0),
1005
+ "files_analysis": int(row.get("files_analysis") or 0),
1006
+ "files_reports": int(row.get("files_reports") or 0),
1007
+ # Rolling 24h throughput from per-event bronze stamps (migration 083); covers
1008
+ # both batch and standalone runs, unlike the batch-scoped disk-scan counters.
1009
+ "files_analysis_recent": int(recent_events.get("analysis") or 0),
1010
+ "files_reports_recent": int(recent_events.get("reports") or 0),
1011
+ "files_analysis_errors_recent": int(recent_events.get("analysis_errors") or 0),
1012
+ "files_reports_errors_recent": int(recent_events.get("reports_errors") or 0),
1013
+ # Most recent stamp per step (all time) for the dashboard "ago" cards.
1014
+ "last_transcript_at": recent_events.get("last_transcript_at") or "",
1015
+ "last_analysis_at": recent_events.get("last_analysis_at") or "",
1016
+ "last_report_at": recent_events.get("last_report_at") or "",
1017
+ }
1018
+ # Prefer the live, de-duplicated bronze-stamp totals for the pipeline cards and
1019
+ # progress %: summing per-batch disk scans inflates transcripts (overlapping
1020
+ # batches) and goes stale for analysis/reports. Only override when the stamps
1021
+ # have data, so a pre-083 DB still shows the batch-summary fallback.
1022
+ transcripts_total = int(recent_events.get("transcripts_total") or 0)
1023
+ analysis_total = int(recent_events.get("analysis_total") or 0)
1024
+ reports_total = int(recent_events.get("reports_total") or 0)
1025
+ if transcripts_total > 0:
1026
+ totals["files_transcripts_disk"] = transcripts_total
1027
+ if analysis_total > 0:
1028
+ totals["files_analysis"] = analysis_total
1029
+ if reports_total > 0:
1030
+ totals["files_reports"] = reports_total
1031
+ last_updated = row.get("last_updated")
1032
+ totals["last_activity_at"] = (
1033
+ last_updated.isoformat() if last_updated is not None else ""
1034
+ )
1035
+ return totals
1036
+
1037
+
1038
+ def list_jurisdiction_rows_from_db(
1039
+ batch_id: str,
1040
+ state_code: str,
1041
+ ) -> List[Dict[str, Any]]:
1042
+ """
1043
+ Extract slim jurisdiction rows for one state via JSONB (no per-video arrays).
1044
+ """
1045
+ st = (state_code or "").strip().upper()
1046
+ if not st:
1047
+ return []
1048
+ with get_db_connection() as conn:
1049
+ ensure_batch_job_tables(conn)
1050
+ with conn.cursor(cursor_factory=RealDictCursor) as cur:
1051
+ cur.execute(
1052
+ """
1053
+ SELECT COALESCE(
1054
+ jsonb_agg(sub.row ORDER BY sub.sort_name),
1055
+ '[]'::jsonb
1056
+ ) AS jurisdictions
1057
+ FROM (
1058
+ SELECT
1059
+ jsonb_build_object(
1060
+ 'state_code', elem->>'state_code',
1061
+ 'jurisdiction_id', elem->>'jurisdiction_id',
1062
+ 'jurisdiction_name', elem->>'jurisdiction_name',
1063
+ 'status', COALESCE(NULLIF(elem->>'status', ''), 'pending'),
1064
+ 'started_at', COALESCE(elem->>'started_at', ''),
1065
+ 'updated_at', COALESCE(elem->>'updated_at', ''),
1066
+ 'finished_at', COALESCE(elem->>'finished_at', ''),
1067
+ 'elapsed_seconds',
1068
+ COALESCE((elem->>'elapsed_seconds')::float, 0),
1069
+ 'exit_code', COALESCE((elem->>'exit_code')::int, 0),
1070
+ 'stats', COALESCE(elem->'stats', '{}'::jsonb),
1071
+ 'file_counts', COALESCE(elem->'file_counts', '{}'::jsonb),
1072
+ 'current_video_id', COALESCE(elem->>'current_video_id', ''),
1073
+ 'current_video_title', COALESCE(elem->>'current_video_title', ''),
1074
+ 'current_video_started_at',
1075
+ COALESCE(elem->>'current_video_started_at', ''),
1076
+ 'videos', '[]'::jsonb
1077
+ ) AS row,
1078
+ lower(
1079
+ COALESCE(
1080
+ elem->>'jurisdiction_name',
1081
+ elem->>'jurisdiction_id',
1082
+ ''
1083
+ )
1084
+ ) AS sort_name
1085
+ FROM bronze.youtube_batch_job_runs b,
1086
+ jsonb_array_elements(
1087
+ CASE
1088
+ WHEN jsonb_typeof(b.payload->'jurisdictions') = 'array'
1089
+ THEN b.payload->'jurisdictions'
1090
+ ELSE '[]'::jsonb
1091
+ END
1092
+ ) elem
1093
+ WHERE b.batch_id = %s
1094
+ AND UPPER(COALESCE(elem->>'state_code', '')) = %s
1095
+ ) sub
1096
+ """,
1097
+ (batch_id, st),
1098
+ )
1099
+ row = cur.fetchone()
1100
+ raw = row.get("jurisdictions") if row else []
1101
+ if isinstance(raw, str):
1102
+ raw = json.loads(raw)
1103
+ if not isinstance(raw, list):
1104
+ return []
1105
+ return [dict(x) for x in raw if isinstance(x, dict)]
1106
+
1107
+
1108
+ def running_batch_activity_from_db() -> Optional[Dict[str, Any]]:
1109
+ """Active in-flight rows for the running batch (JSONB projection; no full payload parse)."""
1110
+ with get_db_connection() as conn:
1111
+ ensure_batch_job_tables(conn)
1112
+ with conn.cursor(cursor_factory=RealDictCursor) as cur:
1113
+ cur.execute(
1114
+ """
1115
+ SELECT
1116
+ b.batch_id,
1117
+ COALESCE(
1118
+ jsonb_agg(sub.row ORDER BY sub.sort_key),
1119
+ '[]'::jsonb
1120
+ ) AS jurisdictions
1121
+ FROM bronze.youtube_batch_job_runs b
1122
+ LEFT JOIN LATERAL (
1123
+ SELECT
1124
+ jsonb_build_object(
1125
+ 'state_code', elem->>'state_code',
1126
+ 'jurisdiction_id', elem->>'jurisdiction_id',
1127
+ 'jurisdiction_name', elem->>'jurisdiction_name',
1128
+ 'status', COALESCE(elem->>'status', 'running'),
1129
+ 'updated_at', COALESCE(elem->>'updated_at', ''),
1130
+ 'current_video_id', COALESCE(elem->>'current_video_id', ''),
1131
+ 'current_video_title', COALESCE(elem->>'current_video_title', ''),
1132
+ 'current_video_started_at',
1133
+ COALESCE(elem->>'current_video_started_at', ''),
1134
+ 'videos', '[]'::jsonb
1135
+ ) AS row,
1136
+ COALESCE(elem->>'current_video_started_at', elem->>'started_at', '')
1137
+ AS sort_key
1138
+ FROM jsonb_array_elements(
1139
+ CASE
1140
+ WHEN jsonb_typeof(b.payload->'jurisdictions') = 'array'
1141
+ THEN b.payload->'jurisdictions'
1142
+ ELSE '[]'::jsonb
1143
+ END
1144
+ ) elem
1145
+ WHERE LOWER(COALESCE(elem->>'status', '')) = 'running'
1146
+ OR COALESCE(elem->>'current_video_id', '') <> ''
1147
+ ) sub ON TRUE
1148
+ WHERE b.status = 'running'
1149
+ GROUP BY b.batch_id
1150
+ ORDER BY MAX(b.updated_at) DESC NULLS LAST
1151
+ LIMIT 1
1152
+ """
1153
+ )
1154
+ row = cur.fetchone()
1155
+ if not row:
1156
+ return None
1157
+ jurs = row.get("jurisdictions") or []
1158
+ if isinstance(jurs, str):
1159
+ jurs = json.loads(jurs)
1160
+ if not isinstance(jurs, list) or not jurs:
1161
+ return None
1162
+ return {"batch_id": row["batch_id"], "jurisdictions": [dict(x) for x in jurs if isinstance(x, dict)]}
1163
+
1164
+
1165
+ _FAILED_VIDEO_STATUSES = frozenset(
1166
+ {"fail", "failed", "tombstoned", "empty", "rate_limit", "error"}
1167
+ )
1168
+
1169
+
1170
+ def list_failed_videos_from_db(
1171
+ *,
1172
+ batch_id: Optional[str] = None,
1173
+ limit: int = 500,
1174
+ batch_limit: int = 25,
1175
+ ) -> Dict[str, Any]:
1176
+ """
1177
+ Extract per-video failure rows from stored batch payloads (JSONB).
1178
+
1179
+ Returns ``rows`` plus ``total_fail_in_summaries`` (sum of ``summary.videos_fail``)
1180
+ which may exceed ``len(rows)`` when failures were counted in stats but not logged
1181
+ per video, or when ``limit`` truncates.
1182
+ """
1183
+ bid = (batch_id or "").strip() or None
1184
+ lim = max(1, min(int(limit), 2000))
1185
+ with get_db_connection() as conn:
1186
+ ensure_batch_job_tables(conn)
1187
+ with conn.cursor(cursor_factory=RealDictCursor) as cur:
1188
+ if bid:
1189
+ cur.execute(
1190
+ """
1191
+ SELECT COALESCE((summary->>'videos_fail')::int, 0) AS n
1192
+ FROM bronze.youtube_batch_job_runs
1193
+ WHERE batch_id = %s
1194
+ """,
1195
+ (bid,),
1196
+ )
1197
+ else:
1198
+ cur.execute(
1199
+ """
1200
+ SELECT COALESCE(SUM((summary->>'videos_fail')::int), 0)::int AS n
1201
+ FROM (
1202
+ SELECT summary
1203
+ FROM bronze.youtube_batch_job_runs
1204
+ ORDER BY updated_at DESC NULLS LAST
1205
+ LIMIT %s
1206
+ ) recent
1207
+ """,
1208
+ (batch_limit,),
1209
+ )
1210
+ summary_row = cur.fetchone() or {}
1211
+ total_fail = int(summary_row.get("n") or 0)
1212
+
1213
+ cur.execute(
1214
+ """
1215
+ SELECT
1216
+ b.batch_id,
1217
+ b.step AS batch_step,
1218
+ j.elem->>'state_code' AS state_code,
1219
+ j.elem->>'jurisdiction_id' AS jurisdiction_id,
1220
+ j.elem->>'jurisdiction_name' AS jurisdiction_name,
1221
+ v.elem->>'video_id' AS video_id,
1222
+ v.elem->>'title' AS title,
1223
+ v.elem->>'status' AS status,
1224
+ v.elem->>'error' AS error,
1225
+ v.elem->>'transcript_source' AS transcript_source,
1226
+ v.elem->>'finished_at' AS finished_at,
1227
+ v.elem->>'duration_seconds' AS duration_seconds
1228
+ FROM bronze.youtube_batch_job_runs b
1229
+ CROSS JOIN LATERAL jsonb_array_elements(
1230
+ CASE
1231
+ WHEN jsonb_typeof(b.payload->'jurisdictions') = 'array'
1232
+ THEN b.payload->'jurisdictions'
1233
+ ELSE '[]'::jsonb
1234
+ END
1235
+ ) AS j(elem)
1236
+ CROSS JOIN LATERAL jsonb_array_elements(
1237
+ CASE
1238
+ WHEN jsonb_typeof(j.elem->'videos') = 'array'
1239
+ THEN j.elem->'videos'
1240
+ ELSE '[]'::jsonb
1241
+ END
1242
+ ) AS v(elem)
1243
+ WHERE (%s::text IS NULL OR b.batch_id = %s)
1244
+ AND COALESCE(v.elem->>'video_id', '') <> ''
1245
+ AND (
1246
+ LOWER(COALESCE(v.elem->>'status', '')) = ANY(%s)
1247
+ OR (
1248
+ LOWER(COALESCE(v.elem->>'status', '')) NOT IN (
1249
+ 'ok', 'pending', 'skipped', 'noop', ''
1250
+ )
1251
+ )
1252
+ )
1253
+ ORDER BY b.updated_at DESC NULLS LAST,
1254
+ v.elem->>'finished_at' DESC NULLS LAST
1255
+ LIMIT %s
1256
+ """,
1257
+ (
1258
+ bid,
1259
+ bid,
1260
+ list(_FAILED_VIDEO_STATUSES),
1261
+ lim + 1,
1262
+ ),
1263
+ )
1264
+ raw_rows = cur.fetchall()
1265
+ truncated = len(raw_rows) > lim
1266
+ rows_out: List[Dict[str, Any]] = []
1267
+ for row in raw_rows[:lim]:
1268
+ dur = row.get("duration_seconds")
1269
+ try:
1270
+ dur_f = float(dur) if dur not in (None, "") else None
1271
+ except (TypeError, ValueError):
1272
+ dur_f = None
1273
+ rows_out.append(
1274
+ {
1275
+ "batch_id": row["batch_id"],
1276
+ "batch_step": row.get("batch_step") or "",
1277
+ "state_code": row.get("state_code") or "",
1278
+ "jurisdiction_id": row.get("jurisdiction_id") or "",
1279
+ "jurisdiction_name": row.get("jurisdiction_name") or "",
1280
+ "video": {
1281
+ "video_id": row.get("video_id") or "",
1282
+ "title": row.get("title") or "",
1283
+ "status": row.get("status") or "",
1284
+ "error": row.get("error") or "",
1285
+ "transcript_source": row.get("transcript_source") or "",
1286
+ "finished_at": row.get("finished_at") or "",
1287
+ "duration_seconds": dur_f,
1288
+ },
1289
+ }
1290
+ )
1291
+ return {
1292
+ "rows": rows_out,
1293
+ "total_fail_in_summaries": total_fail,
1294
+ "truncated": truncated,
1295
+ }
1296
+
1297
+
1298
+ def list_batch_job_meta_from_db(*, limit: int = 30) -> List[Dict[str, Any]]:
1299
+ """Lightweight batch rows (no ``payload``) for fast dashboard summary."""
1300
+ with get_db_connection() as conn:
1301
+ ensure_batch_job_tables(conn)
1302
+ with conn.cursor(cursor_factory=RealDictCursor) as cur:
1303
+ cur.execute(
1304
+ """
1305
+ SELECT
1306
+ batch_id,
1307
+ step,
1308
+ status,
1309
+ started_at,
1310
+ updated_at,
1311
+ finished_at,
1312
+ config,
1313
+ summary
1314
+ FROM bronze.youtube_batch_job_runs
1315
+ ORDER BY updated_at DESC NULLS LAST
1316
+ LIMIT %s
1317
+ """,
1318
+ (limit,),
1319
+ )
1320
+ rows = cur.fetchall()
1321
+ out: List[Dict[str, Any]] = []
1322
+ for row in rows:
1323
+ started = row.get("started_at")
1324
+ updated = row.get("updated_at")
1325
+ finished = row.get("finished_at")
1326
+ out.append(
1327
+ {
1328
+ "batch_id": row["batch_id"],
1329
+ "step": row["step"],
1330
+ "status": row["status"],
1331
+ "started_at": started.isoformat() if started else "",
1332
+ "updated_at": updated.isoformat() if updated else "",
1333
+ "finished_at": finished.isoformat() if finished else "",
1334
+ "config": row.get("config") or {},
1335
+ "summary": row.get("summary") or {},
1336
+ "jurisdictions": [],
1337
+ }
1338
+ )
1339
+ return out
1340
+
1341
+
1342
+ def sync_json_batches_to_db(*, limit: int = 100) -> int:
1343
+ """Import recent JSON batch files into Postgres (one-time / backfill)."""
1344
+ if not _use_db():
1345
+ return 0
1346
+ jobs = list_batches(limit=limit)
1347
+ if not jobs:
1348
+ return 0
1349
+ with get_db_connection() as conn:
1350
+ for job in jobs:
1351
+ upsert_batch_job(conn, job)
1352
+ return len(jobs)
1353
+
1354
+
1355
+ def enrich_transcript_counts_from_bronze(conn: Any, job: BatchJob) -> None:
1356
+ """Set jurisdiction ``bronze_download_rows`` from bronze_event_youtube."""
1357
+ jids = [j.jurisdiction_id for j in job.jurisdictions if j.jurisdiction_id]
1358
+ if not jids:
1359
+ return
1360
+ cur = conn.cursor(cursor_factory=RealDictCursor)
1361
+ try:
1362
+ cur.execute(
1363
+ """
1364
+ SELECT
1365
+ jurisdiction_id,
1366
+ COUNT(*) FILTER (WHERE transcript_download_at IS NOT NULL)::int AS transcripts,
1367
+ COUNT(*) FILTER (
1368
+ WHERE transcript_file_error IS NOT NULL
1369
+ AND BTRIM(transcript_file_error) <> ''
1370
+ )::int AS transcript_errors
1371
+ FROM bronze.bronze_event_youtube
1372
+ WHERE jurisdiction_id = ANY(%s)
1373
+ GROUP BY jurisdiction_id
1374
+ """,
1375
+ (jids,),
1376
+ )
1377
+ by_jid = {r["jurisdiction_id"]: r for r in cur.fetchall()}
1378
+ finally:
1379
+ cur.close()
1380
+
1381
+ for j in job.jurisdictions:
1382
+ row = by_jid.get(j.jurisdiction_id) or {}
1383
+ tx = int(row.get("transcripts") or 0)
1384
+ j.file_counts = dict(j.file_counts or {})
1385
+ j.file_counts["bronze_download_rows"] = tx
1386
+ j.file_counts["bronze_transcript_errors"] = int(
1387
+ row.get("transcript_errors") or 0
1388
+ )
1389
+
1390
+
1391
+ def enrich_transcript_seconds_from_bronze(conn: Any, job: BatchJob) -> None:
1392
+ """
1393
+ Set ``job.summary['transcript_seconds']`` from ``bronze_event_youtube.duration_minutes``.
1394
+
1395
+ Batch payloads often have per-video stats without ``duration_seconds`` (older runs or
1396
+ DB copies). Prefer catalog duration for ok video ids in ``j.videos``; if none, sum
1397
+ transcripts downloaded in processed jurisdictions since ``job.started_at``.
1398
+ """
1399
+ from api.batch_jobs.batch_job_status import (
1400
+ transcript_seconds_from_job_videos,
1401
+ )
1402
+
1403
+ ok_ids = [
1404
+ v.video_id
1405
+ for j in job.jurisdictions
1406
+ for v in j.videos or []
1407
+ if (v.status or "").strip().lower() == "ok" and (v.video_id or "").strip()
1408
+ ]
1409
+ cur = conn.cursor()
1410
+ try:
1411
+ if ok_ids:
1412
+ cur.execute(
1413
+ """
1414
+ SELECT COALESCE(SUM(duration_minutes), 0) * 60.0
1415
+ FROM bronze.bronze_event_youtube
1416
+ WHERE video_id = ANY(%s)
1417
+ AND duration_minutes IS NOT NULL
1418
+ AND duration_minutes > 0
1419
+ """,
1420
+ (ok_ids,),
1421
+ )
1422
+ row = cur.fetchone()
1423
+ secs = float(row[0] or 0) if row else 0.0
1424
+ else:
1425
+ active_jids = [
1426
+ j.jurisdiction_id
1427
+ for j in job.jurisdictions
1428
+ if j.jurisdiction_id
1429
+ and j.status in ("completed", "failed", "running")
1430
+ and (
1431
+ int((j.stats or {}).get("ok") or 0) > 0
1432
+ or any(
1433
+ (v.status or "").strip().lower() == "ok" for v in j.videos or []
1434
+ )
1435
+ )
1436
+ ]
1437
+ if not active_jids:
1438
+ secs = transcript_seconds_from_job_videos(job)
1439
+ elif job.started_at:
1440
+ cur.execute(
1441
+ """
1442
+ SELECT COALESCE(SUM(duration_minutes), 0) * 60.0
1443
+ FROM bronze.bronze_event_youtube
1444
+ WHERE jurisdiction_id = ANY(%s)
1445
+ AND transcript_download_at IS NOT NULL
1446
+ AND transcript_download_at >= %s::timestamptz
1447
+ AND duration_minutes IS NOT NULL
1448
+ AND duration_minutes > 0
1449
+ """,
1450
+ (active_jids, job.started_at),
1451
+ )
1452
+ row = cur.fetchone()
1453
+ secs = float(row[0] or 0) if row else 0.0
1454
+ else:
1455
+ cur.execute(
1456
+ """
1457
+ SELECT COALESCE(SUM(duration_minutes), 0) * 60.0
1458
+ FROM bronze.bronze_event_youtube
1459
+ WHERE jurisdiction_id = ANY(%s)
1460
+ AND transcript_download_at IS NOT NULL
1461
+ AND duration_minutes IS NOT NULL
1462
+ AND duration_minutes > 0
1463
+ """,
1464
+ (active_jids,),
1465
+ )
1466
+ row = cur.fetchone()
1467
+ secs = float(row[0] or 0) if row else 0.0
1468
+ finally:
1469
+ cur.close()
1470
+
1471
+ job.summary = dict(job.summary or {})
1472
+ job.summary["transcript_seconds"] = round(secs, 1)
1473
+
1474
+
1475
+ def enrich_disk_file_counts(job: BatchJob, *, cache_root: Path | None = None) -> None:
1476
+ """Merge on-disk policy cache file counts into each jurisdiction's ``file_counts``."""
1477
+ from api.batch_jobs.batch_job_status import (
1478
+ count_policy_files_for_jurisdiction,
1479
+ policy_disk_file_counts,
1480
+ )
1481
+
1482
+ root = cache_root or (
1483
+ Path(__file__).resolve().parents[3] / "data" / "cache" / "gemini_transcript_policy"
1484
+ )
1485
+ for j in job.jurisdictions:
1486
+ if not j.jurisdiction_id:
1487
+ continue
1488
+ scanned = count_policy_files_for_jurisdiction(
1489
+ root,
1490
+ state_code=j.state_code,
1491
+ jurisdiction_id=j.jurisdiction_id,
1492
+ )
1493
+ j.file_counts = dict(j.file_counts or {})
1494
+ j.file_counts.update(policy_disk_file_counts(scanned))
1495
+
1496
+
1497
+ def enrich_jobs_from_bronze(
1498
+ jobs: List[BatchJob],
1499
+ *,
1500
+ only_running_jurisdictions: bool = False,
1501
+ enrich_disk: bool = True,
1502
+ ) -> None:
1503
+ if not jobs:
1504
+ return
1505
+ try:
1506
+ with get_db_connection() as conn:
1507
+ for job in jobs:
1508
+ if only_running_jurisdictions:
1509
+ pending = [
1510
+ j
1511
+ for j in job.jurisdictions
1512
+ if j.status in ("running", "pending")
1513
+ ]
1514
+ if not pending:
1515
+ continue
1516
+ stub = BatchJob(
1517
+ batch_id=job.batch_id,
1518
+ step=job.step,
1519
+ jurisdictions=pending,
1520
+ )
1521
+ enrich_transcript_counts_from_bronze(conn, stub)
1522
+ enrich_transcript_seconds_from_bronze(conn, stub)
1523
+ if enrich_disk:
1524
+ enrich_disk_file_counts(stub)
1525
+ by_jid = {j.jurisdiction_id: j for j in pending}
1526
+ for j in job.jurisdictions:
1527
+ if j.jurisdiction_id in by_jid:
1528
+ j.file_counts = dict(j.file_counts or {})
1529
+ j.file_counts.update(by_jid[j.jurisdiction_id].file_counts)
1530
+ else:
1531
+ enrich_transcript_counts_from_bronze(conn, job)
1532
+ enrich_transcript_seconds_from_bronze(conn, job)
1533
+ if enrich_disk:
1534
+ enrich_disk_file_counts(job)
1535
+ except Exception as exc:
1536
+ logger.warning("bronze transcript count enrich failed: %s", exc)
1537
+
1538
+
1539
+ def load_batch_job_from_db(batch_id: str) -> Optional[BatchJob]:
1540
+ with get_db_connection() as conn:
1541
+ ensure_batch_job_tables(conn)
1542
+ with conn.cursor(cursor_factory=RealDictCursor) as cur:
1543
+ cur.execute(
1544
+ """
1545
+ SELECT payload FROM bronze.youtube_batch_job_runs
1546
+ WHERE batch_id = %s
1547
+ """,
1548
+ (batch_id,),
1549
+ )
1550
+ row = cur.fetchone()
1551
+ if not row:
1552
+ return None
1553
+ payload = row["payload"]
1554
+ if isinstance(payload, str):
1555
+ payload = json.loads(payload)
1556
+ return BatchJob.from_dict(payload)
1557
+
1558
+
1559
+ def latest_dashboard_revision() -> Optional[str]:
1560
+ """Cheap change detector for SSE (max updated_at + running count)."""
1561
+ try:
1562
+ with get_db_connection() as conn:
1563
+ ensure_batch_job_tables(conn)
1564
+ with conn.cursor() as cur:
1565
+ cur.execute(
1566
+ """
1567
+ SELECT
1568
+ COALESCE(MAX(updated_at)::text, ''),
1569
+ COUNT(*) FILTER (WHERE status = 'running')::int
1570
+ FROM bronze.youtube_batch_job_runs
1571
+ """
1572
+ )
1573
+ updated_at, running = cur.fetchone()
1574
+ return f"{updated_at}|{running}"
1575
+ except Exception:
1576
+ return None
api/batch_jobs/batch_job_status.py ADDED
@@ -0,0 +1,1607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Persist batch job progress for priority-state pipelines (captions, analyze, catalog).
4
+
5
+ Writes JSON under ``data/cache/batch_jobs/`` and syncs to
6
+ ``bronze.youtube_batch_job_runs`` (migration 073) for the live API dashboard.
7
+
8
+ Used by ``run_priority_states_last_n.sh`` and ``backfill_jurisdiction_transcripts.py``.
9
+ View in React: ``/data-explorer/batch-jobs`` (``GET /api/batch-jobs/stream`` SSE).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import functools
16
+ import json
17
+ import os
18
+ import re
19
+ import sys
20
+ import time
21
+ from dataclasses import asdict, dataclass, field
22
+ from datetime import datetime, timezone
23
+ from pathlib import Path
24
+ from typing import Any, Dict, List, Optional
25
+
26
+ _REPO_ROOT = Path(__file__).resolve().parents[3]
27
+ if str(_REPO_ROOT) not in sys.path:
28
+ sys.path.insert(0, str(_REPO_ROOT))
29
+ _DEFAULT_JOBS_DIR = _REPO_ROOT / "data" / "cache" / "batch_jobs"
30
+ _INDEX_NAME = "index.json"
31
+ _SLUG_RE = re.compile(r"[^a-zA-Z0-9._-]+")
32
+
33
+
34
+ def _utc_now_iso() -> str:
35
+ return datetime.now(timezone.utc).isoformat()
36
+
37
+
38
+ def batch_inactivity_seconds() -> float:
39
+ """Mark ``running`` batches cancelled after this many seconds without activity."""
40
+ raw = os.getenv("BATCH_JOB_INACTIVITY_SECONDS", "3600")
41
+ try:
42
+ return max(60.0, float(raw))
43
+ except (TypeError, ValueError):
44
+ return 3600.0
45
+
46
+
47
+ def config_state_codes(cfg: Optional[Dict[str, Any]]) -> List[str]:
48
+ raw = (cfg or {}).get("states") or []
49
+ if isinstance(raw, str):
50
+ return [s.strip().upper() for s in raw.split(",") if s.strip()]
51
+ if isinstance(raw, list):
52
+ return [str(s).strip().upper() for s in raw if str(s).strip()]
53
+ return []
54
+
55
+
56
+ def _parse_utc_iso(iso: str) -> Optional[datetime]:
57
+ text = (iso or "").strip()
58
+ if not text:
59
+ return None
60
+ try:
61
+ return datetime.fromisoformat(text.replace("Z", "+00:00"))
62
+ except ValueError:
63
+ return None
64
+
65
+
66
+ def last_batch_activity_at(job: BatchJob) -> datetime:
67
+ """
68
+ Latest timestamp that indicates real pipeline work (jurisdiction / video progress).
69
+
70
+ Does not use ``job.updated_at`` (dashboard sync metadata). When nothing is recorded,
71
+ falls back to ``started_at`` so idle ``running`` rows can stale-cancel instead of
72
+ looking falsely active.
73
+ """
74
+ best: Optional[datetime] = None
75
+ for j in job.jurisdictions:
76
+ for iso in (
77
+ j.updated_at,
78
+ j.current_video_started_at,
79
+ j.finished_at,
80
+ j.started_at,
81
+ ):
82
+ dt = _parse_utc_iso(iso or "")
83
+ if dt and (best is None or dt > best):
84
+ best = dt
85
+ for v in j.videos or []:
86
+ dt = _parse_utc_iso(v.finished_at or "")
87
+ if dt and (best is None or dt > best):
88
+ best = dt
89
+ if best is not None:
90
+ return best
91
+ dt = _parse_utc_iso(job.started_at or "")
92
+ if dt:
93
+ return dt
94
+ return datetime.fromtimestamp(0, tz=timezone.utc)
95
+
96
+
97
+ def latest_dashboard_activity_at(jobs: List[BatchJob]) -> str:
98
+ """Latest jurisdiction/video progress across batches (not API ``generated_at``)."""
99
+ best: Optional[datetime] = None
100
+ for job in jobs:
101
+ try:
102
+ dt = last_batch_activity_at(job)
103
+ if dt.year > 1971 and (best is None or dt > best):
104
+ best = dt
105
+ except Exception:
106
+ pass
107
+ return best.isoformat() if best is not None and best.year > 1971 else ""
108
+
109
+
110
+ def state_progress_for_job(job: BatchJob) -> Dict[str, Any]:
111
+ """
112
+ Per-batch state coverage from jurisdiction rows.
113
+
114
+ * started — at least one jurisdiction in that state is running or finished
115
+ * completed — every jurisdiction row for that state is finished (none pending/running)
116
+ """
117
+ planned = config_state_codes(job.config)
118
+ by_state: Dict[str, Dict[str, int]] = {}
119
+ for j in job.jurisdictions:
120
+ st = (j.state_code or "").strip().upper()
121
+ if not st:
122
+ continue
123
+ bucket = by_state.setdefault(st, {"pending": 0, "running": 0, "done": 0})
124
+ if j.status == "pending":
125
+ bucket["pending"] += 1
126
+ elif j.status == "running":
127
+ bucket["running"] += 1
128
+ else:
129
+ bucket["done"] += 1
130
+
131
+ universe = sorted(set(planned) | set(by_state))
132
+ started_codes = [
133
+ st
134
+ for st in universe
135
+ if by_state.get(st, {}).get("running", 0) + by_state.get(st, {}).get("done", 0) > 0
136
+ ]
137
+ completed_codes = [
138
+ st
139
+ for st in universe
140
+ if by_state.get(st)
141
+ and by_state[st].get("pending", 0) == 0
142
+ and by_state[st].get("running", 0) == 0
143
+ and by_state[st].get("done", 0) > 0
144
+ ]
145
+ return {
146
+ "states_planned": len(universe),
147
+ "states_started": len(started_codes),
148
+ "states_completed": len(completed_codes),
149
+ "states_started_codes": started_codes,
150
+ "states_completed_codes": completed_codes,
151
+ }
152
+
153
+
154
+ def _maybe_stale_cancel_batch(job: BatchJob) -> bool:
155
+ """Cancel ``running`` batches with no activity for ``batch_inactivity_seconds()``."""
156
+ if (job.status or "").lower() != "running":
157
+ return False
158
+ inactive = batch_inactivity_seconds()
159
+ now = datetime.now(timezone.utc)
160
+ if (now - last_batch_activity_at(job)).total_seconds() <= inactive:
161
+ return False
162
+ finished = _utc_now_iso()
163
+ job.status = "cancelled"
164
+ job.finished_at = finished
165
+ cfg = dict(job.config or {})
166
+ cfg["stale_cancel_reason"] = f"no activity for {int(inactive)}s"
167
+ job.config = cfg
168
+ for j in job.jurisdictions:
169
+ if j.status == "running":
170
+ j.status = "failed"
171
+ j.exit_code = -1
172
+ j.finished_at = finished
173
+ j.updated_at = finished
174
+ j.current_video_id = ""
175
+ j.current_video_title = ""
176
+ j.current_video_started_at = ""
177
+ return True
178
+
179
+
180
+ def persist_batch_job(job: BatchJob) -> None:
181
+ """Write lifecycle changes to Postgres and the JSON cache file when present."""
182
+ job.updated_at = _utc_now_iso()
183
+ _recompute_summary(job)
184
+ try:
185
+ from api.batch_jobs.batch_job_db import sync_batch_job_to_db
186
+
187
+ sync_batch_job_to_db(job)
188
+ except Exception:
189
+ pass
190
+ try:
191
+ store = BatchJobStore(job.batch_id)
192
+ if store.path.is_file():
193
+ tmp = store.path.with_suffix(".json.tmp")
194
+ tmp.write_text(
195
+ json.dumps(job.to_dict(), indent=2, ensure_ascii=False) + "\n",
196
+ encoding="utf-8",
197
+ )
198
+ tmp.replace(store.path)
199
+ _update_index(store.root, job)
200
+ except Exception:
201
+ pass
202
+
203
+
204
+ def duration_seconds_from_catalog_minutes(duration_minutes: object) -> Optional[float]:
205
+ """Convert ``bronze_event_youtube.duration_minutes`` to seconds for batch UI."""
206
+ if duration_minutes is None:
207
+ return None
208
+ try:
209
+ sec = float(duration_minutes) * 60.0
210
+ except (TypeError, ValueError):
211
+ return None
212
+ if sec <= 0 or sec > 86400 * 48: # cap absurd values (~48h)
213
+ return None
214
+ return round(sec, 1)
215
+
216
+
217
+ def _slug(s: str, max_len: int = 48) -> str:
218
+ out = _SLUG_RE.sub("-", (s or "").strip()).strip("-")
219
+ return (out[:max_len] if out else "batch")
220
+
221
+
222
+ def new_batch_id(step: str) -> str:
223
+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
224
+ return f"{_slug(step, 24)}-{ts}"
225
+
226
+
227
+ def jobs_dir() -> Path:
228
+ raw = (os.getenv("BATCH_JOBS_DIR") or "").strip()
229
+ return Path(raw).resolve() if raw else _DEFAULT_JOBS_DIR
230
+
231
+
232
+ def _batch_database_url() -> str:
233
+ return (
234
+ os.getenv("NEON_DATABASE_URL_DEV", "").strip()
235
+ or os.getenv("NEON_DATABASE_URL", "").strip()
236
+ or os.getenv("DATABASE_URL", "").strip()
237
+ )
238
+
239
+
240
+ def _batch_plan_cache_key(states: List[str], *, round_robin: bool) -> str:
241
+ st_list = [s.strip().upper() for s in states if (s or "").strip()]
242
+ return f"{','.join(st_list)}|{int(bool(round_robin))}"
243
+
244
+
245
+ def fetch_batch_plan_jurisdictions(
246
+ states: List[str],
247
+ *,
248
+ round_robin: bool = True,
249
+ database_url: Optional[str] = None,
250
+ include_homepage_channels: bool = False,
251
+ cohort: Optional[str] = None,
252
+ ) -> List[JurisdictionRun]:
253
+ """
254
+ Canonical jurisdictions for the batch plan (``pending``), aligned with
255
+ ``intermediate.int_jurisdictions`` — not legacy ``c-AL-*`` ids on bronze video rows.
256
+
257
+ By default only jurisdictions that already have videos in ``bronze_event_youtube``.
258
+ ``include_homepage_channels=True`` also lists cities and counties whose primary
259
+ channel was found as a link on their own website
260
+ (``youtube_channel_selection_method = 'website_scrape'`` on the scraped tables),
261
+ so a newly found channel gets its first crawl.
262
+ """
263
+ from core_lib.jurisdictions.jurisdiction_id import (
264
+ _PREFIXED_USPS_GEOID_RE,
265
+ _SLUG_GEOID_RE,
266
+ _TYPED_JURISDICTION_ID_RE,
267
+ ensure_canonical_jurisdiction_id,
268
+ )
269
+
270
+ st_list = [s.strip().upper() for s in states if (s or "").strip()]
271
+ if not st_list:
272
+ return []
273
+ url = (database_url or "").strip() or _batch_database_url()
274
+ if not url:
275
+ return []
276
+ try:
277
+ import psycopg2
278
+ from psycopg2.extras import RealDictCursor
279
+ except ImportError:
280
+ return []
281
+
282
+ cohort_norm = (cohort or "").strip().lower() or None
283
+ dc_filter: Optional[List[str]] = None
284
+
285
+ rows: list = []
286
+ try:
287
+ with psycopg2.connect(url) as conn, conn.cursor(
288
+ cursor_factory=RealDictCursor
289
+ ) as cur:
290
+ if cohort_norm == "data_centers":
291
+ from api.batch_jobs.cohorts import data_center_jurisdiction_ids
292
+
293
+ dc_ids = data_center_jurisdiction_ids(conn)
294
+ if not dc_ids:
295
+ return []
296
+ dc_filter = list(dc_ids)
297
+ dc_a: Optional[List[str]] = dc_filter
298
+ dc_b: Optional[List[str]] = dc_filter
299
+ cur.execute(
300
+ """
301
+ WITH yt AS MATERIALIZED (
302
+ -- Each video jurisdiction id once, with the GEOID after its last
303
+ -- underscore. The matches below are equality joins (hashable), not a
304
+ -- LIKE or an OR per jurisdiction, which took minutes per state.
305
+ SELECT DISTINCT
306
+ y.state_code,
307
+ y.jurisdiction_id,
308
+ substring(y.jurisdiction_id FROM '_([0-9]+)$') AS geoid_suffix
309
+ FROM bronze.bronze_event_youtube y
310
+ WHERE y.state_code = ANY(%s)
311
+ ),
312
+ j AS MATERIALIZED (
313
+ SELECT j.state_code, j.jurisdiction_id, j.name, j.geoid, j.jurisdiction_type::text AS jurisdiction_type
314
+ FROM intermediate.int_jurisdictions j
315
+ WHERE j.state_code = ANY(%s)
316
+ AND j.jurisdiction_id IS NOT NULL
317
+ AND BTRIM(j.jurisdiction_id) <> ''
318
+ ),
319
+ with_videos AS (
320
+ SELECT j.jurisdiction_id FROM j JOIN yt ON yt.jurisdiction_id = j.jurisdiction_id
321
+ UNION
322
+ SELECT j.jurisdiction_id FROM j JOIN yt
323
+ ON yt.jurisdiction_id = 'c-' || j.state_code || '-' || j.geoid
324
+ UNION
325
+ SELECT j.jurisdiction_id FROM j JOIN yt
326
+ ON yt.jurisdiction_id = 'municipality_' || j.geoid AND yt.state_code = j.state_code
327
+ UNION
328
+ SELECT j.jurisdiction_id FROM j JOIN yt
329
+ ON yt.geoid_suffix = j.geoid AND yt.state_code = j.state_code
330
+ ),
331
+ with_homepage_channel AS (
332
+ SELECT j.jurisdiction_id FROM j
333
+ JOIN bronze.bronze_jurisdictions_municipalities_scraped s ON s.geoid = j.geoid
334
+ WHERE %s AND j.jurisdiction_type = 'municipality'
335
+ AND s.youtube_channel_selection_method = 'website_scrape'
336
+ AND BTRIM(COALESCE(s.youtube_channel_url, '')) <> ''
337
+ UNION
338
+ SELECT j.jurisdiction_id FROM j
339
+ JOIN bronze.bronze_jurisdictions_counties_scraped s ON s.geoid = j.geoid
340
+ WHERE %s AND j.jurisdiction_type = 'county'
341
+ AND s.youtube_channel_selection_method = 'website_scrape'
342
+ AND BTRIM(COALESCE(s.youtube_channel_url, '')) <> ''
343
+ )
344
+ SELECT
345
+ j.state_code,
346
+ j.jurisdiction_id,
347
+ j.name AS jurisdiction_name,
348
+ j.jurisdiction_type
349
+ FROM j
350
+ WHERE (
351
+ j.jurisdiction_id IN (SELECT jurisdiction_id FROM with_videos)
352
+ OR j.jurisdiction_id IN (SELECT jurisdiction_id FROM with_homepage_channel)
353
+ )
354
+ AND (%s::text[] IS NULL OR j.jurisdiction_id = ANY(%s))
355
+ ORDER BY j.state_code, j.name, j.jurisdiction_id
356
+ """,
357
+ (
358
+ st_list,
359
+ st_list,
360
+ include_homepage_channels,
361
+ include_homepage_channels,
362
+ dc_a,
363
+ dc_b,
364
+ ),
365
+ )
366
+ rows = list(cur.fetchall())
367
+ except Exception as exc:
368
+ # Say so: a silent failure here once sent every plan to the fallback query.
369
+ print(
370
+ f"WARN: batch plan query failed ({type(exc).__name__}: {exc}); "
371
+ "using the bronze_event_youtube fallback",
372
+ file=sys.stderr,
373
+ )
374
+ rows = []
375
+
376
+ if not rows:
377
+ try:
378
+ with psycopg2.connect(url) as conn, conn.cursor(
379
+ cursor_factory=RealDictCursor
380
+ ) as cur:
381
+ fallback_dc = dc_filter
382
+ if cohort_norm == "data_centers" and fallback_dc is None:
383
+ from api.batch_jobs.cohorts import data_center_jurisdiction_ids
384
+
385
+ dc_ids = data_center_jurisdiction_ids(conn)
386
+ if not dc_ids:
387
+ return []
388
+ fallback_dc = list(dc_ids)
389
+ cur.execute(
390
+ """
391
+ SELECT DISTINCT ON (state_code, jurisdiction_id)
392
+ state_code,
393
+ jurisdiction_id,
394
+ jurisdiction_name,
395
+ NULL::text AS jurisdiction_type
396
+ FROM bronze.bronze_event_youtube
397
+ WHERE state_code = ANY(%s)
398
+ AND jurisdiction_id IS NOT NULL
399
+ AND BTRIM(jurisdiction_id) <> ''
400
+ AND (%s::text[] IS NULL OR jurisdiction_id = ANY(%s))
401
+ ORDER BY state_code, jurisdiction_id, jurisdiction_name
402
+ """,
403
+ (st_list, fallback_dc, fallback_dc),
404
+ )
405
+ rows = list(cur.fetchall())
406
+ except Exception:
407
+ return []
408
+
409
+ if round_robin:
410
+ from collections import defaultdict
411
+
412
+ buckets: Dict[str, list] = defaultdict(list)
413
+ for r in rows:
414
+ buckets[str(r["state_code"]).upper()].append(r)
415
+ active = [s for s in st_list if buckets.get(s)]
416
+ max_len = max((len(buckets[s]) for s in active), default=0)
417
+ ordered: list = []
418
+ for i in range(max_len):
419
+ for s in active:
420
+ if i < len(buckets[s]):
421
+ ordered.append(buckets[s][i])
422
+ rows = ordered
423
+
424
+ out: List[JurisdictionRun] = []
425
+ seen_keys: set[str] = set()
426
+ for r in rows:
427
+ raw_id = str(r["jurisdiction_id"]).strip()
428
+ name = str(r.get("jurisdiction_name") or "").strip()
429
+ if not name or name == raw_id or _looks_like_jurisdiction_id_label(name):
430
+ name = ""
431
+ jtype = str(r.get("jurisdiction_type") or "").strip()
432
+ jid = ensure_canonical_jurisdiction_id(
433
+ raw_id,
434
+ name=name or None,
435
+ jurisdiction_type=jtype or None,
436
+ database_url=url,
437
+ ) or raw_id
438
+ if _PREFIXED_USPS_GEOID_RE.match(jid):
439
+ continue
440
+ if not (
441
+ (_SLUG_GEOID_RE.match(jid) and not _TYPED_JURISDICTION_ID_RE.match(jid))
442
+ or _TYPED_JURISDICTION_ID_RE.match(jid)
443
+ ):
444
+ continue
445
+ key = _plan_jurisdiction_key(jid)
446
+ if not key or key in seen_keys:
447
+ continue
448
+ seen_keys.add(key)
449
+ row = JurisdictionRun(
450
+ state_code=str(r["state_code"]).upper(),
451
+ jurisdiction_id=jid,
452
+ jurisdiction_name=name,
453
+ jurisdiction_type=jtype,
454
+ status="pending",
455
+ )
456
+ normalize_jurisdiction_run(row, database_url=url)
457
+ out.append(row)
458
+
459
+ return out
460
+
461
+
462
+ @functools.lru_cache(maxsize=16)
463
+ def _fetch_batch_plan_cached(cache_key: str, database_url: str) -> tuple:
464
+ """Cacheable wrapper; returns tuple of row dicts for ``lru_cache``."""
465
+ parts = cache_key.rsplit("|", 1)
466
+ states = [s for s in parts[0].split(",") if s]
467
+ round_robin = bool(int(parts[1]))
468
+ runs = fetch_batch_plan_jurisdictions(
469
+ states, round_robin=round_robin, database_url=database_url or None
470
+ )
471
+ return tuple(
472
+ (
473
+ r.state_code,
474
+ r.jurisdiction_id,
475
+ r.jurisdiction_name,
476
+ r.jurisdiction_type,
477
+ r.status,
478
+ )
479
+ for r in runs
480
+ )
481
+
482
+
483
+ def fetch_batch_plan_jurisdictions_cached(
484
+ states: List[str],
485
+ *,
486
+ round_robin: bool = True,
487
+ database_url: Optional[str] = None,
488
+ ) -> List[JurisdictionRun]:
489
+ """Same as ``fetch_batch_plan_jurisdictions`` but deduped per process (dashboard load)."""
490
+ url = (database_url or "").strip() or _batch_database_url()
491
+ key = _batch_plan_cache_key(states, round_robin=round_robin)
492
+ if not key or key == "|0":
493
+ return []
494
+ rows = _fetch_batch_plan_cached(key, url or "")
495
+ return [
496
+ JurisdictionRun(
497
+ state_code=row[0],
498
+ jurisdiction_id=row[1],
499
+ jurisdiction_name=row[2],
500
+ jurisdiction_type=row[3],
501
+ status=row[4],
502
+ )
503
+ for row in rows
504
+ ]
505
+
506
+
507
+ _STATUS_RANK = {
508
+ "completed": 5,
509
+ "failed": 4,
510
+ "running": 3,
511
+ "cancelled": 2,
512
+ "pending": 1,
513
+ }
514
+
515
+
516
+ def _plan_jurisdiction_key(jurisdiction_id: str) -> str:
517
+ """Match plan rows to batch rows even when id format differs (``municipality_*`` vs ``slug_geoid``)."""
518
+ from core_lib.jurisdictions.jurisdiction_id import (
519
+ parse_jurisdiction_id,
520
+ resolve_canonical_jurisdiction_id,
521
+ )
522
+
523
+ jid = (jurisdiction_id or "").strip()
524
+ if not jid:
525
+ return ""
526
+ canonical = resolve_canonical_jurisdiction_id(jid).strip().lower()
527
+ _jt, geoid, _slug = parse_jurisdiction_id(canonical or jid)
528
+ if geoid:
529
+ return f"geoid:{geoid}"
530
+ return canonical or jid.lower()
531
+
532
+
533
+ def _looks_like_jurisdiction_id_label(text: str) -> bool:
534
+ """True when ``text`` is an id string, not a place name (e.g. ``c-AL-01021``)."""
535
+ from core_lib.jurisdictions.jurisdiction_id import (
536
+ _PREFIXED_USPS_GEOID_RE,
537
+ _SLUG_GEOID_RE,
538
+ _TYPED_JURISDICTION_ID_RE,
539
+ )
540
+
541
+ t = (text or "").strip()
542
+ if not t:
543
+ return False
544
+ if _PREFIXED_USPS_GEOID_RE.match(t):
545
+ return True
546
+ if _TYPED_JURISDICTION_ID_RE.match(t):
547
+ return True
548
+ if _SLUG_GEOID_RE.match(t) and "_" in t and not re.search(r"\s", t):
549
+ return True
550
+ return False
551
+
552
+
553
+ def _lookup_jurisdiction_name_from_db(
554
+ jurisdiction_id: str,
555
+ *,
556
+ database_url: Optional[str] = None,
557
+ ) -> str:
558
+ """Place name from ``int_jurisdictions`` for a canonical or legacy id."""
559
+ from core_lib.jurisdictions.jurisdiction_id import parse_jurisdiction_id
560
+
561
+ jid = (jurisdiction_id or "").strip()
562
+ if not jid:
563
+ return ""
564
+ url = (database_url or "").strip() or _batch_database_url()
565
+ if not url:
566
+ return ""
567
+ _jt, geoid, _slug = parse_jurisdiction_id(jid)
568
+ try:
569
+ import psycopg2
570
+ except ImportError:
571
+ return ""
572
+ try:
573
+ with psycopg2.connect(url) as conn, conn.cursor() as cur:
574
+ cur.execute(
575
+ """
576
+ SELECT name FROM intermediate.int_jurisdictions
577
+ WHERE jurisdiction_id = %s
578
+ LIMIT 1
579
+ """,
580
+ (jid,),
581
+ )
582
+ row = cur.fetchone()
583
+ if row and row[0]:
584
+ return str(row[0]).strip()
585
+ if geoid:
586
+ cur.execute(
587
+ """
588
+ SELECT name FROM intermediate.int_jurisdictions
589
+ WHERE geoid = %s
590
+ ORDER BY jurisdiction_id
591
+ LIMIT 1
592
+ """,
593
+ (geoid,),
594
+ )
595
+ row = cur.fetchone()
596
+ if row and row[0]:
597
+ return str(row[0]).strip()
598
+ except Exception:
599
+ return ""
600
+ return ""
601
+
602
+
603
+ def normalize_jurisdiction_run(
604
+ j: JurisdictionRun,
605
+ *,
606
+ database_url: Optional[str] = None,
607
+ ) -> JurisdictionRun:
608
+ """Canonical ``jurisdiction_id`` and human ``jurisdiction_name`` for dashboard rows."""
609
+ from core_lib.jurisdictions.jurisdiction_id import (
610
+ _PREFIXED_USPS_GEOID_RE,
611
+ _SLUG_GEOID_RE,
612
+ _TYPED_JURISDICTION_ID_RE,
613
+ ensure_canonical_jurisdiction_id,
614
+ )
615
+
616
+ raw_id = (j.jurisdiction_id or "").strip()
617
+ if not raw_id:
618
+ return j
619
+ name = (j.jurisdiction_name or "").strip()
620
+ if (
621
+ _SLUG_GEOID_RE.match(raw_id)
622
+ and not _TYPED_JURISDICTION_ID_RE.match(raw_id)
623
+ and name
624
+ and not _looks_like_jurisdiction_id_label(name)
625
+ and name != raw_id
626
+ ):
627
+ return j
628
+ if not name or name == raw_id or _looks_like_jurisdiction_id_label(name):
629
+ name = ""
630
+
631
+ jid = ensure_canonical_jurisdiction_id(
632
+ raw_id,
633
+ name=name or None,
634
+ jurisdiction_type=(j.jurisdiction_type or None),
635
+ database_url=database_url,
636
+ ) or raw_id
637
+ if _PREFIXED_USPS_GEOID_RE.match(jid):
638
+ jid = ensure_canonical_jurisdiction_id(
639
+ raw_id,
640
+ name=None,
641
+ jurisdiction_type=(j.jurisdiction_type or "county"),
642
+ database_url=database_url,
643
+ ) or jid
644
+
645
+ j.jurisdiction_id = jid
646
+ if not name or _looks_like_jurisdiction_id_label(name):
647
+ name = _lookup_jurisdiction_name_from_db(jid, database_url=database_url)
648
+ if name and not _looks_like_jurisdiction_id_label(name):
649
+ j.jurisdiction_name = name
650
+ return j
651
+
652
+
653
+ def _upgrade_jurisdiction_from_plan(
654
+ existing: JurisdictionRun, placeholder: JurisdictionRun
655
+ ) -> None:
656
+ """Apply canonical id and display name from the fresh plan row."""
657
+ from core_lib.jurisdictions.jurisdiction_id import (
658
+ _SLUG_GEOID_RE,
659
+ _TYPED_JURISDICTION_ID_RE,
660
+ )
661
+
662
+ def _is_canonical_slug(jid: str) -> bool:
663
+ return bool(_SLUG_GEOID_RE.match(jid) and not _TYPED_JURISDICTION_ID_RE.match(jid))
664
+
665
+ pid = (placeholder.jurisdiction_id or "").strip()
666
+ eid = (existing.jurisdiction_id or "").strip()
667
+ if pid and (_is_canonical_slug(pid) or not _is_canonical_slug(eid)):
668
+ existing.jurisdiction_id = pid
669
+ pname = (placeholder.jurisdiction_name or "").strip()
670
+ if pname and not _looks_like_jurisdiction_id_label(pname):
671
+ existing.jurisdiction_name = pname
672
+ if placeholder.jurisdiction_type and not (existing.jurisdiction_type or "").strip():
673
+ existing.jurisdiction_type = placeholder.jurisdiction_type
674
+
675
+
676
+ def normalize_batch_job_jurisdictions(
677
+ job: BatchJob,
678
+ *,
679
+ database_url: Optional[str] = None,
680
+ ) -> bool:
681
+ """Normalize all jurisdiction rows in place. True when ids/names need a DB persist."""
682
+ from core_lib.jurisdictions.jurisdiction_id import _PREFIXED_USPS_GEOID_RE
683
+
684
+ changed = False
685
+ url = database_url
686
+ for j in job.jurisdictions:
687
+ before_id = (j.jurisdiction_id or "").strip()
688
+ before_name = (j.jurisdiction_name or "").strip()
689
+ normalize_jurisdiction_run(j, database_url=url)
690
+ after_id = (j.jurisdiction_id or "").strip()
691
+ after_name = (j.jurisdiction_name or "").strip()
692
+ if before_id != after_id:
693
+ changed = True
694
+ elif _PREFIXED_USPS_GEOID_RE.match(before_id) and not _PREFIXED_USPS_GEOID_RE.match(
695
+ after_id
696
+ ):
697
+ changed = True
698
+ elif _looks_like_jurisdiction_id_label(before_name) and not _looks_like_jurisdiction_id_label(
699
+ after_name
700
+ ):
701
+ changed = True
702
+ return changed
703
+
704
+
705
+ def _prefer_jurisdiction_run(
706
+ current: JurisdictionRun, other: JurisdictionRun
707
+ ) -> JurisdictionRun:
708
+ """Keep the row with the most advanced status (never downgrade completed → pending)."""
709
+ cur_rank = _STATUS_RANK.get((current.status or "").lower(), 0)
710
+ other_rank = _STATUS_RANK.get((other.status or "").lower(), 0)
711
+ if other_rank > cur_rank:
712
+ return other
713
+ if other_rank < cur_rank:
714
+ return current
715
+ if (other.videos or other.stats) and not (current.videos or current.stats):
716
+ return other
717
+ return current
718
+
719
+
720
+ def needs_plan_expand(job: BatchJob) -> bool:
721
+ """
722
+ True when the dashboard should merge the full state plan into this batch.
723
+
724
+ Skip for finished batches that already have their jurisdiction rows (avoids
725
+ re-merging hundreds of pending placeholders on every API read).
726
+ """
727
+ cfg = job.config or {}
728
+ if cfg.get("seed_plan") is False:
729
+ return False
730
+ if not cfg.get("states"):
731
+ return False
732
+ status = (job.status or "").lower()
733
+ if status == "running":
734
+ return True
735
+ total = int(cfg.get("total_jurisdictions") or 0) or len(job.jurisdictions)
736
+ if status in ("completed", "cancelled", "failed") and job.jurisdictions:
737
+ if total > 0 and len(job.jurisdictions) >= total:
738
+ return False
739
+ if status in ("completed", "cancelled") and len(job.jurisdictions) > 0:
740
+ return False
741
+ return True
742
+
743
+
744
+ def expand_batch_job_plan(
745
+ job: BatchJob,
746
+ plan: Optional[List[JurisdictionRun]] = None,
747
+ ) -> None:
748
+ """Fill in ``pending`` rows for jurisdictions not started yet in this batch."""
749
+ cfg = job.config or {}
750
+ if cfg.get("seed_plan") is False:
751
+ return
752
+ states = cfg.get("states") or []
753
+ if not states:
754
+ return
755
+ rr = cfg.get("round_robin")
756
+ if rr is None:
757
+ rr = True
758
+ if plan is None:
759
+ plan = fetch_batch_plan_jurisdictions_cached(states, round_robin=bool(rr))
760
+ if not plan:
761
+ return
762
+
763
+ by_key: Dict[str, JurisdictionRun] = {}
764
+ for j in job.jurisdictions:
765
+ key = _plan_jurisdiction_key(j.jurisdiction_id)
766
+ if not key:
767
+ continue
768
+ if key in by_key:
769
+ by_key[key] = _prefer_jurisdiction_run(by_key[key], j)
770
+ else:
771
+ by_key[key] = j
772
+
773
+ merged: List[JurisdictionRun] = []
774
+ matched: set[str] = set()
775
+ for placeholder in plan:
776
+ key = _plan_jurisdiction_key(placeholder.jurisdiction_id)
777
+ existing = by_key.get(key) if key else None
778
+ if existing is not None:
779
+ _upgrade_jurisdiction_from_plan(existing, placeholder)
780
+ normalize_jurisdiction_run(existing)
781
+ merged.append(existing)
782
+ matched.add(key)
783
+ else:
784
+ normalize_jurisdiction_run(placeholder)
785
+ merged.append(placeholder)
786
+ if key:
787
+ matched.add(key)
788
+
789
+ for key, j in by_key.items():
790
+ if key in matched:
791
+ continue
792
+ from core_lib.jurisdictions.jurisdiction_id import _PREFIXED_USPS_GEOID_RE
793
+
794
+ if _PREFIXED_USPS_GEOID_RE.match((j.jurisdiction_id or "").strip()):
795
+ continue
796
+ normalize_jurisdiction_run(j)
797
+ merged.append(j)
798
+
799
+ job.jurisdictions = merged
800
+ if not int(cfg.get("total_jurisdictions") or 0):
801
+ job.config["total_jurisdictions"] = len(merged)
802
+
803
+
804
+ @dataclass
805
+ class VideoResult:
806
+ video_id: str
807
+ title: str = ""
808
+ status: str = "pending" # ok | fail | tombstoned | empty | rate_limit | skipped
809
+ error: str = ""
810
+ transcript_source: str = ""
811
+ finished_at: str = ""
812
+ duration_seconds: Optional[float] = None
813
+
814
+
815
+ @dataclass
816
+ class JurisdictionRun:
817
+ state_code: str
818
+ jurisdiction_id: str
819
+ jurisdiction_name: str = ""
820
+ jurisdiction_type: str = ""
821
+ status: str = "pending" # pending | running | completed | failed
822
+ started_at: str = ""
823
+ updated_at: str = ""
824
+ finished_at: str = ""
825
+ elapsed_seconds: float = 0.0
826
+ exit_code: int = 0
827
+ stats: Dict[str, int] = field(default_factory=dict)
828
+ videos: List[VideoResult] = field(default_factory=list)
829
+ file_counts: Dict[str, int] = field(
830
+ default_factory=lambda: {"transcripts": 0, "analysis": 0, "reports": 0}
831
+ )
832
+ current_video_id: str = ""
833
+ current_video_title: str = ""
834
+ current_video_started_at: str = ""
835
+
836
+
837
+ @dataclass
838
+ class BatchJob:
839
+ batch_id: str
840
+ step: str
841
+ status: str = "running" # running | completed | failed | cancelled
842
+ started_at: str = ""
843
+ updated_at: str = ""
844
+ finished_at: str = ""
845
+ config: Dict[str, Any] = field(default_factory=dict)
846
+ summary: Dict[str, Any] = field(default_factory=dict)
847
+ jurisdictions: List[JurisdictionRun] = field(default_factory=list)
848
+
849
+ def to_dict(self) -> Dict[str, Any]:
850
+ return asdict(self)
851
+
852
+ @classmethod
853
+ def from_dict(cls, data: Dict[str, Any]) -> BatchJob:
854
+ jurs = []
855
+ for j in data.get("jurisdictions") or []:
856
+ videos = []
857
+ for v in j.get("videos") or []:
858
+ vd = dict(v)
859
+ if "duration_seconds" not in vd:
860
+ vd["duration_seconds"] = None
861
+ elif vd["duration_seconds"] is not None:
862
+ try:
863
+ vd["duration_seconds"] = float(vd["duration_seconds"])
864
+ except (TypeError, ValueError):
865
+ vd["duration_seconds"] = None
866
+ videos.append(VideoResult(**vd))
867
+ jurs.append(
868
+ JurisdictionRun(
869
+ state_code=j.get("state_code", ""),
870
+ jurisdiction_id=j.get("jurisdiction_id", ""),
871
+ jurisdiction_name=j.get("jurisdiction_name", ""),
872
+ jurisdiction_type=str(j.get("jurisdiction_type") or ""),
873
+ status=j.get("status", "pending"),
874
+ started_at=j.get("started_at", ""),
875
+ updated_at=j.get("updated_at", ""),
876
+ finished_at=j.get("finished_at", ""),
877
+ elapsed_seconds=float(j.get("elapsed_seconds") or 0),
878
+ exit_code=int(j.get("exit_code") or 0),
879
+ stats=dict(j.get("stats") or {}),
880
+ videos=videos,
881
+ file_counts=dict(
882
+ j.get("file_counts")
883
+ or {"transcripts": 0, "analysis": 0, "reports": 0}
884
+ ),
885
+ current_video_id=j.get("current_video_id", ""),
886
+ current_video_title=j.get("current_video_title", ""),
887
+ current_video_started_at=j.get("current_video_started_at", ""),
888
+ )
889
+ )
890
+ return cls(
891
+ batch_id=data["batch_id"],
892
+ step=data.get("step", ""),
893
+ status=data.get("status", "running"),
894
+ started_at=data.get("started_at", ""),
895
+ updated_at=data.get("updated_at", ""),
896
+ finished_at=data.get("finished_at", ""),
897
+ config=dict(data.get("config") or {}),
898
+ summary=dict(data.get("summary") or {}),
899
+ jurisdictions=jurs,
900
+ )
901
+
902
+
903
+ _VIDEO_COUNT_KEYS = ("ok", "fail", "tombstoned", "empty", "rate_limit")
904
+
905
+ _STATUS_TO_STAT_KEY: Dict[str, str] = {
906
+ "ok": "ok",
907
+ "fail": "fail",
908
+ "tombstoned": "tombstoned",
909
+ "empty": "empty",
910
+ "rate_limit": "rate_limit",
911
+ }
912
+
913
+
914
+ def _disk_file_count(fc: Dict[str, int], disk_key: str, legacy_key: str) -> int:
915
+ """Prefer explicit ``*_disk`` keys; fall back to legacy ``transcripts`` / ``analysis`` keys."""
916
+ if disk_key in fc:
917
+ return int(fc.get(disk_key) or 0)
918
+ return int(fc.get(legacy_key) or 0)
919
+
920
+
921
+ def transcript_seconds_from_job_videos(job: BatchJob) -> float:
922
+ """Sum ``duration_seconds`` for batch video rows with status ``ok``."""
923
+ total = 0.0
924
+ for j in job.jurisdictions:
925
+ for v in j.videos or []:
926
+ if (v.status or "").strip().lower() != "ok":
927
+ continue
928
+ if v.duration_seconds is None:
929
+ continue
930
+ total += float(v.duration_seconds)
931
+ return total
932
+
933
+
934
+ def _jurisdiction_video_counts(j: JurisdictionRun) -> Dict[str, int]:
935
+ """Count finished videos for summary totals.
936
+
937
+ While a jurisdiction is running, ``record_video`` appends to ``j.videos`` but
938
+ ``jurisdiction_finish`` has not written final ``j.stats`` yet — prefer the video
939
+ list so the dashboard does not lag behind jurisdiction success counts.
940
+ """
941
+ if j.videos:
942
+ counts = {k: 0 for k in _VIDEO_COUNT_KEYS}
943
+ for v in j.videos:
944
+ key = _STATUS_TO_STAT_KEY.get((v.status or "").strip().lower())
945
+ if key:
946
+ counts[key] += 1
947
+ return counts
948
+ return {k: int((j.stats or {}).get(k) or 0) for k in _VIDEO_COUNT_KEYS}
949
+
950
+
951
+ def _running_file_clock(
952
+ j: JurisdictionRun, now: datetime
953
+ ) -> tuple[Optional[float], str, str, str]:
954
+ """
955
+ Seconds on the in-flight video for a running jurisdiction.
956
+
957
+ Uses explicit ``current_video_started_at`` when set; otherwise time since the
958
+ last completed video in this run, or since the jurisdiction started.
959
+ """
960
+ if j.status != "running":
961
+ return None, "", "", ""
962
+
963
+ if j.current_video_started_at:
964
+ try:
965
+ start = datetime.fromisoformat(
966
+ j.current_video_started_at.replace("Z", "+00:00")
967
+ )
968
+ secs = max(0.0, (now - start).total_seconds())
969
+ return (
970
+ secs,
971
+ j.current_video_id or "",
972
+ (j.current_video_title or "")[:120],
973
+ j.current_video_started_at,
974
+ )
975
+ except ValueError:
976
+ pass
977
+
978
+ start_iso = ""
979
+ video_id = ""
980
+ title = ""
981
+ if j.videos:
982
+ last = j.videos[-1]
983
+ if last.finished_at:
984
+ start_iso = last.finished_at
985
+ video_id = last.video_id
986
+ title = (last.title or "")[:120]
987
+ if not start_iso and j.started_at:
988
+ start_iso = j.started_at
989
+ if not start_iso:
990
+ return None, video_id, title, ""
991
+
992
+ try:
993
+ start = datetime.fromisoformat(start_iso.replace("Z", "+00:00"))
994
+ secs = max(0.0, (now - start).total_seconds())
995
+ return secs, video_id, title, start_iso
996
+ except ValueError:
997
+ return None, video_id, title, start_iso
998
+
999
+
1000
+ def apply_batch_lifecycle(job: BatchJob) -> bool:
1001
+ """Stale-cancel inactive runs, then auto-finish when the plan is done. Returns True if status changed."""
1002
+ before = (job.status or "").lower()
1003
+ _maybe_stale_cancel_batch(job)
1004
+ _maybe_auto_finish_batch(job)
1005
+ return before != (job.status or "").lower()
1006
+
1007
+
1008
+ def _maybe_auto_finish_batch(job: BatchJob) -> None:
1009
+ """
1010
+ Mark the batch completed when every target jurisdiction is done.
1011
+
1012
+ Progress cards use jurisdiction counts; ``job.status`` only flipped on ``finish_batch``
1013
+ before. Single-jurisdiction tests (or a killed shell after the last backfill) left
1014
+ ``running`` at 100%.
1015
+ """
1016
+ if job.status != "running":
1017
+ return
1018
+ total_j = int(job.config.get("total_jurisdictions") or 0) or len(job.jurisdictions)
1019
+ if total_j <= 0:
1020
+ return
1021
+ if any(j.status == "running" for j in job.jurisdictions):
1022
+ return
1023
+ processed = sum(1 for j in job.jurisdictions if j.status in ("completed", "failed"))
1024
+ if processed < total_j:
1025
+ return
1026
+ job.status = "completed"
1027
+ if not job.finished_at:
1028
+ job.finished_at = _utc_now_iso()
1029
+
1030
+
1031
+ def _recompute_summary(job: BatchJob) -> None:
1032
+ if (job.status or "").lower() == "running":
1033
+ _maybe_stale_cancel_batch(job)
1034
+ total_j = int(job.config.get("total_jurisdictions") or 0) or len(job.jurisdictions)
1035
+ processed = sum(1 for j in job.jurisdictions if j.status in ("completed", "failed"))
1036
+ success = sum(1 for j in job.jurisdictions if j.status == "completed" and j.exit_code == 0)
1037
+ failed = sum(1 for j in job.jurisdictions if j.status == "failed" or j.exit_code != 0)
1038
+ remaining = max(0, total_j - processed)
1039
+
1040
+ v_ok = v_fail = v_tomb = v_empty = v_rl = 0
1041
+ for j in job.jurisdictions:
1042
+ counts = _jurisdiction_video_counts(j)
1043
+ v_ok += counts["ok"]
1044
+ v_fail += counts["fail"]
1045
+ v_tomb += counts["tombstoned"]
1046
+ v_empty += counts["empty"]
1047
+ v_rl += counts["rate_limit"]
1048
+
1049
+ elapsed = 0.0
1050
+ if job.started_at:
1051
+ try:
1052
+ start = datetime.fromisoformat(job.started_at.replace("Z", "+00:00"))
1053
+ end = (
1054
+ datetime.fromisoformat(job.finished_at.replace("Z", "+00:00"))
1055
+ if job.finished_at
1056
+ else datetime.now(timezone.utc)
1057
+ )
1058
+ elapsed = max(0.0, (end - start).total_seconds())
1059
+ except ValueError:
1060
+ elapsed = 0.0
1061
+
1062
+ eta_seconds: Optional[float] = None
1063
+ if processed > 0 and remaining > 0 and elapsed > 0:
1064
+ eta_seconds = (elapsed / processed) * remaining
1065
+
1066
+ disk = {"transcripts": 0, "analysis": 0, "reports": 0}
1067
+ recent = {"analysis": 0, "reports": 0}
1068
+ bronze_download_rows = 0
1069
+ for j in job.jurisdictions:
1070
+ fc = j.file_counts or {}
1071
+ disk["transcripts"] += _disk_file_count(
1072
+ fc, "transcripts_disk", "transcripts"
1073
+ )
1074
+ disk["analysis"] += _disk_file_count(fc, "analysis_disk", "analysis")
1075
+ disk["reports"] += _disk_file_count(fc, "reports_disk", "reports")
1076
+ recent["analysis"] += int(fc.get("analysis_recent") or 0)
1077
+ recent["reports"] += int(fc.get("reports_recent") or 0)
1078
+ bronze_download_rows += int(fc.get("bronze_download_rows") or 0)
1079
+
1080
+ files_processed = v_ok + v_fail + v_tomb + v_empty + v_rl
1081
+ videos_attempted = files_processed
1082
+ avg_seconds_per_file: Optional[float] = None
1083
+ if files_processed > 0 and elapsed > 0:
1084
+ avg_seconds_per_file = round(elapsed / files_processed, 1)
1085
+
1086
+ current_file_seconds: Optional[float] = None
1087
+ current_video_id = ""
1088
+ current_video_title = ""
1089
+ current_jurisdiction_id = ""
1090
+ current_video_started_at = ""
1091
+ now = datetime.now(timezone.utc)
1092
+ for j in job.jurisdictions:
1093
+ secs, vid, title, started_iso = _running_file_clock(j, now)
1094
+ if secs is None:
1095
+ continue
1096
+ if current_file_seconds is None or secs >= current_file_seconds:
1097
+ current_file_seconds = secs
1098
+ current_video_id = vid
1099
+ current_video_title = title
1100
+ current_jurisdiction_id = j.jurisdiction_id
1101
+ current_video_started_at = started_iso
1102
+
1103
+ job.summary = {
1104
+ "total_jurisdictions": total_j,
1105
+ "processed_jurisdictions": processed,
1106
+ "success_jurisdictions": success,
1107
+ "failed_jurisdictions": failed,
1108
+ "remaining_jurisdictions": remaining,
1109
+ "elapsed_seconds": round(elapsed, 1),
1110
+ "eta_seconds": round(eta_seconds, 1) if eta_seconds is not None else None,
1111
+ "videos_ok": v_ok,
1112
+ "videos_fail": v_fail,
1113
+ "videos_tombstoned": v_tomb,
1114
+ "videos_empty": v_empty,
1115
+ "videos_rate_limit": v_rl,
1116
+ # Batch-scoped caption outcomes (same source as Videos OK / fail cards).
1117
+ "files_transcripts": v_ok,
1118
+ "files_processed": files_processed,
1119
+ "videos_attempted": videos_attempted,
1120
+ # Policy cache on disk (all JSON under each jurisdiction folder, not this run only).
1121
+ "files_transcripts_disk": disk["transcripts"],
1122
+ "files_analysis": disk["analysis"],
1123
+ "files_reports": disk["reports"],
1124
+ # Rolling 24h throughput: analyses summarised / reports generated whose
1125
+ # files were last written within the past day (mtime-based).
1126
+ "files_analysis_recent": recent["analysis"],
1127
+ "files_reports_recent": recent["reports"],
1128
+ # Bronze rows with transcript_download_at (lifetime per jurisdiction).
1129
+ "bronze_download_rows": bronze_download_rows,
1130
+ "transcript_seconds": round(transcript_seconds_from_job_videos(job), 1),
1131
+ "avg_seconds_per_file": avg_seconds_per_file,
1132
+ "current_file_seconds": (
1133
+ round(current_file_seconds, 1)
1134
+ if current_file_seconds is not None
1135
+ else None
1136
+ ),
1137
+ "current_video_id": current_video_id,
1138
+ "current_video_title": current_video_title,
1139
+ "current_jurisdiction_id": current_jurisdiction_id,
1140
+ "current_video_started_at": current_video_started_at,
1141
+ **state_progress_for_job(job),
1142
+ }
1143
+ _maybe_auto_finish_batch(job)
1144
+
1145
+
1146
+ class BatchJobStore:
1147
+ def __init__(self, batch_id: str, *, jobs_root: Optional[Path] = None) -> None:
1148
+ self.batch_id = batch_id
1149
+ self.root = jobs_root or jobs_dir()
1150
+ self.root.mkdir(parents=True, exist_ok=True)
1151
+ self.path = self.root / f"{batch_id}.json"
1152
+
1153
+ def load(self) -> BatchJob:
1154
+ if not self.path.is_file():
1155
+ raise FileNotFoundError(self.path)
1156
+ data = json.loads(self.path.read_text(encoding="utf-8"))
1157
+ return BatchJob.from_dict(data)
1158
+
1159
+ def save(self, job: BatchJob) -> None:
1160
+ job.updated_at = _utc_now_iso()
1161
+ _recompute_summary(job)
1162
+ tmp = self.path.with_suffix(".json.tmp")
1163
+ tmp.write_text(
1164
+ json.dumps(job.to_dict(), indent=2, ensure_ascii=False) + "\n",
1165
+ encoding="utf-8",
1166
+ )
1167
+ tmp.replace(self.path)
1168
+ _update_index(self.root, job)
1169
+ try:
1170
+ from api.batch_jobs.batch_job_db import sync_batch_job_to_db
1171
+
1172
+ sync_batch_job_to_db(job)
1173
+ except Exception:
1174
+ pass
1175
+
1176
+ def start_batch(
1177
+ self,
1178
+ *,
1179
+ step: str,
1180
+ config: Optional[Dict[str, Any]] = None,
1181
+ ) -> BatchJob:
1182
+ now = _utc_now_iso()
1183
+ cfg = dict(config or {})
1184
+ job = BatchJob(
1185
+ batch_id=self.batch_id,
1186
+ step=step,
1187
+ status="running",
1188
+ started_at=now,
1189
+ updated_at=now,
1190
+ config=cfg,
1191
+ )
1192
+ states = cfg.get("states") or []
1193
+ if states and cfg.get("seed_plan") is not False:
1194
+ plan = fetch_batch_plan_jurisdictions(
1195
+ states,
1196
+ round_robin=bool(cfg.get("round_robin", True)),
1197
+ )
1198
+ if plan:
1199
+ job.jurisdictions = plan
1200
+ if not int(cfg.get("total_jurisdictions") or 0):
1201
+ cfg["total_jurisdictions"] = len(plan)
1202
+ job.config = cfg
1203
+ self.save(job)
1204
+ return job
1205
+
1206
+ def finish_batch(self, *, status: str = "completed") -> BatchJob:
1207
+ job = self.load()
1208
+ job.status = status
1209
+ job.finished_at = _utc_now_iso()
1210
+ self.save(job)
1211
+ return job
1212
+
1213
+ def jurisdiction_start(
1214
+ self,
1215
+ *,
1216
+ state_code: str,
1217
+ jurisdiction_id: str,
1218
+ jurisdiction_name: str = "",
1219
+ pending_videos: int = 0,
1220
+ ) -> JurisdictionRun:
1221
+ from core_lib.jurisdictions.jurisdiction_id import resolve_canonical_jurisdiction_id
1222
+
1223
+ jurisdiction_id = resolve_canonical_jurisdiction_id(
1224
+ jurisdiction_id.strip(),
1225
+ name=(jurisdiction_name or "").strip() or None,
1226
+ )
1227
+ job = self.load()
1228
+ now = _utc_now_iso()
1229
+ run = JurisdictionRun(
1230
+ state_code=state_code.upper(),
1231
+ jurisdiction_id=jurisdiction_id,
1232
+ jurisdiction_name=jurisdiction_name,
1233
+ status="running",
1234
+ started_at=now,
1235
+ updated_at=now,
1236
+ )
1237
+ if pending_videos:
1238
+ run.stats["pending"] = pending_videos
1239
+ start_key = _plan_jurisdiction_key(jurisdiction_id)
1240
+ job.jurisdictions = [
1241
+ j
1242
+ for j in job.jurisdictions
1243
+ if _plan_jurisdiction_key(j.jurisdiction_id) != start_key
1244
+ ]
1245
+ job.jurisdictions.append(run)
1246
+ self.save(job)
1247
+ return run
1248
+
1249
+ def _find_jurisdiction(self, job: BatchJob, jurisdiction_id: str) -> JurisdictionRun:
1250
+ from core_lib.jurisdictions.jurisdiction_id import resolve_canonical_jurisdiction_id
1251
+
1252
+ jid = resolve_canonical_jurisdiction_id((jurisdiction_id or "").strip()) or (
1253
+ jurisdiction_id or ""
1254
+ ).strip()
1255
+ key = _plan_jurisdiction_key(jid)
1256
+ for j in job.jurisdictions:
1257
+ if j.jurisdiction_id == jid:
1258
+ return j
1259
+ if key and _plan_jurisdiction_key(j.jurisdiction_id) == key:
1260
+ return j
1261
+ raise KeyError(jurisdiction_id)
1262
+
1263
+ def video_start(
1264
+ self,
1265
+ *,
1266
+ jurisdiction_id: str,
1267
+ video_id: str,
1268
+ title: str = "",
1269
+ ) -> None:
1270
+ job = self.load()
1271
+ j = self._find_jurisdiction(job, jurisdiction_id)
1272
+ j.current_video_id = video_id
1273
+ j.current_video_title = (title or "")[:200]
1274
+ j.current_video_started_at = _utc_now_iso()
1275
+ j.updated_at = j.current_video_started_at
1276
+ self.save(job)
1277
+
1278
+ def record_video(
1279
+ self,
1280
+ *,
1281
+ jurisdiction_id: str,
1282
+ video_id: str,
1283
+ status: str,
1284
+ title: str = "",
1285
+ error: str = "",
1286
+ transcript_source: str = "",
1287
+ duration_seconds: Optional[float] = None,
1288
+ ) -> None:
1289
+ job = self.load()
1290
+ j = self._find_jurisdiction(job, jurisdiction_id)
1291
+ if j.current_video_id == video_id:
1292
+ j.current_video_id = ""
1293
+ j.current_video_title = ""
1294
+ j.current_video_started_at = ""
1295
+ prior_status = ""
1296
+ for v in j.videos:
1297
+ if v.video_id == video_id:
1298
+ prior_status = (v.status or "").strip().lower()
1299
+ break
1300
+ j.videos = [v for v in j.videos if v.video_id != video_id]
1301
+ if prior_status:
1302
+ old_key = _STATUS_TO_STAT_KEY.get(prior_status)
1303
+ if old_key:
1304
+ j.stats[old_key] = max(0, int(j.stats.get(old_key) or 0) - 1)
1305
+ now = _utc_now_iso()
1306
+ j.videos.append(
1307
+ VideoResult(
1308
+ video_id=video_id,
1309
+ title=title[:200],
1310
+ status=status,
1311
+ error=(error or "")[:500],
1312
+ transcript_source=transcript_source,
1313
+ finished_at=now,
1314
+ duration_seconds=duration_seconds,
1315
+ )
1316
+ )
1317
+ new_key = _STATUS_TO_STAT_KEY.get((status or "").strip().lower())
1318
+ if new_key:
1319
+ j.stats[new_key] = int(j.stats.get(new_key) or 0) + 1
1320
+ j.updated_at = now
1321
+ self.save(job)
1322
+
1323
+ def jurisdiction_finish(
1324
+ self,
1325
+ *,
1326
+ jurisdiction_id: str,
1327
+ exit_code: int,
1328
+ stats: Optional[Dict[str, int]] = None,
1329
+ file_counts: Optional[Dict[str, int]] = None,
1330
+ ) -> None:
1331
+ job = self.load()
1332
+ j = self._find_jurisdiction(job, jurisdiction_id)
1333
+ j.status = "completed" if exit_code == 0 else "failed"
1334
+ j.exit_code = exit_code
1335
+ j.finished_at = _utc_now_iso()
1336
+ j.updated_at = j.finished_at
1337
+ j.current_video_id = ""
1338
+ j.current_video_title = ""
1339
+ j.current_video_started_at = ""
1340
+ if stats:
1341
+ j.stats = {k: int(v) for k, v in stats.items()}
1342
+ if file_counts:
1343
+ j.file_counts = {k: int(v) for k, v in file_counts.items()}
1344
+ if j.started_at:
1345
+ try:
1346
+ start = datetime.fromisoformat(j.started_at.replace("Z", "+00:00"))
1347
+ end = datetime.fromisoformat(j.finished_at.replace("Z", "+00:00"))
1348
+ j.elapsed_seconds = max(0.0, (end - start).total_seconds())
1349
+ except ValueError:
1350
+ j.elapsed_seconds = 0.0
1351
+ self.save(job)
1352
+
1353
+ def shell_jurisdiction_done(
1354
+ self,
1355
+ *,
1356
+ state_code: str,
1357
+ jurisdiction_id: str,
1358
+ jurisdiction_name: str,
1359
+ exit_code: int,
1360
+ ) -> None:
1361
+ """Mark jurisdiction when backfill did not write status (crash / missing --batch-id)."""
1362
+ try:
1363
+ job = self.load()
1364
+ self._find_jurisdiction(job, jurisdiction_id)
1365
+ except (FileNotFoundError, KeyError):
1366
+ self.jurisdiction_start(
1367
+ state_code=state_code,
1368
+ jurisdiction_id=jurisdiction_id,
1369
+ jurisdiction_name=jurisdiction_name,
1370
+ )
1371
+ self.jurisdiction_finish(
1372
+ jurisdiction_id=jurisdiction_id,
1373
+ exit_code=exit_code,
1374
+ stats={"shell_exit": exit_code},
1375
+ )
1376
+
1377
+
1378
+ def _update_index(root: Path, job: BatchJob) -> None:
1379
+ index_path = root / _INDEX_NAME
1380
+ entries: List[Dict[str, Any]] = []
1381
+ if index_path.is_file():
1382
+ try:
1383
+ entries = json.loads(index_path.read_text(encoding="utf-8"))
1384
+ except json.JSONDecodeError:
1385
+ entries = []
1386
+ entries = [e for e in entries if e.get("batch_id") != job.batch_id]
1387
+ entries.insert(
1388
+ 0,
1389
+ {
1390
+ "batch_id": job.batch_id,
1391
+ "step": job.step,
1392
+ "status": job.status,
1393
+ "started_at": job.started_at,
1394
+ "updated_at": job.updated_at,
1395
+ "summary": job.summary,
1396
+ },
1397
+ )
1398
+ entries = entries[:200]
1399
+ index_path.write_text(json.dumps(entries, indent=2) + "\n", encoding="utf-8")
1400
+
1401
+
1402
+ def policy_disk_file_counts(scanned: Dict[str, int]) -> Dict[str, int]:
1403
+ """Map ``count_policy_files_for_jurisdiction`` keys to explicit on-disk counters."""
1404
+ return {
1405
+ "transcripts_disk": int(scanned.get("transcripts") or 0),
1406
+ "analysis_disk": int(scanned.get("analysis") or 0),
1407
+ "reports_disk": int(scanned.get("reports") or 0),
1408
+ # Rolling 24h throughput (mtime within the last day); 0 when the scanner
1409
+ # couldn't attribute per-jurisdiction stats (legacy fallback path).
1410
+ "analysis_recent": int(scanned.get("analysis_recent") or 0),
1411
+ "reports_recent": int(scanned.get("reports_recent") or 0),
1412
+ }
1413
+
1414
+
1415
+ def count_policy_files_for_jurisdiction(
1416
+ cache_root: Path,
1417
+ *,
1418
+ state_code: str,
1419
+ jurisdiction_id: str,
1420
+ ) -> Dict[str, int]:
1421
+ """Count transcript/analysis/report files under policy cache for one jurisdiction."""
1422
+ from llm.gemini.policy_processing_status_report import (
1423
+ _DIR_ANALYSIS,
1424
+ _DIR_REPORTS,
1425
+ _DIR_TRANSCRIPTS,
1426
+ scan_jurisdiction_cache,
1427
+ )
1428
+
1429
+ counts = {
1430
+ "transcripts": 0,
1431
+ "analysis": 0,
1432
+ "reports": 0,
1433
+ "analysis_recent": 0,
1434
+ "reports_recent": 0,
1435
+ }
1436
+ if not cache_root.is_dir():
1437
+ return counts
1438
+ by_jid = scan_jurisdiction_cache(cache_root)
1439
+ st = by_jid.get(jurisdiction_id)
1440
+ if st:
1441
+ counts["transcripts"] = st.transcripts
1442
+ counts["analysis"] = st.analysis_json
1443
+ counts["reports"] = st.reports_md
1444
+ counts["analysis_recent"] = st.analysis_recent
1445
+ counts["reports_recent"] = st.reports_recent
1446
+ return counts
1447
+
1448
+ state = (state_code or "").upper()
1449
+ jid = jurisdiction_id.lower()
1450
+ for state_dir in cache_root.iterdir():
1451
+ if not state_dir.is_dir() or state_dir.name.upper() != state:
1452
+ continue
1453
+ for type_dir in state_dir.iterdir():
1454
+ if not type_dir.is_dir():
1455
+ continue
1456
+ for jdir in type_dir.iterdir():
1457
+ if jdir.name.lower() != jid and jid not in jdir.name.lower():
1458
+ continue
1459
+ for ch in jdir.iterdir():
1460
+ if not ch.is_dir():
1461
+ continue
1462
+ tx = ch / _DIR_TRANSCRIPTS
1463
+ if tx.is_dir():
1464
+ counts["transcripts"] += sum(
1465
+ 1 for p in tx.glob("*.json") if p.is_file()
1466
+ )
1467
+ an = ch / _DIR_ANALYSIS
1468
+ if an.is_dir():
1469
+ counts["analysis"] += sum(
1470
+ 1
1471
+ for p in an.glob("*.json")
1472
+ if p.is_file() and not p.name.startswith("_")
1473
+ )
1474
+ rp = ch / _DIR_REPORTS
1475
+ if rp.is_dir():
1476
+ counts["reports"] += sum(
1477
+ 1 for p in rp.glob("*.md") if p.is_file()
1478
+ )
1479
+ return counts
1480
+
1481
+
1482
+ def list_batches(*, limit: int = 50) -> List[BatchJob]:
1483
+ root = jobs_dir()
1484
+ jobs: List[BatchJob] = []
1485
+ index_path = root / _INDEX_NAME
1486
+ ids: List[str] = []
1487
+ if index_path.is_file():
1488
+ try:
1489
+ for row in json.loads(index_path.read_text(encoding="utf-8")):
1490
+ bid = row.get("batch_id")
1491
+ if bid:
1492
+ ids.append(bid)
1493
+ except json.JSONDecodeError:
1494
+ pass
1495
+ if not ids:
1496
+ ids = sorted(
1497
+ (p.stem for p in root.glob("*.json") if p.name != _INDEX_NAME),
1498
+ reverse=True,
1499
+ )
1500
+ for bid in ids[:limit]:
1501
+ path = root / f"{bid}.json"
1502
+ if path.is_file():
1503
+ try:
1504
+ jobs.append(BatchJob.from_dict(json.loads(path.read_text(encoding="utf-8"))))
1505
+ except (json.JSONDecodeError, KeyError):
1506
+ continue
1507
+ return jobs
1508
+
1509
+
1510
+ def _cli_start(args: argparse.Namespace) -> int:
1511
+ batch_id = (args.batch_id or "").strip() or new_batch_id(args.step)
1512
+ store = BatchJobStore(batch_id)
1513
+ config = {
1514
+ "states": [s.strip().upper() for s in (args.states or "").split(",") if s.strip()],
1515
+ "n": args.n,
1516
+ "delay": args.delay,
1517
+ "total_jurisdictions": args.total_jurisdictions,
1518
+ "transcript_source": args.transcript_source or "",
1519
+ "max_jurisdictions": args.max_jurisdictions or 0,
1520
+ "round_robin": bool(getattr(args, "round_robin", 1)),
1521
+ "seed_plan": not getattr(args, "no_seed_plan", False),
1522
+ }
1523
+ store.start_batch(step=args.step, config=config)
1524
+ print(batch_id)
1525
+ return 0
1526
+
1527
+
1528
+ def _cli_jurisdiction_start(args: argparse.Namespace) -> int:
1529
+ store = BatchJobStore(args.batch_id)
1530
+ store.jurisdiction_start(
1531
+ state_code=args.state,
1532
+ jurisdiction_id=args.jurisdiction_id,
1533
+ jurisdiction_name=args.jurisdiction_name or "",
1534
+ pending_videos=args.pending_videos,
1535
+ )
1536
+ return 0
1537
+
1538
+
1539
+ def _cli_jurisdiction_finish(args: argparse.Namespace) -> int:
1540
+ store = BatchJobStore(args.batch_id)
1541
+ stats = json.loads(args.stats) if args.stats else {}
1542
+ store.jurisdiction_finish(
1543
+ jurisdiction_id=args.jurisdiction_id,
1544
+ exit_code=args.exit_code,
1545
+ stats=stats,
1546
+ )
1547
+ return 0
1548
+
1549
+
1550
+ def _cli_finish(args: argparse.Namespace) -> int:
1551
+ store = BatchJobStore(args.batch_id)
1552
+ store.finish_batch(status=args.status)
1553
+ return 0
1554
+
1555
+
1556
+ def main() -> int:
1557
+ parser = argparse.ArgumentParser(description=__doc__)
1558
+ sub = parser.add_subparsers(dest="command", required=True)
1559
+
1560
+ p_start = sub.add_parser("start", help="Create a new batch job file")
1561
+ p_start.add_argument("--step", required=True)
1562
+ p_start.add_argument("--batch-id", default="")
1563
+ p_start.add_argument("--states", default="")
1564
+ p_start.add_argument("--n", type=int, default=0)
1565
+ p_start.add_argument("--delay", type=float, default=0)
1566
+ p_start.add_argument("--total-jurisdictions", type=int, default=0)
1567
+ p_start.add_argument("--transcript-source", default="")
1568
+ p_start.add_argument("--max-jurisdictions", type=int, default=0)
1569
+ p_start.add_argument(
1570
+ "--round-robin",
1571
+ type=int,
1572
+ default=1,
1573
+ help="1 = interleave states in plan order (default), 0 = state-by-state",
1574
+ )
1575
+ p_start.add_argument(
1576
+ "--no-seed-plan",
1577
+ action="store_true",
1578
+ help="Do not pre-load all jurisdictions as pending rows",
1579
+ )
1580
+ p_start.set_defaults(func=_cli_start)
1581
+
1582
+ p_js = sub.add_parser("jurisdiction-start")
1583
+ p_js.add_argument("--batch-id", required=True)
1584
+ p_js.add_argument("--state", required=True)
1585
+ p_js.add_argument("--jurisdiction-id", required=True)
1586
+ p_js.add_argument("--jurisdiction-name", default="")
1587
+ p_js.add_argument("--pending-videos", type=int, default=0)
1588
+ p_js.set_defaults(func=_cli_jurisdiction_start)
1589
+
1590
+ p_jf = sub.add_parser("jurisdiction-finish")
1591
+ p_jf.add_argument("--batch-id", required=True)
1592
+ p_jf.add_argument("--jurisdiction-id", required=True)
1593
+ p_jf.add_argument("--exit-code", type=int, default=0)
1594
+ p_jf.add_argument("--stats", default="")
1595
+ p_jf.set_defaults(func=_cli_jurisdiction_finish)
1596
+
1597
+ p_fin = sub.add_parser("finish")
1598
+ p_fin.add_argument("--batch-id", required=True)
1599
+ p_fin.add_argument("--status", default="completed")
1600
+ p_fin.set_defaults(func=_cli_finish)
1601
+
1602
+ args = parser.parse_args()
1603
+ return int(args.func(args))
1604
+
1605
+
1606
+ if __name__ == "__main__":
1607
+ raise SystemExit(main())
api/batch_jobs/cohorts.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Batch-job launch cohorts: priority states, data centers, or all US states."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any, Literal, Optional, Sequence
5
+
6
+ CohortName = Literal["priority", "data_centers", "all"]
7
+ PRIORITY_STATE_CODES = ["AL", "GA", "IN", "MA", "MT", "WA", "WI"]
8
+
9
+ # 50 US states + DC — keep in sync with web_app/src/lib/usStates.ts (STATE_CODES).
10
+ ALL_STATE_CODES = [
11
+ "AL",
12
+ "AK",
13
+ "AZ",
14
+ "AR",
15
+ "CA",
16
+ "CO",
17
+ "CT",
18
+ "DE",
19
+ "DC",
20
+ "FL",
21
+ "GA",
22
+ "HI",
23
+ "ID",
24
+ "IL",
25
+ "IN",
26
+ "IA",
27
+ "KS",
28
+ "KY",
29
+ "LA",
30
+ "ME",
31
+ "MD",
32
+ "MA",
33
+ "MI",
34
+ "MN",
35
+ "MS",
36
+ "MO",
37
+ "MT",
38
+ "NE",
39
+ "NV",
40
+ "NH",
41
+ "NJ",
42
+ "NM",
43
+ "NY",
44
+ "NC",
45
+ "ND",
46
+ "OH",
47
+ "OK",
48
+ "OR",
49
+ "PA",
50
+ "RI",
51
+ "SC",
52
+ "SD",
53
+ "TN",
54
+ "TX",
55
+ "UT",
56
+ "VT",
57
+ "VA",
58
+ "WA",
59
+ "WV",
60
+ "WI",
61
+ "WY",
62
+ ]
63
+
64
+ DATA_CENTER_JURISDICTION_IDS_SQL = """
65
+ SELECT DISTINCT jurisdiction_id FROM (
66
+ SELECT jurisdiction_id FROM intermediate.int_data_center_site__jurisdiction
67
+ WHERE jurisdiction_id IS NOT NULL AND BTRIM(jurisdiction_id) <> ''
68
+ UNION
69
+ SELECT jurisdiction_id FROM public.data_center_meeting_mention
70
+ WHERE jurisdiction_id IS NOT NULL AND BTRIM(jurisdiction_id) <> ''
71
+ ) u
72
+ """
73
+
74
+
75
+ def data_center_jurisdiction_ids(conn: Any) -> set[str]:
76
+ with conn.cursor() as cur:
77
+ cur.execute(DATA_CENTER_JURISDICTION_IDS_SQL)
78
+ return {str(r[0]) for r in cur.fetchall() if r and r[0]}
79
+
80
+
81
+ def cohort_state_codes(
82
+ cohort: CohortName,
83
+ *,
84
+ conn: Any = None,
85
+ all_states: Optional[Sequence[str]] = None,
86
+ ) -> list[str]:
87
+ if cohort == "priority":
88
+ return list(PRIORITY_STATE_CODES)
89
+ if cohort == "all":
90
+ return list(all_states or ALL_STATE_CODES)
91
+ if cohort == "data_centers":
92
+ if conn is None:
93
+ raise ValueError("data_centers cohort requires a database connection")
94
+ jids = list(data_center_jurisdiction_ids(conn))
95
+ with conn.cursor() as cur:
96
+ cur.execute(
97
+ """
98
+ SELECT DISTINCT state_code FROM intermediate.int_jurisdictions
99
+ WHERE jurisdiction_id = ANY(%s) AND state_code IS NOT NULL
100
+ ORDER BY 1
101
+ """,
102
+ (jids,),
103
+ )
104
+ return [str(r[0]) for r in cur.fetchall()]
105
+ raise ValueError(f"unknown cohort: {cohort}")
106
+
107
+
108
+ def resolve_launch_states(
109
+ cohort: CohortName,
110
+ states: Sequence[str],
111
+ *,
112
+ conn: Any = None,
113
+ ) -> list[str]:
114
+ allowed = cohort_state_codes(cohort, conn=conn)
115
+ allowed_set = set(allowed)
116
+ wanted = [s.strip().upper() for s in states if (s or "").strip()]
117
+ if not wanted:
118
+ if not allowed:
119
+ raise ValueError(f"cohort {cohort!r} has no states")
120
+ return list(allowed)
121
+ bad = [s for s in wanted if s not in allowed_set]
122
+ if bad:
123
+ raise ValueError(f"state code(s) not in cohort {cohort!r}: {bad}")
124
+ return wanted
api/batch_jobs/failure_reasons.py ADDED
@@ -0,0 +1,584 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Why did these videos fail? Group ``transcript_file_error`` by reason (#792).
2
+
3
+ The Videos and Transcripts stage rows on Batch Job Status both show a failed count, and both count
4
+ ``bronze.bronze_event_youtube`` rows whose ``transcript_file_error`` is not NULL
5
+ (``pipeline_stage_report``). This module reads the same rows with the same cohort and state filters,
6
+ so the reason counts add up to exactly that number.
7
+
8
+ Grouping is by keyword on the stored text. The raw text is always returned next to its group, and
9
+ text that matches no known group is "other" with its raw text, never reworded.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import re
16
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
17
+
18
+ # (key, label, advice). The first keyword match wins, in the order of _KEYWORDS below.
19
+ GROUPS: List[Tuple[str, str, str]] = [
20
+ (
21
+ "bot_block",
22
+ "YouTube blocked the request (bot check)",
23
+ "Refresh youtube_cookies.txt (older than 7 days is the usual cause) and check the VPN is up, then retry.",
24
+ ),
25
+ (
26
+ "rate_limit",
27
+ "Rate limited or over quota",
28
+ "Slow down: wait, then retry a smaller batch. Do not shorten the delay or add parallel caption fetches.",
29
+ ),
30
+ (
31
+ "network",
32
+ "Network, proxy or VPN problem",
33
+ "Check the VPN and the caption proxy are up, then retry.",
34
+ ),
35
+ (
36
+ "not_yet_available",
37
+ "Live event or premiere that has not started",
38
+ "Not a failure yet: YouTube has no captions until the event happens. Retry after it ends.",
39
+ ),
40
+ (
41
+ "no_captions",
42
+ "No captions on the video",
43
+ "Not fixable here: the video has no transcript to download. These stay failed.",
44
+ ),
45
+ (
46
+ "unavailable",
47
+ "Video private, removed or restricted",
48
+ "Not fixable here: the video is gone or not public. These stay failed.",
49
+ ),
50
+ (
51
+ "unknown",
52
+ "No reason recorded",
53
+ "The failure was stamped without any error text. Retry, and read the Transcripts log if it fails again.",
54
+ ),
55
+ (
56
+ "other",
57
+ "Other",
58
+ "Not recognised. Read the raw text below; if it repeats, it needs its own group.",
59
+ ),
60
+ ]
61
+ _META = {k: (label, advice) for k, label, advice in GROUPS}
62
+
63
+ # Groups where trying again can work. The rest (no captions, private or removed) stay failed.
64
+ RETRYABLE_GROUPS = frozenset(
65
+ {"bot_block", "rate_limit", "network", "not_yet_available", "unknown", "other"}
66
+ )
67
+
68
+ # Keyword tables, lower-case. Checked in this order against the CAUSE of the failure (see _cause).
69
+ _KEYWORDS: List[Tuple[str, Tuple[str, ...]]] = [
70
+ ("bot_block", ("sign in to confirm", "not a bot", "bot check", "bot detection")),
71
+ ("rate_limit", ("429", "too many requests", "rate limit", "rate-limit", "quota")),
72
+ ("not_yet_available", ("live event will begin", "premieres in", "premiere", "will begin in")),
73
+ (
74
+ "no_captions",
75
+ (
76
+ "no transcript",
77
+ "transcripts disabled",
78
+ "transcriptsdisabled",
79
+ "subtitles are disabled",
80
+ "no captions",
81
+ "no subtitles",
82
+ "notranscriptfound",
83
+ ),
84
+ ),
85
+ (
86
+ "unavailable",
87
+ (
88
+ "removed by the uploader",
89
+ "private video",
90
+ "video is private",
91
+ "is a private video",
92
+ "video unavailable",
93
+ "unavailable",
94
+ "has been removed",
95
+ "removed by",
96
+ "deleted",
97
+ "terminated",
98
+ "members-only",
99
+ "members only",
100
+ "age-restricted",
101
+ "age restricted",
102
+ "not available in your country",
103
+ ),
104
+ ),
105
+ (
106
+ "network",
107
+ (
108
+ "proxy",
109
+ "timed out",
110
+ "timeout",
111
+ "connection",
112
+ "ssl",
113
+ "name resolution",
114
+ "temporary failure",
115
+ "vpn",
116
+ "unreachable",
117
+ ),
118
+ ),
119
+ ]
120
+
121
+ # yt-dlp and youtube-transcript-api share one opening ("Could not retrieve a transcript for the video
122
+ # <url>! This is most likely caused by: <cause> If you are sure ..."). That opening says nothing about
123
+ # the failure, so classification reads the cause and ignores the rest.
124
+ _CAUSE = re.compile(r"most likely caused by:\s*(.*?)(?:\s*if you are sure|\s*$)", re.I | re.S)
125
+ _GENERIC_OPENING = re.compile(r"could not retrieve a transcript for the video\s+\S+?!", re.I)
126
+
127
+ STAGES = ("videos", "transcripts") # both count the same rows; see module docstring
128
+ _DIGITS = re.compile(r"[0-9]{3,}")
129
+ # A YouTube video id inside a message: only in `v=<id>` or `youtu.be/<id>` form, so an ordinary
130
+ # 11-letter word is never taken for one.
131
+ _VIDEO_ID = re.compile(r"(v=|youtu\.be/)[A-Za-z0-9_-]{11}")
132
+
133
+
134
+ def normalize_reason(text: Optional[str]) -> str:
135
+ """Merge messages that differ only by a video id or a long number (a byte count, a port).
136
+
137
+ Must stay identical to ``_NORM_SQL`` below, which groups in the database."""
138
+ t = _VIDEO_ID.sub(r"\1#", (text or "").strip())
139
+ return _DIGITS.sub("#", t)
140
+
141
+
142
+ def reason_id(normalized_reason: str) -> str:
143
+ """Short, URL-safe id for a normalized reason: its md5, same as ``md5()`` in Postgres (UTF-8)."""
144
+ return hashlib.md5((normalized_reason or "").encode("utf-8")).hexdigest()
145
+
146
+
147
+ def _cause(text: str) -> str:
148
+ """The part of a message that says why it failed (the text after "most likely caused by:")."""
149
+ m = _CAUSE.search(text)
150
+ if m and m.group(1).strip():
151
+ return m.group(1)
152
+ return _GENERIC_OPENING.sub("", text)
153
+
154
+
155
+ def classify_reason(text: Optional[str]) -> str:
156
+ """Group key for one stored error text."""
157
+ low = (text or "").strip().lower()
158
+ if not low:
159
+ return "unknown"
160
+ cause = _cause(low)
161
+ for key, words in _KEYWORDS:
162
+ if any(w in cause for w in words):
163
+ return key
164
+ return "other"
165
+
166
+
167
+ def build_groups(rows: Iterable[Tuple[Any, ...]]) -> List[Dict[str, Any]]:
168
+ """``rows`` = (normalized reason, count, raw example[, example video id]). Groups, biggest first.
169
+
170
+ Every input row lands in exactly one group, so the group counts sum to the input total.
171
+ """
172
+ buckets: Dict[str, List[Dict[str, Any]]] = {}
173
+ for row in rows:
174
+ reason, count, example = row[0], row[1], row[2]
175
+ example_video_id = (row[3] if len(row) > 3 else None) or None
176
+ key = classify_reason(example or reason)
177
+ buckets.setdefault(key, []).append(
178
+ {
179
+ "reason": reason,
180
+ "reason_id": reason_id(reason),
181
+ "count": int(count),
182
+ "example": example or reason,
183
+ "example_video_id": example_video_id,
184
+ }
185
+ )
186
+ out: List[Dict[str, Any]] = []
187
+ for key, items in buckets.items():
188
+ items.sort(key=lambda r: r["count"], reverse=True)
189
+ label, advice = _META[key]
190
+ out.append(
191
+ {
192
+ "key": key,
193
+ "label": label,
194
+ "advice": advice,
195
+ "retryable": key in RETRYABLE_GROUPS,
196
+ "count": sum(i["count"] for i in items),
197
+ "reasons": items,
198
+ }
199
+ )
200
+ out.sort(key=lambda g: g["count"], reverse=True)
201
+ return out
202
+
203
+
204
+ def _scope_params(
205
+ cohort: Optional[str], state: Optional[str], conn: Any
206
+ ) -> Tuple[Optional[List[str]], Optional[List[str]], Optional[str]]:
207
+ """Same cohort filters as the stage report, plus an optional single state."""
208
+ from api.batch_jobs.batch_job_db import _stage_report_filters
209
+
210
+ jids, states = _stage_report_filters(cohort, conn)
211
+ st = (state or "").strip().upper() or None
212
+ return jids, states, st
213
+
214
+
215
+ _WHERE = """
216
+ WHERE y.transcript_file_error IS NOT NULL
217
+ AND (%(jids)s::text[] IS NULL OR y.jurisdiction_id = ANY(%(jids)s))
218
+ AND (%(states)s::text[] IS NULL OR y.state_code = ANY(%(states)s))
219
+ AND (%(state)s::text IS NULL OR y.state_code = %(state)s)
220
+ """
221
+
222
+ # Same two steps as normalize_reason: video id first, then long numbers.
223
+ _NORM_SQL = (
224
+ r"regexp_replace(regexp_replace(btrim(y.transcript_file_error), "
225
+ r"'(v=|youtu\.be/)[A-Za-z0-9_-]{11}', '\1#', 'g'), '[0-9]{3,}', '#', 'g')"
226
+ )
227
+
228
+
229
+ def failure_reasons(
230
+ conn: Any, *, stage: str, cohort: Optional[str], state: Optional[str], max_reasons: int = 2000
231
+ ) -> Dict[str, Any]:
232
+ """Failed videos for a stage and scope, grouped by reason. Empty groups when none failed."""
233
+ jids, states, st = _scope_params(cohort, state, conn)
234
+ base: Dict[str, Any] = {
235
+ "stage": stage,
236
+ "cohort": (cohort or "").strip().lower() or "all",
237
+ "state": st or "",
238
+ "total": 0,
239
+ "truncated": False,
240
+ "groups": [],
241
+ }
242
+ if (jids is not None and not jids) or (states is not None and not states):
243
+ return base # a cohort with no members has no failures
244
+ params = {"jids": jids, "states": states, "state": st}
245
+ with conn.cursor() as cur:
246
+ cur.execute(f"SELECT COUNT(*)::int FROM bronze.bronze_event_youtube y {_WHERE}", params)
247
+ total = int(cur.fetchone()[0])
248
+ cur.execute(
249
+ f"""
250
+ SELECT {_NORM_SQL} AS reason,
251
+ COUNT(*)::int AS n,
252
+ (array_agg(btrim(y.transcript_file_error)
253
+ ORDER BY y.last_updated DESC NULLS LAST))[1] AS example,
254
+ (array_agg(y.video_id
255
+ ORDER BY y.last_updated DESC NULLS LAST))[1] AS example_video_id
256
+ FROM bronze.bronze_event_youtube y
257
+ {_WHERE}
258
+ GROUP BY 1
259
+ ORDER BY 2 DESC
260
+ LIMIT {int(max_reasons) + 1}
261
+ """,
262
+ params,
263
+ )
264
+ fetched = cur.fetchall()
265
+ truncated = len(fetched) > max_reasons
266
+ rows = [(r[0], int(r[1]), r[2], r[3]) for r in fetched[:max_reasons]]
267
+ shown = sum(r[1] for r in rows)
268
+ if truncated and total > shown:
269
+ rows.append((f"(+{total - shown} more rows in rarer messages)", total - shown, ""))
270
+ base.update(total=total, truncated=truncated, groups=build_groups(rows))
271
+ return base
272
+
273
+
274
+ def failure_rows(
275
+ conn: Any,
276
+ *,
277
+ stage: str,
278
+ cohort: Optional[str],
279
+ state: Optional[str],
280
+ reason_id: str,
281
+ limit: int = 50,
282
+ offset: int = 0,
283
+ ) -> Dict[str, Any]:
284
+ """The failed videos behind one reason, found by its ``reason_id`` (as returned by ``failure_reasons``)."""
285
+ jids, states, st = _scope_params(cohort, state, conn)
286
+ out: Dict[str, Any] = {"stage": stage, "reason_id": reason_id, "total": 0, "rows": []}
287
+ if (jids is not None and not jids) or (states is not None and not states):
288
+ return out
289
+ params = {
290
+ "jids": jids,
291
+ "states": states,
292
+ "state": st,
293
+ "reason_id": reason_id,
294
+ "limit": int(limit),
295
+ "offset": int(offset),
296
+ }
297
+ where = _WHERE + f" AND md5({_NORM_SQL}) = %(reason_id)s"
298
+ with conn.cursor() as cur:
299
+ cur.execute(f"SELECT COUNT(*)::int FROM bronze.bronze_event_youtube y {where}", params)
300
+ out["total"] = int(cur.fetchone()[0])
301
+ cur.execute(
302
+ f"""
303
+ SELECT y.video_id, y.title, y.jurisdiction_id, y.jurisdiction_name,
304
+ y.state_code, btrim(y.transcript_file_error)
305
+ FROM bronze.bronze_event_youtube y
306
+ {where}
307
+ ORDER BY y.last_updated DESC NULLS LAST, y.video_id
308
+ LIMIT %(limit)s OFFSET %(offset)s
309
+ """,
310
+ params,
311
+ )
312
+ out["rows"] = [
313
+ {
314
+ "video_id": r[0],
315
+ "title": r[1] or "",
316
+ "jurisdiction_id": r[2] or "",
317
+ "jurisdiction_name": r[3] or "",
318
+ "state_code": r[4] or "",
319
+ "error": r[5] or "",
320
+ }
321
+ for r in cur.fetchall()
322
+ ]
323
+ return out
324
+
325
+
326
+ # --- #800: one grid for every stage with a failed count -------------------------------------------
327
+ # Stage -> the error column the stage report counts (``pipeline_stage_report``), all on
328
+ # ``bronze.bronze_event_youtube``. Column names come only from this dict, never from the request.
329
+ STAGE_ERROR_COLUMN: Dict[str, str] = {
330
+ "videos": "transcript_file_error",
331
+ "transcripts": "transcript_file_error",
332
+ "analyses_light": "policy_analysis_error",
333
+ "reports_light": "policy_report_error",
334
+ "analyses_full": "policy_analysis_full_error",
335
+ "reports_full": "policy_report_full_error",
336
+ }
337
+ GRID_STAGES = tuple(STAGE_ERROR_COLUMN)
338
+
339
+ # Where to read more, per stage: the step on the Batch Job Status page whose log holds the failure.
340
+ STAGE_WHERE_TO_LOOK: Dict[str, str] = {
341
+ "videos": "Batch Job Status, Videos row: open its log. The error is the caption fetch result.",
342
+ "transcripts": "Batch Job Status, Transcripts row: open its log (caption backfill).",
343
+ "analyses_light": "Batch Job Status, Analysis light row: open its log (light analysis step).",
344
+ "reports_light": "Batch Job Status, Reports light row: open its log (light report step).",
345
+ "analyses_full": "Batch Job Status, Analysis full row: open its log (full analysis step).",
346
+ "reports_full": "Batch Job Status, Reports full row: open its log (full report step).",
347
+ }
348
+
349
+ # Sort allow-list: request value -> SQL. ``{err}`` is the stage's error column. No request text reaches SQL.
350
+ _SORT_SQL: Dict[str, str] = {
351
+ "video_id": "y.video_id",
352
+ "title": "y.title",
353
+ "state_code": "y.state_code",
354
+ "jurisdiction_name": "y.jurisdiction_name",
355
+ "error": "btrim(y.{err})",
356
+ "last_updated": "y.last_updated",
357
+ "event_date": "y.event_date",
358
+ "meeting_type": "y.meeting_type",
359
+ }
360
+ SORT_KEYS = tuple(_SORT_SQL)
361
+
362
+ GRID_COLUMNS: List[Dict[str, Any]] = [
363
+ {"key": "video_id", "label": "Video", "sortable": True},
364
+ {"key": "title", "label": "Title", "sortable": True},
365
+ {"key": "jurisdiction_name", "label": "Jurisdiction", "sortable": True},
366
+ {"key": "state_code", "label": "State", "sortable": True},
367
+ {"key": "channel_id", "label": "Channel", "sortable": False},
368
+ {"key": "event_date", "label": "Meeting date", "sortable": True},
369
+ {"key": "meeting_type", "label": "Meeting type", "sortable": True},
370
+ {"key": "error", "label": "Error", "sortable": True},
371
+ {"key": "group", "label": "Reason", "sortable": False},
372
+ {"key": "last_updated", "label": "Last changed", "sortable": True},
373
+ ]
374
+
375
+
376
+ def _norm_sql_for(col: str) -> str:
377
+ return (
378
+ f"regexp_replace(regexp_replace(btrim(y.{col}), "
379
+ r"'(v=|youtu\.be/)[A-Za-z0-9_-]{11}', '\1#', 'g'), '[0-9]{3,}', '#', 'g')"
380
+ )
381
+
382
+
383
+ def _iso(v: Any) -> str:
384
+ return v.isoformat() if hasattr(v, "isoformat") else ("" if v is None else str(v))
385
+
386
+
387
+ def failure_grid(
388
+ conn: Any,
389
+ *,
390
+ stage: str,
391
+ cohort: Optional[str],
392
+ state: Optional[str],
393
+ q: Optional[str] = None,
394
+ group: Optional[str] = None,
395
+ sort: str = "last_updated",
396
+ direction: str = "desc",
397
+ limit: int = 50,
398
+ offset: int = 0,
399
+ ) -> Dict[str, Any]:
400
+ """Failed items for a stage and scope: one row per failed video, sortable and pageable (#800).
401
+
402
+ ``total`` uses the same row filter and cohort/state scope as ``pipeline_stage_report``'s failed
403
+ count for the stage, so with no ``q``/``group`` it equals the badge on the stage row. Raises
404
+ ``ValueError`` for an unknown stage, sort key or group.
405
+ """
406
+ col = STAGE_ERROR_COLUMN.get(stage)
407
+ if col is None:
408
+ raise ValueError(f"unknown stage {stage!r}")
409
+ if sort not in _SORT_SQL:
410
+ raise ValueError(f"unknown sort {sort!r}")
411
+ if group is not None and group != "" and group not in _META:
412
+ raise ValueError(f"unknown group {group!r}")
413
+ desc = str(direction).lower() != "asc"
414
+ jids, states, st = _scope_params(cohort, state, conn)
415
+ out: Dict[str, Any] = {
416
+ "stage": stage,
417
+ "cohort": (cohort or "").strip().lower() or "all",
418
+ "state": st or "",
419
+ "error_column": col,
420
+ "where_to_look": STAGE_WHERE_TO_LOOK[stage],
421
+ "total": 0,
422
+ "columns": GRID_COLUMNS,
423
+ "rows": [],
424
+ }
425
+ if (jids is not None and not jids) or (states is not None and not states):
426
+ return out
427
+ params: Dict[str, Any] = {
428
+ "jids": jids,
429
+ "states": states,
430
+ "state": st,
431
+ "q": (q or "").strip().lower() or None,
432
+ "limit": int(limit),
433
+ "offset": int(offset),
434
+ }
435
+ where = f"""
436
+ WHERE y.{col} IS NOT NULL
437
+ AND (%(jids)s::text[] IS NULL OR y.jurisdiction_id = ANY(%(jids)s))
438
+ AND (%(states)s::text[] IS NULL OR y.state_code = ANY(%(states)s))
439
+ AND (%(state)s::text IS NULL OR y.state_code = %(state)s)
440
+ AND (%(q)s::text IS NULL OR position(%(q)s in lower(
441
+ concat_ws(' ', y.title, y.video_id, y.jurisdiction_name, y.{col}))) > 0)
442
+ """
443
+ norm = _norm_sql_for(col)
444
+ with conn.cursor() as cur:
445
+ if group:
446
+ # Group is decided in Python (keywords), so find the reasons that fall in it, then filter by id.
447
+ cur.execute(
448
+ f"SELECT {norm} AS reason FROM bronze.bronze_event_youtube y "
449
+ f"WHERE y.{col} IS NOT NULL GROUP BY 1 LIMIT 5000"
450
+ )
451
+ ids = [reason_id(r[0] or "") for r in cur.fetchall() if classify_reason(r[0]) == group]
452
+ if not ids:
453
+ return out
454
+ where += f" AND md5({norm}) = ANY(%(gids)s)"
455
+ params["gids"] = ids
456
+ cur.execute(f"SELECT COUNT(*)::int FROM bronze.bronze_event_youtube y {where}", params)
457
+ out["total"] = int(cur.fetchone()[0])
458
+ order = _SORT_SQL[sort].format(err=col)
459
+ cur.execute(
460
+ f"""
461
+ SELECT y.video_id, y.title, y.jurisdiction_id, y.jurisdiction_name, y.state_code,
462
+ y.channel_id, y.channel_url, y.event_date, y.meeting_type,
463
+ btrim(y.{col}), y.last_updated, y.event_id
464
+ FROM bronze.bronze_event_youtube y
465
+ {where}
466
+ ORDER BY {order} {"DESC" if desc else "ASC"} NULLS LAST, y.video_id
467
+ LIMIT %(limit)s OFFSET %(offset)s
468
+ """,
469
+ params,
470
+ )
471
+ fetched = cur.fetchall()
472
+ rows = []
473
+ for r in fetched:
474
+ key = classify_reason(r[9])
475
+ label, advice = _META[key]
476
+ rows.append(
477
+ {
478
+ "video_id": r[0] or "",
479
+ "title": r[1] or "",
480
+ "jurisdiction_id": r[2] or "",
481
+ "jurisdiction_name": r[3] or "",
482
+ "state_code": r[4] or "",
483
+ "channel_id": r[5] or "",
484
+ "channel_url": r[6] or "",
485
+ "event_date": _iso(r[7]),
486
+ "meeting_type": r[8] or "",
487
+ "error": r[9] or "",
488
+ "group": key,
489
+ "group_label": label,
490
+ "advice": advice,
491
+ "retryable": key in RETRYABLE_GROUPS,
492
+ "last_updated": _iso(r[10]),
493
+ "event_id": r[11] or "",
494
+ }
495
+ )
496
+ out["rows"] = rows
497
+ return out
498
+
499
+
500
+ def pick_retry_reason_ids(
501
+ groups: List[Dict[str, Any]], *, group: Optional[str] = None, reason_id: Optional[str] = None
502
+ ) -> List[str]:
503
+ """The reason ids to retry for one group or one reason. Raises ``ValueError`` when none apply,
504
+ when both or neither selector is given, or when the group cannot be retried."""
505
+ if bool(group) == bool(reason_id):
506
+ raise ValueError("give exactly one of group or reason_id")
507
+ wanted: List[str] = []
508
+ for g in groups:
509
+ if group and g["key"] != group:
510
+ continue
511
+ for r in g["reasons"]:
512
+ if reason_id and r["reason_id"] != reason_id:
513
+ continue
514
+ if not g["retryable"]:
515
+ raise ValueError(f"{g['label']!r} cannot be retried: {g['advice']}")
516
+ wanted.append(r["reason_id"])
517
+ if not wanted:
518
+ raise ValueError("no failed videos match that group or reason in this scope")
519
+ return wanted
520
+
521
+
522
+ def retry_failures(
523
+ conn: Any,
524
+ *,
525
+ stage: str,
526
+ cohort: Optional[str],
527
+ state: Optional[str],
528
+ group: Optional[str] = None,
529
+ reason_id: Optional[str] = None,
530
+ dry_run: bool = False,
531
+ ) -> Dict[str, Any]:
532
+ """Make the failed videos of one retryable group (or one reason) due for the next fetch.
533
+
534
+ The caption backfill skips a video for ``--retry-after-days`` after a failed attempt (the negative
535
+ cache, ``bronze.bronze_transcript_fetch_attempts``). This sets that attempt's time back to the epoch
536
+ for the matching videos so the next Backfill picks them up. It deletes nothing: the attempt count
537
+ and last error stay, and the error on the video row stays until a new attempt replaces it.
538
+
539
+ Only retryable groups are accepted. Raises ``ValueError`` for anything else.
540
+ """
541
+ data = failure_reasons(conn, stage=stage, cohort=cohort, state=state)
542
+ wanted = pick_retry_reason_ids(data["groups"], group=group, reason_id=reason_id)
543
+
544
+ jids, states, st = _scope_params(cohort, state, conn)
545
+ params = {"jids": jids, "states": states, "state": st, "ids": wanted}
546
+ out: Dict[str, Any] = {
547
+ "stage": stage,
548
+ "group": group or "",
549
+ "reason_id": reason_id or "",
550
+ "dry_run": bool(dry_run),
551
+ "matched": 0,
552
+ "made_due": 0,
553
+ "already_due": 0,
554
+ }
555
+ with conn.cursor() as cur:
556
+ cur.execute(
557
+ f"SELECT y.video_id FROM bronze.bronze_event_youtube y {_WHERE} "
558
+ f"AND md5({_NORM_SQL}) = ANY(%(ids)s)",
559
+ params,
560
+ )
561
+ video_ids = [r[0] for r in cur.fetchall()]
562
+ out["matched"] = len(video_ids)
563
+ cur.execute("SELECT to_regclass('bronze.bronze_transcript_fetch_attempts') IS NOT NULL")
564
+ has_cache = bool(cur.fetchone()[0])
565
+ if not video_ids or not has_cache:
566
+ out["already_due"] = len(video_ids)
567
+ return out
568
+ cur.execute(
569
+ "SELECT count(*) FROM bronze.bronze_transcript_fetch_attempts "
570
+ "WHERE video_id = ANY(%s) AND last_attempt_at > TIMESTAMP '1970-01-02'",
571
+ (video_ids,),
572
+ )
573
+ cooling = int(cur.fetchone()[0])
574
+ out["made_due"] = cooling
575
+ out["already_due"] = len(video_ids) - cooling
576
+ if not dry_run and cooling:
577
+ cur.execute(
578
+ "UPDATE bronze.bronze_transcript_fetch_attempts SET last_attempt_at = TIMESTAMP '1970-01-01' "
579
+ "WHERE video_id = ANY(%s) AND last_attempt_at > TIMESTAMP '1970-01-02'",
580
+ (video_ids,),
581
+ )
582
+ if not dry_run:
583
+ conn.commit()
584
+ return out
api/database.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Database connection and session management
3
+ """
4
+ import os
5
+ from urllib.parse import urlparse
6
+
7
+ from loguru import logger
8
+ from sqlalchemy import create_engine
9
+ from sqlalchemy.orm import sessionmaker, Session
10
+ from sqlalchemy.pool import StaticPool
11
+ from typing import Generator
12
+
13
+ from api.models import Base
14
+
15
+ # Database URL priority:
16
+ # 1. NEON_DATABASE_URL_DEV (local development with PostgreSQL)
17
+ # 2. NEON_DATABASE_URL (production Neon PostgreSQL)
18
+ # 3. DATABASE_URL (backwards compatibility)
19
+ # 4. SQLite fallback (no setup required)
20
+ DATABASE_URL = os.getenv(
21
+ "NEON_DATABASE_URL_DEV",
22
+ os.getenv(
23
+ "NEON_DATABASE_URL",
24
+ os.getenv(
25
+ "DATABASE_URL",
26
+ "sqlite:///./data/users.db"
27
+ )
28
+ )
29
+ )
30
+
31
+ def sqlalchemy_url(url: str) -> str:
32
+ """The URL the ORM engine uses: PostgreSQL always names the psycopg2 driver.
33
+
34
+ SQLAlchemy 2.1 changed the default driver for ``postgresql://`` from psycopg2 to
35
+ psycopg 3, which isn't installed (only ``psycopg2-binary`` is), so an implicit
36
+ driver made ``api.main`` fail at import (#282). ``postgres://`` and
37
+ ``postgresql://`` get ``+psycopg2``; a URL that already names a driver, and
38
+ SQLite, are left as they are.
39
+ """
40
+ for prefix in ("postgres://", "postgresql://"):
41
+ if url.startswith(prefix):
42
+ return "postgresql+psycopg2://" + url[len(prefix):]
43
+ return url
44
+
45
+
46
+ # The asyncpg pools elsewhere read the plain URL; only the ORM engine gets the driver.
47
+ if DATABASE_URL.startswith("postgres://"):
48
+ DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql://", 1)
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # Serving schema (gold/public split).
52
+ #
53
+ # The warehouse is split into two Postgres schemas in open_navigator:
54
+ # * `public` — ONLY the API-served relations, as views over gold; the
55
+ # person-graph PII is absent and `contact_official` is PII-light. This is
56
+ # what the PUBLIC API serves (default).
57
+ # * `gold` — the FULL warehouse (incl. the person graph, un-redacted). A
58
+ # PRIVATE/internal API instance reads this by setting API_DB_SCHEMA=gold.
59
+ #
60
+ # API_DB_SCHEMA names the DATA schema (default `public`). Table references in
61
+ # route SQL are UNqualified so they resolve via search_path. The data pools
62
+ # (asyncpg) use `search_path = <API_DB_SCHEMA>, public` — the data schema first,
63
+ # `public` as the fallback for the operational/ORM tables (user/social_follows/
64
+ # prefs) which ALWAYS live in public. The ORM engine below uses `public` FIRST
65
+ # so auth tables never get shadowed into gold by create_all.
66
+ # See dbt_project/macros/publish_public_serving.sql.
67
+ # ---------------------------------------------------------------------------
68
+ DB_SCHEMA = os.getenv("API_DB_SCHEMA", "public").strip() or "public"
69
+ # NOTE: no spaces in these search_path strings — they feed libpq's `-csearch_path=`
70
+ # options below, and libpq splits the options value on whitespace (a space turns
71
+ # "public, gold" into the malformed search_path "public,"). Commas only.
72
+ #: search_path for raw DATA reads (asyncpg pools): data schema first, public fallback.
73
+ DATA_SEARCH_PATH = DB_SCHEMA if DB_SCHEMA == "public" else f"{DB_SCHEMA},public"
74
+ #: search_path for the ORM/auth engine: public FIRST so operational tables stay in public.
75
+ _ORM_SEARCH_PATH = "public" if DB_SCHEMA == "public" else f"public,{DB_SCHEMA}"
76
+
77
+ def orm_connect_args(url: str) -> dict:
78
+ """libpq connect args for the ORM/auth engine (#367).
79
+
80
+ Pins ``search_path`` (public first) with a startup ``options`` parameter, except
81
+ on a Neon *pooled* endpoint (host contains ``-pooler``): PgBouncer rejects
82
+ startup ``options`` ("unsupported startup parameter in options: search_path"),
83
+ which failed every ORM connection and took sign-in down. There the server
84
+ default ``"$user", public`` already resolves the ORM tables to ``public``.
85
+ """
86
+ host = urlparse(url).hostname or ""
87
+ if "-pooler" in host:
88
+ if _ORM_SEARCH_PATH != "public":
89
+ logger.warning(
90
+ "Neon pooled host {}: search_path pin {!r} not applied (pooler rejects "
91
+ "startup options); ORM tables resolve via the default search_path.",
92
+ host,
93
+ _ORM_SEARCH_PATH,
94
+ )
95
+ return {}
96
+ return {"options": f"-csearch_path={_ORM_SEARCH_PATH}"}
97
+
98
+
99
+ # Create engine
100
+ if "sqlite" in DATABASE_URL:
101
+ # SQLite needs special handling for concurrent access
102
+ engine = create_engine(
103
+ DATABASE_URL,
104
+ connect_args={"check_same_thread": False},
105
+ poolclass=StaticPool,
106
+ )
107
+ else:
108
+ # PostgreSQL configuration
109
+ engine = create_engine(
110
+ sqlalchemy_url(DATABASE_URL),
111
+ pool_pre_ping=True,
112
+ pool_size=10,
113
+ max_overflow=20,
114
+ # Pin the ORM/auth search_path (public-first) so Base.metadata.create_all
115
+ # always targets public even when a private instance serves data from gold.
116
+ connect_args=orm_connect_args(DATABASE_URL),
117
+ )
118
+
119
+ # Create session factory
120
+ SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
121
+
122
+
123
+ def init_db():
124
+ """Create all tables"""
125
+ Base.metadata.create_all(bind=engine)
126
+ print(f"✅ Database initialized at: {DATABASE_URL}")
127
+
128
+
129
+ def get_db() -> Generator[Session, None, None]:
130
+ """
131
+ Database session dependency for FastAPI
132
+
133
+ Usage:
134
+ @app.get("/users")
135
+ def get_users(db: Session = Depends(get_db)):
136
+ return db.query(User).all()
137
+ """
138
+ db = SessionLocal()
139
+ try:
140
+ yield db
141
+ finally:
142
+ db.close()
api/error_pages.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Content-negotiated error responses for the API.
3
+
4
+ Browser navigations (e.g. the OAuth redirect endpoints, which the frontend
5
+ reaches via ``window.location.href``) should see a styled HTML page with a
6
+ clickable ``mailto:`` support link — not a wall of raw JSON. Programmatic API
7
+ clients still get JSON. ``error_response`` picks the representation from the
8
+ request's ``Accept`` header.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ from html import escape
14
+ from urllib.parse import quote
15
+ from typing import Any, Optional
16
+
17
+ from fastapi import Request
18
+ from fastapi.responses import HTMLResponse, JSONResponse
19
+
20
+ # Single source of truth for the support address — referenced by the HTML page,
21
+ # the mailto link, and the JSON ``support`` field.
22
+ SUPPORT_EMAIL = "johnbowyer@communityone.com"
23
+
24
+
25
+ def wants_html(request: Request) -> bool:
26
+ """True when the client prefers HTML (a browser) over JSON.
27
+
28
+ A browser sends ``Accept: text/html,...`` and ranks it ahead of JSON;
29
+ ``fetch``/``httpx`` clients typically send ``*/*`` or ``application/json``.
30
+ """
31
+ accept = request.headers.get("accept", "")
32
+ if "text/html" not in accept:
33
+ return False
34
+ # If JSON is explicitly preferred over HTML, honour that (API tooling).
35
+ if "application/json" in accept:
36
+ return accept.index("text/html") < accept.index("application/json")
37
+ return True
38
+
39
+
40
+ def _frontend_base(request: Request) -> str:
41
+ """Origin to resolve in-app links (``/support``, home) against.
42
+
43
+ The error page can be served by the API on a *different* origin than the
44
+ React app (local dev: API :8001 vs Vite :5173). A relative ``/support``
45
+ would then hit the API host and 404. When ``FRONTEND_URL`` names a
46
+ different origin than this request, return it as an absolute prefix;
47
+ otherwise return ``""`` so links stay relative (prod is same-origin).
48
+ """
49
+ fe = (os.getenv("FRONTEND_URL") or "").rstrip("/")
50
+ if not fe:
51
+ return ""
52
+ req_origin = f"{request.url.scheme}://{request.url.netloc}"
53
+ return fe if fe != req_origin else ""
54
+
55
+
56
+ def _mailto(subject: str, body: str) -> str:
57
+ """Build a ``mailto:`` link to support with a prefilled subject/body."""
58
+ query = f"subject={quote(subject)}&body={quote(body)}"
59
+ return f"mailto:{SUPPORT_EMAIL}?{query}"
60
+
61
+
62
+ def _html_page(
63
+ *,
64
+ status_code: int,
65
+ title: str,
66
+ message: str,
67
+ suggestion: Optional[str],
68
+ path: str,
69
+ frontend_base: str = "",
70
+ ) -> str:
71
+ subject = f"CommunityOne support — {status_code} on {path or 'the site'}"
72
+ body = (
73
+ "Hi CommunityOne team,\n\n"
74
+ f"I ran into a problem.\n\n"
75
+ f"What I was doing: \n"
76
+ f"Page / action: {path}\n"
77
+ f"Error: {status_code} {title}\n\n"
78
+ "Thanks!"
79
+ )
80
+ mailto = _mailto(subject, body)
81
+ # Deep-link into the in-app support form (creates a GitHub-issue ticket),
82
+ # prefilled with the failing path/status via query params it reads.
83
+ report_url = (
84
+ f"{frontend_base}/support?category=bug"
85
+ f"&subject={quote(subject)}"
86
+ f"&path={quote(path or '')}"
87
+ )
88
+ home_url = f"{frontend_base}/" if frontend_base else "/"
89
+ safe_title = escape(title)
90
+ safe_message = escape(message)
91
+ safe_suggestion = escape(suggestion) if suggestion else ""
92
+ suggestion_html = (
93
+ f'<p class="suggestion">{safe_suggestion}</p>' if safe_suggestion else ""
94
+ )
95
+ return f"""<!DOCTYPE html>
96
+ <html lang="en">
97
+ <head>
98
+ <meta charset="utf-8" />
99
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
100
+ <title>{status_code} · {safe_title} · CommunityOne</title>
101
+ <style>
102
+ :root {{ color-scheme: light dark; }}
103
+ * {{ box-sizing: border-box; }}
104
+ body {{
105
+ margin: 0; min-height: 100vh; display: flex; align-items: center;
106
+ justify-content: center; padding: 24px;
107
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
108
+ background: #0f172a; color: #e2e8f0;
109
+ }}
110
+ .card {{
111
+ max-width: 540px; width: 100%; background: #1e293b; border: 1px solid #334155;
112
+ border-radius: 16px; padding: 40px; box-shadow: 0 10px 40px rgba(0,0,0,.35);
113
+ }}
114
+ .code {{ font-size: 13px; letter-spacing: .12em; text-transform: uppercase; color: #64748b; }}
115
+ h1 {{ margin: 8px 0 12px; font-size: 26px; line-height: 1.2; color: #f8fafc; }}
116
+ p {{ margin: 0 0 16px; line-height: 1.6; color: #cbd5e1; }}
117
+ .suggestion {{ color: #94a3b8; font-size: 15px; }}
118
+ .actions {{ display: flex; flex-wrap: wrap; gap: 12px; margin-top: 28px; }}
119
+ a.btn {{
120
+ display: inline-block; padding: 11px 18px; border-radius: 10px;
121
+ text-decoration: none; font-weight: 600; font-size: 15px;
122
+ }}
123
+ a.primary {{ background: #6366f1; color: #fff; }}
124
+ a.primary:hover {{ background: #4f46e5; }}
125
+ a.ghost {{ background: transparent; color: #cbd5e1; border: 1px solid #475569; }}
126
+ a.ghost:hover {{ border-color: #94a3b8; color: #f1f5f9; }}
127
+ .path {{ margin-top: 24px; font-size: 12px; color: #64748b; word-break: break-all; }}
128
+ </style>
129
+ </head>
130
+ <body>
131
+ <main class="card">
132
+ <div class="code">Error {status_code}</div>
133
+ <h1>{safe_title}</h1>
134
+ <p>{safe_message}</p>
135
+ {suggestion_html}
136
+ <div class="actions">
137
+ <a class="btn primary" href="{escape(report_url)}">Report this issue</a>
138
+ <a class="btn ghost" href="{escape(mailto)}">Email support</a>
139
+ <a class="btn ghost" href="{escape(home_url)}">Back to CommunityOne</a>
140
+ </div>
141
+ <div class="path">{escape(path)}</div>
142
+ </main>
143
+ </body>
144
+ </html>"""
145
+
146
+
147
+ def error_response(
148
+ request: Request,
149
+ *,
150
+ status_code: int,
151
+ title: str,
152
+ message: str,
153
+ suggestion: Optional[str] = None,
154
+ extra: Optional[dict[str, Any]] = None,
155
+ ) -> HTMLResponse | JSONResponse:
156
+ """Return an HTML error page for browsers, JSON otherwise.
157
+
158
+ ``extra`` is merged into the JSON body only (e.g. validation ``errors``,
159
+ a ``login`` URL); the HTML page stays intentionally simple.
160
+ """
161
+ path = request.url.path
162
+ if wants_html(request):
163
+ return HTMLResponse(
164
+ status_code=status_code,
165
+ content=_html_page(
166
+ status_code=status_code,
167
+ title=title,
168
+ message=message,
169
+ suggestion=suggestion,
170
+ path=path,
171
+ frontend_base=_frontend_base(request),
172
+ ),
173
+ )
174
+
175
+ body: dict[str, Any] = {
176
+ "error": title,
177
+ "message": message,
178
+ "path": path,
179
+ "support": SUPPORT_EMAIL,
180
+ }
181
+ if suggestion:
182
+ body["suggestion"] = suggestion
183
+ if extra:
184
+ body.update(extra)
185
+ return JSONResponse(status_code=status_code, content=body)
api/errors.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Structured error models for API responses.
3
+
4
+ Provides user-friendly error messages with expandable technical details.
5
+ """
6
+ from pydantic import BaseModel, Field
7
+ from typing import Optional, Dict, Any
8
+
9
+
10
+ class ErrorDetail(BaseModel):
11
+ """Structured error detail with user-friendly message and technical info."""
12
+
13
+ message: str = Field(
14
+ ...,
15
+ description="User-friendly error message"
16
+ )
17
+
18
+ error_type: str = Field(
19
+ ...,
20
+ description="Type of error (e.g., 'data_not_found', 'network_error', 'validation_error')"
21
+ )
22
+
23
+ technical_details: Optional[str] = Field(
24
+ None,
25
+ description="Technical error details for debugging (expandable in UI)"
26
+ )
27
+
28
+ suggestions: Optional[list[str]] = Field(
29
+ None,
30
+ description="Helpful suggestions for the user"
31
+ )
32
+
33
+ metadata: Optional[Dict[str, Any]] = Field(
34
+ None,
35
+ description="Additional context (state, dataset name, etc.)"
36
+ )
37
+
38
+
39
+ def parse_error(exception: Exception, context: Optional[Dict[str, Any]] = None) -> ErrorDetail:
40
+ """
41
+ Parse an exception into a structured ErrorDetail with user-friendly message.
42
+
43
+ Args:
44
+ exception: The exception to parse
45
+ context: Additional context (state, dataset, etc.)
46
+
47
+ Returns:
48
+ ErrorDetail with user-friendly message and technical details
49
+ """
50
+ error_str = str(exception)
51
+ context = context or {}
52
+
53
+ # Parse HuggingFace dataset not found errors
54
+ if "HTTP 404 Not Found" in error_str and "huggingface.co/datasets" in error_str:
55
+ # Extract dataset name from URL
56
+ import re
57
+ match = re.search(r'datasets/([^/]+/[^/]+)/', error_str)
58
+ dataset_name = match.group(1) if match else "unknown"
59
+
60
+ # Extract state from dataset name or context
61
+ state = context.get('state', 'Unknown')
62
+ data_type = 'bills' if 'bills' in dataset_name else 'data'
63
+
64
+ return ErrorDetail(
65
+ message=f"No {data_type} data available for {state.upper()}",
66
+ error_type="data_not_found",
67
+ technical_details=f"Dataset '{dataset_name}' not found on HuggingFace.\n\nFull error: {error_str}",
68
+ suggestions=[
69
+ f"Try a different state - we have data for 50+ states",
70
+ f"Check /api/bills/map to see which states have {data_type} data",
71
+ "Contact support if you believe this data should be available"
72
+ ],
73
+ metadata={
74
+ "dataset": dataset_name,
75
+ "state": state,
76
+ "data_type": data_type
77
+ }
78
+ )
79
+
80
+ # Parse file not found errors (local environment)
81
+ elif "No such file or directory" in error_str or "FileNotFoundError" in error_str:
82
+ state = context.get('state', 'Unknown')
83
+ data_type = context.get('data_type', 'data')
84
+
85
+ return ErrorDetail(
86
+ message=f"No {data_type} available for {state.upper()}",
87
+ error_type="data_not_found",
88
+ technical_details=error_str,
89
+ suggestions=[
90
+ f"This state may not have {data_type} in our database yet",
91
+ "Try a different state or check which states have data",
92
+ "Data is being continuously added - check back later"
93
+ ],
94
+ metadata={
95
+ "state": state,
96
+ "data_type": data_type
97
+ }
98
+ )
99
+
100
+ # Parse DuckDB/SQL errors
101
+ elif "DuckDB" in error_str or "SYNTAX ERROR" in error_str or "LINE" in error_str:
102
+ return ErrorDetail(
103
+ message="Database query error - please check your search parameters",
104
+ error_type="query_error",
105
+ technical_details=error_str,
106
+ suggestions=[
107
+ "Try simplifying your search query",
108
+ "Check that all parameters are valid",
109
+ "Contact support if the issue persists"
110
+ ],
111
+ metadata=context
112
+ )
113
+
114
+ # Parse network/timeout errors
115
+ elif "timeout" in error_str.lower() or "connection" in error_str.lower():
116
+ return ErrorDetail(
117
+ message="Network request timed out - please try again",
118
+ error_type="network_error",
119
+ technical_details=error_str,
120
+ suggestions=[
121
+ "Try again in a few seconds",
122
+ "Check your internet connection",
123
+ "The server may be temporarily busy"
124
+ ],
125
+ metadata=context
126
+ )
127
+
128
+ # Parse validation errors
129
+ elif "validation" in error_str.lower() or "invalid" in error_str.lower():
130
+ return ErrorDetail(
131
+ message="Invalid request parameters",
132
+ error_type="validation_error",
133
+ technical_details=error_str,
134
+ suggestions=[
135
+ "Check that all required parameters are provided",
136
+ "Verify parameter formats (e.g., state codes should be 2 letters)",
137
+ "See API documentation for valid parameter values"
138
+ ],
139
+ metadata=context
140
+ )
141
+
142
+ # Generic error fallback
143
+ else:
144
+ return ErrorDetail(
145
+ message="An unexpected error occurred",
146
+ error_type="server_error",
147
+ technical_details=error_str,
148
+ suggestions=[
149
+ "Try again in a few moments",
150
+ "Contact support if the issue persists",
151
+ "Check the technical details for more information"
152
+ ],
153
+ metadata=context
154
+ )
api/main.py ADDED
@@ -0,0 +1,1806 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI application for the CommunityOne Open Navigator system.
3
+
4
+ Provides REST API endpoints for:
5
+ - Initiating policy analysis workflows
6
+ - Querying advocacy opportunities
7
+ - Retrieving generated materials
8
+ - Accessing visualizations
9
+ - System status and monitoring
10
+ """
11
+ from typing import List, Dict, Any, Optional
12
+ from datetime import datetime, date
13
+ import sys
14
+ import time
15
+ from pathlib import Path
16
+ from fastapi import FastAPI, HTTPException, Query, BackgroundTasks, Request, Response
17
+ from fastapi.responses import HTMLResponse, JSONResponse
18
+ from fastapi.middleware.cors import CORSMiddleware
19
+ from fastapi.middleware.gzip import GZipMiddleware
20
+ from fastapi.staticfiles import StaticFiles
21
+ from fastapi.openapi.docs import get_swagger_ui_html
22
+ from api.static_cache import CachedStaticFiles
23
+ from pydantic import BaseModel, Field
24
+ from loguru import logger
25
+ import os
26
+
27
+ from agents.orchestrator import OrchestratorAgent
28
+ from agents.scraper import ScraperAgent
29
+ from agents.parser import ParserAgent
30
+ from agents.classifier import ClassifierAgent
31
+ from agents.sentiment import SentimentAnalyzerAgent
32
+ from agents.advocacy import AdvocacyWriterAgent
33
+ from ingestion.delta_lake import DeltaLakePipeline
34
+ from scripts.visualization.heatmap import AdvocacyHeatmap
35
+ from config import settings
36
+
37
+ # Configure logging with rotation and retention
38
+ # Output to both file (with rotation) and stderr (for HuggingFace container logs)
39
+ logger.remove() # Remove default handler
40
+
41
+ # Add console output (shows in HuggingFace container logs)
42
+ logger.add(
43
+ sys.stderr,
44
+ format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan> - <level>{message}</level>",
45
+ level=settings.log_level
46
+ )
47
+
48
+ # Add file output with rotation and retention
49
+ logger.add(
50
+ settings.log_file,
51
+ rotation="500 MB", # Create new file when size exceeds 500MB
52
+ retention="10 days", # Delete logs older than 10 days
53
+ level=settings.log_level,
54
+ format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function} - {message}"
55
+ )
56
+
57
+ # Initialize FastAPI app
58
+ app = FastAPI(
59
+ title="Open Navigator API",
60
+ description="Multi-agent system for analyzing local government oral health policy discussions",
61
+ version="1.0.0",
62
+ docs_url=None, # Disable default docs to use custom
63
+ redoc_url="/redoc", # Keep ReDoc at /redoc
64
+ openapi_tags=[
65
+ {
66
+ "name": "auth",
67
+ "description": "Authentication and user management"
68
+ },
69
+ {
70
+ "name": "social",
71
+ "description": "Social features - follow users, leaders, organizations, and causes"
72
+ },
73
+ {
74
+ "name": "workflows",
75
+ "description": "Policy analysis workflows"
76
+ },
77
+ {
78
+ "name": "opportunities",
79
+ "description": "Advocacy opportunities"
80
+ }
81
+ ]
82
+ )
83
+
84
+ # Custom OpenAPI schema with logo
85
+ def custom_openapi():
86
+ if app.openapi_schema:
87
+ return app.openapi_schema
88
+
89
+ from fastapi.openapi.utils import get_openapi
90
+
91
+ openapi_schema = get_openapi(
92
+ title=app.title,
93
+ version=app.version,
94
+ description=app.description,
95
+ routes=app.routes,
96
+ )
97
+
98
+ # Add custom logo
99
+ openapi_schema["info"]["x-logo"] = {
100
+ "url": "/static/communityone_logo.svg",
101
+ "altText": "CommunityOne Logo"
102
+ }
103
+
104
+ app.openapi_schema = openapi_schema
105
+ return app.openapi_schema
106
+
107
+ app.openapi = custom_openapi
108
+
109
+ # Bootstrap OpenTelemetry: instrument the app at startup and configure the
110
+ # exporter (OTLP collector if OTEL_EXPORTER_OTLP_ENDPOINT is set, else a console
111
+ # exporter for dev). Idempotent. Spans for the search DB path are opened in
112
+ # api/routes/search*.py via the shared `tracer`.
113
+ from api.telemetry import setup_telemetry
114
+
115
+ setup_telemetry(app)
116
+
117
+ # Add CORS middleware. Origins come from an explicit env-driven allowlist
118
+ # (api/origins.py), never "*": with allow_credentials=True, Starlette reflects
119
+ # the caller's Origin, so "*" would trust every site on the internet.
120
+ from api.origins import allowed_origins
121
+
122
+ app.add_middleware(
123
+ CORSMiddleware,
124
+ allow_origins=list(allowed_origins()),
125
+ allow_credentials=True,
126
+ allow_methods=["*"],
127
+ allow_headers=["*"],
128
+ )
129
+
130
+ # Compress responses (notably the large /data JSON marts — county_metrics is
131
+ # ~2.6MB, jurisdiction_mapping_quality ~6.6MB; both compress ~5-10x).
132
+ app.add_middleware(GZipMiddleware, minimum_size=1000)
133
+
134
+ # Request logging middleware
135
+ @app.middleware("http")
136
+ async def log_requests(request: Request, call_next):
137
+ """Log all API requests with timing and response info"""
138
+ start_time = time.time()
139
+
140
+ # Get client info
141
+ client_host = request.client.host if request.client else "unknown"
142
+
143
+ # Log incoming request
144
+ logger.info(f"➡️ {request.method} {request.url.path} - Client: {client_host}")
145
+
146
+ # Process request
147
+ try:
148
+ response = await call_next(request)
149
+
150
+ # Calculate duration
151
+ duration_ms = (time.time() - start_time) * 1000
152
+
153
+ # Get response size if available
154
+ response_size = response.headers.get("content-length", "unknown")
155
+
156
+ # Log response with appropriate emoji based on status
157
+ if response.status_code < 400:
158
+ logger.info(
159
+ f"✅ {request.method} {request.url.path} - "
160
+ f"Status: {response.status_code} - "
161
+ f"Duration: {duration_ms:.2f}ms - "
162
+ f"Size: {response_size} bytes"
163
+ )
164
+ elif response.status_code < 500:
165
+ logger.warning(
166
+ f"⚠️ {request.method} {request.url.path} - "
167
+ f"Status: {response.status_code} - "
168
+ f"Duration: {duration_ms:.2f}ms"
169
+ )
170
+ else:
171
+ logger.error(
172
+ f"❌ {request.method} {request.url.path} - "
173
+ f"Status: {response.status_code} - "
174
+ f"Duration: {duration_ms:.2f}ms"
175
+ )
176
+
177
+ return response
178
+
179
+ except Exception as e:
180
+ duration_ms = (time.time() - start_time) * 1000
181
+
182
+ # A client that disconnects mid-flight (e.g. the frontend's
183
+ # AbortController timing out a slow request) cancels the downstream
184
+ # task, so Starlette's BaseHTTPMiddleware reports
185
+ # "No response returned." That's a normal client abort, not a server
186
+ # fault — log it quietly and return 499 (Client Closed Request) instead
187
+ # of re-raising a 500 with a noisy traceback.
188
+ if (
189
+ isinstance(e, RuntimeError)
190
+ and str(e) == "No response returned."
191
+ and await request.is_disconnected()
192
+ ):
193
+ logger.info(
194
+ f"🚫 {request.method} {request.url.path} - "
195
+ f"Client disconnected - Duration: {duration_ms:.2f}ms"
196
+ )
197
+ return Response(status_code=499)
198
+
199
+ logger.error(
200
+ f"💥 {request.method} {request.url.path} - "
201
+ f"Error: {str(e)} - "
202
+ f"Duration: {duration_ms:.2f}ms"
203
+ )
204
+ raise
205
+
206
+ # Mount static files for logo
207
+ static_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "web_app", "public")
208
+ if os.path.exists(static_dir):
209
+ app.mount("/static", StaticFiles(directory=static_dir), name="static")
210
+ # Serve the whole public /data tree the way Vite does in dev. Besides the
211
+ # census-map marts this covers the per-state ZCTA (ZIP) tiles under
212
+ # /data/zctas (the lowest drilldown tier) and the jurisdiction-quality
213
+ # snapshot — mounting only /data/census-map left those paths 404ing.
214
+ data_dir = Path(static_dir) / "data"
215
+ if data_dir.is_dir():
216
+ app.mount("/data", CachedStaticFiles(directory=data_dir), name="public_data")
217
+ else:
218
+ logger.warning(f"Public data bundle missing (expected {data_dir})")
219
+ else:
220
+ logger.warning(f"Static directory not found: {static_dir}")
221
+
222
+ # Serve favicon at root
223
+ @app.get("/favicon.ico", include_in_schema=False)
224
+ async def favicon():
225
+ """Serve favicon — HF deploy strips binary assets, so fall back to PNG/SVG."""
226
+ from fastapi.responses import FileResponse
227
+
228
+ candidates = [
229
+ (Path(__file__).parent / "static" / "favicon.ico", "image/x-icon"),
230
+ (Path(static_dir) / "favicon.ico", "image/x-icon"),
231
+ (Path(__file__).parent / "static" / "communityone_logo_64.png", "image/png"),
232
+ (Path(static_dir) / "communityone_logo_64.png", "image/png"),
233
+ (Path(__file__).parent / "static" / "communityone_logo.svg", "image/svg+xml"),
234
+ (Path(static_dir) / "communityone_logo.svg", "image/svg+xml"),
235
+ ]
236
+ for path, media_type in candidates:
237
+ if path.exists():
238
+ return FileResponse(path, media_type=media_type)
239
+ raise HTTPException(status_code=404, detail="Favicon not found")
240
+
241
+
242
+ # Custom Exception Handlers for better error messages
243
+ from fastapi.exceptions import RequestValidationError
244
+ from starlette.exceptions import HTTPException as StarletteHTTPException
245
+ from api.error_pages import error_response
246
+
247
+ @app.exception_handler(StarletteHTTPException)
248
+ async def http_exception_handler(request: Request, exc: StarletteHTTPException):
249
+ """Handle HTTP exceptions with user-friendly, content-negotiated messages."""
250
+ if exc.status_code == 404:
251
+ return error_response(
252
+ request,
253
+ status_code=404,
254
+ title="Page not found",
255
+ message=f"We couldn't find '{request.url.path}'.",
256
+ suggestion="Check the link and try again, or head back to the homepage.",
257
+ extra={"documentation": "/api/docs"},
258
+ )
259
+ elif exc.status_code == 401:
260
+ return error_response(
261
+ request,
262
+ status_code=401,
263
+ title="Sign-in required",
264
+ message=exc.detail or "You need to be signed in to access this.",
265
+ suggestion="Please sign in and try again.",
266
+ extra={"login": "/api/auth/login/google"},
267
+ )
268
+ elif exc.status_code == 403:
269
+ return error_response(
270
+ request,
271
+ status_code=403,
272
+ title="Access denied",
273
+ message=exc.detail or "You don't have permission to access this.",
274
+ suggestion="Contact support if you believe this is a mistake.",
275
+ )
276
+ elif exc.status_code == 503:
277
+ return error_response(
278
+ request,
279
+ status_code=503,
280
+ title="Temporarily unavailable",
281
+ message=exc.detail or "This service is temporarily unavailable.",
282
+ suggestion="Please try again in a few minutes.",
283
+ )
284
+ else:
285
+ return error_response(
286
+ request,
287
+ status_code=exc.status_code,
288
+ title=str(exc.detail) if exc.detail else "Something went wrong",
289
+ message=str(exc.detail) if exc.detail else "An error occurred while processing your request.",
290
+ )
291
+
292
+ @app.exception_handler(RequestValidationError)
293
+ async def validation_exception_handler(request: Request, exc: RequestValidationError):
294
+ """Handle validation errors with detailed, user-friendly messages"""
295
+ errors = []
296
+ for error in exc.errors():
297
+ field = " -> ".join(str(loc) for loc in error["loc"])
298
+ errors.append({
299
+ "field": field,
300
+ "message": error["msg"],
301
+ "type": error["type"]
302
+ })
303
+
304
+ return error_response(
305
+ request,
306
+ status_code=422,
307
+ title="Validation Error",
308
+ message="The request data is invalid. Please check the fields and try again.",
309
+ suggestion="Review the error details and correct the invalid fields.",
310
+ extra={"errors": errors, "documentation": "/api/docs"},
311
+ )
312
+
313
+ @app.exception_handler(500)
314
+ async def internal_server_error_handler(request: Request, exc: Exception):
315
+ """Handle internal server errors with a generic message (hide details from users)."""
316
+ logger.error(f"Internal server error on {request.url.path}: {exc}")
317
+ return error_response(
318
+ request,
319
+ status_code=500,
320
+ title="Something went wrong",
321
+ message="Something went wrong on our end. We've been notified and are working to fix it.",
322
+ suggestion="Please try again in a little while. If it keeps happening, email support and we'll help.",
323
+ )
324
+
325
+
326
+ # Include authentication routes
327
+ from api.routes import auth as auth_routes
328
+ from api.routes import social as social_routes
329
+ from api.routes import search as search_routes
330
+ from api.routes import people as people_routes
331
+ from api.routes import decisions as decisions_routes
332
+ from api.routes import policy_questions as policy_questions_routes
333
+ from api.routes import documents as documents_routes
334
+ from api.routes import jurisdiction_documents as jurisdiction_documents_routes
335
+ from api.routes import jurisdiction_meeting_documents as jurisdiction_meeting_documents_routes
336
+ from api.routes import event_bills as event_bills_routes
337
+ from api.routes import meetings as meetings_routes
338
+ from api.routes import meeting_comparison as meeting_comparison_routes
339
+ # Use Neon database for fast stats queries (500x faster than parquet)
340
+ from api.routes import stats_neon as stats_routes # Was: stats
341
+ from api.routes import contact as contact_routes
342
+ from api.routes import chat_meetings as chat_meetings_routes
343
+ from api.routes import stance as stance_routes
344
+ # Use hybrid approach for bills: Neon for map, parquet for drill-down (saves space)
345
+ from api.routes import bills_neon as bills_routes # Was: bills
346
+ from api.routes import data_deletion as data_deletion_routes
347
+ from api.routes import trending as trending_routes
348
+ from api.routes import lighthouse_reports as lighthouse_reports_routes
349
+ from api.routes import jurisdiction_mapping as jurisdiction_mapping_routes
350
+ from api.routes import batch_jobs as batch_jobs_routes
351
+ from api.routes import deployments as deployments_routes
352
+ from api.routes import locations as locations_routes
353
+ from api.routes import addresses as addresses_routes
354
+ from api.routes import geocode as geocode_routes
355
+ from api.routes import cpi as cpi_routes
356
+ from api.routes import grants as grants_routes
357
+ from api.routes import efile990 as efile990_routes
358
+ from api.routes import lenses as lenses_routes
359
+ from api.routes import money_flow as money_flow_routes
360
+ from api.routes import topics as topics_routes
361
+ from api.routes import short_term_rentals as short_term_rentals_routes
362
+ from api.routes import topic_companies as topic_companies_routes
363
+ from api.routes import topic_timeline as topic_timeline_routes
364
+ from api.routes import topic_policy as topic_policy_routes
365
+ from api.routes import topic_upcoming as topic_upcoming_routes
366
+ from api.routes import topic_caption_facts as topic_caption_facts_routes
367
+ from api.routes import organizations as organizations_routes
368
+ from api.routes import money_and_talk as money_and_talk_routes
369
+ from api.routes import grandkid_outlook as grandkid_outlook_routes
370
+ from api.routes import local_finance as local_finance_routes
371
+ from api.routes import browse as browse_routes
372
+ from api.routes import decision_browse as decision_browse_routes
373
+ from api.routes import meeting_browse as meeting_browse_routes
374
+ from api.routes import feed as feed_routes
375
+ from api.routes import alerts as alerts_routes
376
+ from api.routes import data_centers as data_centers_routes
377
+ from api.routes import data_center_comments as data_center_comments_routes
378
+ from api.routes import data_center_drill as data_center_drill_routes
379
+ from api.database import init_db
380
+
381
+ app.include_router(auth_routes.router, prefix="/api")
382
+ app.include_router(social_routes.router, prefix="/api")
383
+ app.include_router(search_routes.router, prefix="/api")
384
+ app.include_router(people_routes.router, prefix="/api")
385
+ app.include_router(decisions_routes.router, prefix="/api")
386
+ app.include_router(policy_questions_routes.router, prefix="/api")
387
+ app.include_router(jurisdiction_documents_routes.router, prefix="/api")
388
+ app.include_router(jurisdiction_meeting_documents_routes.router, prefix="/api")
389
+ app.include_router(documents_routes.router, prefix="/api")
390
+ app.include_router(event_bills_routes.router, prefix="/api")
391
+ app.include_router(meetings_routes.router, prefix="/api")
392
+ app.include_router(meeting_comparison_routes.router, prefix="/api")
393
+ app.include_router(stats_routes.router, prefix="/api", tags=["stats"])
394
+ app.include_router(contact_routes.router, prefix="/api")
395
+ app.include_router(chat_meetings_routes.router, prefix="/api")
396
+ app.include_router(stance_routes.router, prefix="/api")
397
+ app.include_router(bills_routes.router, prefix="/api")
398
+ app.include_router(data_deletion_routes.router, prefix="/api", tags=["privacy"])
399
+ app.include_router(trending_routes.router)
400
+ app.include_router(lighthouse_reports_routes.router, prefix="/api")
401
+ app.include_router(jurisdiction_mapping_routes.router, prefix="/api")
402
+ app.include_router(batch_jobs_routes.router, prefix="/api")
403
+ app.include_router(deployments_routes.router, prefix="/api")
404
+ app.include_router(locations_routes.router, prefix="/api")
405
+ app.include_router(addresses_routes.router, prefix="/api")
406
+ app.include_router(geocode_routes.router, prefix="/api")
407
+ app.include_router(cpi_routes.router, prefix="/api", tags=["cpi"])
408
+ app.include_router(grants_routes.router, prefix="/api")
409
+ app.include_router(efile990_routes.router, prefix="/api")
410
+ # Prefix ("/api/lenses") is baked into the router — include with NO extra prefix
411
+ # (mirrors how trending_routes is registered).
412
+ app.include_router(lenses_routes.router)
413
+ # Prefix ("/api/money-flow") baked into the router — include with NO extra prefix.
414
+ app.include_router(money_flow_routes.router)
415
+ # Prefix ("/api/topics") baked into the router — include with NO extra prefix.
416
+ app.include_router(topics_routes.router)
417
+ # Prefix ("/api/short-term-rentals") baked into the router (#1015).
418
+ app.include_router(short_term_rentals_routes.router)
419
+ app.include_router(topic_companies_routes.router)
420
+ # Topic timeline + period dumbbell (#1140); prefix /api/topics baked in.
421
+ app.include_router(topic_timeline_routes.router)
422
+ # State bills, local actions and public positions on a topic (#1274); prefix /api/topics baked in.
423
+ app.include_router(topic_policy_routes.router)
424
+ app.include_router(topic_upcoming_routes.router)
425
+ # Prefix ("/api/topics") baked into the router (#1125): the facts behind a topic caption.
426
+ app.include_router(topic_caption_facts_routes.router)
427
+ # Prefix ("/api/organizations") baked into the router (#1015): the organization page.
428
+ app.include_router(organizations_routes.router)
429
+ # Prefix ("/api/money-and-talk") baked into the router — include with NO extra prefix.
430
+ app.include_router(money_and_talk_routes.router)
431
+ # Prefix ("/api/grandkid-outlook") baked into the router — include with NO extra prefix.
432
+ app.include_router(grandkid_outlook_routes.router)
433
+ # Prefix ("/api/local-finance") baked into the router — include with NO extra prefix.
434
+ app.include_router(local_finance_routes.router)
435
+ # Prefix ("/api/browse") baked into the router — include with NO extra prefix.
436
+ app.include_router(browse_routes.router)
437
+ # Flat decision-browse list. Router prefix is "/decisions"; add the shared "/api"
438
+ # prefix the other routers use (distinct from decisions_routes' "/decision" detail).
439
+ app.include_router(decision_browse_routes.router, prefix="/api")
440
+ # Flat meeting-browse list. Router prefix is "/meetings"; add the shared "/api"
441
+ # prefix (meeting-grain analogue of decision_browse_routes).
442
+ app.include_router(meeting_browse_routes.router, prefix="/api")
443
+ app.include_router(alerts_routes.router, prefix="/api")
444
+ app.include_router(feed_routes.router, prefix="/api")
445
+ # Data-center job claims by phase (#246). Router prefix is "/data-centers".
446
+ app.include_router(data_centers_routes.router, prefix="/api")
447
+ app.include_router(data_center_comments_routes.router, prefix="/api")
448
+ app.include_router(data_center_drill_routes.router, prefix="/api")
449
+ # Data-center job-application links (#248): public list + admin screen.
450
+ from api.routes import application_links as application_links_routes
451
+
452
+ app.include_router(application_links_routes.public_router, prefix="/api")
453
+ app.include_router(application_links_routes.admin_router, prefix="/api")
454
+ # Jev meeting-kind review / override (#668).
455
+ from api.routes import meeting_kind_reviews as meeting_kind_reviews_routes
456
+
457
+ app.include_router(meeting_kind_reviews_routes.admin_router, prefix="/api")
458
+ # Official profile claims + pending edits (#1062). Router prefix is "/people".
459
+ from api.routes import person_claims as person_claims_routes
460
+
461
+ app.include_router(person_claims_routes.router, prefix="/api")
462
+
463
+ # Custom Swagger UI with logo.
464
+ # Served at /api/docs (not /docs) so the /docs/ path is free for the Docusaurus
465
+ # documentation bundle in single-process deployments (Databricks Apps) and to
466
+ # match the HuggingFace layout where nginx owns /docs/. ReDoc stays at /redoc.
467
+ @app.get("/api/docs", include_in_schema=False)
468
+ async def custom_swagger_ui_html():
469
+ """Custom Swagger UI with CommunityOne logo"""
470
+ return get_swagger_ui_html(
471
+ openapi_url=app.openapi_url,
472
+ title=f"{app.title} - API Documentation",
473
+ swagger_favicon_url="/static/communityone_logo_64.png",
474
+ swagger_ui_parameters={
475
+ "defaultModelsExpandDepth": -1,
476
+ "docExpansion": "list",
477
+ "filter": True,
478
+ "syntaxHighlight.theme": "monokai"
479
+ }
480
+ )
481
+
482
+ # Initialize database on startup
483
+ @app.on_event("startup")
484
+ async def init_database():
485
+ """Initialize authentication database"""
486
+ try:
487
+ init_db()
488
+ logger.info("✅ Authentication database initialized")
489
+ except Exception as e:
490
+ logger.warning(f"⚠️ Database initialization skipped: {e}")
491
+
492
+ # Initialize components
493
+ orchestrator = OrchestratorAgent()
494
+ pipeline = DeltaLakePipeline()
495
+ heatmap_generator = AdvocacyHeatmap()
496
+
497
+
498
+ # Pydantic models for API
499
+ class ScrapeTarget(BaseModel):
500
+ """Configuration for a scraping target."""
501
+ url: str
502
+ municipality: str
503
+ state: str
504
+ platform: str = "generic"
505
+
506
+
507
+ class WorkflowRequest(BaseModel):
508
+ """Request to start a new analysis workflow."""
509
+ scrape_targets: List[ScrapeTarget]
510
+ date_range: Optional[Dict[str, str]] = None
511
+ description: Optional[str] = None
512
+
513
+
514
+ class WorkflowResponse(BaseModel):
515
+ """Response for workflow operations."""
516
+ workflow_id: str
517
+ status: str
518
+ message: str
519
+
520
+
521
+ class OpportunityFilter(BaseModel):
522
+ """Filters for querying opportunities."""
523
+ state: Optional[str] = None
524
+ municipality: Optional[str] = None
525
+ topic: Optional[str] = None
526
+ urgency: Optional[str] = None
527
+ min_date: Optional[date] = None
528
+ max_date: Optional[date] = None
529
+
530
+
531
+ class OpportunityResponse(BaseModel):
532
+ """Response containing advocacy opportunities."""
533
+ opportunities: List[Dict[str, Any]]
534
+ total_count: int
535
+ filters_applied: Dict[str, Any]
536
+
537
+
538
+ class SystemStatus(BaseModel):
539
+ """System status information."""
540
+ status: str
541
+ active_workflows: int
542
+ agent_status: Dict[str, Any]
543
+ last_update: datetime
544
+
545
+
546
+ class StatesResponse(BaseModel):
547
+ """Response containing US state codes with active opportunities."""
548
+ states: List[str] = Field(..., description="List of 2-letter US state codes")
549
+ count: int = Field(..., description="Total count of states")
550
+
551
+
552
+ # API Endpoints
553
+
554
+ @app.get("/", response_class=HTMLResponse)
555
+ async def root():
556
+ """Root endpoint.
557
+
558
+ Single-process deployments (Databricks Apps) have no nginx in front to serve
559
+ the built React SPA, so when the Vite build is present (``api/static/index.html``)
560
+ we serve it here. Without a build (e.g. an API-only container) we fall back to
561
+ the informational API landing page below.
562
+ """
563
+ spa_index = Path(__file__).parent / "static" / "index.html"
564
+ if spa_index.is_file():
565
+ from fastapi.responses import FileResponse
566
+ return FileResponse(spa_index, media_type="text/html")
567
+ html_content = """
568
+ <!DOCTYPE html>
569
+ <html>
570
+ <head>
571
+ <title>Open Navigator API</title>
572
+ <style>
573
+ body {
574
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
575
+ max-width: 900px;
576
+ margin: 50px auto;
577
+ padding: 20px;
578
+ line-height: 1.6;
579
+ }
580
+ .header {
581
+ display: flex;
582
+ align-items: center;
583
+ gap: 20px;
584
+ margin-bottom: 30px;
585
+ border-bottom: 2px solid #1976d2;
586
+ padding-bottom: 20px;
587
+ }
588
+ .logo {
589
+ width: 80px;
590
+ height: 80px;
591
+ }
592
+ h1 {
593
+ color: #1976d2;
594
+ margin: 0;
595
+ }
596
+ .tagline {
597
+ color: #666;
598
+ font-size: 1.1em;
599
+ }
600
+ .endpoint {
601
+ background: linear-gradient(135deg, #f5f5f5 0%, #e8f4f8 100%);
602
+ padding: 15px;
603
+ margin: 10px 0;
604
+ border-radius: 8px;
605
+ border-left: 4px solid #1976d2;
606
+ }
607
+ .endpoint strong {
608
+ color: #1976d2;
609
+ }
610
+ code {
611
+ background: #e0e0e0;
612
+ padding: 3px 8px;
613
+ border-radius: 4px;
614
+ font-family: 'Courier New', monospace;
615
+ }
616
+ .docs-link {
617
+ display: inline-block;
618
+ background: #1976d2;
619
+ color: white;
620
+ padding: 12px 24px;
621
+ text-decoration: none;
622
+ border-radius: 6px;
623
+ margin-top: 20px;
624
+ transition: background 0.3s;
625
+ }
626
+ .docs-link:hover {
627
+ background: #1565c0;
628
+ }
629
+ </style>
630
+ </head>
631
+ <body>
632
+ <div class="header">
633
+ <img src="/static/communityone_logo.svg" alt="CommunityOne Logo" class="logo">
634
+ <div>
635
+ <h1>Open Navigator API</h1>
636
+ <p class="tagline">CommunityOne: The open path to everything local</p>
637
+ </div>
638
+ </div>
639
+
640
+ <h2>🔑 Key Endpoints:</h2>
641
+ <div class="endpoint">
642
+ <strong>POST /workflow/start</strong> - Start a new analysis workflow
643
+ </div>
644
+ <div class="endpoint">
645
+ <strong>GET /opportunities</strong> - Query advocacy opportunities
646
+ </div>
647
+ <div class="endpoint">
648
+ <strong>GET /heatmap</strong> - Get advocacy heatmap visualization
649
+ </div>
650
+ <div class="endpoint">
651
+ <strong>GET /status</strong> - System status and health
652
+ </div>
653
+ <div class="endpoint">
654
+ <strong>POST /auth/login/{provider}</strong> - OAuth login (HuggingFace, Google, Facebook, GitHub)
655
+ </div>
656
+
657
+ <a href="/api/docs" class="docs-link">📚 View Full API Documentation</a>
658
+ </body>
659
+ </html>
660
+ """
661
+ return HTMLResponse(content=html_content)
662
+
663
+
664
+ @app.post("/workflow/start", response_model=WorkflowResponse)
665
+ async def start_workflow(
666
+ request: WorkflowRequest,
667
+ background_tasks: BackgroundTasks
668
+ ):
669
+ """
670
+ Start a new policy analysis workflow.
671
+
672
+ This initiates the full multi-agent pipeline:
673
+ 1. Scrape meeting minutes from specified sources
674
+ 2. Parse and structure the data
675
+ 3. Classify by oral health topics
676
+ 4. Analyze sentiment and policy stance
677
+ 5. Generate advocacy materials
678
+ """
679
+ try:
680
+ # Register agents with orchestrator
681
+ orchestrator.register_agent(ScraperAgent())
682
+ orchestrator.register_agent(ParserAgent())
683
+ orchestrator.register_agent(ClassifierAgent())
684
+ orchestrator.register_agent(SentimentAnalyzerAgent())
685
+ orchestrator.register_agent(AdvocacyWriterAgent())
686
+
687
+ # Convert targets to dict format
688
+ targets = [target.dict() for target in request.scrape_targets]
689
+
690
+ # Start workflow in background
691
+ background_tasks.add_task(
692
+ orchestrator.execute_pipeline,
693
+ targets,
694
+ request.date_range
695
+ )
696
+
697
+ return WorkflowResponse(
698
+ workflow_id="wf-" + datetime.utcnow().strftime("%Y%m%d-%H%M%S"),
699
+ status="started",
700
+ message=f"Workflow started with {len(targets)} targets"
701
+ )
702
+
703
+ except Exception as e:
704
+ logger.error(f"Error starting workflow: {e}")
705
+ raise HTTPException(status_code=500, detail=str(e))
706
+
707
+
708
+ @app.get("/workflow/{workflow_id}/status")
709
+ async def get_workflow_status(workflow_id: str):
710
+ """Get the status of a specific workflow."""
711
+ # Query workflow status from orchestrator
712
+ # This is a placeholder - would query actual workflow state
713
+ return {
714
+ "workflow_id": workflow_id,
715
+ "status": "running",
716
+ "stage": "classification",
717
+ "progress": 0.6
718
+ }
719
+
720
+
721
+ @app.get("/opportunities", response_model=OpportunityResponse)
722
+ async def get_opportunities(
723
+ state: Optional[str] = Query(None, description="Filter by state code"),
724
+ municipality: Optional[str] = Query(None, description="Filter by municipality"),
725
+ topic: Optional[str] = Query(None, description="Filter by policy topic"),
726
+ urgency: Optional[str] = Query(None, description="Filter by urgency level"),
727
+ limit: int = Query(100, ge=1, le=1000, description="Maximum results to return")
728
+ ):
729
+ """
730
+ Query advocacy opportunities.
731
+
732
+ Returns a list of identified opportunities for advocacy action
733
+ based on the specified filters.
734
+ """
735
+ try:
736
+ # Query from Delta Lake
737
+ opportunities = pipeline.query_opportunities_by_state(state, urgency)
738
+
739
+ # Apply additional filters
740
+ if municipality:
741
+ opportunities = [
742
+ opp for opp in opportunities
743
+ if opp.get("municipality", "").lower() == municipality.lower()
744
+ ]
745
+
746
+ if topic:
747
+ opportunities = [
748
+ opp for opp in opportunities
749
+ if opp.get("topic") == topic
750
+ ]
751
+
752
+ # Limit results
753
+ opportunities = opportunities[:limit]
754
+
755
+ return OpportunityResponse(
756
+ opportunities=opportunities,
757
+ total_count=len(opportunities),
758
+ filters_applied={
759
+ "state": state,
760
+ "municipality": municipality,
761
+ "topic": topic,
762
+ "urgency": urgency
763
+ }
764
+ )
765
+
766
+ except Exception as e:
767
+ logger.error(f"Error querying opportunities: {e}")
768
+ raise HTTPException(status_code=500, detail=str(e))
769
+
770
+
771
+ # Deterministic state center coordinates (WGS84) used as a fallback when a bill's
772
+ # linked jurisdiction row does not provide explicit latitude/longitude coordinates.
773
+ STATE_COORDS: Dict[str, tuple[float, float]] = {
774
+ "AL": (32.806671, -86.791130),
775
+ "AK": (61.370716, -152.404419),
776
+ "AZ": (33.729759, -111.431221),
777
+ "AR": (34.969704, -92.373123),
778
+ "CA": (36.116203, -119.681564),
779
+ "CO": (39.059811, -105.311104),
780
+ "CT": (41.597782, -72.755371),
781
+ "DE": (39.318523, -75.507141),
782
+ "DC": (38.897438, -77.026817),
783
+ "FL": (27.766279, -81.686783),
784
+ "GA": (33.040619, -83.643074),
785
+ "HI": (21.094318, -157.498337),
786
+ "ID": (44.240459, -114.478828),
787
+ "IL": (40.349457, -88.986137),
788
+ "IN": (39.849426, -86.258278),
789
+ "IA": (42.011539, -93.210526),
790
+ "KS": (38.526600, -96.726486),
791
+ "KY": (37.668140, -84.670067),
792
+ "LA": (31.169546, -91.867805),
793
+ "ME": (44.693947, -69.381927),
794
+ "MD": (39.063946, -76.802101),
795
+ "MA": (42.230171, -71.530106),
796
+ "MI": (43.326618, -84.536095),
797
+ "MN": (45.694454, -93.900192),
798
+ "MS": (32.741646, -89.678696),
799
+ "MO": (38.456085, -92.288368),
800
+ "MT": (46.921925, -110.454353),
801
+ "NE": (41.125370, -98.268082),
802
+ "NV": (38.313515, -117.055374),
803
+ "NH": (43.452492, -71.563896),
804
+ "NJ": (40.298904, -74.521011),
805
+ "NM": (34.840515, -106.248482),
806
+ "NY": (42.165726, -74.948051),
807
+ "NC": (35.630066, -79.806419),
808
+ "ND": (47.528912, -99.784012),
809
+ "OH": (40.388783, -82.764915),
810
+ "OK": (35.565342, -96.928917),
811
+ "OR": (44.572021, -122.070938),
812
+ "PA": (40.590752, -77.209755),
813
+ "RI": (41.680893, -71.511780),
814
+ "SC": (33.856892, -80.945007),
815
+ "SD": (44.299782, -99.438828),
816
+ "TN": (35.747845, -86.692345),
817
+ "TX": (31.054487, -97.563461),
818
+ "UT": (40.150032, -111.862434),
819
+ "VT": (44.045876, -72.710686),
820
+ "VA": (37.769337, -78.169968),
821
+ "WA": (47.400902, -121.490494),
822
+ "WV": (38.491226, -80.954453),
823
+ "WI": (44.268543, -89.616508),
824
+ "WY": (42.755966, -107.302490),
825
+ }
826
+
827
+ DEFAULT_OPPORTUNITY_STATES: tuple[str, ...] = ("AL", "GA", "IN", "MA", "WA", "WI")
828
+
829
+ _OPPORTUNITY_TOPIC_ALIASES: Dict[str, str] = {
830
+ "fluoride": "water_fluoridation",
831
+ "water_fluoridation": "water_fluoridation",
832
+ "dental": "school_dental_screening",
833
+ "school_dental_screening": "school_dental_screening",
834
+ "medicaid": "medicaid_dental_expansion",
835
+ "medicaid_dental_expansion": "medicaid_dental_expansion",
836
+ }
837
+
838
+
839
+ # React frontend endpoints with /api/ prefix
840
+ @app.get("/api/opportunities")
841
+ async def get_api_opportunities(
842
+ state: Optional[str] = Query(None),
843
+ topic: Optional[str] = Query(None),
844
+ urgency: Optional[str] = Query(None),
845
+ limit: int = Query(100, ge=1, le=1000)
846
+ ):
847
+ """API endpoint for React frontend opportunities page - returns fluoridation bills as advocacy opportunities."""
848
+ try:
849
+ from api.routes.bills_neon import get_pool
850
+
851
+ if state is not None:
852
+ state_norm = state.strip().upper()
853
+ if state_norm not in STATE_COORDS:
854
+ return {"opportunities": [], "total": 0}
855
+ states = [state_norm]
856
+ else:
857
+ states = list(DEFAULT_OPPORTUNITY_STATES)
858
+
859
+ topic_norm: Optional[str] = None
860
+ if topic is not None and topic.strip():
861
+ raw_topic = topic.strip().lower()
862
+ topic_norm = _OPPORTUNITY_TOPIC_ALIASES.get(raw_topic, raw_topic)
863
+
864
+ urgency_norm: Optional[str] = (
865
+ urgency.strip().lower() if urgency is not None and urgency.strip() else None
866
+ )
867
+
868
+ pool = await get_pool()
869
+ if pool is None:
870
+ return {"opportunities": [], "total": 0}
871
+
872
+ sql_limit = min(max(limit * 5, limit), 1000) if (topic_norm or urgency_norm) else limit
873
+
874
+ # Query the Postgres `bills` mart joined to `jurisdictions` so real
875
+ # jurisdiction coordinates are used when available, with deterministic
876
+ # fallback to STATE_COORDS.
877
+ query_with_jurisdictions = """
878
+ SELECT
879
+ b.state_code,
880
+ b.title,
881
+ b.identifier,
882
+ b.session_identifier,
883
+ b.latest_action_description,
884
+ b.latest_action_date,
885
+ j.latitude::float8 AS jurisdiction_latitude,
886
+ j.longitude::float8 AS jurisdiction_longitude
887
+ FROM bills b
888
+ LEFT JOIN jurisdictions j
889
+ ON j.jurisdiction_id = b.jurisdiction_id
890
+ WHERE b.state_code = ANY($1::text[])
891
+ AND (LOWER(b.title) LIKE '%fluorid%'
892
+ OR LOWER(b.title) LIKE '%dental%'
893
+ OR LOWER(b.title) LIKE '%oral health%'
894
+ OR LOWER(b.title) LIKE '%water treat%')
895
+ ORDER BY b.latest_action_date DESC NULLS LAST, b.identifier ASC
896
+ LIMIT $2
897
+ """
898
+ fallback_query = """
899
+ SELECT
900
+ state_code,
901
+ title,
902
+ identifier,
903
+ session_identifier,
904
+ latest_action_description,
905
+ latest_action_date
906
+ FROM bills
907
+ WHERE state_code = ANY($1::text[])
908
+ AND (LOWER(title) LIKE '%fluorid%'
909
+ OR LOWER(title) LIKE '%dental%'
910
+ OR LOWER(title) LIKE '%oral health%'
911
+ OR LOWER(title) LIKE '%water treat%')
912
+ ORDER BY latest_action_date DESC NULLS LAST, identifier ASC
913
+ LIMIT $2
914
+ """
915
+
916
+ async with pool.acquire() as conn:
917
+ try:
918
+ result = await conn.fetch(query_with_jurisdictions, states, sql_limit)
919
+ except Exception:
920
+ result = await conn.fetch(fallback_query, states, sql_limit)
921
+
922
+ opportunities = []
923
+ for row in result:
924
+ row_dict = dict(row)
925
+ state_code = (row_dict.get("state_code") or "").strip().upper()
926
+ title = row_dict.get("title")
927
+ identifier = row_dict.get("identifier")
928
+ session = row_dict.get("session_identifier")
929
+ latest_action = row_dict.get("latest_action_description")
930
+ latest_action_date = row_dict.get("latest_action_date")
931
+
932
+ title_lower = title.lower() if title else ""
933
+ if "fluoride" in title_lower or "fluorin" in title_lower or "water" in title_lower:
934
+ urgency_level = "critical"
935
+ confidence = 0.9
936
+ topic_type = "water_fluoridation"
937
+ elif "dental" in title_lower:
938
+ urgency_level = "high"
939
+ confidence = 0.75
940
+ topic_type = "school_dental_screening"
941
+ else:
942
+ urgency_level = "medium"
943
+ confidence = 0.6
944
+ topic_type = "medicaid_dental_expansion"
945
+
946
+ if topic_norm and topic_type != topic_norm:
947
+ continue
948
+
949
+ if urgency_norm and urgency_level != urgency_norm:
950
+ continue
951
+
952
+ juris_lat = row_dict.get("jurisdiction_latitude")
953
+ juris_lon = row_dict.get("jurisdiction_longitude")
954
+ if juris_lat is not None and juris_lon is not None:
955
+ latitude = float(juris_lat)
956
+ longitude = float(juris_lon)
957
+ elif state_code in STATE_COORDS:
958
+ latitude, longitude = STATE_COORDS[state_code]
959
+ else:
960
+ continue
961
+
962
+ opportunities.append({
963
+ "state": state_code,
964
+ "municipality": f"{state_code} Legislature",
965
+ "latitude": latitude,
966
+ "longitude": longitude,
967
+ "topic": topic_type,
968
+ "urgency": urgency_level,
969
+ "confidence": confidence,
970
+ "meeting_date": latest_action_date.isoformat() if hasattr(latest_action_date, "isoformat") else (str(latest_action_date) if latest_action_date else None),
971
+ "title": title,
972
+ "bill_id": identifier,
973
+ "session": session,
974
+ "latest_action": latest_action,
975
+ })
976
+
977
+ if len(opportunities) >= limit:
978
+ break
979
+
980
+ return {"opportunities": opportunities, "total": len(opportunities)}
981
+ except Exception as e:
982
+ logger.error(f"Error: {e}")
983
+ return {"opportunities": [], "total": 0}
984
+
985
+
986
+ @app.get("/api/documents")
987
+ async def get_api_documents(
988
+ search: Optional[str] = Query(None),
989
+ page: int = Query(1),
990
+ limit: int = Query(20)
991
+ ):
992
+ """API endpoint for React frontend documents page."""
993
+ try:
994
+ # Get all opportunities (documents)
995
+ documents = pipeline.query_opportunities_by_state(None, None)
996
+
997
+ # Apply search filter
998
+ if search:
999
+ search_lower = search.lower()
1000
+ documents = [
1001
+ d for d in documents
1002
+ if search_lower in d.get("title", "").lower() or
1003
+ search_lower in d.get("municipality", "").lower() or
1004
+ search_lower in d.get("content", "").lower()
1005
+ ]
1006
+
1007
+ # Paginate
1008
+ start = (page - 1) * limit
1009
+ end = start + limit
1010
+
1011
+ return {
1012
+ "documents": documents[start:end],
1013
+ "total": len(documents),
1014
+ "page": page,
1015
+ "limit": limit
1016
+ }
1017
+ except Exception as e:
1018
+ logger.error(f"Error: {e}")
1019
+ return {"documents": [], "total": 0}
1020
+
1021
+
1022
+ @app.get("/opportunities/{opportunity_id}")
1023
+ async def get_opportunity_detail(opportunity_id: str):
1024
+ """Get detailed information about a specific opportunity."""
1025
+ # Query specific opportunity
1026
+ document = pipeline.get_document_by_id(opportunity_id)
1027
+
1028
+ if not document:
1029
+ raise HTTPException(status_code=404, detail="Opportunity not found")
1030
+
1031
+ return document
1032
+
1033
+
1034
+ @app.get("/opportunities/{opportunity_id}/materials")
1035
+ async def get_advocacy_materials(opportunity_id: str):
1036
+ """Get generated advocacy materials for an opportunity."""
1037
+ # Query materials from Delta Lake
1038
+ # This is a placeholder
1039
+ return {
1040
+ "opportunity_id": opportunity_id,
1041
+ "materials": {
1042
+ "email": {
1043
+ "subject": "Support Oral Health Policy",
1044
+ "body": "..."
1045
+ },
1046
+ "talking_points": [],
1047
+ "social_media": {}
1048
+ }
1049
+ }
1050
+
1051
+
1052
+ @app.get("/heatmap", response_class=HTMLResponse)
1053
+ async def get_heatmap(
1054
+ urgency: Optional[str] = Query(None, description="Filter by urgency level")
1055
+ ):
1056
+ """
1057
+ Get interactive heatmap visualization.
1058
+
1059
+ Returns an HTML page with an interactive map showing
1060
+ advocacy opportunities across the country.
1061
+ """
1062
+ try:
1063
+ # Query opportunities
1064
+ opportunities = pipeline.query_opportunities_by_state(None, urgency)
1065
+
1066
+ # Generate map
1067
+ m = heatmap_generator.create_folium_map(
1068
+ opportunities,
1069
+ title="Open Navigator - Advocacy Heatmap"
1070
+ )
1071
+
1072
+ # Return HTML
1073
+ return HTMLResponse(content=m._repr_html_())
1074
+
1075
+ except Exception as e:
1076
+ logger.error(f"Error generating heatmap: {e}")
1077
+ raise HTTPException(status_code=500, detail=str(e))
1078
+
1079
+
1080
+ @app.get("/dashboard")
1081
+ async def get_dashboard():
1082
+ """
1083
+ Get complete dashboard data including statistics and visualizations.
1084
+ """
1085
+ try:
1086
+ # Query all opportunities
1087
+ opportunities = pipeline.query_opportunities_by_state(None, None)
1088
+
1089
+ # Generate dashboard
1090
+ dashboard = heatmap_generator.create_dashboard(opportunities)
1091
+
1092
+ # Convert visualizations to JSON-serializable format
1093
+ return {
1094
+ "statistics": dashboard["statistics"],
1095
+ "topic_distribution": dashboard["topic_distribution"].to_json(),
1096
+ "timeline": dashboard["timeline"].to_json()
1097
+ }
1098
+
1099
+ except Exception as e:
1100
+ logger.error(f"Error generating dashboard: {e}")
1101
+ raise HTTPException(status_code=500, detail=str(e))
1102
+
1103
+
1104
+ @app.get("/api/dashboard")
1105
+ async def get_api_dashboard():
1106
+ """
1107
+ Get dashboard statistics for React frontend.
1108
+ Returns data in format expected by frontend Dashboard component.
1109
+ """
1110
+ try:
1111
+ # Query all opportunities
1112
+ opportunities = pipeline.query_opportunities_by_state(None, None)
1113
+
1114
+ # Count topics
1115
+ topics_count = {}
1116
+ for opp in opportunities:
1117
+ topic = opp.get("topic", "unknown")
1118
+ topics_count[topic] = topics_count.get(topic, 0) + 1
1119
+
1120
+ # Get unique states
1121
+ states = set(opp.get("state") for opp in opportunities if opp.get("state"))
1122
+
1123
+ # Get recent opportunities (last 10)
1124
+ recent = sorted(
1125
+ opportunities,
1126
+ key=lambda x: x.get("meeting_date", ""),
1127
+ reverse=True
1128
+ )[:10]
1129
+
1130
+ return {
1131
+ "total_documents": len(opportunities),
1132
+ "total_opportunities": len(opportunities),
1133
+ "states_monitored": len(states),
1134
+ "topics": topics_count,
1135
+ "recent_opportunities": recent
1136
+ }
1137
+
1138
+ except Exception as e:
1139
+ logger.error(f"Error generating API dashboard: {e}")
1140
+ # Return mock data if there's an error
1141
+ return {
1142
+ "total_documents": 0,
1143
+ "total_opportunities": 0,
1144
+ "states_monitored": 0,
1145
+ "topics": {},
1146
+ "recent_opportunities": []
1147
+ }
1148
+
1149
+
1150
+ @app.get("/topics")
1151
+ async def get_topics():
1152
+ """Get list of all policy topics being tracked."""
1153
+ return {
1154
+ "topics": settings.policy_topics,
1155
+ "count": len(settings.policy_topics)
1156
+ }
1157
+
1158
+
1159
+ @app.get("/states", response_model=StatesResponse, tags=["opportunities"])
1160
+ @app.get("/api/states", response_model=StatesResponse, tags=["opportunities"])
1161
+ async def get_states() -> StatesResponse:
1162
+ """Get list of all states with active opportunities.
1163
+
1164
+ Queries distinct state codes from active bills in the database if available.
1165
+ When the query fails or returns nothing, uses the configured
1166
+ `settings.target_states` (real configuration). If that is not set either,
1167
+ returns an empty list rather than inventing states.
1168
+ """
1169
+ try:
1170
+ from api.routes.bills_neon import get_pool
1171
+ pool = await get_pool()
1172
+ if pool is not None:
1173
+ query = """
1174
+ SELECT DISTINCT UPPER(state_code) AS state_code
1175
+ FROM bills
1176
+ WHERE state_code IS NOT NULL
1177
+ AND state_code != ''
1178
+ AND (
1179
+ LOWER(title) LIKE '%fluorid%'
1180
+ OR LOWER(title) LIKE '%dental%'
1181
+ OR LOWER(title) LIKE '%oral health%'
1182
+ OR LOWER(title) LIKE '%water treat%'
1183
+ )
1184
+ ORDER BY UPPER(state_code)
1185
+ """
1186
+ async with pool.acquire() as conn:
1187
+ rows = await conn.fetch(query)
1188
+ db_states = sorted(set(str(row["state_code"]).strip().upper() for row in rows if row.get("state_code")))
1189
+ if db_states:
1190
+ return StatesResponse(states=db_states, count=len(db_states))
1191
+ except Exception as e:
1192
+ logger.warning(f"Failed to query active opportunity states from bills database: {e}")
1193
+
1194
+ # No database result: use configured target states (real configuration), never an invented list.
1195
+ configured_states = settings.target_states
1196
+ if configured_states:
1197
+ resolved = sorted(set(st.strip().upper() for st in configured_states if st and st.strip()))
1198
+ else:
1199
+ resolved = []
1200
+ logger.warning("No active opportunity states from the database and settings.target_states is not set; returning an empty list")
1201
+
1202
+ return StatesResponse(states=resolved, count=len(resolved))
1203
+
1204
+
1205
+ @app.get("/status", response_model=SystemStatus)
1206
+ async def get_system_status():
1207
+ """Get current system status and health."""
1208
+ try:
1209
+ agent_status = orchestrator.get_all_agent_states()
1210
+
1211
+ return SystemStatus(
1212
+ status="operational",
1213
+ active_workflows=len(orchestrator.active_workflows),
1214
+ agent_status=agent_status,
1215
+ last_update=datetime.utcnow()
1216
+ )
1217
+
1218
+ except Exception as e:
1219
+ logger.error(f"Error getting system status: {e}")
1220
+ return SystemStatus(
1221
+ status="error",
1222
+ active_workflows=0,
1223
+ agent_status={},
1224
+ last_update=datetime.utcnow()
1225
+ )
1226
+
1227
+
1228
+ @app.get("/nonprofits")
1229
+ async def search_nonprofits(
1230
+ location: str = Query("Tuscaloosa, AL", description="City, State format"),
1231
+ keyword: Optional[str] = Query(None, description="Service keyword (e.g., 'dental', 'health')"),
1232
+ state: Optional[str] = Query(None, description="2-letter state code (e.g., 'AL')"),
1233
+ ntee_code: Optional[str] = Query(None, description="NTEE code (e.g., 'E' for health)"),
1234
+ source: Optional[str] = Query(None, description="Data source: 'propublica', 'everyorg', 'all'")
1235
+ ):
1236
+ """
1237
+ Search for nonprofits using free open data APIs.
1238
+
1239
+ Integrates data from:
1240
+ - ProPublica Nonprofit Explorer (financial data, NTEE codes)
1241
+ - Every.org (mission statements, logos)
1242
+ - IRS TEOS (official tax-exempt status)
1243
+
1244
+ Example: /nonprofits?location=Tuscaloosa,AL&keyword=dental&ntee_code=E
1245
+ """
1246
+ try:
1247
+ from scrapers.irs.nonprofit_discovery import NonprofitDiscovery
1248
+
1249
+ discovery = NonprofitDiscovery()
1250
+ results = []
1251
+
1252
+ # Parse location for state/city
1253
+ location_parts = location.split(',')
1254
+ city = location_parts[0].strip() if len(location_parts) > 0 else None
1255
+ state_from_location = location_parts[1].strip() if len(location_parts) > 1 else None
1256
+ state_code = state or state_from_location or "AL"
1257
+
1258
+ # Determine which sources to query
1259
+ sources_to_query = ['propublica', 'everyorg'] if source == 'all' or not source else [source]
1260
+
1261
+ # Query ProPublica
1262
+ if 'propublica' in sources_to_query:
1263
+ try:
1264
+ propublica_results = discovery.search_propublica(
1265
+ state=state_code,
1266
+ city=city,
1267
+ ntee_code=ntee_code
1268
+ )
1269
+ results.extend(propublica_results)
1270
+ logger.info(f"ProPublica: Found {len(propublica_results)} organizations")
1271
+ except Exception as e:
1272
+ logger.warning(f"ProPublica search failed: {e}")
1273
+
1274
+ # Query Every.org
1275
+ if 'everyorg' in sources_to_query:
1276
+ try:
1277
+ causes = []
1278
+ if keyword:
1279
+ # Map keywords to causes
1280
+ keyword_lower = keyword.lower()
1281
+ if 'health' in keyword_lower or 'dental' in keyword_lower or 'medical' in keyword_lower:
1282
+ causes.append('health')
1283
+ if 'education' in keyword_lower or 'school' in keyword_lower:
1284
+ causes.append('education')
1285
+
1286
+ everyorg_results = discovery.search_everyorg(
1287
+ location=location,
1288
+ causes=causes if causes else None
1289
+ )
1290
+ results.extend(everyorg_results)
1291
+ logger.info(f"Every.org: Found {len(everyorg_results)} organizations")
1292
+ except Exception as e:
1293
+ logger.warning(f"Every.org search failed: {e}")
1294
+
1295
+ # Filter by keyword if provided
1296
+ if keyword and results:
1297
+ keyword_lower = keyword.lower()
1298
+ filtered_results = []
1299
+ for org in results:
1300
+ # Search in name, description, mission, ntee_description
1301
+ searchable_text = ' '.join([
1302
+ str(org.get('name', '')),
1303
+ str(org.get('description', '')),
1304
+ str(org.get('mission', '')),
1305
+ str(org.get('ntee_description', ''))
1306
+ ]).lower()
1307
+
1308
+ if keyword_lower in searchable_text:
1309
+ filtered_results.append(org)
1310
+
1311
+ results = filtered_results
1312
+
1313
+ return {
1314
+ "location": location,
1315
+ "keyword": keyword,
1316
+ "state": state_code,
1317
+ "ntee_code": ntee_code,
1318
+ "count": len(results),
1319
+ "nonprofits": results,
1320
+ "data_sources": {
1321
+ "propublica": "https://projects.propublica.org/nonprofits/api",
1322
+ "everyorg": "https://www.every.org/nonprofit-api",
1323
+ "irs_teos": "https://www.irs.gov/charities-non-profits/tax-exempt-organization-search-bulk-data-downloads"
1324
+ }
1325
+ }
1326
+
1327
+ except Exception as e:
1328
+ logger.error(f"Nonprofit search error: {e}")
1329
+ raise HTTPException(status_code=500, detail=str(e))
1330
+
1331
+
1332
+ @app.get("/api/nonprofits")
1333
+ async def search_nonprofits_api(
1334
+ location: str = Query("Tuscaloosa, AL", description="City, State format"),
1335
+ keyword: Optional[str] = Query(None, description="Service keyword (e.g., 'dental', 'health')"),
1336
+ state: Optional[str] = Query(None, description="2-letter state code (e.g., 'AL')"),
1337
+ ntee_code: Optional[str] = Query(None, description="NTEE code (e.g., 'E' for health)"),
1338
+ source: Optional[str] = Query(None, description="Data source: 'propublica', 'everyorg', 'all'")
1339
+ ):
1340
+ """
1341
+ Search for nonprofits using free open data APIs (API-prefixed endpoint for frontend).
1342
+
1343
+ This is a duplicate of /nonprofits with /api prefix for frontend routing.
1344
+ """
1345
+ return await search_nonprofits(location, keyword, state, ntee_code, source)
1346
+
1347
+
1348
+ @app.get("/data/status")
1349
+ async def get_data_ingestion_status():
1350
+ """
1351
+ Get status of reference data ingestions.
1352
+
1353
+ Shows Census jurisdictions, NCES school districts, and nonprofit cache status.
1354
+
1355
+ Every count is a real warehouse value (see
1356
+ ``stats_neon.fetch_national_reference_counts``) or ``null`` when it can't be
1357
+ computed — never a hard-coded estimate (CLAUDE.md, "No Fabricated Data").
1358
+ """
1359
+ try:
1360
+ from pathlib import Path
1361
+
1362
+ from api.routes.stats_neon import fetch_national_reference_counts
1363
+
1364
+ counts = await fetch_national_reference_counts()
1365
+ status = {
1366
+ "census": {
1367
+ "jurisdictions": counts["jurisdictions"],
1368
+ "counties": counts["counties"],
1369
+ "municipalities": counts["municipalities"],
1370
+ "status": "public.jurisdiction_state_aggregate (national) + public.civic_jurisdiction",
1371
+ },
1372
+ "nces": {
1373
+ "school_districts": counts["school_districts"],
1374
+ "status": "public.jurisdiction_state_aggregate (national)",
1375
+ },
1376
+ "nonprofits": {
1377
+ "total_available": counts["nonprofits"],
1378
+ "cached_searches": 0,
1379
+ "cache_path": "data/cache/nonprofits"
1380
+ },
1381
+ # Per-source meeting counts (MeetingBank, City Scrapers, Open States)
1382
+ # are not modeled in `public`; unavailable rather than guessed.
1383
+ "meetings": {
1384
+ "meetingbank": None,
1385
+ "city_scrapers": None,
1386
+ "open_states": None,
1387
+ }
1388
+ }
1389
+
1390
+ # Check cache directories
1391
+ cache_dir = Path("data/cache/nonprofits")
1392
+ if cache_dir.exists():
1393
+ cached_files = list(cache_dir.glob("*.json"))
1394
+ status["nonprofits"]["cached_searches"] = len(cached_files)
1395
+
1396
+ return status
1397
+
1398
+ except Exception as e:
1399
+ logger.error(f"Data status error: {e}")
1400
+ return {"error": str(e)}
1401
+
1402
+
1403
+ @app.post("/data/ingest/nonprofits")
1404
+ async def bulk_ingest_nonprofits(
1405
+ state: str = Query(..., description="State code (e.g., AL)"),
1406
+ ntee_code: Optional[str] = Query("E", description="NTEE code (default: E for Health)")
1407
+ ):
1408
+ """
1409
+ Bulk ingest nonprofit data for a state.
1410
+
1411
+ Caches ProPublica API results for offline use.
1412
+ """
1413
+ try:
1414
+ from scrapers.irs.nonprofit_discovery import NonprofitDiscovery
1415
+
1416
+ discovery = NonprofitDiscovery()
1417
+ orgs = discovery.search_propublica(state=state, ntee_code=ntee_code)
1418
+
1419
+ return {
1420
+ "message": f"Ingested {len(orgs)} nonprofits for {state}",
1421
+ "state": state,
1422
+ "ntee_code": ntee_code,
1423
+ "count": len(orgs),
1424
+ "cache_location": "data/cache/nonprofits"
1425
+ }
1426
+
1427
+ except Exception as e:
1428
+ logger.error(f"Nonprofit ingestion error: {e}")
1429
+ raise HTTPException(status_code=500, detail=str(e))
1430
+
1431
+
1432
+ @app.get("/health")
1433
+ async def health_check():
1434
+ """Health check endpoint for monitoring."""
1435
+ return {
1436
+ "status": "healthy",
1437
+ "timestamp": datetime.utcnow().isoformat(),
1438
+ "version": "1.0.0"
1439
+ }
1440
+
1441
+
1442
+ @app.get("/api/health")
1443
+ async def api_health_check():
1444
+ """Health check endpoint for monitoring (API path)."""
1445
+ return {
1446
+ "status": "healthy",
1447
+ "timestamp": datetime.utcnow().isoformat(),
1448
+ "version": "1.0.0"
1449
+ }
1450
+
1451
+
1452
+ @app.post("/admin/initialize")
1453
+ async def initialize_system():
1454
+ """Initialize Delta Lake tables and system components."""
1455
+ try:
1456
+ pipeline.initialize_tables()
1457
+
1458
+ return {
1459
+ "status": "success",
1460
+ "message": "System initialized successfully"
1461
+ }
1462
+
1463
+ except Exception as e:
1464
+ logger.error(f"Error initializing system: {e}")
1465
+ raise HTTPException(status_code=500, detail=str(e))
1466
+
1467
+
1468
+ # Startup event
1469
+ @app.post("/api/debate-grade")
1470
+ async def grade_decision_with_debate_framework(
1471
+ document_id: Optional[str] = Query(None, description="Document ID to grade"),
1472
+ text: Optional[str] = Query(None, description="Text to grade directly"),
1473
+ title: Optional[str] = Query("", description="Document title")
1474
+ ):
1475
+ """
1476
+ Grade a government decision using debate framework (Harms/Solvency/Topicality).
1477
+
1478
+ Translates debate concepts for laypeople:
1479
+ - Harms → "The Problem": Why is this a crisis?
1480
+ - Solvency → "The Fix": How does this solution work?
1481
+ - Topicality → "The Scope": Does the government have authority?
1482
+
1483
+ Example: /api/debate-grade?text=The city council approved funding for dental screening...
1484
+ """
1485
+ try:
1486
+ from agents.debate_grader import DebateGraderAgent
1487
+
1488
+ grader = DebateGraderAgent()
1489
+
1490
+ # Get document content
1491
+ if document_id:
1492
+ document = pipeline.get_document_by_id(document_id)
1493
+ if not document:
1494
+ raise HTTPException(status_code=404, detail="Document not found")
1495
+ elif text:
1496
+ document = {
1497
+ "content": text,
1498
+ "title": title,
1499
+ "id": "custom_text"
1500
+ }
1501
+ else:
1502
+ raise HTTPException(status_code=400, detail="Provide either document_id or text")
1503
+
1504
+ # Grade the document
1505
+ grade = await grader._grade_document(document)
1506
+
1507
+ return {
1508
+ "document_id": document.get("id"),
1509
+ "title": document.get("title", ""),
1510
+ "debate_grade": grade,
1511
+ "explanation": {
1512
+ "harms": "This measures how well the decision identifies and documents the problem using data and evidence",
1513
+ "solvency": "This measures how clearly the solution is defined and whether it will actually fix the problem",
1514
+ "topicality": "This measures whether the government body has the legal authority to take this action"
1515
+ }
1516
+ }
1517
+
1518
+ except HTTPException:
1519
+ raise
1520
+ except Exception as e:
1521
+ logger.error(f"Debate grading error: {e}")
1522
+ raise HTTPException(status_code=500, detail=str(e))
1523
+
1524
+
1525
+ @app.post("/api/debate-grade/batch")
1526
+ async def grade_decisions_batch(
1527
+ state: Optional[str] = Query(None, description="Filter by state"),
1528
+ topic: Optional[str] = Query(None, description="Filter by topic"),
1529
+ limit: int = Query(50, description="Number of documents to grade")
1530
+ ):
1531
+ """
1532
+ Grade multiple government decisions using debate framework.
1533
+
1534
+ Returns aggregate insights about decision quality across dimensions.
1535
+ """
1536
+ try:
1537
+ from agents.debate_grader import DebateGraderAgent
1538
+ from agents.base import AgentMessage, MessageType, AgentRole
1539
+
1540
+ grader = DebateGraderAgent()
1541
+
1542
+ # Get documents to grade
1543
+ documents = pipeline.query_opportunities_by_state(state, None)
1544
+
1545
+ if topic:
1546
+ documents = [d for d in documents if d.get("topic") == topic]
1547
+
1548
+ documents = documents[:limit]
1549
+
1550
+ # Create message and process
1551
+ message = AgentMessage(
1552
+ message_id=f"batch_grade_{datetime.utcnow().timestamp()}",
1553
+ sender=AgentRole.ORCHESTRATOR,
1554
+ recipient=AgentRole.DEBATE_GRADER,
1555
+ message_type=MessageType.COMMAND,
1556
+ payload={"documents": documents}
1557
+ )
1558
+
1559
+ result = await grader.process(message)
1560
+ graded_documents = result[0].payload.get("documents", [])
1561
+ insights = result[0].payload.get("insights", {})
1562
+
1563
+ return {
1564
+ "graded_count": len(graded_documents),
1565
+ "documents": graded_documents,
1566
+ "insights": insights,
1567
+ "explanation": {
1568
+ "average_scores": "Average scores across all three debate dimensions (out of 5)",
1569
+ "strongest_dimension": "Which dimension governments perform best on",
1570
+ "weakest_dimension": "Which dimension needs the most improvement"
1571
+ }
1572
+ }
1573
+
1574
+ except Exception as e:
1575
+ logger.error(f"Batch debate grading error: {e}")
1576
+ raise HTTPException(status_code=500, detail=str(e))
1577
+
1578
+
1579
+ @app.on_event("startup")
1580
+ async def startup_event():
1581
+ """Initialize system on startup with data validation."""
1582
+ logger.info("="*80)
1583
+ logger.info("🚀 STARTING Open Navigator API")
1584
+ logger.info("="*80)
1585
+ logger.info(f"Configuration: {settings.catalog_name}.{settings.schema_name}")
1586
+ logger.info(f"Log Level: {settings.log_level}")
1587
+ logger.info(f"Log File: {settings.log_file}")
1588
+
1589
+ # Check if running on HuggingFace Spaces
1590
+ IS_HF_SPACES = os.getenv("HF_SPACES") == "1"
1591
+ if IS_HF_SPACES:
1592
+ logger.info(f"🤗 Running on HuggingFace Spaces")
1593
+ else:
1594
+ logger.info(f"💻 Running in local/standard environment")
1595
+
1596
+ # Validate critical data files
1597
+ logger.info("")
1598
+ logger.info("📊 VALIDATING DATA AVAILABILITY...")
1599
+ logger.info("-" * 80)
1600
+
1601
+ data_dir = Path("data/gold")
1602
+ critical_files = []
1603
+ optional_files = []
1604
+
1605
+ # Check reference data (critical). These now come from the Postgres `public`
1606
+ # schema rather than local parquet (CLAUDE.md: API must read `public`).
1607
+ # Each probe reports its live row count via SELECT count(*).
1608
+ import psycopg2
1609
+ _ref_dsn = os.getenv(
1610
+ "NEON_DATABASE_URL_DEV",
1611
+ "postgresql://postgres:password@localhost:5433/open_navigator",
1612
+ )
1613
+ # label -> SQL count query against public schema
1614
+ reference_db_checks = [
1615
+ ("jurisdictions (city/town/county)",
1616
+ "SELECT count(*) FROM public.jurisdictions "
1617
+ "WHERE jurisdiction_type IN ('city','town','county')"),
1618
+ ("jurisdictions (counties)",
1619
+ "SELECT count(*) FROM public.jurisdictions "
1620
+ "WHERE jurisdiction_type = 'county'"),
1621
+ ("causes (public.tag)", "SELECT count(*) FROM public.tag"),
1622
+ ]
1623
+ try:
1624
+ _ref_conn = psycopg2.connect(_ref_dsn)
1625
+ _ref_cur = _ref_conn.cursor()
1626
+ for label, query in reference_db_checks:
1627
+ try:
1628
+ _ref_cur.execute(query)
1629
+ _count = _ref_cur.fetchone()[0]
1630
+ logger.info(f" ✅ {label}: {_count:,} records (public schema)")
1631
+ critical_files.append(label)
1632
+ except Exception as e:
1633
+ logger.error(f" ❌ {label}: ERROR - {e}")
1634
+ _ref_cur.close()
1635
+ _ref_conn.close()
1636
+ except Exception as e:
1637
+ logger.error(f" ❌ reference counts: could not connect to public schema - {e}")
1638
+
1639
+ # State data availability — served from the Postgres `public` schema.
1640
+ # events -> public.event grouped by state_code (NOT per-state parquet dirs).
1641
+ # NOTE: nonprofits (public.mdm_organization_nonprofit) has no state_code and
1642
+ # no usable org->location join, so a per-state nonprofit count is not
1643
+ # available here; only the national count is logged below.
1644
+ logger.info("")
1645
+ logger.info("📍 STATE DATA AVAILABILITY:")
1646
+ try:
1647
+ _state_conn = psycopg2.connect(_ref_dsn)
1648
+ _state_cur = _state_conn.cursor()
1649
+ _state_cur.execute(
1650
+ "SELECT state_code, count(*) FROM public.event "
1651
+ "WHERE state_code IS NOT NULL GROUP BY state_code ORDER BY state_code"
1652
+ )
1653
+ _state_rows = _state_cur.fetchall()
1654
+
1655
+ _state_cur.execute("SELECT count(*) FROM public.mdm_organization_nonprofit")
1656
+ _np_national = _state_cur.fetchone()[0]
1657
+
1658
+ _state_cur.close()
1659
+ _state_conn.close()
1660
+
1661
+ for sc, cnt in _state_rows[:10]: # Show first 10 states
1662
+ logger.info(f" ✅ {sc}: {cnt:,} events")
1663
+ total_states = len(_state_rows)
1664
+ if total_states > 10:
1665
+ logger.info(f" ... and {total_states - 10} more states")
1666
+ logger.info(f"")
1667
+ logger.info(f" 📊 Total states with events: {total_states}")
1668
+ logger.info(f" 🏢 public.mdm_organization_nonprofit: {_np_national:,} nonprofits (national)")
1669
+ except Exception as e:
1670
+ logger.warning(f" ⚠️ Could not read per-state event counts from public schema: {e}")
1671
+
1672
+ # Officials are served from contact_official (not parquet). Log the
1673
+ # live row count once so the startup banner still reports officials volume.
1674
+ try:
1675
+ import psycopg2
1676
+ _officials_dsn = os.getenv(
1677
+ "NEON_DATABASE_URL_DEV",
1678
+ "postgresql://postgres:password@localhost:5433/open_navigator",
1679
+ )
1680
+ _conn = psycopg2.connect(_officials_dsn)
1681
+ _cur = _conn.cursor()
1682
+ _cur.execute("SELECT count(*) FROM contact_official")
1683
+ _officials_count = _cur.fetchone()[0]
1684
+ _cur.close()
1685
+ _conn.close()
1686
+ logger.info(f" 🏛️ contact_official: {_officials_count:,} officials")
1687
+ except Exception as e:
1688
+ logger.warning(f" ⚠️ Could not count contact_official: {e}")
1689
+
1690
+ # Validate HuggingFace datasets if running on HF Spaces
1691
+ if IS_HF_SPACES:
1692
+ logger.info("")
1693
+ logger.info("🤗 VALIDATING HUGGINGFACE DATASETS...")
1694
+ logger.info("-" * 80)
1695
+
1696
+ # Check a sample of critical datasets (using new consolidated datasets)
1697
+ import requests
1698
+
1699
+ test_datasets = [
1700
+ ("https://huggingface.co/datasets/CommunityOne/one-bills/resolve/main/data/train-00000-of-00001.parquet", "Bills (Consolidated)"),
1701
+ ("https://huggingface.co/datasets/CommunityOne/one-local-officials/resolve/main/data/train-00000-of-00001.parquet", "Local Officials (Consolidated)"),
1702
+ ("https://huggingface.co/datasets/CommunityOne/one-nonprofits-organizations/resolve/main/data/train-00000-of-00001.parquet", "Nonprofits (Consolidated)"),
1703
+ ]
1704
+
1705
+ hf_datasets_ok = 0
1706
+ for url, display_name in test_datasets:
1707
+ try:
1708
+ response = requests.head(url, timeout=10, allow_redirects=True)
1709
+ if response.status_code == 200:
1710
+ logger.info(f" ✅ {display_name}: Accessible")
1711
+ hf_datasets_ok += 1
1712
+ else:
1713
+ logger.error(f" ❌ {display_name}: HTTP {response.status_code}")
1714
+ logger.error(f" URL: {url}")
1715
+ except Exception as e:
1716
+ logger.error(f" ❌ {display_name}: {type(e).__name__} - {e}")
1717
+ logger.error(f" URL: {url}")
1718
+
1719
+ logger.info("")
1720
+ logger.info(f" 📊 HuggingFace datasets validated: {hf_datasets_ok}/{len(test_datasets)}")
1721
+
1722
+ if hf_datasets_ok < len(test_datasets):
1723
+ logger.warning(" ⚠️ Some datasets are not accessible - API may have limited functionality")
1724
+
1725
+ logger.info("")
1726
+ logger.info("="*80)
1727
+ logger.info(f"✅ API READY - {len(critical_files)}/{len(reference_db_checks)} critical files available")
1728
+ if IS_HF_SPACES:
1729
+ logger.info(f"✅ HuggingFace datasets validated")
1730
+ logger.info("="*80)
1731
+ logger.info("")
1732
+
1733
+
1734
+ # Shutdown event
1735
+ @app.on_event("shutdown")
1736
+ async def shutdown_event():
1737
+ """Cleanup on shutdown."""
1738
+ logger.info("Shutting down CommunityOne Open Navigator API")
1739
+
1740
+
1741
+ # ---------------------------------------------------------------------------
1742
+ # Built frontend (React/Vite) + docs (Docusaurus) — single-process serving
1743
+ # ---------------------------------------------------------------------------
1744
+ # In the HuggingFace deployment nginx serves these static bundles and proxies
1745
+ # only /api to uvicorn. Databricks Apps run ONE process with no fronting proxy,
1746
+ # so FastAPI itself must serve the SPA and the docs. These routes are registered
1747
+ # LAST (after every API router) so the greedy ``/{full_path:path}`` catch-all
1748
+ # cannot shadow a real API route. The whole block is a no-op when no build is
1749
+ # present (api/static/index.html missing), e.g. an API-only container.
1750
+ _spa_static_dir = Path(__file__).parent / "static"
1751
+ if (_spa_static_dir / "index.html").is_file():
1752
+ from fastapi.responses import FileResponse
1753
+
1754
+ # Hashed JS/CSS produced by Vite (build outDir = api/static, so /assets here).
1755
+ _assets_dir = _spa_static_dir / "assets"
1756
+ if _assets_dir.is_dir():
1757
+ app.mount("/assets", StaticFiles(directory=_assets_dir), name="spa_assets")
1758
+
1759
+ logger.info(f"Serving built SPA + docs from {_spa_static_dir}")
1760
+
1761
+ @app.get("/{full_path:path}", include_in_schema=False)
1762
+ async def serve_spa_and_docs(full_path: str):
1763
+ """Serve the built docs / SPA for any non-API path.
1764
+
1765
+ Resolution order:
1766
+ 1. /api/* that fell through the routers -> 404 (never serve the SPA for
1767
+ a missing API endpoint, which would mask bugs with a 200 HTML body).
1768
+ 2. A concrete static file inside api/static (assets handled by the mount
1769
+ above; this covers /docs/*, /robots.txt, /pdf/*, favicon, etc.).
1770
+ 3. A directory request that has an index.html (e.g. /docs/ -> docs/index.html).
1771
+ 4. Otherwise the React index.html (client-side routing).
1772
+ Path traversal is guarded via ``relative_to``.
1773
+ """
1774
+ if full_path == "api" or full_path.startswith("api/"):
1775
+ raise HTTPException(status_code=404, detail="API endpoint not found")
1776
+
1777
+ if full_path:
1778
+ candidate = (_spa_static_dir / full_path).resolve()
1779
+ try:
1780
+ candidate.relative_to(_spa_static_dir.resolve())
1781
+ except ValueError:
1782
+ candidate = None
1783
+ if candidate is not None:
1784
+ if candidate.is_file():
1785
+ return FileResponse(candidate)
1786
+ # Directory (e.g. /docs/) -> its index.html if present.
1787
+ index_in_dir = candidate / "index.html"
1788
+ if candidate.is_dir() and index_in_dir.is_file():
1789
+ return FileResponse(index_in_dir)
1790
+
1791
+ return FileResponse(_spa_static_dir / "index.html", media_type="text/html")
1792
+
1793
+
1794
+ if __name__ == "__main__":
1795
+ import uvicorn
1796
+
1797
+ # Honor DATABRICKS_APP_PORT when running this module directly so a local
1798
+ # `python api/main.py` mirrors the platform launch. The app.yaml command is
1799
+ # the authoritative entry point in production.
1800
+ _port = int(os.getenv("DATABRICKS_APP_PORT", str(settings.api_port)))
1801
+ uvicorn.run(
1802
+ app,
1803
+ host="0.0.0.0",
1804
+ port=_port,
1805
+ workers=settings.api_workers,
1806
+ )
api/meeting_type.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Meeting type label for decision and meeting pages (#797).
2
+
3
+ The stored value (``event_youtube_with_jurisdiction.meeting_type``, e.g. ``CITY_COUNCIL``) is shown as a short
4
+ label. Only capitalization and spacing are normalized; the words are never changed or guessed. A blank or
5
+ UNKNOWN value gives ``None`` so the page omits the label.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import time
12
+ from typing import Any, Optional
13
+
14
+ _OMIT = {"", "unknown"}
15
+ _SMALL_WORDS = {"of", "and", "the", "for", "to", "a", "an", "on", "in"}
16
+ _ACRONYMS = {"id", "pta", "pto", "tif", "cip", "hoa", "ems", "mpo"}
17
+
18
+
19
+ def meeting_type_label(raw: Any) -> Optional[str]:
20
+ """``CITY_COUNCIL`` -> ``City Council``; None for blank/UNKNOWN."""
21
+ if raw is None:
22
+ return None
23
+ text = re.sub(r"[\s_]+", " ", str(raw)).strip()
24
+ if text.lower() in _OMIT:
25
+ return None
26
+ words = []
27
+ for i, w in enumerate(text.split(" ")):
28
+ lw = w.lower()
29
+ if lw in _ACRONYMS:
30
+ words.append(w.upper())
31
+ elif i > 0 and lw in _SMALL_WORDS:
32
+ words.append(lw)
33
+ else:
34
+ words.append(lw[:1].upper() + lw[1:])
35
+ return " ".join(words)
36
+
37
+
38
+ #: The relation the type is read from. It is built in ``gold`` and is not in the public serving list, so an API
39
+ #: that reads ``public`` cannot resolve it (#840).
40
+ MEETING_TYPE_RELATION = "event_youtube_with_jurisdiction"
41
+
42
+ #: How long a "relation is missing" answer is trusted before it is checked again.
43
+ _MISSING_RECHECK_SECONDS = 300.0
44
+
45
+ _available: bool | None = None
46
+ _checked_at: float = 0.0
47
+
48
+
49
+ async def meeting_type_available(conn: Any) -> bool:
50
+ """Whether ``event_youtube_with_jurisdiction`` resolves on this connection's search path.
51
+
52
+ A true answer is kept for the life of the process. A false one is kept for five minutes, so publishing the
53
+ relation later needs no restart. A failed check counts as missing."""
54
+ global _available, _checked_at
55
+ now = time.monotonic()
56
+ if _available is True:
57
+ return True
58
+ if _available is False and now - _checked_at < _MISSING_RECHECK_SECONDS:
59
+ return False
60
+ try:
61
+ found = bool(await conn.fetchval("SELECT to_regclass($1::text) IS NOT NULL", MEETING_TYPE_RELATION))
62
+ except Exception: # noqa: BLE001 - the label is optional; never fail the page for it
63
+ found = False
64
+ _available, _checked_at = found, now
65
+ return found
66
+
67
+
68
+ def meeting_type_by_video_sql(video_expr: str, available: bool = True) -> str:
69
+ """``meeting_type`` column for a row that has the meeting's video id in ``video_expr``.
70
+
71
+ NULL when the relation is not published to the schema the API reads (``available`` false)."""
72
+ if not available:
73
+ return "NULL::text AS meeting_type"
74
+ return (
75
+ f"(SELECT y.meeting_type FROM {MEETING_TYPE_RELATION} y "
76
+ f"WHERE y.video_id = {video_expr} LIMIT 1) AS meeting_type"
77
+ )
78
+
79
+
80
+ def meeting_type_subquery(alias: str, available: bool = True) -> str:
81
+ """Correlated subquery for a decision-list row: the raw meeting_type of the decision's meeting recording,
82
+ read from event_youtube_with_jurisdiction by video_id. Selected as ``meeting_type`` (NULL when none, and
83
+ NULL for every row when the relation is not published; see ``meeting_type_available``)."""
84
+ if not available:
85
+ return "NULL::text AS meeting_type"
86
+ return (
87
+ f"(SELECT y.meeting_type FROM event_decision ed "
88
+ f"JOIN event_meeting m ON m.c1_event_id = ed.c1_event_id "
89
+ f"JOIN {MEETING_TYPE_RELATION} y ON y.video_id = m.video_id "
90
+ f"WHERE ed.event_decision_id = {alias}.event_decision_id "
91
+ f"AND m.video_id IS NOT NULL LIMIT 1) AS meeting_type"
92
+ )
api/models.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Database models for authentication, user management, and social features
3
+ """
4
+ from datetime import datetime, timezone
5
+ from sqlalchemy import CheckConstraint, Column, Integer, String, DateTime, Boolean, Text, Float, ForeignKey, Identity, Index, UniqueConstraint, func, text
6
+ from sqlalchemy.ext.declarative import declarative_base
7
+
8
+ Base = declarative_base()
9
+
10
+
11
+ class User(Base):
12
+ """User account model"""
13
+ __tablename__ = "user"
14
+
15
+ user_id = Column(Integer, primary_key=True, index=True)
16
+ email = Column(String(255), unique=True, index=True, nullable=False)
17
+ username = Column(String(100), unique=True, index=True, nullable=True)
18
+ full_name = Column(String(255), nullable=True)
19
+ # OAuth avatar URLs (esp. Google's lh3.googleusercontent.com) routinely
20
+ # exceed 500 chars — use unbounded Text to avoid StringDataRightTruncation.
21
+ avatar_url = Column(Text, nullable=True)
22
+
23
+ # OAuth provider info
24
+ oauth_provider = Column(String(50), nullable=True) # 'huggingface', 'google', 'facebook', 'github'
25
+ oauth_id = Column(String(255), nullable=True) # Provider-specific user ID
26
+
27
+ # Authentication
28
+ hashed_password = Column(String(255), nullable=True) # For email/password (optional)
29
+ is_active = Column(Boolean, default=True)
30
+ is_verified = Column(Boolean, default=False)
31
+ # Operator/admin flag — gates the Admin area (Lighthouse report + batch jobs)
32
+ # surfaced via the profile menu and the /admin route. See migration
33
+ # packages/hosting/scripts/neon/migrations/110_add_user_is_admin.sql
34
+ is_admin = Column(Boolean, nullable=False, default=False, server_default="false")
35
+
36
+ # Location preferences
37
+ state = Column(String(100), nullable=True) # US State
38
+ county = Column(String(100), nullable=True) # County
39
+ city = Column(String(100), nullable=True) # City
40
+ school_board = Column(String(255), nullable=True) # School board/district
41
+
42
+ # Profile completion
43
+ profile_completed = Column(Boolean, default=False)
44
+
45
+ # Timestamps
46
+ created_at = Column(DateTime, default=datetime.utcnow)
47
+ updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
48
+ last_login = Column(DateTime, nullable=True)
49
+
50
+ # User preferences (JSON stored as text)
51
+ preferences = Column(Text, nullable=True)
52
+
53
+ def __repr__(self):
54
+ return f"<User {self.email}>"
55
+
56
+
57
+ class OAuthState(Base):
58
+ """Temporary storage for OAuth state tokens (CSRF protection)"""
59
+ __tablename__ = "contact_oauth_state"
60
+
61
+ id = Column(Integer, primary_key=True, index=True)
62
+ state_token = Column(String(255), unique=True, index=True, nullable=False)
63
+ provider = Column(String(50), nullable=False)
64
+ redirect_uri = Column(String(500), nullable=True)
65
+ created_at = Column(DateTime, default=datetime.utcnow)
66
+ expires_at = Column(DateTime, nullable=False)
67
+
68
+ def __repr__(self):
69
+ return f"<OAuthState {self.provider} - {self.state_token[:8]}...>"
70
+
71
+
72
+ class ContactSubmission(Base):
73
+ """One contact-form submission, kept privately for follow-up (#448).
74
+
75
+ Grain: one row per accepted ``POST /api/contact/submit``. App-owned like
76
+ ``user``: created by ``Base.metadata.create_all``, not dbt, and never copied by
77
+ the local-to-Neon serving sync (see ``RUNTIME_OWNED`` in
78
+ ``hosting.neon.sync_public_to_neon``). The public GitHub issue carries only
79
+ ``contact_submission_id``; the sender's email lives here and nowhere public.
80
+ No foreign keys. Retention: see
81
+ ``web_docs/docs/development/contact-form-privacy.md``.
82
+ """
83
+
84
+ __tablename__ = "contact_submission"
85
+
86
+ contact_submission_id = Column(Integer, Identity(), primary_key=True)
87
+ created_at = Column(
88
+ DateTime(timezone=True),
89
+ default=lambda: datetime.now(timezone.utc),
90
+ server_default=func.now(),
91
+ nullable=False,
92
+ )
93
+ sender_name = Column(Text, nullable=False)
94
+ sender_email = Column(Text, nullable=True) # nullable so retention can clear it
95
+ subject = Column(Text, nullable=False)
96
+ github_issue_number = Column(Integer, nullable=True)
97
+ github_issue_url = Column(Text, nullable=True)
98
+
99
+ def __repr__(self):
100
+ return f"<ContactSubmission {self.contact_submission_id}>"
101
+
102
+
103
+ # ============================================================================
104
+ # SOCIAL FEATURES MODELS
105
+ # ============================================================================
106
+
107
+ # NOTE: the integer-keyed `organization` ORM entity was folded into the MDM
108
+ # golden record `mdm_organization` (a dbt mart, PK master_org_id — not an ORM
109
+ # table). Organizations are now followed by their text master_org_id via
110
+ # SocialFollow.target_uid; see api/routes/social.py and migration 093.
111
+
112
+
113
+ # NOTE: the integer-keyed `cause` ORM entity was retired in favour of the dbt tag
114
+ # taxonomy (a mart, PK tag_id text -- not an ORM table). Causes/topics are now
115
+ # followed by their text tag_id via SocialFollow.target_uid, exactly like
116
+ # organizations; see api/routes/social.py and migration 099.
117
+
118
+
119
+ # NOTE: the `Official` ORM entity (table contact_official) was retired by
120
+ # migration 052, which dropped the empty table. Officials data lives in per-state
121
+ # parquet gold files (data/gold/states/<ST>/contact_official.parquet), read directly
122
+ # by api/routes/search.py — never as a queryable table. The follow-an-official
123
+ # feature that depended on this model was orphaned (the frontend never called its
124
+ # routes) and was removed alongside it; see api/routes/social.py.
125
+
126
+
127
+ # ============================================================================
128
+ # FOLLOW RELATIONSHIPS (Many-to-Many)
129
+ # ============================================================================
130
+
131
+ class SocialFollow(Base):
132
+ """A user following another entity (user, organization, or tag).
133
+
134
+ Consolidates the former user_follows / contact_official_follows /
135
+ organization_follows / cause_follows tables into one polymorphic table.
136
+ ``follower_id`` is always the acting user; ``target_type`` + the matching
137
+ target key identify what is being followed.
138
+
139
+ Two target-key columns coexist because targets are keyed differently:
140
+ - integer-keyed targets ('user') use ``target_id``.
141
+ - text-keyed targets use ``target_uid``: 'organization' =
142
+ mdm_organization.master_org_id, 'tag' = tag.tag_id.
143
+ Exactly one of the two is set per row; uniqueness is enforced by the two
144
+ partial indexes below.
145
+ """
146
+ __tablename__ = "social_follows"
147
+ __table_args__ = (
148
+ Index('uq_social_follow_intid', 'follower_id', 'target_type', 'target_id',
149
+ unique=True, postgresql_where=text('target_uid IS NULL')),
150
+ Index('uq_social_follow_uid', 'follower_id', 'target_type', 'target_uid',
151
+ unique=True, postgresql_where=text('target_uid IS NOT NULL')),
152
+ )
153
+
154
+ # Allowed target_type values. target_id keys user; target_uid keys
155
+ # organization (mdm_organization.master_org_id) and tag (tag.tag_id).
156
+ TARGET_TYPES = ("user", "organization", "tag")
157
+ UID_TARGET_TYPES = ("organization", "tag")
158
+
159
+ id = Column(Integer, primary_key=True, index=True)
160
+ follower_id = Column(Integer, ForeignKey('user.user_id', ondelete='CASCADE'), nullable=False, index=True)
161
+ target_type = Column(String, nullable=False, index=True)
162
+ target_id = Column(Integer, nullable=True, index=True)
163
+ target_uid = Column(String, nullable=True, index=True)
164
+ created_at = Column(DateTime, default=datetime.utcnow)
165
+
166
+ def __repr__(self):
167
+ key = self.target_uid if self.target_uid is not None else self.target_id
168
+ return f"<SocialFollow user:{self.follower_id} -> {self.target_type}:{key}>"
169
+
170
+
171
+ # ============================================================================
172
+ # FEED PERSONALIZATION MODELS
173
+ # ============================================================================
174
+ # Operational user-preference tables for the feed-setup screen. Like User /
175
+ # SocialFollow these are ORM-managed public-schema tables (NOT dbt marts),
176
+ # auto-created by Base.metadata.create_all in api/database.py at startup. All
177
+ # three cascade-delete with their owning user.
178
+
179
+
180
+ class UserLocation(Base):
181
+ """A location a user follows in their feed, at a chosen `shared_level`.
182
+
183
+ `name` is the human label (e.g. "Tuscaloosa, AL"); the resolved geo columns
184
+ are filled in from the place typeahead selection (all nullable). One row per
185
+ location; `is_primary` marks the one synced into User.city/county/state.
186
+ """
187
+ __tablename__ = "user_locations"
188
+
189
+ id = Column(Integer, primary_key=True, autoincrement=True, index=True)
190
+ user_id = Column(Integer, ForeignKey('user.user_id', ondelete='CASCADE'), nullable=False, index=True)
191
+ name = Column(String(255), nullable=False) # e.g. "Tuscaloosa, AL"
192
+ # One of street | district | city | county | state
193
+ shared_level = Column(String(20), nullable=False, default='city')
194
+ is_primary = Column(Boolean, default=False)
195
+
196
+ # Resolved geo (all nullable — filled from the typeahead selection)
197
+ state_code = Column(String(2), nullable=True)
198
+ state = Column(String(100), nullable=True)
199
+ county = Column(String(100), nullable=True)
200
+ place_fips = Column(String(10), nullable=True)
201
+ county_fips = Column(String(10), nullable=True)
202
+ latitude = Column(Float, nullable=True)
203
+ longitude = Column(Float, nullable=True)
204
+ jurisdiction_id = Column(String(100), nullable=True)
205
+
206
+ created_at = Column(DateTime, default=datetime.utcnow)
207
+
208
+ def __repr__(self):
209
+ return f"<UserLocation user:{self.user_id} {self.name} ({self.shared_level})>"
210
+
211
+
212
+ class UserLensPref(Base):
213
+ """A topical lens a user has enabled for their feed (composite PK)."""
214
+ __tablename__ = "user_lens_prefs"
215
+
216
+ user_id = Column(Integer, ForeignKey('user.user_id', ondelete='CASCADE'), primary_key=True)
217
+ lens_slug = Column(String(50), primary_key=True)
218
+ created_at = Column(DateTime, default=datetime.utcnow)
219
+
220
+ def __repr__(self):
221
+ return f"<UserLensPref user:{self.user_id} {self.lens_slug}>"
222
+
223
+
224
+ class UserSignalPref(Base):
225
+ """A story signal a user has enabled for their feed (composite PK)."""
226
+ __tablename__ = "user_signal_prefs"
227
+
228
+ user_id = Column(Integer, ForeignKey('user.user_id', ondelete='CASCADE'), primary_key=True)
229
+ signal_slug = Column(String(50), primary_key=True)
230
+ created_at = Column(DateTime, default=datetime.utcnow)
231
+
232
+ def __repr__(self):
233
+ return f"<UserSignalPref user:{self.user_id} {self.signal_slug}>"
234
+
235
+
236
+ # ============================================================================
237
+ # GEOSPATIAL FEATURES
238
+ # ============================================================================
239
+
240
+ class ProximityAlert(Base):
241
+ """Geospatial alert for a user, monitoring a specific radius."""
242
+ __tablename__ = "proximity_alerts"
243
+
244
+ id = Column(Integer, primary_key=True, index=True)
245
+ user_id = Column(Integer, ForeignKey('user.user_id', ondelete='CASCADE'), nullable=False, index=True)
246
+ alert_name = Column(String(255), nullable=False)
247
+ target_radius_meters = Column(Float, nullable=False)
248
+ is_active = Column(Boolean, default=True)
249
+
250
+ latitude = Column(Float, nullable=False)
251
+ longitude = Column(Float, nullable=False)
252
+
253
+ created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
254
+ updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
255
+
256
+ def __repr__(self):
257
+ return f"<ProximityAlert user:{self.user_id} radius:{self.target_radius_meters}m>"
258
+
259
+
260
+ # ============================================================================
261
+ # DATA CENTER ACCOUNTABILITY
262
+ # ============================================================================
263
+
264
+ class JobApplicationLink(Base):
265
+ """A job-application link for a data center project, kept by admins (DC-1.3, #248).
266
+
267
+ Grain: one row per application URL. App-owned like ``user``: created by
268
+ ``Base.metadata.create_all``, not dbt. The place is carried as text
269
+ (state_code / state / city) rather than a FK to ``jurisdictions``, because dbt
270
+ drops and rebuilds that relation. ``last_verified_at`` is set only by a check
271
+ that reached a live page or by an admin confirming it by hand; a link is stale
272
+ when it is null or more than 30 days old.
273
+ """
274
+
275
+ __tablename__ = "job_application_link"
276
+ __table_args__ = (
277
+ CheckConstraint(
278
+ "last_check_status IN ('live', 'dead', 'error')",
279
+ name="ck_job_application_link_check_status",
280
+ ),
281
+ CheckConstraint("length(state_code) = 2", name="ck_job_application_link_state_code"),
282
+ Index("ix_job_application_link_place", "state_code", "city"),
283
+ )
284
+
285
+ job_application_link_id = Column(Integer, primary_key=True)
286
+ project_name = Column(Text, nullable=False)
287
+ employer = Column(Text, nullable=True)
288
+ state_code = Column(String(2), nullable=False)
289
+ state = Column(Text, nullable=True)
290
+ city = Column(Text, nullable=True)
291
+ url = Column(Text, nullable=False, unique=True)
292
+ source_note = Column(Text, nullable=True)
293
+ last_verified_at = Column(DateTime(timezone=True), nullable=True)
294
+ last_checked_at = Column(DateTime(timezone=True), nullable=True)
295
+ last_check_status = Column(String(5), nullable=True)
296
+ last_http_status = Column(Integer, nullable=True)
297
+ created_by_user_id = Column(
298
+ Integer, ForeignKey("user.user_id", ondelete="SET NULL"), nullable=True, index=True
299
+ )
300
+ created_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
301
+ updated_at = Column(
302
+ DateTime(timezone=True),
303
+ default=lambda: datetime.now(timezone.utc),
304
+ onupdate=lambda: datetime.now(timezone.utc),
305
+ nullable=False,
306
+ )
307
+
308
+ def __repr__(self):
309
+ return f"<JobApplicationLink {self.job_application_link_id} {self.url}>"
310
+
311
+
312
+ # ============================================================================
313
+ # PROFILE CLAIMS (#1062)
314
+ # ============================================================================
315
+
316
+ def _utcnow() -> datetime:
317
+ return datetime.now(timezone.utc)
318
+
319
+
320
+ class PersonClaim(Base):
321
+ """A signed-in user's claim on an official's profile (#1062).
322
+
323
+ Grain: one row per (person_id, user_id). ``person_id`` is the official's
324
+ ``person_government.person_id`` (the OCD membership id) carried as text, not a
325
+ FK, because dbt drops and rebuilds that relation. App-owned like ``user``:
326
+ created by ``Base.metadata.create_all``. ``status`` is 'verified' only when the
327
+ user's verified sign-in email hashes to the official's ``email_sha256``
328
+ (``verified_via='official_email'``); otherwise 'pending' for manual review.
329
+ """
330
+
331
+ __tablename__ = "person_claim"
332
+ __table_args__ = (
333
+ UniqueConstraint("person_id", "user_id", name="uq_person_claim_person_user"),
334
+ CheckConstraint(
335
+ "status IN ('pending', 'verified', 'rejected')", name="ck_person_claim_status"
336
+ ),
337
+ )
338
+
339
+ person_claim_id = Column(Integer, primary_key=True)
340
+ person_id = Column(Text, nullable=False, index=True)
341
+ user_id = Column(
342
+ Integer, ForeignKey("user.user_id", ondelete="CASCADE"), nullable=False, index=True
343
+ )
344
+ status = Column(String(10), nullable=False, default="pending")
345
+ verified_via = Column(String(32), nullable=True)
346
+ note = Column(Text, nullable=True)
347
+ created_at = Column(DateTime(timezone=True), default=_utcnow, nullable=False)
348
+ updated_at = Column(DateTime(timezone=True), default=_utcnow, onupdate=_utcnow, nullable=False)
349
+
350
+ def __repr__(self):
351
+ return f"<PersonClaim {self.person_claim_id} {self.person_id} {self.status}>"
352
+
353
+
354
+ class PersonProfileEdit(Base):
355
+ """A proposed profile edit or feedback note from a claimant (#1062).
356
+
357
+ Grain: one row per submission. Nothing is published automatically: every row
358
+ starts 'pending' until the owner approves it.
359
+ """
360
+
361
+ __tablename__ = "person_profile_edit"
362
+ __table_args__ = (
363
+ CheckConstraint(
364
+ "field IN ('title', 'biography', 'photo_url', 'feedback')",
365
+ name="ck_person_profile_edit_field",
366
+ ),
367
+ CheckConstraint(
368
+ "status IN ('pending', 'approved', 'rejected')",
369
+ name="ck_person_profile_edit_status",
370
+ ),
371
+ )
372
+
373
+ person_profile_edit_id = Column(Integer, primary_key=True)
374
+ person_claim_id = Column(
375
+ Integer,
376
+ ForeignKey("person_claim.person_claim_id", ondelete="CASCADE"),
377
+ nullable=False,
378
+ index=True,
379
+ )
380
+ field = Column(String(16), nullable=False)
381
+ new_value = Column(Text, nullable=False)
382
+ status = Column(String(10), nullable=False, default="pending")
383
+ created_at = Column(DateTime(timezone=True), default=_utcnow, nullable=False)
384
+
385
+ def __repr__(self):
386
+ return f"<PersonProfileEdit {self.person_profile_edit_id} {self.field} {self.status}>"
api/origins.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared web-origin allowlist for CORS and OAuth redirect validation.
2
+
3
+ Security-critical: this is the single source of truth for which browser origins
4
+ the API trusts. Two callers depend on it:
5
+
6
+ - CORS middleware (``api/main.py``, ``api/app.py``) — which origins may read
7
+ API responses cross-site.
8
+ - OAuth ``redirect_uri`` validation (``api/routes/auth.py``) — where a freshly
9
+ minted 7-day JWT is appended to the redirect target after login, so an
10
+ unvalidated target leaks the token to an attacker-controlled site.
11
+
12
+ Configuration (env):
13
+ CORS_ALLOWED_ORIGINS Comma-separated absolute origins, e.g.
14
+ "https://www.communityone.com,https://foo.hf.space".
15
+ When set, it is the *exact* allowlist and the built-in
16
+ defaults are ignored.
17
+ FRONTEND_URL Single production frontend origin. Added to the defaults
18
+ only when CORS_ALLOWED_ORIGINS is not set.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ from functools import lru_cache
24
+ from typing import Optional, Tuple
25
+ from urllib.parse import urlsplit
26
+
27
+ # Local dev origins that are always safe when no explicit allowlist is set:
28
+ # Vite (5173), Docusaurus (3000), and the API itself (8001), on both loopback
29
+ # spellings.
30
+ _DEV_DEFAULT_ORIGINS: Tuple[str, ...] = (
31
+ "http://localhost:5173",
32
+ "http://127.0.0.1:5173",
33
+ "http://localhost:3000",
34
+ "http://127.0.0.1:3000",
35
+ "http://localhost:8001",
36
+ "http://127.0.0.1:8001",
37
+ )
38
+
39
+ # Established production origin for this project (see the FRONTEND_URL default in
40
+ # api/routes/data_deletion.py). Included so a default deploy still works if the
41
+ # operator hasn't set CORS_ALLOWED_ORIGINS yet.
42
+ _PROD_DEFAULT_ORIGINS: Tuple[str, ...] = ("https://www.communityone.com",)
43
+
44
+
45
+ def _normalize_origin(value: str) -> Optional[str]:
46
+ """Reduce a URL/origin string to canonical ``scheme://host[:port]``.
47
+
48
+ Returns None when it is not an absolute http(s) origin. Default ports
49
+ (443/80) are dropped so ``https://x:443`` matches ``https://x``.
50
+ """
51
+ if not value:
52
+ return None
53
+ # urlsplit (bad IPv6 literal) and the .port property (out-of-range or
54
+ # non-numeric port) raise ValueError on malformed input. A malformed
55
+ # candidate is simply not a usable origin — drop it, never propagate. This
56
+ # matters because the value can be an attacker-supplied redirect_uri (a raw
57
+ # 500 would hard-fail login) or an operator typo in CORS_ALLOWED_ORIGINS /
58
+ # FRONTEND_URL (would otherwise crash the app at startup).
59
+ try:
60
+ parts = urlsplit(value.strip())
61
+ port = parts.port
62
+ except ValueError:
63
+ return None
64
+ if parts.scheme not in ("http", "https") or not parts.hostname:
65
+ return None
66
+ host = parts.hostname.lower()
67
+ if port is not None and not (
68
+ (parts.scheme == "https" and port == 443)
69
+ or (parts.scheme == "http" and port == 80)
70
+ ):
71
+ return f"{parts.scheme}://{host}:{port}"
72
+ return f"{parts.scheme}://{host}"
73
+
74
+
75
+ @lru_cache(maxsize=1)
76
+ def allowed_origins() -> Tuple[str, ...]:
77
+ """The trusted origins, normalized and de-duplicated (order preserved).
78
+
79
+ ``CORS_ALLOWED_ORIGINS`` is authoritative when set; otherwise fall back to
80
+ the dev + production defaults plus ``FRONTEND_URL`` if present. Cached for
81
+ the process lifetime — env is read once at startup, matching how the CORS
82
+ middleware consumes it.
83
+ """
84
+ raw = os.getenv("CORS_ALLOWED_ORIGINS", "").strip()
85
+ if raw:
86
+ candidates = raw.split(",")
87
+ else:
88
+ candidates = list(_DEV_DEFAULT_ORIGINS) + list(_PROD_DEFAULT_ORIGINS)
89
+
90
+ # FRONTEND_URL is the app's own frontend — always trusted, whether or not an
91
+ # explicit CORS_ALLOWED_ORIGINS list is set, so login redirects back to it
92
+ # never get dropped.
93
+ frontend_url = os.getenv("FRONTEND_URL", "").strip()
94
+ if frontend_url:
95
+ candidates.append(frontend_url)
96
+
97
+ # dict preserves insertion order while de-duplicating.
98
+ seen: "dict[str, None]" = {}
99
+ for candidate in candidates:
100
+ normalized = _normalize_origin(candidate)
101
+ if normalized:
102
+ seen.setdefault(normalized, None)
103
+ return tuple(seen)
104
+
105
+
106
+ def is_allowed_origin(value: str) -> bool:
107
+ """True if ``value``'s origin is in the allowlist."""
108
+ normalized = _normalize_origin(value)
109
+ return normalized is not None and normalized in allowed_origins()
110
+
111
+
112
+ def is_safe_redirect(value: Optional[str]) -> bool:
113
+ """True if ``value`` is a safe post-login redirect target.
114
+
115
+ Safe means one of:
116
+ - absent/empty (the caller falls back to a trusted default);
117
+ - a same-origin relative path like ``/dashboard`` (but NOT a
118
+ protocol-relative ``//evil.com`` or a backslash-smuggled variant);
119
+ - an absolute URL whose origin is in the allowlist.
120
+ """
121
+ if not value:
122
+ return True
123
+ # WHATWG: browsers strip ASCII tab/newline/CR from anywhere in a URL before
124
+ # parsing it. Do the same first, so a smuggled "/\t/evil.com" can't pose as
125
+ # a relative path here yet resolve to protocol-relative "//evil.com" in the
126
+ # browser. (Starlette's Location quoting happens to neutralize this today,
127
+ # but the validator must be self-sufficient for any other caller.)
128
+ cleaned = value.translate({0x09: None, 0x0A: None, 0x0D: None})
129
+ if not cleaned:
130
+ return True
131
+ if cleaned.startswith("/") and not cleaned.startswith("//") and "\\" not in cleaned[:2]:
132
+ return True
133
+ return is_allowed_origin(cleaned)
api/provenance.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The "how this summary was made" facts for a decision (#798).
2
+
3
+ Only facts the analysis run recorded are returned; a missing fact is None and the page leaves it out.
4
+ Nothing here guesses a tier, prompt or source.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any, Mapping, Optional
10
+
11
+ from pydantic import BaseModel
12
+
13
+
14
+ class Provenance(BaseModel):
15
+ model: Optional[str] = None
16
+ generated_at: Optional[str] = None # ISO timestamp
17
+ tier: Optional[str] = None # "light" | "full"
18
+ prompt_name: Optional[str] = None
19
+ prompt_version: Optional[str] = None # first 12 hex of the prompt's SHA-256
20
+ transcript_source: Optional[str] = None
21
+ video_url: Optional[str] = None
22
+ # How many analyses existed for the meeting; more than 1 means the preferred one was chosen.
23
+ analyses_for_meeting: Optional[int] = None
24
+
25
+
26
+ def _text(v: Any) -> Optional[str]:
27
+ s = str(v).strip() if v is not None else ""
28
+ return s or None
29
+
30
+
31
+ def _iso(v: Any) -> Optional[str]:
32
+ if v is None:
33
+ return None
34
+ return v.isoformat() if hasattr(v, "isoformat") else _text(v)
35
+
36
+
37
+ def build_provenance(
38
+ prov_row: Optional[Mapping[str, Any]],
39
+ *,
40
+ source_ai_model: Any = None,
41
+ extracted_at: Any = None,
42
+ video_id: Any = None,
43
+ ) -> Optional[Provenance]:
44
+ """Merge the provenance mart row with the decision's own recorded model and time.
45
+
46
+ Returns None when there is nothing recorded at all (so the page renders no footer)."""
47
+ row = prov_row or {}
48
+ tier = _text(row.get("analysis_tier"))
49
+ vid = _text(video_id) or _text(row.get("video_id"))
50
+ p = Provenance(
51
+ model=_text(row.get("ai_model")) or _text(source_ai_model),
52
+ generated_at=_iso(row.get("generated_at")) or _iso(extracted_at),
53
+ tier=tier.lower() if tier and tier.lower() in ("light", "full") else None,
54
+ prompt_name=_text(row.get("prompt_name")),
55
+ prompt_version=_text(row.get("prompt_sha")),
56
+ transcript_source=_text(row.get("transcript_source")),
57
+ video_url=f"https://www.youtube.com/watch?v={vid}" if vid else None,
58
+ analyses_for_meeting=(
59
+ int(row["analyses_for_meeting"]) if row.get("analyses_for_meeting") is not None else None
60
+ ),
61
+ )
62
+ return p if any(v is not None for v in p.model_dump().values()) else None
api/routes/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """
2
+ API routes package
3
+ """
api/routes/addresses.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Property / parcel addresses from ``bronze.bronze_addresses``.
3
+
4
+ Source: Esri FeatureServer / MapServer attribute harvest (returnGeometry=false)
5
+ of county assessor parcel data. Carries situs + owner + parcel attributes, not
6
+ geometry — so this API is keyed off identifiers (serial id, source_record_id,
7
+ parcel number) rather than lat/lng radius searches.
8
+
9
+ Used by the property-click drilldown: the frontend maps a parcel polygon (with
10
+ its source parcel number or record id) to the full address row here.
11
+
12
+ See: packages/hosting/scripts/neon/migrations/074_create_bronze_addresses.sql
13
+ """
14
+ from __future__ import annotations
15
+
16
+ from typing import Any, Dict, List, Optional
17
+
18
+ from fastapi import APIRouter, HTTPException, Query
19
+ from loguru import logger
20
+ from pydantic import BaseModel, Field
21
+
22
+ from api.routes.stats_neon import get_db_pool
23
+
24
+ router = APIRouter(prefix="/addresses", tags=["addresses"])
25
+
26
+ # Per-request safety net: list endpoints are paged, but a runaway scan would be
27
+ # expensive on the bronze table (parcel harvests can run into millions of rows).
28
+ _MAX_LIST_LIMIT = 5_000
29
+
30
+
31
+ class AddressDetail(BaseModel):
32
+ """One parcel/property record from ``bronze.bronze_addresses``."""
33
+
34
+ id: int
35
+ source_dataset: str
36
+ source_record_id: str
37
+ state_code: str
38
+ county_fips: Optional[str] = None
39
+ county_name: Optional[str] = None
40
+ jurisdiction_id: Optional[str] = None
41
+
42
+ owner_name: Optional[str] = None
43
+
44
+ # Situs (where the property is) — both pieces and a pre-joined display string.
45
+ situs_location: Optional[str] = None
46
+ street_number: Optional[str] = None
47
+ street_line1: Optional[str] = None
48
+ street_line2: Optional[str] = None
49
+ city: Optional[str] = None
50
+ state_abbr: Optional[str] = None
51
+ postal_code: Optional[str] = None
52
+ situs_full: Optional[str] = None
53
+
54
+ parcel_number: Optional[str] = None
55
+ parcel_number_formatted: Optional[str] = None
56
+ appraised_value: Optional[int] = None
57
+ tax_class: Optional[str] = None
58
+
59
+ data_source: str
60
+ esri_endpoint: Optional[str] = None
61
+ # `include_raw=true` is required to populate this — the JSONB blob can be
62
+ # large (full Esri attribute dump) so we drop it by default.
63
+ raw_attributes: Optional[Dict[str, Any]] = None
64
+ loaded_at: Optional[str] = None
65
+
66
+
67
+ class AddressListResponse(BaseModel):
68
+ state: Optional[str] = None
69
+ county_fips: Optional[str] = None
70
+ jurisdiction_id: Optional[str] = None
71
+ total: int = Field(..., description="Matching rows before LIMIT.")
72
+ limit: int
73
+ offset: int
74
+ addresses: List[AddressDetail]
75
+
76
+
77
+ _SELECT_COLUMNS_NO_RAW = """
78
+ id,
79
+ source_dataset,
80
+ source_record_id,
81
+ state_code,
82
+ county_fips,
83
+ county_name,
84
+ jurisdiction_id,
85
+ owner_name,
86
+ situs_location,
87
+ street_number,
88
+ street_line1,
89
+ street_line2,
90
+ city,
91
+ state_abbr,
92
+ postal_code,
93
+ situs_full,
94
+ parcel_number,
95
+ parcel_number_formatted,
96
+ appraised_value,
97
+ tax_class,
98
+ data_source,
99
+ esri_endpoint,
100
+ NULL::jsonb AS raw_attributes,
101
+ loaded_at
102
+ """
103
+
104
+ _SELECT_COLUMNS_WITH_RAW = _SELECT_COLUMNS_NO_RAW.replace(
105
+ "NULL::jsonb AS raw_attributes", "raw_attributes"
106
+ )
107
+
108
+
109
+ def _row_to_address(row) -> AddressDetail:
110
+ return AddressDetail(
111
+ id=int(row["id"]),
112
+ source_dataset=str(row["source_dataset"]),
113
+ source_record_id=str(row["source_record_id"]),
114
+ state_code=str(row["state_code"]),
115
+ county_fips=row["county_fips"],
116
+ county_name=row["county_name"],
117
+ jurisdiction_id=row["jurisdiction_id"],
118
+ owner_name=row["owner_name"],
119
+ situs_location=row["situs_location"],
120
+ street_number=row["street_number"],
121
+ street_line1=row["street_line1"],
122
+ street_line2=row["street_line2"],
123
+ city=row["city"],
124
+ state_abbr=row["state_abbr"],
125
+ postal_code=row["postal_code"],
126
+ situs_full=row["situs_full"],
127
+ parcel_number=row["parcel_number"],
128
+ parcel_number_formatted=row["parcel_number_formatted"],
129
+ appraised_value=(int(row["appraised_value"]) if row["appraised_value"] is not None else None),
130
+ tax_class=row["tax_class"],
131
+ data_source=str(row["data_source"]),
132
+ esri_endpoint=row["esri_endpoint"],
133
+ raw_attributes=row["raw_attributes"],
134
+ loaded_at=(row["loaded_at"].isoformat() if row["loaded_at"] is not None else None),
135
+ )
136
+
137
+
138
+ async def _table_exists(conn) -> bool:
139
+ row = await conn.fetchval(
140
+ """
141
+ SELECT EXISTS (
142
+ SELECT 1
143
+ FROM information_schema.tables
144
+ WHERE table_schema = 'bronze' AND table_name = 'bronze_addresses'
145
+ )
146
+ """
147
+ )
148
+ return bool(row)
149
+
150
+
151
+ async def _ensure_table(conn) -> None:
152
+ """Raises 503 with a hint to run the migration if the table is missing."""
153
+ if not await _table_exists(conn):
154
+ raise HTTPException(
155
+ status_code=503,
156
+ detail=(
157
+ "bronze.bronze_addresses not found. Apply migration: "
158
+ "packages/hosting/scripts/neon/migrations/074_create_bronze_addresses.sql"
159
+ ),
160
+ )
161
+
162
+
163
+ @router.get("/{address_id}", response_model=AddressDetail)
164
+ async def get_address_by_id(
165
+ address_id: int,
166
+ include_raw: bool = Query(
167
+ False, description="Include the raw Esri attribute JSON blob in the response."
168
+ ),
169
+ ):
170
+ """
171
+ Look up a single property/parcel by its internal ``bronze_addresses.id``.
172
+
173
+ This is the primary "property-click → details" endpoint. The frontend
174
+ typically gets the id by clicking a parcel polygon whose attributes
175
+ include the bronze id (or by resolving via ``/addresses/by-parcel`` when
176
+ only a parcel number is available).
177
+ """
178
+ select_cols = _SELECT_COLUMNS_WITH_RAW if include_raw else _SELECT_COLUMNS_NO_RAW
179
+ pool = await get_db_pool()
180
+ async with pool.acquire() as conn:
181
+ await _ensure_table(conn)
182
+ row = await conn.fetchrow(
183
+ f"""
184
+ SELECT {select_cols}
185
+ FROM bronze.bronze_addresses
186
+ WHERE id = $1
187
+ """,
188
+ address_id,
189
+ )
190
+ if row is None:
191
+ raise HTTPException(status_code=404, detail=f"Address id={address_id} not found.")
192
+ return _row_to_address(row)
193
+
194
+
195
+ @router.get("/by-parcel/lookup", response_model=AddressDetail)
196
+ async def get_address_by_parcel(
197
+ state: str = Query(..., min_length=2, max_length=2, description="USPS state code (e.g. AL)"),
198
+ parcel: str = Query(..., min_length=1, description="parcel_number_formatted as it appears in bronze"),
199
+ include_raw: bool = Query(False),
200
+ ):
201
+ """
202
+ Resolve a parcel number to its address record.
203
+
204
+ Uses the ``(state_code, parcel_number_formatted)`` index (see migration 074),
205
+ so this is the fast path when the polygon click only has a parcel number,
206
+ not the bronze internal id. State code is required because parcel numbers
207
+ are not nationally unique.
208
+ """
209
+ select_cols = _SELECT_COLUMNS_WITH_RAW if include_raw else _SELECT_COLUMNS_NO_RAW
210
+ state_upper = state.strip().upper()
211
+ pool = await get_db_pool()
212
+ async with pool.acquire() as conn:
213
+ await _ensure_table(conn)
214
+ row = await conn.fetchrow(
215
+ f"""
216
+ SELECT {select_cols}
217
+ FROM bronze.bronze_addresses
218
+ WHERE state_code = $1
219
+ AND parcel_number_formatted = $2
220
+ LIMIT 1
221
+ """,
222
+ state_upper,
223
+ parcel,
224
+ )
225
+ if row is None:
226
+ raise HTTPException(
227
+ status_code=404,
228
+ detail=f"No address found for state={state_upper} parcel={parcel}",
229
+ )
230
+ return _row_to_address(row)
231
+
232
+
233
+ @router.get("/by-source/lookup", response_model=AddressDetail)
234
+ async def get_address_by_source(
235
+ source_dataset: str = Query(..., description="The harvest source dataset key."),
236
+ source_record_id: str = Query(..., description="The id within the source dataset."),
237
+ include_raw: bool = Query(False),
238
+ ):
239
+ """
240
+ Resolve a ``(source_dataset, source_record_id)`` pair. This is the
241
+ canonical natural-key lookup (UNIQUE constraint on the table) and is
242
+ the right path when the polygon click can carry the source attributes
243
+ directly.
244
+ """
245
+ select_cols = _SELECT_COLUMNS_WITH_RAW if include_raw else _SELECT_COLUMNS_NO_RAW
246
+ pool = await get_db_pool()
247
+ async with pool.acquire() as conn:
248
+ await _ensure_table(conn)
249
+ row = await conn.fetchrow(
250
+ f"""
251
+ SELECT {select_cols}
252
+ FROM bronze.bronze_addresses
253
+ WHERE source_dataset = $1 AND source_record_id = $2
254
+ """,
255
+ source_dataset,
256
+ source_record_id,
257
+ )
258
+ if row is None:
259
+ raise HTTPException(
260
+ status_code=404,
261
+ detail=f"No address found for source_dataset={source_dataset} record_id={source_record_id}",
262
+ )
263
+ return _row_to_address(row)
264
+
265
+
266
+ @router.get("/search", response_model=AddressListResponse)
267
+ async def search_addresses(
268
+ q: str = Query(..., min_length=3, description="Free-text query (matched against situs_full / street_line1 / city)."),
269
+ state: Optional[str] = Query(None, min_length=2, max_length=2, description="USPS state code."),
270
+ limit: int = Query(20, ge=1, le=200),
271
+ ):
272
+ """
273
+ Free-text address search — for the property-pin click flow.
274
+
275
+ The bronze table has no geometry, so we can't resolve a lat/lng pin to
276
+ a parcel row directly. Instead we ILIKE-match the situs/street string
277
+ from the geocoder. Provide ``state`` whenever possible to constrain the
278
+ scan and avoid cross-state false positives.
279
+
280
+ Returns the same envelope as the listing endpoint so callers can reuse
281
+ the rendering. Empty list (200) means "no parcel match" — distinct from
282
+ a 503 (table missing) or 4xx (bad query).
283
+ """
284
+ state_upper = state.strip().upper() if state else None
285
+ # Extract a likely-house-number prefix to tighten ILIKE matches (e.g.
286
+ # "5617 Lakeridge..." → "5617"). Helps when the user pastes a full
287
+ # display_name like "5617 Lakeridge Court, Tuscaloosa, AL 35406, USA".
288
+ head = q.strip().split(",", 1)[0].strip()
289
+ where_parts = [
290
+ "(situs_full ILIKE $1 OR street_line1 ILIKE $1 OR street_number || ' ' || street_line1 ILIKE $1)",
291
+ ]
292
+ params: list = [f"%{head}%"]
293
+ idx = 2
294
+ if state_upper:
295
+ where_parts.append(f"state_code = ${idx}")
296
+ params.append(state_upper)
297
+ idx += 1
298
+ where_sql = " AND ".join(where_parts)
299
+
300
+ pool = await get_db_pool()
301
+ async with pool.acquire() as conn:
302
+ await _ensure_table(conn)
303
+ total = await conn.fetchval(
304
+ f"SELECT COUNT(*)::bigint FROM bronze.bronze_addresses WHERE {where_sql}",
305
+ *params,
306
+ )
307
+ rows = await conn.fetch(
308
+ f"""
309
+ SELECT {_SELECT_COLUMNS_NO_RAW}
310
+ FROM bronze.bronze_addresses
311
+ WHERE {where_sql}
312
+ ORDER BY state_code, situs_full NULLS LAST, id
313
+ LIMIT ${idx}
314
+ """,
315
+ *params,
316
+ limit,
317
+ )
318
+
319
+ return AddressListResponse(
320
+ state=state_upper,
321
+ county_fips=None,
322
+ jurisdiction_id=None,
323
+ total=int(total or 0),
324
+ limit=limit,
325
+ offset=0,
326
+ addresses=[_row_to_address(r) for r in rows],
327
+ )
328
+
329
+
330
+ @router.get("", response_model=AddressListResponse)
331
+ async def list_addresses(
332
+ state: Optional[str] = Query(None, min_length=2, max_length=2),
333
+ county_fips: Optional[str] = Query(
334
+ None, min_length=3, max_length=5, description="3-digit county FIPS or 5-digit GEOID."
335
+ ),
336
+ jurisdiction_id: Optional[str] = Query(None),
337
+ owner_q: Optional[str] = Query(
338
+ None, description="Free-text owner_name search (uses the GIN tsvector index)."
339
+ ),
340
+ limit: int = Query(200, ge=1, le=_MAX_LIST_LIMIT),
341
+ offset: int = Query(0, ge=0),
342
+ ):
343
+ """
344
+ Paged list of parcels within a jurisdiction filter.
345
+
346
+ At least one of ``state``, ``county_fips``, ``jurisdiction_id``, or
347
+ ``owner_q`` must be provided — an unfiltered scan of the bronze table
348
+ is rejected (it would table-scan millions of rows).
349
+
350
+ Example::
351
+
352
+ GET /api/addresses?state=AL&county_fips=01125&limit=200
353
+ GET /api/addresses?state=AL&owner_q=university
354
+ """
355
+ if not (state or county_fips or jurisdiction_id or owner_q):
356
+ raise HTTPException(
357
+ status_code=400,
358
+ detail="Provide at least one of: state, county_fips, jurisdiction_id, owner_q.",
359
+ )
360
+
361
+ where_parts: List[str] = []
362
+ params: list = []
363
+ idx = 1
364
+
365
+ state_upper = state.strip().upper() if state else None
366
+ if state_upper:
367
+ where_parts.append(f"state_code = ${idx}")
368
+ params.append(state_upper)
369
+ idx += 1
370
+
371
+ if county_fips:
372
+ fips = county_fips.strip()
373
+ # Accept either '125' (3-digit county part) or '01125' (5-digit GEOID).
374
+ # Stored as county_fips VARCHAR(5), values vary by loader — match both.
375
+ if len(fips) == 5:
376
+ where_parts.append(f"county_fips = ${idx}")
377
+ params.append(fips)
378
+ idx += 1
379
+ else:
380
+ where_parts.append(f"(county_fips = ${idx} OR county_fips LIKE '%' || ${idx})")
381
+ params.append(fips)
382
+ idx += 1
383
+
384
+ if jurisdiction_id:
385
+ where_parts.append(f"jurisdiction_id = ${idx}")
386
+ params.append(jurisdiction_id)
387
+ idx += 1
388
+
389
+ if owner_q:
390
+ # Uses idx_bronze_addresses_owner GIN index from the migration.
391
+ where_parts.append(
392
+ f"to_tsvector('english', coalesce(owner_name, '')) @@ plainto_tsquery('english', ${idx})"
393
+ )
394
+ params.append(owner_q)
395
+ idx += 1
396
+
397
+ where_sql = " AND ".join(where_parts) if where_parts else "TRUE"
398
+
399
+ pool = await get_db_pool()
400
+ async with pool.acquire() as conn:
401
+ await _ensure_table(conn)
402
+
403
+ total = await conn.fetchval(
404
+ f"SELECT COUNT(*)::bigint FROM bronze.bronze_addresses WHERE {where_sql}",
405
+ *params,
406
+ )
407
+
408
+ limit_idx = idx
409
+ offset_idx = idx + 1
410
+ rows = await conn.fetch(
411
+ f"""
412
+ SELECT {_SELECT_COLUMNS_NO_RAW}
413
+ FROM bronze.bronze_addresses
414
+ WHERE {where_sql}
415
+ ORDER BY state_code, county_fips NULLS LAST, situs_full NULLS LAST, id
416
+ LIMIT ${limit_idx} OFFSET ${offset_idx}
417
+ """,
418
+ *params,
419
+ limit,
420
+ offset,
421
+ )
422
+
423
+ return AddressListResponse(
424
+ state=state_upper,
425
+ county_fips=county_fips,
426
+ jurisdiction_id=jurisdiction_id,
427
+ total=int(total or 0),
428
+ limit=limit,
429
+ offset=offset,
430
+ addresses=[_row_to_address(r) for r in rows],
431
+ )
api/routes/alerts.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Depends
2
+ from opentelemetry import trace
3
+ from sqlalchemy.orm import Session
4
+ from sqlalchemy import text
5
+ from typing import Dict, Any
6
+
7
+ from api.database import get_db
8
+ from api.models import User, ProximityAlert
9
+ from api.auth import require_auth
10
+ from models.proximity_alert import ProximityAlertCreate
11
+
12
+ router = APIRouter(prefix="/alerts", tags=["alerts"])
13
+ tracer = trace.get_tracer(__name__)
14
+
15
+
16
+ @router.post("/proximity", response_model=Dict[str, Any])
17
+ def create_proximity_alert_and_scan(
18
+ alert_in: ProximityAlertCreate,
19
+ current_user: User = Depends(require_auth),
20
+ db: Session = Depends(get_db),
21
+ ):
22
+ """Create a proximity alert and scan for nearby municipal meeting places.
23
+
24
+ Persists a ProximityAlert row for the authenticated user, then runs a
25
+ Haversine-distance scan against ``event_place_geocoded`` (the public
26
+ serving view of geocoded meeting venues) to return nearby items within
27
+ the requested radius. The alert and scan results are committed
28
+ atomically — if the scan fails the alert is rolled back.
29
+
30
+ The ``acos()`` argument is clamped to [-1, 1] via LEAST/GREATEST to
31
+ guard against floating-point rounding on near-identical points, which
32
+ would otherwise raise ``ERROR: input is out of range`` in Postgres.
33
+ """
34
+ with tracer.start_as_current_span("alerts.create_proximity_alert") as span:
35
+ span.set_attribute("alert.radius_meters", alert_in.target_radius_meters)
36
+
37
+ # Stage the alert — do NOT commit yet so a scan failure rolls back
38
+ new_alert = ProximityAlert(
39
+ user_id=current_user.user_id,
40
+ alert_name=alert_in.alert_name,
41
+ target_radius_meters=alert_in.target_radius_meters,
42
+ is_active=alert_in.is_active,
43
+ latitude=alert_in.latitude,
44
+ longitude=alert_in.longitude,
45
+ )
46
+ db.add(new_alert)
47
+ db.flush() # assigns new_alert.id without committing the transaction
48
+
49
+ # Haversine distance scan against the public serving view.
50
+ # Table name is UNQUALIFIED so it resolves via the ORM session's
51
+ # search_path (public-first); never hard-code a schema qualifier.
52
+ # acos() input is clamped to [-1, 1] to prevent domain errors, and
53
+ # distance is computed once in a CTE to avoid duplicate evaluation.
54
+ sql_query = text("""
55
+ WITH scored_places AS (
56
+ SELECT
57
+ event_place_id AS id,
58
+ COALESCE(normalized_address, raw_text, place_id) AS name,
59
+ latitude,
60
+ longitude,
61
+ jurisdiction_name,
62
+ city,
63
+ state_code,
64
+ (6371000 * acos(
65
+ LEAST(1.0, GREATEST(-1.0,
66
+ cos(radians(:lat)) * cos(radians(latitude))
67
+ * cos(radians(longitude) - radians(:lon))
68
+ + sin(radians(:lat)) * sin(radians(latitude))
69
+ ))
70
+ )) AS distance
71
+ FROM event_place_geocoded
72
+ WHERE latitude IS NOT NULL
73
+ AND longitude IS NOT NULL
74
+ )
75
+ SELECT
76
+ id,
77
+ name,
78
+ latitude,
79
+ longitude,
80
+ jurisdiction_name,
81
+ city,
82
+ state_code,
83
+ distance
84
+ FROM scored_places
85
+ WHERE distance <= :radius
86
+ ORDER BY distance
87
+ LIMIT 100;
88
+ """)
89
+
90
+ result = db.execute(
91
+ sql_query,
92
+ {"lat": alert_in.latitude, "lon": alert_in.longitude, "radius": alert_in.target_radius_meters},
93
+ )
94
+
95
+ nearby_items = [dict(row._mapping) for row in result]
96
+ span.set_attribute("alert.nearby_count", len(nearby_items))
97
+
98
+ # Commit atomically after the scan succeeds
99
+ db.commit()
100
+ db.refresh(new_alert)
101
+
102
+ return {
103
+ "alert_id": new_alert.id,
104
+ "status": "created",
105
+ "nearby_municipal_items_found": len(nearby_items),
106
+ "items": nearby_items,
107
+ }
api/routes/application_links.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Job-application links for data center projects (issue #248, DC-1.3).
3
+
4
+ Admins keep the links on the admin screen; the public page shows the ones still
5
+ worth following. Backed by the app-owned table ``public.job_application_link``
6
+ (``api.models.JobApplicationLink``), not a dbt model.
7
+
8
+ Public:
9
+ GET /api/data-centers/application-links?state=&city=&limit=
10
+ Links for the scope, newest-verified first. Links whose last check found
11
+ the page gone (``dead``) are left out; every item says when it was last
12
+ verified and whether that was more than 30 days ago (``is_stale``).
13
+
14
+ Admin (``require_admin``):
15
+ GET /api/admin/application-links[?stale=true]
16
+ POST /api/admin/application-links
17
+ PATCH /api/admin/application-links/{id}
18
+ DELETE /api/admin/application-links/{id}
19
+ POST /api/admin/application-links/{id}/check request the page now
20
+ POST /api/admin/application-links/{id}/verify an admin confirmed it by hand
21
+
22
+ Nothing is defaulted: a link never verified has ``last_verified_at = null`` and is
23
+ stale (CLAUDE.md, No Fabricated Data).
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from datetime import datetime, timezone
29
+ from typing import Literal
30
+
31
+ from fastapi import APIRouter, Depends, HTTPException, Query, Response
32
+ from ingestion.data_centers.application_links import check_link, is_http_url, is_stale
33
+ from loguru import logger
34
+ from opentelemetry import trace
35
+ from pydantic import BaseModel, Field, field_validator
36
+ from sqlalchemy import func, or_
37
+ from sqlalchemy.exc import IntegrityError
38
+ from sqlalchemy.orm import Session
39
+
40
+ from api.auth import require_admin
41
+ from api.database import get_db
42
+ from api.models import JobApplicationLink, User
43
+ from api.routes.data_centers import JobClaimScope, build_scope
44
+
45
+ public_router = APIRouter(prefix="/data-centers", tags=["data-centers"])
46
+ admin_router = APIRouter(
47
+ prefix="/admin/application-links",
48
+ tags=["admin"],
49
+ dependencies=[Depends(require_admin)],
50
+ )
51
+
52
+ tracer = trace.get_tracer(__name__)
53
+
54
+ DEFAULT_LIMIT = 100
55
+ MAX_LIMIT = 500
56
+
57
+ CheckStatus = Literal["live", "dead", "error"]
58
+
59
+
60
+ # --- models -------------------------------------------------------------------
61
+
62
+
63
+ class ApplicationLink(BaseModel):
64
+ """A link as the public page shows it."""
65
+
66
+ job_application_link_id: int
67
+ project_name: str
68
+ employer: str | None = None
69
+ state_code: str
70
+ state: str | None = None
71
+ city: str | None = None
72
+ url: str
73
+ last_verified_at: datetime | None = Field(
74
+ None, description="When a check or an admin last confirmed the page works; null if never."
75
+ )
76
+ is_stale: bool = Field(..., description="Never verified, or not verified in the last 30 days.")
77
+
78
+
79
+ class ApplicationLinksResponse(BaseModel):
80
+ scope: JobClaimScope
81
+ items: list[ApplicationLink]
82
+
83
+
84
+ class AdminApplicationLink(ApplicationLink):
85
+ """A link with everything the admin screen needs."""
86
+
87
+ source_note: str | None = None
88
+ last_checked_at: datetime | None = None
89
+ last_check_status: CheckStatus | None = None
90
+ last_http_status: int | None = None
91
+ created_at: datetime | None = None
92
+ updated_at: datetime | None = None
93
+
94
+
95
+ class AdminApplicationLinksResponse(BaseModel):
96
+ total: int = Field(..., description="Links in the list (after the stale filter).")
97
+ stale: int = Field(..., description="Of those, how many are stale.")
98
+ items: list[AdminApplicationLink]
99
+
100
+
101
+ def _clean(value: str | None) -> str | None:
102
+ if value is None:
103
+ return None
104
+ stripped = value.strip()
105
+ return stripped or None
106
+
107
+
108
+ class ApplicationLinkIn(BaseModel):
109
+ project_name: str = Field(..., min_length=1, max_length=300)
110
+ employer: str | None = Field(None, max_length=300)
111
+ state_code: str = Field(..., description="2-letter state code (a full name is normalized).")
112
+ city: str | None = Field(None, max_length=200)
113
+ url: str = Field(..., max_length=2000)
114
+ source_note: str | None = Field(None, max_length=1000)
115
+
116
+ @field_validator("project_name", "employer", "city", "source_note", mode="before")
117
+ @classmethod
118
+ def _strip(cls, v: str | None) -> str | None:
119
+ return _clean(v) if isinstance(v, str) or v is None else v
120
+
121
+ @field_validator("url")
122
+ @classmethod
123
+ def _http_only(cls, v: str) -> str:
124
+ v = v.strip()
125
+ if not is_http_url(v):
126
+ raise ValueError("url must be an absolute http(s) URL")
127
+ return v
128
+
129
+
130
+ class ApplicationLinkPatch(BaseModel):
131
+ project_name: str | None = Field(None, min_length=1, max_length=300)
132
+ employer: str | None = Field(None, max_length=300)
133
+ state_code: str | None = None
134
+ city: str | None = Field(None, max_length=200)
135
+ url: str | None = Field(None, max_length=2000)
136
+ source_note: str | None = Field(None, max_length=1000)
137
+
138
+ @field_validator("url")
139
+ @classmethod
140
+ def _http_only(cls, v: str | None) -> str | None:
141
+ if v is None:
142
+ return v
143
+ v = v.strip()
144
+ if not is_http_url(v):
145
+ raise ValueError("url must be an absolute http(s) URL")
146
+ return v
147
+
148
+
149
+ # --- helpers ------------------------------------------------------------------
150
+
151
+
152
+ def _place(state_code_raw: str) -> tuple[str, str | None]:
153
+ """Normalize a state code or name to (code, full name); 422 when unknown."""
154
+ scope = build_scope(state_code_raw, None, None)
155
+ if not scope.state_code or not scope.state:
156
+ raise HTTPException(status_code=422, detail=f"Unknown state: {state_code_raw!r}")
157
+ return scope.state_code, scope.state
158
+
159
+
160
+ def _public(link: JobApplicationLink, now: datetime) -> ApplicationLink:
161
+ return ApplicationLink(
162
+ job_application_link_id=link.job_application_link_id,
163
+ project_name=link.project_name,
164
+ employer=link.employer,
165
+ state_code=link.state_code,
166
+ state=link.state,
167
+ city=link.city,
168
+ url=link.url,
169
+ last_verified_at=link.last_verified_at,
170
+ is_stale=is_stale(link.last_verified_at, now),
171
+ )
172
+
173
+
174
+ def _admin(link: JobApplicationLink, now: datetime) -> AdminApplicationLink:
175
+ return AdminApplicationLink(
176
+ **_public(link, now).model_dump(),
177
+ source_note=link.source_note,
178
+ last_checked_at=link.last_checked_at,
179
+ last_check_status=link.last_check_status,
180
+ last_http_status=link.last_http_status,
181
+ created_at=link.created_at,
182
+ updated_at=link.updated_at,
183
+ )
184
+
185
+
186
+ def _get_or_404(db: Session, link_id: int) -> JobApplicationLink:
187
+ link = db.get(JobApplicationLink, link_id)
188
+ if link is None:
189
+ raise HTTPException(status_code=404, detail=f"No application link {link_id}")
190
+ return link
191
+
192
+
193
+ def _commit_unique(db: Session) -> None:
194
+ try:
195
+ db.commit()
196
+ except IntegrityError:
197
+ db.rollback()
198
+ raise HTTPException(status_code=409, detail="That URL is already in the list")
199
+
200
+
201
+ # --- public -------------------------------------------------------------------
202
+
203
+
204
+ @public_router.get("/application-links", response_model=ApplicationLinksResponse)
205
+ def list_application_links(
206
+ state: str | None = Query(None, description="2-letter state code (a full name is normalized)."),
207
+ city: str | None = Query(None, description="City; case-insensitive substring."),
208
+ limit: int = Query(DEFAULT_LIMIT, ge=1, le=MAX_LIMIT),
209
+ db: Session = Depends(get_db),
210
+ ) -> ApplicationLinksResponse:
211
+ """Application links for the scope; dead links are left out, stale ones are flagged."""
212
+ scope = build_scope(state, city, None)
213
+ with tracer.start_as_current_span("data-centers.application-links") as span:
214
+ span.set_attribute("application_links.scope_level", scope.level)
215
+ q = db.query(JobApplicationLink).filter(
216
+ or_(
217
+ JobApplicationLink.last_check_status.is_(None),
218
+ JobApplicationLink.last_check_status != "dead",
219
+ )
220
+ )
221
+ if scope.state_code:
222
+ q = q.filter(JobApplicationLink.state_code == scope.state_code)
223
+ if scope.city:
224
+ q = q.filter(JobApplicationLink.city.ilike(f"%{scope.city}%"))
225
+ rows = (
226
+ q.order_by(
227
+ JobApplicationLink.last_verified_at.desc().nulls_last(),
228
+ JobApplicationLink.job_application_link_id,
229
+ )
230
+ .limit(limit)
231
+ .all()
232
+ )
233
+ now = datetime.now(timezone.utc)
234
+ span.set_attribute("application_links.count", len(rows))
235
+ return ApplicationLinksResponse(scope=scope, items=[_public(r, now) for r in rows])
236
+
237
+
238
+ # --- admin --------------------------------------------------------------------
239
+
240
+
241
+ @admin_router.get("", response_model=AdminApplicationLinksResponse)
242
+ def admin_list(
243
+ stale: bool = Query(False, description="Only links not verified in the last 30 days."),
244
+ db: Session = Depends(get_db),
245
+ ) -> AdminApplicationLinksResponse:
246
+ rows = (
247
+ db.query(JobApplicationLink)
248
+ .order_by(func.lower(JobApplicationLink.project_name), JobApplicationLink.job_application_link_id)
249
+ .all()
250
+ )
251
+ now = datetime.now(timezone.utc)
252
+ items = [_admin(r, now) for r in rows]
253
+ if stale:
254
+ items = [i for i in items if i.is_stale]
255
+ return AdminApplicationLinksResponse(
256
+ total=len(items), stale=sum(1 for i in items if i.is_stale), items=items
257
+ )
258
+
259
+
260
+ @admin_router.post("", response_model=AdminApplicationLink, status_code=201)
261
+ def admin_create(
262
+ body: ApplicationLinkIn,
263
+ db: Session = Depends(get_db),
264
+ user: User = Depends(require_admin),
265
+ ) -> AdminApplicationLink:
266
+ state_code, state_name = _place(body.state_code)
267
+ link = JobApplicationLink(
268
+ project_name=body.project_name,
269
+ employer=body.employer,
270
+ state_code=state_code,
271
+ state=state_name,
272
+ city=body.city,
273
+ url=body.url,
274
+ source_note=body.source_note,
275
+ created_by_user_id=getattr(user, "user_id", None),
276
+ )
277
+ db.add(link)
278
+ _commit_unique(db)
279
+ db.refresh(link)
280
+ logger.info("Application link {} added: {}", link.job_application_link_id, link.url)
281
+ return _admin(link, datetime.now(timezone.utc))
282
+
283
+
284
+ @admin_router.patch("/{link_id}", response_model=AdminApplicationLink)
285
+ def admin_update(
286
+ link_id: int, body: ApplicationLinkPatch, db: Session = Depends(get_db)
287
+ ) -> AdminApplicationLink:
288
+ link = _get_or_404(db, link_id)
289
+ changes = body.model_dump(exclude_unset=True)
290
+ if "state_code" in changes:
291
+ link.state_code, link.state = _place(changes.pop("state_code") or "")
292
+ if "url" in changes and changes["url"] != link.url:
293
+ # A new URL hasn't been verified: clear the old check so it reads as stale.
294
+ link.last_verified_at = None
295
+ link.last_checked_at = None
296
+ link.last_check_status = None
297
+ link.last_http_status = None
298
+ for key, value in changes.items():
299
+ if key == "project_name" and not _clean(value):
300
+ raise HTTPException(status_code=422, detail="project_name can't be blank")
301
+ setattr(link, key, _clean(value) if isinstance(value, str) else value)
302
+ _commit_unique(db)
303
+ db.refresh(link)
304
+ return _admin(link, datetime.now(timezone.utc))
305
+
306
+
307
+ @admin_router.delete("/{link_id}", status_code=204)
308
+ def admin_delete(link_id: int, db: Session = Depends(get_db)) -> Response:
309
+ link = _get_or_404(db, link_id)
310
+ db.delete(link)
311
+ db.commit()
312
+ return Response(status_code=204)
313
+
314
+
315
+ @admin_router.post("/{link_id}/check", response_model=AdminApplicationLink)
316
+ def admin_check(link_id: int, db: Session = Depends(get_db)) -> AdminApplicationLink:
317
+ """Request the page now; a live answer counts as verifying it."""
318
+ link = _get_or_404(db, link_id)
319
+ with tracer.start_as_current_span("admin.application-links.check") as span:
320
+ result = check_link(link.url)
321
+ span.set_attribute("application_links.check_status", result.status)
322
+ link.last_checked_at = result.checked_at
323
+ link.last_check_status = result.status
324
+ link.last_http_status = result.http_status
325
+ if result.verified:
326
+ link.last_verified_at = result.checked_at
327
+ db.commit()
328
+ db.refresh(link)
329
+ return _admin(link, datetime.now(timezone.utc))
330
+
331
+
332
+ @admin_router.post("/{link_id}/verify", response_model=AdminApplicationLink)
333
+ def admin_verify(link_id: int, db: Session = Depends(get_db)) -> AdminApplicationLink:
334
+ """An admin opened the page and confirmed the posting is open."""
335
+ link = _get_or_404(db, link_id)
336
+ link.last_verified_at = datetime.now(timezone.utc)
337
+ db.commit()
338
+ db.refresh(link)
339
+ return _admin(link, datetime.now(timezone.utc))
api/routes/auth.py ADDED
@@ -0,0 +1,699 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ OAuth authentication routes - HuggingFace, Google, Facebook, GitHub
3
+ """
4
+ import os
5
+ import hmac
6
+ import hashlib
7
+ import httpx
8
+ from datetime import datetime, timedelta
9
+ from typing import Optional
10
+ from urllib.parse import urlencode
11
+ from dotenv import load_dotenv
12
+ from loguru import logger
13
+
14
+ from fastapi import APIRouter, Depends, HTTPException, Request, status
15
+ from fastapi.responses import RedirectResponse
16
+ from sqlalchemy.orm import Session
17
+ from pydantic import BaseModel
18
+
19
+ from api.database import get_db
20
+ from api.models import User, OAuthState
21
+ from api.auth import create_access_token, generate_state_token, is_admin_email
22
+ from api.origins import is_safe_redirect
23
+
24
+ # Load environment variables from .env file
25
+ load_dotenv()
26
+
27
+ router = APIRouter(prefix="/auth", tags=["authentication"])
28
+
29
+ # OAuth provider configurations
30
+ OAUTH_PROVIDERS = {
31
+ 'huggingface': {
32
+ 'authorize_url': 'https://huggingface.co/oauth/authorize',
33
+ 'token_url': 'https://huggingface.co/oauth/token',
34
+ 'userinfo_url': 'https://huggingface.co/api/whoami-v2',
35
+ 'scope': 'openid profile email',
36
+ 'client_id_env': 'HUGGINGFACE_CLIENT_ID',
37
+ 'client_secret_env': 'HUGGINGFACE_CLIENT_SECRET',
38
+ },
39
+ 'google': {
40
+ 'authorize_url': 'https://accounts.google.com/o/oauth2/v2/auth',
41
+ 'token_url': 'https://oauth2.googleapis.com/token',
42
+ 'userinfo_url': 'https://www.googleapis.com/oauth2/v2/userinfo',
43
+ 'scope': 'openid email profile',
44
+ 'client_id_env': 'GOOGLE_CLIENT_ID',
45
+ 'client_secret_env': 'GOOGLE_CLIENT_SECRET',
46
+ },
47
+ 'facebook': {
48
+ 'authorize_url': 'https://www.facebook.com/v18.0/dialog/oauth',
49
+ 'token_url': 'https://graph.facebook.com/v18.0/oauth/access_token',
50
+ 'userinfo_url': 'https://graph.facebook.com/me?fields=id,name,email,picture',
51
+ 'scope': 'email public_profile',
52
+ 'client_id_env': 'FACEBOOK_APP_ID',
53
+ 'client_secret_env': 'FACEBOOK_APP_SECRET',
54
+ },
55
+ 'github': {
56
+ 'authorize_url': 'https://github.com/login/oauth/authorize',
57
+ 'token_url': 'https://github.com/login/oauth/access_token',
58
+ 'userinfo_url': 'https://api.github.com/user',
59
+ 'scope': 'user:email',
60
+ 'client_id_env': 'GITHUB_CLIENT_ID',
61
+ 'client_secret_env': 'GITHUB_CLIENT_SECRET',
62
+ },
63
+ }
64
+
65
+
66
+ # Response models
67
+ class TokenResponse(BaseModel):
68
+ access_token: str
69
+ token_type: str = "bearer"
70
+ user: dict
71
+
72
+
73
+ class UserResponse(BaseModel):
74
+ user_id: int
75
+ email: str
76
+ username: Optional[str]
77
+ full_name: Optional[str]
78
+ avatar_url: Optional[str]
79
+ oauth_provider: Optional[str]
80
+ state: Optional[str]
81
+ county: Optional[str]
82
+ city: Optional[str]
83
+ school_board: Optional[str]
84
+ profile_completed: Optional[bool]
85
+ is_admin: Optional[bool] = False
86
+
87
+
88
+ # Helper functions
89
+ def get_base_url(request: Request) -> str:
90
+ """
91
+ Get the base URL from the request, handling proxy headers
92
+
93
+ In production (HuggingFace Spaces with nginx reverse proxy):
94
+ - Returns: https://www.communityone.com
95
+
96
+ In local development:
97
+ - Returns: http://localhost:8001
98
+ """
99
+ # Check for explicit API_BASE_URL override first
100
+ if base_url := os.getenv('API_BASE_URL'):
101
+ # Only use if it's not the default localhost value
102
+ if 'localhost' not in base_url and '127.0.0.1' not in base_url:
103
+ return base_url
104
+
105
+ # Detect from request headers (handles nginx reverse proxy)
106
+ scheme = request.headers.get('x-forwarded-proto', request.url.scheme)
107
+ host = request.headers.get('x-forwarded-host', request.headers.get('host', request.url.netloc))
108
+
109
+ # Clean up host (remove port if it's standard)
110
+ if ':' in host:
111
+ host_parts = host.split(':')
112
+ port = host_parts[1]
113
+ # Remove standard ports
114
+ if (scheme == 'https' and port == '443') or (scheme == 'http' and port == '80'):
115
+ host = host_parts[0]
116
+
117
+ return f"{scheme}://{host}"
118
+
119
+
120
+ def get_or_create_user(
121
+ db: Session,
122
+ email: str,
123
+ provider: str,
124
+ oauth_id: str,
125
+ full_name: Optional[str] = None,
126
+ avatar_url: Optional[str] = None,
127
+ username: Optional[str] = None,
128
+ email_verified: bool = False,
129
+ ) -> User:
130
+ """Get existing user or create new one from OAuth data"""
131
+
132
+ # Try to find existing user by OAuth ID first
133
+ user = db.query(User).filter(
134
+ User.oauth_provider == provider,
135
+ User.oauth_id == oauth_id
136
+ ).first()
137
+
138
+ # Admin status is derived from the ADMIN_EMAILS allowlist and re-evaluated on
139
+ # every login, so promoting/demoting an admin is a config change, not a DB edit.
140
+ admin = is_admin_email(email)
141
+
142
+ if user:
143
+ # Update user info if changed. Keep email in sync with the provider: it
144
+ # is the identity `is_admin`/`require_admin` key off, so letting it drift
145
+ # would silently lock out an admin whose provider email changed.
146
+ user.email = email
147
+ user.full_name = full_name or user.full_name
148
+ user.avatar_url = avatar_url or user.avatar_url
149
+ user.username = username or user.username
150
+ user.last_login = datetime.utcnow()
151
+ user.is_admin = admin
152
+ db.commit()
153
+ return user
154
+
155
+ # Try to find by email
156
+ user = db.query(User).filter(User.email == email).first()
157
+
158
+ if user:
159
+ # Merging a new OAuth identity into a pre-existing account (matched only
160
+ # by email, not by this provider's own oauth_id) is an account-takeover
161
+ # vector unless the provider attests the email is verified. Refuse
162
+ # otherwise — email is unique, so a separate account isn't possible.
163
+ if not email_verified:
164
+ raise HTTPException(
165
+ status_code=status.HTTP_409_CONFLICT,
166
+ detail=(
167
+ "An account with this email already exists. Sign in with the "
168
+ "method you used originally, then link this provider from "
169
+ "settings."
170
+ ),
171
+ )
172
+ # Link OAuth account to existing user
173
+ user.oauth_provider = provider
174
+ user.oauth_id = oauth_id
175
+ user.full_name = full_name or user.full_name
176
+ user.avatar_url = avatar_url or user.avatar_url
177
+ user.username = username or user.username
178
+ user.last_login = datetime.utcnow()
179
+ user.is_verified = True # OAuth emails are verified
180
+ user.is_admin = admin
181
+ db.commit()
182
+ return user
183
+
184
+ # Create new user
185
+ user = User(
186
+ email=email,
187
+ username=username,
188
+ full_name=full_name,
189
+ avatar_url=avatar_url,
190
+ oauth_provider=provider,
191
+ oauth_id=oauth_id,
192
+ is_verified=True,
193
+ is_active=True,
194
+ is_admin=admin,
195
+ last_login=datetime.utcnow(),
196
+ )
197
+ db.add(user)
198
+ db.commit()
199
+ db.refresh(user)
200
+ return user
201
+
202
+
203
+ # OAuth routes
204
+ @router.get("/login/{provider}")
205
+ async def oauth_login(
206
+ provider: str,
207
+ request: Request,
208
+ db: Session = Depends(get_db),
209
+ redirect_uri: Optional[str] = None
210
+ ):
211
+ """
212
+ Initiate OAuth login flow
213
+
214
+ Supported providers: huggingface, google, facebook, github
215
+ """
216
+ if provider not in OAUTH_PROVIDERS:
217
+ raise HTTPException(status_code=400, detail=f"Unsupported provider: {provider}")
218
+
219
+ # The callback appends the freshly minted JWT to redirect_uri, so an
220
+ # attacker-controlled target would exfiltrate the token. Drop anything not
221
+ # provably safe (an allowlisted origin or a same-origin relative path) and
222
+ # fall back to the trusted default — never hard-fail login over it.
223
+ if redirect_uri and not is_safe_redirect(redirect_uri):
224
+ logger.warning("Dropping unsafe OAuth redirect_uri: {}", redirect_uri)
225
+ redirect_uri = None
226
+
227
+ config = OAUTH_PROVIDERS[provider]
228
+ client_id = os.getenv(config['client_id_env'])
229
+ client_secret = os.getenv(config['client_secret_env'])
230
+
231
+ # Missing OAuth credentials is a configuration problem, not a server crash.
232
+ # Return a clear 503 so the cause is visible instead of a swallowed 500.
233
+ if not client_id or not client_secret:
234
+ missing = config['client_id_env'] if not client_id else config['client_secret_env']
235
+ logger.error("OAuth not configured for {}: missing env var {}", provider, missing)
236
+ raise HTTPException(
237
+ status_code=503,
238
+ detail=(
239
+ f"{provider.title()} sign-in is temporarily unavailable "
240
+ f"(server is missing {missing}). Please try another sign-in method "
241
+ "or contact johnbowyer@communityone.com."
242
+ ),
243
+ )
244
+
245
+ # Generate state token for CSRF protection and persist it.
246
+ # A failure here is almost always a missing/unmigrated oauth_states table —
247
+ # surface that explicitly rather than letting it fall through as a generic 500.
248
+ state = generate_state_token()
249
+ try:
250
+ oauth_state = OAuthState(
251
+ state_token=state,
252
+ provider=provider,
253
+ redirect_uri=redirect_uri,
254
+ expires_at=datetime.utcnow() + timedelta(minutes=10),
255
+ )
256
+ db.add(oauth_state)
257
+ db.commit()
258
+ except Exception as e:
259
+ db.rollback()
260
+ logger.exception("Failed to persist OAuth state for {}: {}", provider, e)
261
+ raise HTTPException(
262
+ status_code=503,
263
+ detail=(
264
+ f"{provider.title()} sign-in is temporarily unavailable "
265
+ "(could not start the login session). Please try again shortly "
266
+ "or contact johnbowyer@communityone.com."
267
+ ),
268
+ )
269
+
270
+ # Build callback URL dynamically from request (handles both local and production)
271
+ base_url = get_base_url(request)
272
+ callback_url = f"{base_url}/api/auth/callback/{provider}"
273
+
274
+ # Build authorization URL
275
+ params = {
276
+ 'client_id': client_id,
277
+ 'redirect_uri': callback_url,
278
+ 'scope': config['scope'],
279
+ 'state': state,
280
+ 'response_type': 'code',
281
+ }
282
+
283
+ auth_url = f"{config['authorize_url']}?{urlencode(params)}"
284
+ return RedirectResponse(url=auth_url)
285
+
286
+
287
+ def _safe_error_redirect_base(oauth_state) -> str:
288
+ """Base URL for an OAuth *error* redirect, re-validated against the allowlist.
289
+
290
+ ``redirect_uri`` is validated at ``/login`` before it is stored, but a stale
291
+ ``OAuthState`` row (one written before a deploy, or by any future code path
292
+ that skips that check) could still carry an unsafe target. An error redirect
293
+ echoes attacker-controllable text in the query string, so never bounce it to
294
+ anything not provably safe — fall back to a same-origin ``/``.
295
+ """
296
+ frontend_url = os.getenv('FRONTEND_URL', '')
297
+ redirect_url = oauth_state.redirect_uri or (
298
+ frontend_url if frontend_url and 'localhost' not in frontend_url else '/'
299
+ )
300
+ return redirect_url if is_safe_redirect(redirect_url) else '/'
301
+
302
+
303
+ @router.get("/callback/{provider}", name="oauth_callback")
304
+ async def oauth_callback(
305
+ provider: str,
306
+ request: Request,
307
+ code: Optional[str] = None,
308
+ state: Optional[str] = None,
309
+ error: Optional[str] = None,
310
+ db: Session = Depends(get_db)
311
+ ):
312
+ """OAuth callback handler"""
313
+
314
+ if error:
315
+ raise HTTPException(status_code=400, detail=f"OAuth error: {error}")
316
+
317
+ if not code or not state:
318
+ raise HTTPException(status_code=400, detail="Missing code or state parameter")
319
+
320
+ if provider not in OAUTH_PROVIDERS:
321
+ raise HTTPException(status_code=400, detail=f"Unsupported provider: {provider}")
322
+
323
+ # Verify state token
324
+ oauth_state = db.query(OAuthState).filter(
325
+ OAuthState.state_token == state,
326
+ OAuthState.provider == provider
327
+ ).first()
328
+
329
+ if not oauth_state or oauth_state.expires_at < datetime.utcnow():
330
+ raise HTTPException(status_code=400, detail="Invalid or expired state token")
331
+
332
+ config = OAUTH_PROVIDERS[provider]
333
+ client_id = os.getenv(config['client_id_env'])
334
+ client_secret = os.getenv(config['client_secret_env'])
335
+
336
+ # Build callback URL dynamically from request (must match the one sent to authorize)
337
+ base_url = get_base_url(request)
338
+ callback_url = f"{base_url}/api/auth/callback/{provider}"
339
+
340
+ # Exchange code for access token
341
+ try:
342
+ logger.info(f"🔐 [{provider.upper()}] Starting token exchange")
343
+ logger.info(f"🔐 [{provider.upper()}] Token URL: {config['token_url']}")
344
+ logger.info(f"🔐 [{provider.upper()}] Callback URL: {callback_url}")
345
+ logger.info(f"🔐 [{provider.upper()}] Client ID configured: {bool(client_id)}")
346
+ logger.info(f"🔐 [{provider.upper()}] Client Secret configured: {bool(client_secret)}")
347
+
348
+ async with httpx.AsyncClient() as client:
349
+ token_response = await client.post(
350
+ config['token_url'],
351
+ data={
352
+ 'client_id': client_id,
353
+ 'client_secret': client_secret,
354
+ 'code': code,
355
+ 'redirect_uri': callback_url,
356
+ 'grant_type': 'authorization_code',
357
+ },
358
+ headers={'Accept': 'application/json'}
359
+ )
360
+
361
+ logger.info(f"📊 [{provider.upper()}] Token response status: {token_response.status_code}")
362
+
363
+ if token_response.status_code != 200:
364
+ logger.error(f"❌ [{provider.upper()}] Token exchange failed!")
365
+ logger.error(f"❌ [{provider.upper()}] Response: {token_response.text}")
366
+
367
+ # Parse error response for user-friendly message
368
+ error_msg = "Authentication failed"
369
+ try:
370
+ error_data = token_response.json()
371
+ # Facebook error format: {"error": {"message": "...", "type": "..."}}
372
+ if 'error' in error_data:
373
+ if isinstance(error_data['error'], dict):
374
+ error_msg = error_data['error'].get('message', error_msg)
375
+ # Special handling for Facebook's "error validating web secret"
376
+ if provider == 'facebook' and 'validating' in error_msg.lower() and 'secret' in error_msg.lower():
377
+ error_msg = "Invalid App Secret. Please update FACEBOOK_APP_SECRET in your .env file with the correct secret from Facebook Developer Console."
378
+ else:
379
+ error_msg = str(error_data['error'])
380
+ # Google/other providers: {"error": "...", "error_description": "..."}
381
+ elif 'error_description' in error_data:
382
+ error_msg = error_data['error_description']
383
+ elif 'error' in error_data:
384
+ error_msg = error_data['error']
385
+ except:
386
+ error_msg = f"Authentication failed (HTTP {token_response.status_code})"
387
+
388
+ # Log full error for debugging
389
+ logger.error(f"OAuth token exchange failed for {provider}: {token_response.text}")
390
+
391
+ # Redirect to frontend with error
392
+ redirect_url = _safe_error_redirect_base(oauth_state)
393
+ params = urlencode({'error': f'{provider.title()} login failed: {error_msg}'})
394
+ return RedirectResponse(url=f"{redirect_url}?{params}")
395
+
396
+ token_data = token_response.json()
397
+ logger.info(f"✅ [{provider.upper()}] Token response keys: {list(token_data.keys())}")
398
+ access_token = token_data.get('access_token')
399
+
400
+ if not access_token:
401
+ logger.error(f"❌ [{provider.upper()}] No access token in response!")
402
+ logger.error(f"No access token in response from {provider}: {token_data}")
403
+ redirect_url = _safe_error_redirect_base(oauth_state)
404
+ params = urlencode({'error': f'{provider.title()} login failed: No access token received'})
405
+ return RedirectResponse(url=f"{redirect_url}?{params}")
406
+
407
+ logger.info(f"✅ [{provider.upper()}] Got access token (first 20 chars): {access_token[:20]}...")
408
+
409
+ # Get user info from provider
410
+ logger.info(f"🔍 [{provider.upper()}] Fetching user info...")
411
+ user_info = await get_user_info(provider, access_token, config)
412
+ logger.info(f"📊 [{provider.upper()}] User info result: {user_info is not None}")
413
+
414
+ # Validate we got user info (email is now always set, even if placeholder for Facebook)
415
+ if not user_info:
416
+ logger.error(f"❌ [{provider.upper()}] Could not retrieve user info! Check API response logs above.")
417
+ logger.error(f"Could not retrieve user info from {provider}. Check API response logs above.")
418
+ redirect_url = _safe_error_redirect_base(oauth_state)
419
+ params = urlencode({'error': f'{provider.title()} login failed: Could not retrieve user information'})
420
+ return RedirectResponse(url=f"{redirect_url}?{params}")
421
+
422
+ except Exception as e:
423
+ logger.error(f"Unexpected error during {provider} OAuth: {str(e)}")
424
+ redirect_url = _safe_error_redirect_base(oauth_state)
425
+ params = urlencode({'error': f'{provider.title()} login failed: {str(e)}'})
426
+ return RedirectResponse(url=f"{redirect_url}?{params}")
427
+
428
+ # Get or create user. A verified-email conflict (an existing account owns
429
+ # this email under a different identity) surfaces as a friendly error
430
+ # redirect rather than a raw 409.
431
+ try:
432
+ user = get_or_create_user(
433
+ db=db,
434
+ email=user_info['email'],
435
+ provider=provider,
436
+ oauth_id=user_info['oauth_id'],
437
+ full_name=user_info.get('full_name'),
438
+ avatar_url=user_info.get('avatar_url'),
439
+ username=user_info.get('username'),
440
+ email_verified=bool(user_info.get('email_verified')),
441
+ )
442
+ except HTTPException as exc:
443
+ redirect_url = _safe_error_redirect_base(oauth_state)
444
+ params = urlencode({'error': exc.detail})
445
+ return RedirectResponse(url=f"{redirect_url}?{params}")
446
+
447
+ # Clean up state token
448
+ db.delete(oauth_state)
449
+ db.commit()
450
+
451
+ # Create JWT token (sub must be string, not int)
452
+ jwt_token = create_access_token(data={"sub": str(user.user_id)})
453
+
454
+ # Redirect to frontend with token
455
+ # On HuggingFace/production, frontend and backend are same domain - use relative path
456
+ # On local dev, frontend is separate server - use FRONTEND_URL
457
+ frontend_url = os.getenv('FRONTEND_URL', '')
458
+
459
+ # If FRONTEND_URL is localhost or not set, assume same-domain deployment (HuggingFace)
460
+ if not frontend_url or 'localhost' in frontend_url:
461
+ # Use relative redirect (works on HuggingFace where both are same domain)
462
+ redirect_url = oauth_state.redirect_uri or '/'
463
+ else:
464
+ # Use absolute URL for separate frontend server
465
+ redirect_url = oauth_state.redirect_uri or frontend_url
466
+
467
+ # Defense-in-depth: redirect_uri was validated at /login, but never append
468
+ # the token to a target that isn't provably safe.
469
+ if not is_safe_redirect(redirect_url):
470
+ logger.warning("Refusing token redirect to unsafe target: {}", redirect_url)
471
+ redirect_url = '/'
472
+
473
+ # Append token as URL parameter
474
+ params = urlencode({'token': jwt_token})
475
+ full_redirect_url = f"{redirect_url}?{params}" if '?' not in redirect_url else f"{redirect_url}&{params}"
476
+
477
+ return RedirectResponse(url=full_redirect_url)
478
+
479
+
480
+ async def get_user_info(provider: str, access_token: str, config: dict) -> dict:
481
+ """Get user information from OAuth provider"""
482
+
483
+ async with httpx.AsyncClient() as client:
484
+ headers = {'Authorization': f'Bearer {access_token}'}
485
+
486
+ user_info = {}
487
+
488
+ if provider == 'huggingface':
489
+ resp = await client.get(config['userinfo_url'], headers=headers)
490
+ data = resp.json()
491
+ user_info = {
492
+ 'email': data.get('email'),
493
+ # whoami-v2 returns camelCase `emailVerified`; the OIDC
494
+ # /oauth/userinfo endpoint uses snake_case. Accept either.
495
+ 'email_verified': bool(data.get('emailVerified') or data.get('email_verified')),
496
+ 'oauth_id': str(data.get('id')),
497
+ 'full_name': data.get('fullname') or data.get('name'),
498
+ 'avatar_url': data.get('avatarUrl'),
499
+ 'username': data.get('name'),
500
+ }
501
+
502
+ elif provider == 'google':
503
+ resp = await client.get(config['userinfo_url'], headers=headers)
504
+ data = resp.json()
505
+ user_info = {
506
+ 'email': data.get('email'),
507
+ # Google v2 userinfo returns `verified_email`; OIDC returns
508
+ # `email_verified`. Accept either.
509
+ 'email_verified': bool(
510
+ data.get('verified_email') or data.get('email_verified')
511
+ ),
512
+ 'oauth_id': data.get('id'),
513
+ 'full_name': data.get('name'),
514
+ 'avatar_url': data.get('picture'),
515
+ 'username': data.get('email', '').split('@')[0],
516
+ }
517
+
518
+ elif provider == 'facebook':
519
+ # Facebook requires appsecret_proof for server-side API calls
520
+ # Generate HMAC-SHA256 hash of access token using app secret
521
+ app_secret = os.getenv('FACEBOOK_APP_SECRET')
522
+ if not app_secret:
523
+ logger.error("❌ [FACEBOOK] FACEBOOK_APP_SECRET not configured!")
524
+ return None
525
+
526
+ # Create appsecret_proof
527
+ appsecret_proof = hmac.new(
528
+ app_secret.encode('utf-8'),
529
+ access_token.encode('utf-8'),
530
+ hashlib.sha256
531
+ ).hexdigest()
532
+
533
+ # Facebook uses access token as query parameter, not Bearer header
534
+ # Add appsecret_proof for security
535
+ userinfo_url_with_token = f"{config['userinfo_url']}&access_token={access_token}&appsecret_proof={appsecret_proof}"
536
+
537
+ logger.info(f"🔍 [FACEBOOK] Requesting user info from: {config['userinfo_url']}")
538
+ logger.info(f"🔍 [FACEBOOK] Access token (first 20 chars): {access_token[:20]}...")
539
+ logger.info(f"🔐 [FACEBOOK] Generated appsecret_proof: {appsecret_proof[:20]}...")
540
+
541
+ try:
542
+ resp = await client.get(userinfo_url_with_token)
543
+
544
+ # Enhanced logging for debugging
545
+ logger.info(f"📊 [FACEBOOK] API response status: {resp.status_code}")
546
+ logger.info(f"📊 [FACEBOOK] API response headers: {dict(resp.headers)}")
547
+ logger.info(f"📊 [FACEBOOK] API response body: {resp.text[:1000]}")
548
+
549
+ if resp.status_code != 200:
550
+ logger.error(f"❌ [FACEBOOK] Userinfo request failed!")
551
+ logger.error(f"❌ [FACEBOOK] Status: {resp.status_code}")
552
+ logger.error(f"❌ [FACEBOOK] Full response: {resp.text}")
553
+ return None
554
+
555
+ data = resp.json()
556
+ logger.info(f"✅ [FACEBOOK] Successfully parsed JSON response")
557
+ logger.info(f"✅ [FACEBOOK] Data keys: {list(data.keys())}")
558
+
559
+ # Validate we got required data
560
+ if not data.get('id'):
561
+ logger.error(f"❌ [FACEBOOK] Missing user ID in response!")
562
+ logger.error(f"❌ [FACEBOOK] Full response data: {data}")
563
+ return None
564
+
565
+ logger.info(f"✅ [FACEBOOK] Got user ID: {data.get('id')}")
566
+
567
+ # Facebook may not return email if permission not approved in App Review
568
+ # Generate a placeholder email using Facebook ID if email not available
569
+ email = data.get('email')
570
+ if not email:
571
+ fb_id = data.get('id')
572
+ email = f"facebook_{fb_id}@communityone.placeholder"
573
+ logger.warning(f"⚠️ [FACEBOOK] No email returned for user {fb_id}. Using placeholder: {email}")
574
+ else:
575
+ logger.info(f"✅ [FACEBOOK] Got email: {email}")
576
+
577
+ user_info = {
578
+ 'email': email,
579
+ # Graph API exposes no email-verification flag, and the email
580
+ # may be a synthetic placeholder — never treat it as verified
581
+ # for the purpose of merging into an existing account.
582
+ 'email_verified': False,
583
+ 'oauth_id': str(data.get('id')),
584
+ 'full_name': data.get('name'),
585
+ 'avatar_url': data.get('picture', {}).get('data', {}).get('url') if isinstance(data.get('picture'), dict) else None,
586
+ 'username': data.get('name', '').replace(' ', '_').lower(),
587
+ }
588
+ logger.info(f"✅ [FACEBOOK] Created user_info: {user_info}")
589
+
590
+ except Exception as e:
591
+ logger.error(f"❌ [FACEBOOK] Exception during user info fetch: {str(e)}")
592
+ logger.error(f"❌ [FACEBOOK] Exception type: {type(e).__name__}")
593
+ import traceback
594
+ logger.error(f"❌ [FACEBOOK] Traceback: {traceback.format_exc()}")
595
+ return None
596
+
597
+ elif provider == 'github':
598
+ # Get user profile
599
+ resp = await client.get(config['userinfo_url'], headers=headers)
600
+ data = resp.json()
601
+
602
+ # Resolve the primary email and its verified status from
603
+ # /user/emails — the /user profile email alone carries no
604
+ # verification signal.
605
+ email = None
606
+ email_verified = False
607
+ resp_emails = await client.get('https://api.github.com/user/emails', headers=headers)
608
+ if resp_emails.status_code == 200:
609
+ emails = resp_emails.json()
610
+ primary = next(
611
+ (e for e in emails if e.get('primary')),
612
+ emails[0] if emails else None,
613
+ )
614
+ if primary:
615
+ email = primary.get('email')
616
+ email_verified = bool(primary.get('verified'))
617
+ if not email:
618
+ # Fallback to the profile email; verification stays unknown.
619
+ email = data.get('email')
620
+
621
+ user_info = {
622
+ 'email': email,
623
+ 'email_verified': email_verified,
624
+ 'oauth_id': str(data.get('id')),
625
+ 'full_name': data.get('name'),
626
+ 'avatar_url': data.get('avatar_url'),
627
+ 'username': data.get('login'),
628
+ }
629
+
630
+ return user_info
631
+
632
+
633
+ @router.get("/me", response_model=UserResponse)
634
+ def get_current_user_info(
635
+ request: Request,
636
+ db: Session = Depends(get_db)
637
+ ):
638
+ """Get current authenticated user info"""
639
+
640
+ # Get token from Authorization header
641
+ auth_header = request.headers.get('Authorization')
642
+ if not auth_header or not auth_header.startswith('Bearer '):
643
+ raise HTTPException(status_code=401, detail="Not authenticated")
644
+
645
+ token = auth_header.split(' ')[1]
646
+
647
+ # Decode token and get user
648
+ from api.auth import decode_access_token
649
+ payload = decode_access_token(token)
650
+ user_id = int(payload.get('sub')) # Convert back to int for DB query
651
+
652
+ user = db.query(User).filter(User.user_id == user_id).first()
653
+ if not user:
654
+ raise HTTPException(status_code=404, detail="User not found")
655
+
656
+ return user
657
+
658
+
659
+ @router.patch("/profile", response_model=UserResponse)
660
+ def update_user_profile(
661
+ profile_data: dict,
662
+ request: Request,
663
+ db: Session = Depends(get_db)
664
+ ):
665
+ """Update user profile (location preferences)"""
666
+
667
+ # Get token from Authorization header
668
+ auth_header = request.headers.get('Authorization')
669
+ if not auth_header or not auth_header.startswith('Bearer '):
670
+ raise HTTPException(status_code=401, detail="Not authenticated")
671
+
672
+ token = auth_header.split(' ')[1]
673
+
674
+ # Decode token and get user
675
+ from api.auth import decode_access_token
676
+ payload = decode_access_token(token)
677
+ user_id = int(payload.get('sub'))
678
+
679
+ user = db.query(User).filter(User.user_id == user_id).first()
680
+ if not user:
681
+ raise HTTPException(status_code=404, detail="User not found")
682
+
683
+ # Update allowed fields
684
+ allowed_fields = ['state', 'county', 'city', 'school_board', 'profile_completed']
685
+ for field, value in profile_data.items():
686
+ if field in allowed_fields and hasattr(user, field):
687
+ setattr(user, field, value)
688
+
689
+ user.updated_at = datetime.utcnow()
690
+ db.commit()
691
+ db.refresh(user)
692
+
693
+ return user
694
+
695
+
696
+ @router.post("/logout")
697
+ def logout():
698
+ """Logout endpoint (client-side token removal)"""
699
+ return {"message": "Logged out successfully. Please remove the token from client."}
api/routes/batch_jobs.py ADDED
@@ -0,0 +1,1956 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ YouTube / policy pipeline batch job status for the Data explorer React UI.
3
+
4
+ Reads from ``bronze.youtube_batch_job_runs`` (real-time). JSON files under
5
+ ``data/cache/batch_jobs/`` are synced on read when the DB is empty.
6
+
7
+ Live updates: ``GET /api/batch-jobs/stream`` (Server-Sent Events).
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import json
13
+ import os
14
+ import re
15
+ import signal
16
+ import subprocess
17
+ from datetime import datetime, timezone
18
+ from pathlib import Path
19
+ from typing import Any, AsyncIterator, Dict, List, Optional
20
+
21
+ # A "running" launch that has produced no pipeline activity for this long is
22
+ # treated as stalled/timed-out, so the dashboard re-enables launching.
23
+ _LAUNCH_STALL_SECONDS = 3600
24
+ # Softer signal: warn on the dashboard well before the stall reap (#750).
25
+ _LAUNCH_WARN_SECONDS_DEFAULT = 900
26
+
27
+ from fastapi import APIRouter, Depends, HTTPException, Query
28
+ from fastapi.responses import StreamingResponse
29
+ from loguru import logger
30
+ from pydantic import BaseModel, Field
31
+
32
+ from api.auth import require_admin
33
+
34
+ router = APIRouter(prefix="/batch-jobs", tags=["batch-jobs"])
35
+
36
+
37
+ def _launch_warn_seconds() -> float:
38
+ raw = os.getenv("BATCH_JOB_LAUNCH_WARN_SECONDS", str(_LAUNCH_WARN_SECONDS_DEFAULT))
39
+ try:
40
+ return max(60.0, float(raw))
41
+ except (TypeError, ValueError):
42
+ return float(_LAUNCH_WARN_SECONDS_DEFAULT)
43
+
44
+
45
+ # Launch-log lines that mean YouTube traffic cannot leave through the VPN (#488 / #750).
46
+ _VPN_DOWN_RE = re.compile(
47
+ r"Surfshark is off|VpnRequiredError|no VPN tunnel route",
48
+ re.IGNORECASE,
49
+ )
50
+ # Gemini prepaid billing exhaustion in launch logs (#699) — not free-tier daily 429.
51
+ _BILLING_EXHAUSTED_RE = re.compile(
52
+ r"402\s*RESOURCE_EXHAUSTED|prepayment credits are depleted|credits are depleted|"
53
+ r"billing exhaustion \(402|ClientError:\s*402|prepaid credits depleted",
54
+ re.IGNORECASE,
55
+ )
56
+
57
+
58
+ class BatchJobsTotals(BaseModel):
59
+ batches: int = 0
60
+ running: int = 0
61
+ states: int = 0
62
+ states_planned: int = 0
63
+ states_started: int = 0
64
+ states_completed: int = 0
65
+ processed_jurisdictions: int = 0
66
+ failed_jurisdictions: int = 0
67
+ remaining_jurisdictions: int = 0
68
+ videos_ok: int = 0
69
+ videos_fail: int = 0
70
+ videos_attempted: int = 0
71
+ files_transcripts: int = 0
72
+ files_transcripts_disk: int = 0
73
+ transcript_hours: float = 0.0
74
+ bronze_download_rows: int = 0
75
+ files_analysis: int = 0
76
+ files_reports: int = 0
77
+ # Rolling 24h throughput from per-event bronze stamps (migration 083).
78
+ files_analysis_recent: int = 0
79
+ files_reports_recent: int = 0
80
+ files_analysis_errors_recent: int = 0
81
+ files_reports_errors_recent: int = 0
82
+ # Most recent stamp per step (all time) for the "ago" cards.
83
+ last_transcript_at: str = ""
84
+ last_analysis_at: str = ""
85
+ last_report_at: str = ""
86
+
87
+
88
+ class VideoResultModel(BaseModel):
89
+ video_id: str
90
+ title: str = ""
91
+ status: str = "pending"
92
+ error: str = ""
93
+ transcript_source: str = ""
94
+ finished_at: str = ""
95
+ duration_seconds: float | None = None
96
+
97
+
98
+ class JurisdictionRunModel(BaseModel):
99
+ state_code: str
100
+ jurisdiction_id: str
101
+ jurisdiction_name: str = ""
102
+ status: str = "pending"
103
+ started_at: str = ""
104
+ finished_at: str = ""
105
+ elapsed_seconds: float = 0
106
+ exit_code: int = 0
107
+ stats: Dict[str, int] = Field(default_factory=dict)
108
+ videos: List[VideoResultModel] = Field(default_factory=list)
109
+ file_counts: Dict[str, int] = Field(default_factory=dict)
110
+ current_video_id: str = ""
111
+ current_video_title: str = ""
112
+ current_video_started_at: str = ""
113
+
114
+
115
+ class BatchJobModel(BaseModel):
116
+ batch_id: str
117
+ step: str
118
+ status: str
119
+ started_at: str = ""
120
+ updated_at: str = ""
121
+ finished_at: str = ""
122
+ config: Dict[str, Any] = Field(default_factory=dict)
123
+ summary: Dict[str, Any] = Field(default_factory=dict)
124
+ jurisdictions: List[JurisdictionRunModel] = Field(default_factory=list)
125
+
126
+
127
+ class StageBreakdownEntry(BaseModel):
128
+ # Per-entity split of a stage's coverage (e.g. discover: counties vs
129
+ # municipalities). Entries sum back to the parent row's done/total.
130
+ entity: str
131
+ done: int = 0
132
+ total: int = 0
133
+ failed: int = 0
134
+
135
+
136
+ class StageReportRow(BaseModel):
137
+ # One (scope, stage) row. scope is a 2-letter state code or "ALL" (rollup).
138
+ scope: str
139
+ stage: str
140
+ done: int = 0
141
+ total: int = 0
142
+ failed: int = 0
143
+ last_at: str = ""
144
+ # Optional per-entity split (only populated for the discover stage today).
145
+ breakdown: List[StageBreakdownEntry] = Field(default_factory=list)
146
+
147
+
148
+ class StageReport(BaseModel):
149
+ states: List[str] = Field(default_factory=list)
150
+ rows: List[StageReportRow] = Field(default_factory=list)
151
+ # Per-stage cadence/last-file:
152
+ # {stage: {avg_seconds, last_path, last_at, stale_seconds, effective_seconds}}.
153
+ # effective_seconds = max(avg_seconds, stale_seconds) so /hr and ETA reflect a
154
+ # stall in progress, not just the historical pace between completions.
155
+ timing: Dict[str, Any] = Field(default_factory=dict)
156
+
157
+
158
+ class BatchJobsDashboardResponse(BaseModel):
159
+ generated_at: str
160
+ last_activity_at: str = ""
161
+ totals: BatchJobsTotals
162
+ batches: List[BatchJobModel]
163
+ stage_report: StageReport = Field(default_factory=StageReport)
164
+ source: str = "database"
165
+ detail: str = "full"
166
+
167
+
168
+ def _sanitize_dashboard_payload(payload: Dict[str, Any]) -> Dict[str, Any]:
169
+ """Coerce DB payloads so Pydantic response validation does not 500."""
170
+ import math
171
+
172
+ totals = payload.get("totals")
173
+ if isinstance(totals, dict):
174
+ th = totals.get("transcript_hours")
175
+ if isinstance(th, float) and (math.isnan(th) or math.isinf(th)):
176
+ totals["transcript_hours"] = 0.0
177
+
178
+ for batch in payload.get("batches") or []:
179
+ if not isinstance(batch, dict):
180
+ continue
181
+ for j in batch.get("jurisdictions") or []:
182
+ if not isinstance(j, dict):
183
+ continue
184
+ raw_stats = j.get("stats")
185
+ if isinstance(raw_stats, dict):
186
+ clean: Dict[str, int] = {}
187
+ for key, val in raw_stats.items():
188
+ try:
189
+ clean[str(key)] = int(val)
190
+ except (TypeError, ValueError):
191
+ continue
192
+ j["stats"] = clean
193
+ for field in ("elapsed_seconds",):
194
+ try:
195
+ j[field] = float(j.get(field) or 0)
196
+ except (TypeError, ValueError):
197
+ j[field] = 0.0
198
+ return payload
199
+
200
+
201
+ def _parse_dashboard_cohort(cohort: Optional[str] = None) -> Optional[str]:
202
+ """Normalize optional dashboard ``?cohort=`` (priority / data_centers scope stage_report)."""
203
+ if cohort is None or not str(cohort).strip():
204
+ return None
205
+ c = str(cohort).strip().lower()
206
+ if c not in ("priority", "data_centers", "all"):
207
+ raise HTTPException(
208
+ status_code=400,
209
+ detail="cohort must be one of priority, data_centers, all",
210
+ )
211
+ return c
212
+
213
+
214
+ async def _latest_dashboard_revision_async() -> Optional[str]:
215
+ try:
216
+ from api.batch_jobs.batch_job_db import latest_dashboard_revision
217
+
218
+ return await asyncio.to_thread(latest_dashboard_revision)
219
+ except Exception:
220
+ return None
221
+
222
+
223
+ async def _load_dashboard_async(
224
+ *,
225
+ refresh_files: bool,
226
+ enrich_bronze: bool,
227
+ enrich_bronze_only_running: bool = False,
228
+ detail: str = "full",
229
+ batch_limit: int = 25,
230
+ cohort: Optional[str] = None,
231
+ ) -> Dict[str, Any]:
232
+ return await asyncio.to_thread(
233
+ _load_dashboard,
234
+ refresh_files=refresh_files,
235
+ enrich_bronze=enrich_bronze,
236
+ enrich_bronze_only_running=enrich_bronze_only_running,
237
+ detail=detail,
238
+ batch_limit=batch_limit,
239
+ cohort=cohort,
240
+ )
241
+
242
+
243
+ def _load_dashboard(
244
+ *,
245
+ refresh_files: bool,
246
+ enrich_bronze: bool,
247
+ enrich_bronze_only_running: bool = False,
248
+ detail: str = "full",
249
+ batch_limit: int = 25,
250
+ cohort: Optional[str] = None,
251
+ ) -> Dict[str, Any]:
252
+ from api.batch_jobs.batch_job_dashboard import (
253
+ VideoPayloadMode,
254
+ build_dashboard_data,
255
+ build_dashboard_summary,
256
+ )
257
+
258
+ if detail == "summary":
259
+ payload = build_dashboard_summary(limit=batch_limit, cohort=cohort)
260
+ else:
261
+ video_mode: VideoPayloadMode = "all" if detail == "full" else "running"
262
+ payload = build_dashboard_data(
263
+ refresh_files=refresh_files,
264
+ enrich_bronze=enrich_bronze,
265
+ enrich_bronze_only_running=enrich_bronze_only_running,
266
+ batch_limit=batch_limit,
267
+ video_mode=video_mode,
268
+ cohort=cohort,
269
+ )
270
+ return _sanitize_dashboard_payload(payload)
271
+
272
+
273
+ @router.get("/stream")
274
+ async def stream_batch_jobs(
275
+ refresh_files: bool = Query(False),
276
+ enrich_bronze: bool = Query(
277
+ False,
278
+ description="When true, refresh transcript counts from bronze each tick (heavier)",
279
+ ),
280
+ cohort: Optional[str] = Query(
281
+ None,
282
+ description="Launch cohort; data_centers scopes stage_report to DC jurisdictions",
283
+ ),
284
+ ) -> StreamingResponse:
285
+ """SSE stream of dashboard JSON; pushes when DB revision changes."""
286
+ cohort_norm = _parse_dashboard_cohort(cohort)
287
+
288
+ async def event_generator() -> AsyncIterator[str]:
289
+ last_rev: Optional[str] = None
290
+ running_batches = 0
291
+ last_push_mono = 0.0
292
+ # Catalog/discover launches do not bump youtube_batch_job_runs, so a
293
+ # revision-only stream freezes Last activity while those runs land
294
+ # rows (#757 / #761). Refresh on a short interval when a launch PID is live.
295
+ launch_refresh_seconds = 5.0
296
+ loop = asyncio.get_running_loop()
297
+ while True:
298
+ rev = await _latest_dashboard_revision_async()
299
+ launches_live = await asyncio.to_thread(_any_launch_pid_alive)
300
+ now_mono = loop.time()
301
+ due_for_launch = launches_live and (
302
+ last_rev is None
303
+ or (now_mono - last_push_mono) >= launch_refresh_seconds
304
+ )
305
+
306
+ if last_rev is None or rev != last_rev or due_for_launch:
307
+ summary = await _load_dashboard_async(
308
+ refresh_files=False,
309
+ enrich_bronze=False,
310
+ detail="summary",
311
+ cohort=cohort_norm,
312
+ )
313
+ yield (
314
+ "event: summary\n"
315
+ f"data: {json.dumps(summary, ensure_ascii=False)}\n\n"
316
+ )
317
+ totals = summary.get("totals") or {}
318
+ running_batches = int(totals.get("running") or 0)
319
+ last_rev = rev
320
+ last_push_mono = now_mono
321
+
322
+ await asyncio.sleep(
323
+ 1.0 if (running_batches > 0 or launches_live) else 3.0
324
+ )
325
+
326
+ return StreamingResponse(
327
+ event_generator(),
328
+ media_type="text/event-stream",
329
+ headers={
330
+ "Cache-Control": "no-cache",
331
+ "Connection": "keep-alive",
332
+ "X-Accel-Buffering": "no",
333
+ },
334
+ )
335
+
336
+
337
+ # --- Dashboard response cache -------------------------------------------------
338
+ # The dashboard aggregates (especially the int_events_union transcript-coverage
339
+ # view) take ~30s, and the UI polls frequently — so without caching every poll
340
+ # re-runs the whole thing and competes with the analyze backfill's writes, the
341
+ # endpoint exceeds the client timeout, and the UI shows "empty response". Cache
342
+ # the assembled payload per param-set with a short TTL: single-flight (concurrent
343
+ # polls share one computation), stale-while-revalidate (serve the last result
344
+ # instantly and refresh in the background once stale), and shielded so a client
345
+ # disconnect still lets the in-flight computation finish and populate the cache —
346
+ # so the next "Retry load" hits it warm. Tune via BATCH_JOBS_DASHBOARD_TTL_SECONDS
347
+ # (default 20); set to 0 to disable caching.
348
+ _DASH_CACHE: Dict[tuple, tuple] = {}
349
+ _DASH_INFLIGHT: Dict[tuple, Any] = {}
350
+
351
+
352
+ def _dash_ttl() -> float:
353
+ try:
354
+ return max(0.0, float(os.environ.get("BATCH_JOBS_DASHBOARD_TTL_SECONDS", "20")))
355
+ except ValueError:
356
+ return 20.0
357
+
358
+
359
+ async def _load_dashboard_cached(**kwargs: Any) -> Dict[str, Any]:
360
+ ttl = _dash_ttl()
361
+ if ttl <= 0:
362
+ return await _load_dashboard_async(**kwargs)
363
+
364
+ key = tuple(sorted(kwargs.items()))
365
+ loop = asyncio.get_running_loop()
366
+ hit = _DASH_CACHE.get(key)
367
+ if hit is not None and loop.time() - hit[0] < ttl:
368
+ return hit[1] # fresh
369
+
370
+ async def _compute() -> Dict[str, Any]:
371
+ try:
372
+ payload = await _load_dashboard_async(**kwargs)
373
+ _DASH_CACHE[key] = (loop.time(), payload)
374
+ return payload
375
+ finally:
376
+ _DASH_INFLIGHT.pop(key, None)
377
+
378
+ task = _DASH_INFLIGHT.get(key)
379
+ if task is None or task.done():
380
+ task = loop.create_task(_compute())
381
+ _DASH_INFLIGHT[key] = task
382
+
383
+ if hit is not None:
384
+ return hit[1] # stale-while-revalidate: serve stale, refresh in background
385
+ # Cold cache: must wait for the first computation. Shield it so a client
386
+ # timeout/disconnect doesn't cancel the work — it still caches for the retry.
387
+ return await asyncio.shield(task)
388
+
389
+
390
+ @router.get("/", response_model=BatchJobsDashboardResponse)
391
+ @router.get("", response_model=BatchJobsDashboardResponse, include_in_schema=False)
392
+ async def list_batch_jobs(
393
+ refresh_files: bool = Query(
394
+ False,
395
+ description="Scan policy cache on disk for analysis/report counts (slow)",
396
+ ),
397
+ enrich_bronze: bool = Query(
398
+ False,
399
+ description="Refresh transcript metrics from bronze (slow; stream uses lighter enrich)",
400
+ ),
401
+ detail: str = Query(
402
+ "summary",
403
+ description="summary = aggregates + batch list (default); standard/full load jurisdiction payloads (slow)",
404
+ ),
405
+ batch_limit: int = Query(25, ge=1, le=100),
406
+ cohort: Optional[str] = Query(
407
+ None,
408
+ description="Launch cohort; data_centers scopes stage_report to DC jurisdictions",
409
+ ),
410
+ ) -> BatchJobsDashboardResponse:
411
+ if detail not in ("summary", "standard", "full"):
412
+ raise HTTPException(
413
+ status_code=400,
414
+ detail="detail must be summary, standard, or full",
415
+ )
416
+ cohort_norm = _parse_dashboard_cohort(cohort)
417
+ try:
418
+ payload = await _load_dashboard_cached(
419
+ refresh_files=refresh_files,
420
+ enrich_bronze=enrich_bronze,
421
+ detail=detail,
422
+ batch_limit=batch_limit,
423
+ cohort=cohort_norm,
424
+ )
425
+ return BatchJobsDashboardResponse(**payload)
426
+ except Exception as exc:
427
+ logger.exception("batch-jobs dashboard failed")
428
+ raise HTTPException(
429
+ status_code=500,
430
+ detail=f"Batch jobs dashboard failed: {exc}",
431
+ ) from exc
432
+
433
+
434
+ # --- Re-kick: (re)launch a stopped pipeline run from the dashboard --------------
435
+ # Spawns the existing wrapper script as a detached subprocess. Hardened against
436
+ # misuse: a fixed argv (no shell), an allowlisted step, validated state codes, a
437
+ # single-run guard (won't double-launch), and an opt-out kill switch.
438
+ _LAUNCH_SCRIPT = "packages/scrapers/scripts/youtube_run_priority_states_last_n.sh"
439
+ # Stage 0 (discover) runs a different, per-state script; the rest run the wrapper.
440
+ _DISCOVER_SCRIPT = "packages/scrapers/src/scrapers/youtube/load_missing_county_channels.py"
441
+ # `backfill` runs the flat, mart-wide transcript sweep (reaches LocalView/union
442
+ # videos with no jurisdiction the per-jurisdiction `captions` loop never visits).
443
+ _BACKFILL_SCRIPT = "packages/scrapers/src/scrapers/youtube/backfill_transcripts.py"
444
+ # analyze / analyze-light are aliases (light Part 1). reports-* = Part 2 only.
445
+ # analyze-full / reports-full are opt-in and require full_filters (#755).
446
+ # Stages 1–5 started together by Run all (#763). Each is its own launch.json
447
+ # entry with its own log / Stop / VPN auto-resume — not a sequential chain.
448
+ _RUN_ALL_PARALLEL_STEPS = (
449
+ "discover",
450
+ "catalog",
451
+ "captions",
452
+ "analyze-light",
453
+ "reports-light",
454
+ )
455
+ _LAUNCH_STEPS = (
456
+ "discover",
457
+ "catalog",
458
+ "captions",
459
+ "backfill",
460
+ "analyze",
461
+ "analyze-light",
462
+ "reports-light",
463
+ "analyze-full",
464
+ "reports-full",
465
+ "each",
466
+ "all",
467
+ )
468
+ _FULL_FILTER_STEPS = frozenset({"analyze-full", "reports-full"})
469
+ _FULL_FILTER_KEYS = frozenset({"has_decisions", "interestingness", "data_center"})
470
+ # Steps that talk to YouTube and must wait for the VPN tunnel before auto-resume (#752).
471
+ _LAUNCH_STEPS_NEED_VPN = frozenset(_LAUNCH_STEPS)
472
+ _STATE_RE = re.compile(r"^[A-Z]{2}$")
473
+ _VPN_EXIT_CODE = 5
474
+
475
+
476
+ def _auto_resume_enabled() -> bool:
477
+ if not _launch_enabled():
478
+ return False
479
+ v = (os.getenv("BATCH_JOBS_AUTO_RESUME") or "1").strip().lower()
480
+ return v not in ("0", "false", "no", "off")
481
+
482
+
483
+ def _auto_resume_max() -> int:
484
+ raw = os.getenv("BATCH_JOBS_AUTO_RESUME_MAX", "5")
485
+ try:
486
+ return max(0, min(20, int(raw)))
487
+ except (TypeError, ValueError):
488
+ return 5
489
+
490
+
491
+ def _vpn_tunnel_up_for_resume() -> bool:
492
+ """Route-table only (no public-IP lookups) so the watchdog cannot hang (#752)."""
493
+ try:
494
+ from scrapers.youtube.vpn_guard import read_routes, vpn_required
495
+
496
+ if not vpn_required():
497
+ return True
498
+ return bool(read_routes().tunnel_interface)
499
+ except Exception as exc:
500
+ logger.debug("vpn tunnel check for resume failed: {!r}", exc)
501
+ return False
502
+
503
+
504
+ def _read_exit_code(meta: Dict[str, Any]) -> Optional[int]:
505
+ path = Path(str(meta.get("exit_path") or ""))
506
+ if not path.is_file():
507
+ return None
508
+ try:
509
+ text = path.read_text(encoding="utf-8").strip().splitlines()[0].strip()
510
+ return int(text)
511
+ except (OSError, ValueError, IndexError):
512
+ return None
513
+
514
+
515
+ def _repo_root() -> Path:
516
+ # api/routes/batch_jobs.py -> repo root
517
+ return Path(__file__).resolve().parents[2]
518
+
519
+
520
+ def _launch_enabled() -> bool:
521
+ # Opt-in: disabled unless BATCH_JOBS_ALLOW_LAUNCH is explicitly truthy on this
522
+ # deploy (defaults off, matching deployments.py). The mutating endpoints are
523
+ # additionally gated by require_admin.
524
+ return os.getenv("BATCH_JOBS_ALLOW_LAUNCH", "0").strip().lower() in (
525
+ "1",
526
+ "true",
527
+ "yes",
528
+ "on",
529
+ )
530
+
531
+
532
+ def _launch_meta_path() -> Path:
533
+ return _repo_root() / "data" / "cache" / "batch_jobs" / "launch.json"
534
+
535
+
536
+ def _read_launches() -> List[Dict[str, Any]]:
537
+ """All tracked launches: list of {pid, step, states, started_at}."""
538
+ try:
539
+ data = json.loads(_launch_meta_path().read_text())
540
+ except (OSError, ValueError, FileNotFoundError):
541
+ return []
542
+ if isinstance(data, dict): # legacy single-launch file
543
+ return [data]
544
+ return [m for m in data if isinstance(m, dict)] if isinstance(data, list) else []
545
+
546
+
547
+ def _write_launches(launches: List[Dict[str, Any]]) -> None:
548
+ try:
549
+ _launch_meta_path().write_text(json.dumps(launches))
550
+ except Exception:
551
+ pass
552
+
553
+
554
+ def _pid_alive(pid: Any) -> bool:
555
+ try:
556
+ p = int(pid)
557
+ except (TypeError, ValueError):
558
+ return False
559
+ try:
560
+ os.kill(p, 0) # signal 0 = exists (but zombies pass this too)
561
+ except OSError:
562
+ return False
563
+ # A finished-but-unreaped child shows as a zombie ("Z"/"X"); treat it as dead
564
+ # so a completed launch doesn't pin the dashboard at "running" forever.
565
+ try:
566
+ with open(f"/proc/{p}/stat") as fh:
567
+ state = fh.read().split(") ", 1)[1][:1]
568
+ if state in ("Z", "X"):
569
+ try:
570
+ os.waitpid(p, os.WNOHANG) # reap if it's our child
571
+ except (ChildProcessError, OSError):
572
+ pass
573
+ return False
574
+ except (FileNotFoundError, IndexError):
575
+ pass
576
+ return True
577
+
578
+
579
+ def _any_launch_pid_alive() -> bool:
580
+ """True when launch.json tracks a live catalog/discover/etc process (#761)."""
581
+ try:
582
+ return any(_pid_alive(m.get("pid")) for m in _read_launches())
583
+ except Exception:
584
+ return False
585
+
586
+
587
+ def _dashboard_runtime() -> "tuple[int, str]":
588
+ """(# running batch rows, freshest pipeline-activity ISO) in one DB hit."""
589
+ try:
590
+ from api.batch_jobs.batch_job_db import aggregate_dashboard_totals_from_db
591
+
592
+ t = aggregate_dashboard_totals_from_db(limit=10) or {}
593
+ running = int(t.get("running") or 0)
594
+ freshest = max(
595
+ str(t.get(k) or "")
596
+ for k in (
597
+ "last_activity_at",
598
+ "last_transcript_at",
599
+ "last_analysis_at",
600
+ "last_report_at",
601
+ )
602
+ )
603
+ return running, freshest
604
+ except Exception:
605
+ return 0, ""
606
+
607
+
608
+ def _iso_age_seconds(iso: str) -> Optional[float]:
609
+ try:
610
+ dt = datetime.fromisoformat(iso.replace("Z", "+00:00"))
611
+ if dt.tzinfo is None:
612
+ dt = dt.replace(tzinfo=timezone.utc)
613
+ return (datetime.now(timezone.utc) - dt).total_seconds()
614
+ except Exception:
615
+ return None
616
+
617
+
618
+ def _latest_launch_log(step: str) -> Optional[Path]:
619
+ log_dir = _repo_root() / "data" / "cache" / "batch_jobs"
620
+ candidates = sorted(log_dir.glob(f"launch_{step}_*.log"), reverse=True)
621
+ return candidates[0] if candidates else None
622
+
623
+
624
+ def _launch_log_signals(step: str, *, lines: int = 80) -> Dict[str, Any]:
625
+ """Last activity + VPN / billing hints from the newest launch log for ``step``."""
626
+ path = _latest_launch_log(step)
627
+ if path is None:
628
+ return {
629
+ "last_at": "",
630
+ "vpn_down": False,
631
+ "billing_exhausted": False,
632
+ "path": "",
633
+ }
634
+ tail = _tail_lines(path, lines)
635
+ _current, since = _parse_current(tail)
636
+ if not since:
637
+ try:
638
+ since = datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc).isoformat()
639
+ except OSError:
640
+ since = ""
641
+ recent = tail[-40:]
642
+ vpn_down = any(_VPN_DOWN_RE.search(ln or "") for ln in recent)
643
+ billing_exhausted = any(_BILLING_EXHAUSTED_RE.search(ln or "") for ln in recent)
644
+ return {
645
+ "last_at": since,
646
+ "vpn_down": vpn_down,
647
+ "billing_exhausted": billing_exhausted,
648
+ "path": str(path),
649
+ }
650
+
651
+
652
+ def _launch_activity_iso(live: Dict[str, Any], freshest: str) -> str:
653
+ """Best-effort 'last progress' for a live launch.
654
+
655
+ Discover/backfill do not stamp ``youtube_batch_job_runs`` the way catalog/
656
+ captions do, so unrelated analyze/transcript freshest must not hide a hung
657
+ discover log (#750).
658
+ """
659
+ step = str(live.get("step") or "")
660
+ started = str(live.get("started_at") or "")
661
+ log_at = str(_launch_log_signals(step).get("last_at") or "")
662
+ if step in ("discover", "backfill"):
663
+ return max(started, log_at)
664
+ return max(freshest or "", started, log_at)
665
+
666
+
667
+ def _launch_stalled(live: Dict[str, Any], freshest: str) -> bool:
668
+ """A live launch with no activity (or none since it started) for over the
669
+ stall window — i.e. stuck. ``freshest`` and ``started_at`` are UTC ISO."""
670
+ last_seen = _launch_activity_iso(live, freshest)
671
+ age = _iso_age_seconds(last_seen) if last_seen else None
672
+ return age is not None and age > _LAUNCH_STALL_SECONDS
673
+
674
+
675
+ def _kill_launch(meta: Dict[str, Any], *, sig: int = signal.SIGTERM) -> None:
676
+ """Best-effort signal to a launch's process group (SIGTERM by default).
677
+
678
+ Launches start with ``start_new_session=True`` so the pid is its own process
679
+ group leader; signalling the group reaches the whole pipeline subtree.
680
+ """
681
+ try:
682
+ os.killpg(os.getpgid(int(meta["pid"])), sig)
683
+ except Exception:
684
+ # Fall back to signalling just the pid if the group lookup fails.
685
+ try:
686
+ os.kill(int(meta["pid"]), sig)
687
+ except Exception:
688
+ pass
689
+
690
+
691
+ def _classify_launches(freshest: str) -> "tuple[List[Dict[str, Any]], List[Dict[str, Any]]]":
692
+ """(running, stalled) metas among live launches; dead ones are ignored."""
693
+ running: List[Dict[str, Any]] = []
694
+ stalled: List[Dict[str, Any]] = []
695
+ for m in _read_launches():
696
+ if not _pid_alive(m.get("pid")):
697
+ continue
698
+ (stalled if _launch_stalled(m, freshest) else running).append(m)
699
+ return running, stalled
700
+
701
+
702
+ class LaunchRequest(BaseModel):
703
+ step: str = "analyze"
704
+ states: List[str] = Field(default_factory=list)
705
+ n: int = 10
706
+ parallel: int = 4
707
+ cohort: str = "priority"
708
+ # Multi-select eligibility for analyze-full / reports-full (#755). OR semantics.
709
+ full_filters: List[str] = Field(default_factory=list)
710
+
711
+
712
+ class LaunchStatusResponse(BaseModel):
713
+ enabled: bool
714
+ busy: bool = False
715
+ running: int = 0
716
+ # Per-step concurrency: different steps may run at once; the same step may not.
717
+ running_steps: List[str] = Field(default_factory=list)
718
+ stalled_steps: List[str] = Field(default_factory=list)
719
+ steps: List[str] = Field(default_factory=lambda: list(_LAUNCH_STEPS))
720
+ # Operator-facing stall / VPN / billing signals (#750 / #699).
721
+ # ``warning`` is empty when idle.
722
+ warning: str = ""
723
+ vpn_down: bool = False
724
+ billing_exhausted: bool = False
725
+ inactive_seconds: Optional[float] = None
726
+ # Steps the watchdog re-spawned on this status poll (#752).
727
+ resumed_steps: List[str] = Field(default_factory=list)
728
+ auto_resume_note: str = ""
729
+
730
+
731
+ class LaunchResponse(BaseModel):
732
+ launched: bool
733
+ pid: Optional[int] = None
734
+ step: str = ""
735
+ states: List[str] = Field(default_factory=list)
736
+ log: str = ""
737
+ detail: str = ""
738
+
739
+
740
+ def _recent_log_flag(
741
+ flag: str, *, max_age_seconds: float = 7200.0
742
+ ) -> "tuple[bool, List[str]]":
743
+ """True + matching steps when a recent launch log (even after PID exit) has ``flag``."""
744
+ hits: List[str] = []
745
+ for step in _LAUNCH_STEPS:
746
+ signals = _launch_log_signals(step)
747
+ if not signals.get(flag):
748
+ continue
749
+ age = _iso_age_seconds(str(signals.get("last_at") or ""))
750
+ if age is not None and age <= max_age_seconds:
751
+ hits.append(step)
752
+ return bool(hits), hits
753
+
754
+
755
+ def _recent_log_vpn_down(*, max_age_seconds: float = 7200.0) -> bool:
756
+ """True when a recent launch log (even after the PID exited) mentions VPN down."""
757
+ hit, _steps = _recent_log_flag("vpn_down", max_age_seconds=max_age_seconds)
758
+ return hit
759
+
760
+
761
+ def _launch_operator_signals(
762
+ freshest: str,
763
+ running: List[Dict[str, Any]],
764
+ stalled: List[Dict[str, Any]],
765
+ ) -> Dict[str, Any]:
766
+ """Build warning / vpn_down / billing_exhausted / inactive_seconds for the header."""
767
+ warn_after = _launch_warn_seconds()
768
+ warning = ""
769
+ vpn_down = False
770
+ billing_exhausted = False
771
+ billing_steps: List[str] = []
772
+ inactive_seconds: Optional[float] = None
773
+ for m in (*running, *stalled):
774
+ step = str(m.get("step") or "") or "pipeline"
775
+ signals = _launch_log_signals(step)
776
+ if signals.get("vpn_down"):
777
+ vpn_down = True
778
+ if signals.get("billing_exhausted"):
779
+ billing_exhausted = True
780
+ if step not in billing_steps:
781
+ billing_steps.append(step)
782
+ last_seen = _launch_activity_iso(m, freshest)
783
+ age = _iso_age_seconds(last_seen) if last_seen else None
784
+ if age is None:
785
+ continue
786
+ inactive_seconds = age if inactive_seconds is None else max(inactive_seconds, age)
787
+ if age >= warn_after and not warning:
788
+ mins = max(1, int(age // 60))
789
+ warning = (
790
+ f"{step}: no launch-log activity for {mins}m — "
791
+ "job may be stuck (check VPN / Surfshark)."
792
+ )
793
+ # Process already exited after VpnRequiredError — still show the error for a while.
794
+ if not vpn_down and _recent_log_vpn_down():
795
+ vpn_down = True
796
+ # Live tunnel wins over a stale Surfshark-off line: after reconnect the same
797
+ # launch log still matches for up to two hours (#834).
798
+ if vpn_down and _vpn_tunnel_up_for_resume():
799
+ vpn_down = False
800
+ if not billing_exhausted:
801
+ recent_billing, recent_steps = _recent_log_flag("billing_exhausted")
802
+ if recent_billing:
803
+ billing_exhausted = True
804
+ for s in recent_steps:
805
+ if s not in billing_steps:
806
+ billing_steps.append(s)
807
+ # Billing / VPN beat inactivity — operator must top up or reconnect (#699 / #750).
808
+ if vpn_down:
809
+ warning = (
810
+ "VPN appears down (Surfshark off in launch log). "
811
+ "Connect Surfshark and re-run."
812
+ + (f" {warning}" if warning and "Surfshark off" not in warning else "")
813
+ )
814
+ elif billing_exhausted:
815
+ steps = ", ".join(sorted(billing_steps)) or "analyze"
816
+ warning = (
817
+ f"{steps}: Gemini prepaid credits depleted (402). "
818
+ "Top up at https://ai.studio/projects — this is not a free-tier daily wall "
819
+ "and will not clear at midnight Pacific. Stop the run until billed."
820
+ )
821
+ elif stalled and not warning:
822
+ steps = ", ".join(sorted({str(m.get("step") or "") for m in stalled} - {""})) or "pipeline"
823
+ warning = f"{steps}: timed out (no activity >1h) — re-launch after fixing VPN/blockers."
824
+ return {
825
+ "warning": warning,
826
+ "vpn_down": vpn_down,
827
+ "billing_exhausted": billing_exhausted,
828
+ "inactive_seconds": inactive_seconds,
829
+ }
830
+
831
+
832
+ def _discover_argv(states: List[str], cohort: str) -> List[str]:
833
+ """Argv for the Discover CLI (channel candidates). Raises ValueError if missing."""
834
+ if not states:
835
+ raise ValueError("discover requires at least one state.")
836
+ target = _repo_root() / _DISCOVER_SCRIPT
837
+ if not target.is_file():
838
+ raise ValueError(f"discover script missing: {target}")
839
+ import sys as _sys
840
+
841
+ # --load: after each state CSV, catalog candidates so scraped bronze
842
+ # youtube_channel_* / discovered_at update as loads land (#740).
843
+ argv = [
844
+ _sys.executable,
845
+ str(target),
846
+ "--states",
847
+ ",".join(states),
848
+ "--load",
849
+ ]
850
+ if cohort == "data_centers":
851
+ argv += ["--cohort", "data_centers"]
852
+ return argv
853
+
854
+
855
+ def _normalize_full_filters(raw: Optional[List[str]]) -> List[str]:
856
+ out: List[str] = []
857
+ seen: set[str] = set()
858
+ for item in raw or []:
859
+ key = str(item or "").strip().lower()
860
+ if key not in _FULL_FILTER_KEYS or key in seen:
861
+ continue
862
+ seen.add(key)
863
+ out.append(key)
864
+ return out
865
+
866
+
867
+ def _shell_step_for_launch(step: str) -> str:
868
+ """Map API launch step → shell wrapper argument."""
869
+ if step in ("analyze", "analyze-light"):
870
+ return "analyze-light"
871
+ return step
872
+
873
+
874
+ def _build_launch_argv(
875
+ step: str,
876
+ *,
877
+ states: List[str],
878
+ cohort: str,
879
+ n: int,
880
+ parallel: int,
881
+ full_filters: Optional[List[str]] = None,
882
+ ) -> "tuple[List[str], Dict[str, str]]":
883
+ """Return (argv, env updates) for a pipeline step. Raises ValueError on bad paths."""
884
+ import shlex
885
+
886
+ root = _repo_root()
887
+ # Drop exported bash completion functions. A broken BASH_FUNC_* (e.g.
888
+ # _xinetd_services with an extglob pattern) is reimported by every child
889
+ # `bash` and aborts the pipeline before the script runs — Run all then
890
+ # looks like a no-op (#687).
891
+ env = {k: v for k, v in os.environ.items() if not k.startswith("BASH_FUNC_")}
892
+ env["COHORT"] = cohort
893
+ env["STATES"] = ",".join(states)
894
+ if step == "discover":
895
+ return _discover_argv(states, cohort), env
896
+ if step == "backfill":
897
+ target = root / _BACKFILL_SCRIPT
898
+ if not target.is_file():
899
+ raise ValueError(f"backfill script missing: {target}")
900
+ import sys as _sys
901
+
902
+ backfill_limit = int(n or 0)
903
+ argv = [_sys.executable, str(target)]
904
+ if backfill_limit > 0:
905
+ argv += ["--limit", str(min(backfill_limit, 100000))]
906
+ if states:
907
+ argv += ["--states", ",".join(states)]
908
+ if cohort == "data_centers":
909
+ argv += ["--cohort", "data_centers"]
910
+ return argv, env
911
+ script = root / _LAUNCH_SCRIPT
912
+ if not script.is_file():
913
+ raise ValueError(f"launch script missing: {script}")
914
+ env["BATCH_STATUS"] = "1"
915
+ env["N"] = str(n)
916
+ env["PARALLEL"] = str(parallel)
917
+ filters = _normalize_full_filters(full_filters)
918
+ if filters:
919
+ env["FULL_FILTERS"] = ",".join(filters)
920
+ analyze_like = {
921
+ "analyze",
922
+ "analyze-light",
923
+ "reports-light",
924
+ "analyze-full",
925
+ "reports-full",
926
+ "each",
927
+ "all",
928
+ }
929
+ if cohort == "data_centers" and step in analyze_like:
930
+ env.setdefault("SKIP_JEV_MEETING_BELOW", "0.6")
931
+ # Run all = Discover → catalog → captions → analyze-light → reports-light (#755).
932
+ # Discover is a separate Python CLI; the shell wrapper never ran it.
933
+ if step == "all":
934
+ disc = _discover_argv(states, cohort)
935
+ disc_cmd = " ".join(shlex.quote(a) for a in disc)
936
+ # --noprofile/--norc: don't load operator rc files; BASH_FUNC_* already stripped (#687).
937
+ pipe_cmd = " ".join(
938
+ shlex.quote(a)
939
+ for a in ["bash", "--noprofile", "--norc", str(script), "all"]
940
+ )
941
+ chain = (
942
+ f'echo "=== Discover (channel candidates) ==="; {disc_cmd}; '
943
+ f'disc_ec=$?; '
944
+ f'if [ "$disc_ec" -eq {_VPN_EXIT_CODE} ]; then '
945
+ f'echo "Discover stopped: VPN required (exit {_VPN_EXIT_CODE})"; exit {_VPN_EXIT_CODE}; '
946
+ f'fi; '
947
+ f'if [ "$disc_ec" -ne 0 ]; then '
948
+ f'echo "WARN: Discover exited $disc_ec — continuing to catalog"; '
949
+ f'fi; '
950
+ f'echo "=== Catalog → captions → analyze-light → reports-light ==="; '
951
+ f'{pipe_cmd}; exit $?'
952
+ )
953
+ return ["bash", "--noprofile", "--norc", "-c", chain], env
954
+ shell_step = _shell_step_for_launch(step)
955
+ return ["bash", "--noprofile", "--norc", str(script), shell_step], env
956
+
957
+
958
+ def _spawn_launch(
959
+ step: str,
960
+ *,
961
+ states: List[str],
962
+ cohort: str,
963
+ n: int,
964
+ parallel: int,
965
+ resume_count: int = 0,
966
+ auto_resume: bool = True,
967
+ full_filters: Optional[List[str]] = None,
968
+ ) -> Dict[str, Any]:
969
+ """Start a detached launch and return its tracking meta (includes exit_path)."""
970
+ import datetime as _dt
971
+ import shlex
972
+
973
+ filters = _normalize_full_filters(full_filters)
974
+ argv, env = _build_launch_argv(
975
+ step,
976
+ states=states,
977
+ cohort=cohort,
978
+ n=n,
979
+ parallel=parallel,
980
+ full_filters=filters,
981
+ )
982
+ root = _repo_root()
983
+ log_dir = root / "data" / "cache" / "batch_jobs"
984
+ log_dir.mkdir(parents=True, exist_ok=True)
985
+ stamp = _dt.datetime.now().strftime("%Y%m%d_%H%M%S")
986
+ log_path = log_dir / f"launch_{step}_{stamp}.log"
987
+ exit_path = log_dir / f"launch_{step}_{stamp}.exit"
988
+ # Record exit code so auto-resume can tell clean finish (0) from VPN (5) / crash.
989
+ inner = " ".join(shlex.quote(a) for a in argv)
990
+ wrapper = (
991
+ f"{inner}; ec=$?; echo \"$ec\" > {shlex.quote(str(exit_path))}; exit \"$ec\""
992
+ )
993
+ logf = open(log_path, "ab")
994
+ proc = subprocess.Popen(
995
+ ["bash", "--noprofile", "--norc", "-c", wrapper],
996
+ cwd=str(root),
997
+ env=env,
998
+ stdout=logf,
999
+ stderr=subprocess.STDOUT,
1000
+ stdin=subprocess.DEVNULL,
1001
+ start_new_session=True,
1002
+ )
1003
+ return {
1004
+ "pid": proc.pid,
1005
+ "step": step,
1006
+ "states": list(states),
1007
+ "cohort": cohort,
1008
+ "n": int(n),
1009
+ "parallel": int(parallel),
1010
+ "full_filters": list(filters),
1011
+ "started_at": _dt.datetime.now(_dt.timezone.utc).isoformat(),
1012
+ "log": str(log_path.relative_to(root)),
1013
+ "exit_path": str(exit_path),
1014
+ "auto_resume": bool(auto_resume),
1015
+ "resume_count": int(resume_count),
1016
+ "stopped": False,
1017
+ "awaiting_vpn": False,
1018
+ }
1019
+
1020
+
1021
+ def _maybe_auto_resume_launches(freshest: str) -> "tuple[List[str], str]":
1022
+ """Re-spawn dead/stalled auto-resume launches. Returns (resumed_steps, note)."""
1023
+ if not _auto_resume_enabled():
1024
+ return [], ""
1025
+ max_resumes = _auto_resume_max()
1026
+ vpn_up = _vpn_tunnel_up_for_resume()
1027
+ resumed: List[str] = []
1028
+ notes: List[str] = []
1029
+ kept: List[Dict[str, Any]] = []
1030
+ live_steps = {
1031
+ str(m.get("step") or "")
1032
+ for m in _read_launches()
1033
+ if _pid_alive(m.get("pid")) and not _launch_stalled(m, freshest)
1034
+ }
1035
+
1036
+ for m in _read_launches():
1037
+ step = str(m.get("step") or "")
1038
+ if m.get("stopped") or m.get("auto_resume") is False:
1039
+ # Drop operator-stopped / capped tombstones once the PID is gone.
1040
+ if _pid_alive(m.get("pid")):
1041
+ kept.append(m)
1042
+ continue
1043
+
1044
+ alive = _pid_alive(m.get("pid"))
1045
+ stalled = alive and _launch_stalled(m, freshest)
1046
+ exit_code = _read_exit_code(m)
1047
+
1048
+ if alive and not stalled:
1049
+ kept.append(m)
1050
+ continue
1051
+
1052
+ if stalled:
1053
+ _kill_launch(m)
1054
+ alive = False
1055
+
1056
+ # Clean successful finish — do not relaunch.
1057
+ if not alive and exit_code == 0:
1058
+ logger.info("launch finished ok step={} pid={} — not resuming", step, m.get("pid"))
1059
+ continue
1060
+
1061
+ count = int(m.get("resume_count") or 0)
1062
+ if count >= max_resumes:
1063
+ notes.append(f"{step}: auto-resume cap ({max_resumes}) reached")
1064
+ kept.append({**m, "pid": None, "auto_resume": False, "awaiting_vpn": False})
1065
+ continue
1066
+
1067
+ needs_vpn = step in _LAUNCH_STEPS_NEED_VPN
1068
+ vpn_exit = exit_code == _VPN_EXIT_CODE
1069
+ log_vpn = bool(_launch_log_signals(step).get("vpn_down"))
1070
+ if needs_vpn and (vpn_exit or log_vpn or m.get("awaiting_vpn")) and not vpn_up:
1071
+ kept.append({**m, "pid": None, "awaiting_vpn": True})
1072
+ notes.append(f"{step}: waiting for VPN before auto-resume")
1073
+ continue
1074
+
1075
+ if step in live_steps or step in resumed:
1076
+ kept.append({**m, "pid": None})
1077
+ continue
1078
+
1079
+ try:
1080
+ new_meta = _spawn_launch(
1081
+ step,
1082
+ states=[str(s) for s in (m.get("states") or []) if str(s).strip()],
1083
+ cohort=str(m.get("cohort") or "priority"),
1084
+ n=int(m.get("n") or 10),
1085
+ parallel=int(m.get("parallel") or 1),
1086
+ resume_count=count + 1,
1087
+ auto_resume=True,
1088
+ full_filters=[
1089
+ str(f) for f in (m.get("full_filters") or []) if str(f).strip()
1090
+ ],
1091
+ )
1092
+ except Exception as exc:
1093
+ logger.warning("auto-resume spawn failed step={}: {!r}", step, exc)
1094
+ kept.append({**m, "pid": None, "awaiting_vpn": bool(needs_vpn and not vpn_up)})
1095
+ notes.append(f"{step}: auto-resume failed ({exc})")
1096
+ continue
1097
+
1098
+ logger.info(
1099
+ "auto-resumed launch step={} resume_count={} pid={}",
1100
+ step,
1101
+ new_meta.get("resume_count"),
1102
+ new_meta.get("pid"),
1103
+ )
1104
+ kept.append(new_meta)
1105
+ resumed.append(step)
1106
+ live_steps.add(step)
1107
+
1108
+ _write_launches(kept)
1109
+ note = "; ".join(notes)
1110
+ if resumed:
1111
+ note = (
1112
+ f"Auto-resumed: {', '.join(resumed)}"
1113
+ + (f". {note}" if note else "")
1114
+ )
1115
+ return resumed, note
1116
+
1117
+
1118
+ @router.get("/launch", response_model=LaunchStatusResponse)
1119
+ async def launch_status() -> LaunchStatusResponse:
1120
+ """Per-step running/stalled state for the dashboard's Run buttons."""
1121
+ running_rows, freshest = await asyncio.to_thread(_dashboard_runtime)
1122
+ resumed_steps, resume_note = await asyncio.to_thread(
1123
+ _maybe_auto_resume_launches, freshest
1124
+ )
1125
+ running, stalled = _classify_launches(freshest)
1126
+ running_steps = sorted({str(m.get("step") or "") for m in running} - {""})
1127
+ stalled_steps = sorted({str(m.get("step") or "") for m in stalled} - {""})
1128
+ signals = _launch_operator_signals(freshest, running, stalled)
1129
+ warning = str(signals.get("warning") or "")
1130
+ if resume_note and "waiting for VPN" in resume_note and not warning:
1131
+ warning = resume_note
1132
+ elif resume_note and resumed_steps:
1133
+ warning = (warning + " · " if warning else "") + resume_note
1134
+ return LaunchStatusResponse(
1135
+ enabled=_launch_enabled(),
1136
+ running=running_rows,
1137
+ running_steps=running_steps,
1138
+ stalled_steps=stalled_steps,
1139
+ busy=running_rows > 0 or bool(running_steps),
1140
+ warning=warning,
1141
+ vpn_down=bool(signals.get("vpn_down")),
1142
+ billing_exhausted=bool(signals.get("billing_exhausted")),
1143
+ inactive_seconds=signals.get("inactive_seconds"),
1144
+ resumed_steps=resumed_steps,
1145
+ auto_resume_note=resume_note,
1146
+ )
1147
+
1148
+
1149
+ @router.post(
1150
+ "/launch",
1151
+ response_model=LaunchResponse,
1152
+ dependencies=[Depends(require_admin)],
1153
+ )
1154
+ async def launch_pipeline(req: LaunchRequest) -> LaunchResponse:
1155
+ """(Re)launch a pipeline step. Refuses if a run is already active."""
1156
+ if not _launch_enabled():
1157
+ raise HTTPException(
1158
+ status_code=403, detail="Job launch disabled (set BATCH_JOBS_ALLOW_LAUNCH=1)."
1159
+ )
1160
+ step = (req.step or "").strip().lower()
1161
+ if step not in _LAUNCH_STEPS:
1162
+ raise HTTPException(status_code=400, detail=f"step must be one of {list(_LAUNCH_STEPS)}")
1163
+ full_filters = _normalize_full_filters(req.full_filters)
1164
+ if step in _FULL_FILTER_STEPS and not full_filters:
1165
+ raise HTTPException(
1166
+ status_code=400,
1167
+ detail=(
1168
+ f"{step} requires a non-empty full_filters list "
1169
+ f"(one of {sorted(_FULL_FILTER_KEYS)})"
1170
+ ),
1171
+ )
1172
+ cohort = (req.cohort or "priority").strip().lower()
1173
+ if cohort not in ("priority", "data_centers", "all"):
1174
+ raise HTTPException(
1175
+ status_code=400,
1176
+ detail="cohort must be one of priority, data_centers, all",
1177
+ )
1178
+ from api.batch_jobs.batch_job_db import get_db_connection
1179
+ from api.batch_jobs.cohorts import resolve_launch_states
1180
+
1181
+ conn = None
1182
+ try:
1183
+ if cohort == "data_centers":
1184
+ conn = get_db_connection()
1185
+ states = resolve_launch_states(cohort, req.states or [], conn=conn)
1186
+ except ValueError as exc:
1187
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
1188
+ finally:
1189
+ if conn is not None:
1190
+ conn.close()
1191
+ bad = [s for s in states if not _STATE_RE.match(s)]
1192
+ if bad:
1193
+ raise HTTPException(status_code=400, detail=f"invalid state code(s): {bad}")
1194
+ if len(states) > 60:
1195
+ raise HTTPException(status_code=400, detail="too many states")
1196
+ n = max(1, min(2000, int(req.n or 10)))
1197
+ parallel = max(1, min(8, int(req.parallel or 1)))
1198
+
1199
+ # Per-step guard: different steps may run concurrently; the same step (or a
1200
+ # full-pipeline run) may not overlap. Reap dead/stalled launches first.
1201
+ _, freshest = await asyncio.to_thread(_dashboard_runtime)
1202
+ kept: List[Dict[str, Any]] = []
1203
+ for m in _read_launches():
1204
+ if not _pid_alive(m.get("pid")):
1205
+ continue
1206
+ if _launch_stalled(m, freshest):
1207
+ _kill_launch(m) # reap the stalled run, free the slot
1208
+ continue
1209
+ kept.append(m)
1210
+ running_steps = {str(m.get("step")) for m in kept}
1211
+ if (
1212
+ step in running_steps
1213
+ or (step in ("all", "each") and running_steps)
1214
+ or (running_steps & {"all", "each"})
1215
+ ):
1216
+ raise HTTPException(
1217
+ status_code=409,
1218
+ detail=f"A conflicting run is already active ({', '.join(sorted(running_steps))}).",
1219
+ )
1220
+
1221
+ # Backfill: UI size picker sends n = 100/500/2000/4000, or 0 for "All".
1222
+ # Discover / wrapper steps still use the clamped n above.
1223
+ launch_n = int(req.n or 0) if step == "backfill" else n
1224
+
1225
+ # Run all = five concurrent stage launches (#763), not one sequential chain.
1226
+ if step == "all":
1227
+ metas: List[Dict[str, Any]] = []
1228
+ try:
1229
+ for stage_step in _RUN_ALL_PARALLEL_STEPS:
1230
+ metas.append(
1231
+ _spawn_launch(
1232
+ stage_step,
1233
+ states=states,
1234
+ cohort=cohort,
1235
+ n=launch_n,
1236
+ parallel=parallel,
1237
+ resume_count=0,
1238
+ auto_resume=True,
1239
+ full_filters=full_filters if stage_step in _FULL_FILTER_STEPS else None,
1240
+ )
1241
+ )
1242
+ except ValueError as exc:
1243
+ for m in metas:
1244
+ _kill_launch(m)
1245
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
1246
+ except Exception as exc:
1247
+ for m in metas:
1248
+ _kill_launch(m)
1249
+ logger.exception("pipeline Run all fan-out failed")
1250
+ raise HTTPException(status_code=500, detail=f"launch failed: {exc}") from exc
1251
+
1252
+ fan_steps = set(_RUN_ALL_PARALLEL_STEPS) | {"all"}
1253
+ others = [
1254
+ m for m in kept if str(m.get("step") or "") not in fan_steps
1255
+ ]
1256
+ try:
1257
+ _write_launches(others + metas)
1258
+ except Exception:
1259
+ pass
1260
+
1261
+ pids = [int(m["pid"]) for m in metas if m.get("pid") is not None]
1262
+ steps_started = [str(m.get("step") or "") for m in metas]
1263
+ logger.info(
1264
+ "launched Run all in parallel steps={} states={} n={} parallel={} pids={}",
1265
+ steps_started,
1266
+ states or "default",
1267
+ launch_n,
1268
+ parallel,
1269
+ pids,
1270
+ )
1271
+ return LaunchResponse(
1272
+ launched=True,
1273
+ pid=pids[0] if pids else None,
1274
+ step="all",
1275
+ states=states,
1276
+ log=str(metas[0].get("log") or "") if metas else "",
1277
+ detail=(
1278
+ f"Started stages 1–5 in parallel ({', '.join(steps_started)}; "
1279
+ f"pids {', '.join(str(p) for p in pids)}). "
1280
+ "Each stage has its own log and auto-resume (Stop all disables it)."
1281
+ ),
1282
+ )
1283
+
1284
+ try:
1285
+ meta = _spawn_launch(
1286
+ step,
1287
+ states=states,
1288
+ cohort=cohort,
1289
+ n=launch_n,
1290
+ parallel=parallel,
1291
+ resume_count=0,
1292
+ auto_resume=True,
1293
+ full_filters=full_filters,
1294
+ )
1295
+ except ValueError as exc:
1296
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
1297
+ except Exception as exc:
1298
+ logger.exception("pipeline launch failed")
1299
+ raise HTTPException(status_code=500, detail=f"launch failed: {exc}") from exc
1300
+
1301
+ try:
1302
+ # Drop prior tombstones for this step so a fresh Run replaces them.
1303
+ others = [
1304
+ m
1305
+ for m in kept
1306
+ if str(m.get("step") or "") != step
1307
+ ]
1308
+ _write_launches(others + [meta])
1309
+ except Exception:
1310
+ pass
1311
+
1312
+ rel_log = str(meta.get("log") or "")
1313
+ logger.info(
1314
+ f"launched pipeline step={step} states={states or 'default'} "
1315
+ f"n={launch_n} parallel={parallel} pid={meta.get('pid')} log={rel_log} "
1316
+ f"auto_resume=1"
1317
+ )
1318
+ return LaunchResponse(
1319
+ launched=True,
1320
+ pid=int(meta["pid"]) if meta.get("pid") is not None else None,
1321
+ step=step,
1322
+ states=states,
1323
+ log=rel_log,
1324
+ detail=(
1325
+ f"Started '{step}' (pid {meta.get('pid')}). "
1326
+ "Auto-resume is on if it dies or stalls (Stop all disables it)."
1327
+ ),
1328
+ )
1329
+
1330
+
1331
+ class StopRequest(BaseModel):
1332
+ # Stop only this step's launch(es); omit/empty to stop every running launch.
1333
+ step: Optional[str] = None
1334
+ # SIGTERM by default (lets the pipeline exit cleanly); force = SIGKILL.
1335
+ force: bool = False
1336
+
1337
+
1338
+ class StopResponse(BaseModel):
1339
+ stopped: int = 0
1340
+ steps: List[str] = Field(default_factory=list)
1341
+ pids: List[int] = Field(default_factory=list)
1342
+ detail: str = ""
1343
+
1344
+
1345
+ @router.post(
1346
+ "/launch/stop",
1347
+ response_model=StopResponse,
1348
+ dependencies=[Depends(require_admin)],
1349
+ )
1350
+ async def stop_pipeline(req: StopRequest) -> StopResponse:
1351
+ """Stop running pipeline launch(es). Signals the detached process group so the
1352
+ whole subtree exits. ``step`` targets one step; omit it to stop everything."""
1353
+ if not _launch_enabled():
1354
+ raise HTTPException(
1355
+ status_code=403, detail="Job control disabled (set BATCH_JOBS_ALLOW_LAUNCH=1)."
1356
+ )
1357
+ step = (req.step or "").strip().lower()
1358
+ if step and step not in _LAUNCH_STEPS:
1359
+ raise HTTPException(status_code=400, detail=f"step must be one of {list(_LAUNCH_STEPS)}")
1360
+ sig = signal.SIGKILL if req.force else signal.SIGTERM
1361
+
1362
+ def _do_stop() -> "tuple[List[str], List[int]]":
1363
+ kept: List[Dict[str, Any]] = []
1364
+ stopped_steps: List[str] = []
1365
+ stopped_pids: List[int] = []
1366
+ for m in _read_launches():
1367
+ alive = _pid_alive(m.get("pid"))
1368
+ m_step = str(m.get("step") or "")
1369
+ if (alive or m.get("awaiting_vpn")) and (not step or m_step == step):
1370
+ if alive:
1371
+ _kill_launch(m, sig=sig)
1372
+ try:
1373
+ stopped_pids.append(int(m["pid"]))
1374
+ except (KeyError, TypeError, ValueError):
1375
+ pass
1376
+ stopped_steps.append(m_step)
1377
+ # Tombstone: auto-resume must not revive an operator Stop (#752).
1378
+ kept.append(
1379
+ {
1380
+ **m,
1381
+ "pid": None,
1382
+ "auto_resume": False,
1383
+ "stopped": True,
1384
+ "awaiting_vpn": False,
1385
+ }
1386
+ )
1387
+ continue
1388
+ if alive or m.get("awaiting_vpn"):
1389
+ kept.append(m) # not targeted → keep tracking
1390
+ # finished (exit 0) / unreaped dead without awaiting_vpn → drop
1391
+ _write_launches(kept)
1392
+ return stopped_steps, stopped_pids
1393
+
1394
+ stopped_steps, stopped_pids = await asyncio.to_thread(_do_stop)
1395
+ steps = sorted(set(s for s in stopped_steps if s))
1396
+
1397
+ # Also clear orphan ``running`` batch rows so Run all re-enables (#742).
1398
+ # Stop may find no live PIDs (launch.json already empty) while
1399
+ # youtube_batch_job_runs still shows status=running.
1400
+ from api.batch_jobs.batch_job_db import cancel_running_batches
1401
+
1402
+ cancelled_rows = await asyncio.to_thread(
1403
+ cancel_running_batches,
1404
+ reason="operator Stop all (#742)",
1405
+ step=step or None,
1406
+ )
1407
+
1408
+ if not stopped_pids and cancelled_rows == 0:
1409
+ scope = f"step '{step}'" if step else "any step"
1410
+ return StopResponse(detail=f"No running launch found for {scope}.")
1411
+ how = "SIGKILL" if req.force else "SIGTERM"
1412
+ logger.info(
1413
+ f"stopped pipeline launches via {how}: steps={steps} pids={stopped_pids} "
1414
+ f"cancelled_rows={cancelled_rows}"
1415
+ )
1416
+ parts: List[str] = []
1417
+ if stopped_pids:
1418
+ parts.append(
1419
+ f"Stopped {len(stopped_pids)} launch(es) ({', '.join(steps) or 'unknown'}). "
1420
+ "Auto-resume disabled for those steps"
1421
+ )
1422
+ if cancelled_rows:
1423
+ parts.append(f"cancelled {cancelled_rows} running batch row(s)")
1424
+ return StopResponse(
1425
+ stopped=len(steps),
1426
+ steps=steps,
1427
+ pids=stopped_pids,
1428
+ detail="; ".join(parts) + ". The dashboard will clear shortly.",
1429
+ )
1430
+
1431
+
1432
+ # Lines worth showing as "current item" in a launch log (most recent wins).
1433
+ _LOG_ITEM_RE = re.compile(
1434
+ r"(=== .*===|\[\d+/\d+\]|Calling gemini|Wrote |Analyz|Discover|Caption|catalog)",
1435
+ re.IGNORECASE,
1436
+ )
1437
+ _LOG_TS_RE = re.compile(r"(\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?)")
1438
+
1439
+
1440
+ def _tail_lines(path: Path, n: int) -> List[str]:
1441
+ try:
1442
+ # Read at most the last ~256 KiB so huge logs stay cheap.
1443
+ size = path.stat().st_size
1444
+ with open(path, "rb") as fh:
1445
+ if size > 262144:
1446
+ fh.seek(-262144, 2)
1447
+ data = fh.read()
1448
+ text = data.decode("utf-8", "replace")
1449
+ return text.splitlines()[-n:]
1450
+ except Exception:
1451
+ return []
1452
+
1453
+
1454
+ def _parse_current(lines: List[str]) -> "tuple[str, str]":
1455
+ """(current item line, ISO timestamp of latest activity) from a log tail."""
1456
+ current = ""
1457
+ for ln in reversed(lines):
1458
+ if ln.strip() and _LOG_ITEM_RE.search(ln):
1459
+ current = ln.strip()
1460
+ break
1461
+ since = ""
1462
+ for ln in reversed(lines):
1463
+ m = _LOG_TS_RE.search(ln)
1464
+ if m:
1465
+ since = m.group(1).replace(" ", "T")
1466
+ break
1467
+ return current[:300], since
1468
+
1469
+
1470
+ class LaunchLogResponse(BaseModel):
1471
+ step: str
1472
+ path: str = ""
1473
+ lines: List[str] = Field(default_factory=list)
1474
+ current: str = ""
1475
+ current_since: str = ""
1476
+ # Operator blocker from the log tail (#699) — e.g. Gemini 402 billing.
1477
+ blocker: Optional[str] = None
1478
+
1479
+
1480
+ @router.get(
1481
+ "/launch/log",
1482
+ response_model=LaunchLogResponse,
1483
+ dependencies=[Depends(require_admin)],
1484
+ )
1485
+ async def launch_log(
1486
+ step: str = Query(..., description="Pipeline step whose latest log to tail"),
1487
+ lines: int = Query(120, ge=1, le=1000),
1488
+ ) -> LaunchLogResponse:
1489
+ step = (step or "").strip().lower()
1490
+ if step not in _LAUNCH_STEPS:
1491
+ raise HTTPException(status_code=400, detail=f"step must be one of {list(_LAUNCH_STEPS)}")
1492
+ log_dir = _repo_root() / "data" / "cache" / "batch_jobs"
1493
+ candidates = sorted(log_dir.glob(f"launch_{step}_*.log"), reverse=True)
1494
+ if not candidates:
1495
+ return LaunchLogResponse(step=step)
1496
+ path = candidates[0]
1497
+ tail = await asyncio.to_thread(_tail_lines, path, lines)
1498
+ current, since = _parse_current(tail)
1499
+ blocker: Optional[str] = None
1500
+ recent = tail[-40:]
1501
+ if any(_BILLING_EXHAUSTED_RE.search(ln or "") for ln in recent):
1502
+ blocker = (
1503
+ "Gemini prepaid credits depleted (402). "
1504
+ "Top up at https://ai.studio/projects — not a free-tier daily wall."
1505
+ )
1506
+ elif any(_VPN_DOWN_RE.search(ln or "") for ln in recent):
1507
+ blocker = "VPN appears down (Surfshark off). Connect Surfshark and re-run."
1508
+ return LaunchLogResponse(
1509
+ step=step,
1510
+ path=str(path.relative_to(_repo_root())),
1511
+ lines=tail,
1512
+ current=current,
1513
+ current_since=since,
1514
+ blocker=blocker,
1515
+ )
1516
+
1517
+
1518
+ class BatchJurisdictionsResponse(BaseModel):
1519
+ batch_id: str
1520
+ state_code: str
1521
+ jurisdictions: List[JurisdictionRunModel] = Field(default_factory=list)
1522
+
1523
+
1524
+ class FailedVideoRowModel(BaseModel):
1525
+ batch_id: str
1526
+ batch_step: str = ""
1527
+ state_code: str = ""
1528
+ jurisdiction_id: str = ""
1529
+ jurisdiction_name: str = ""
1530
+ video: VideoResultModel
1531
+
1532
+
1533
+ class FailedVideosListResponse(BaseModel):
1534
+ rows: List[FailedVideoRowModel] = Field(default_factory=list)
1535
+ total_fail_in_summaries: int = 0
1536
+ truncated: bool = False
1537
+
1538
+
1539
+ class CohortsResponse(BaseModel):
1540
+ priority: List[str]
1541
+ data_centers: List[str]
1542
+ all: List[str]
1543
+
1544
+
1545
+ @router.get("/cohorts", response_model=CohortsResponse)
1546
+ async def list_cohorts() -> CohortsResponse:
1547
+ """State-code lists for priority, data-center, and full-US launch cohorts."""
1548
+ from api.batch_jobs.batch_job_db import get_db_connection
1549
+ from api.batch_jobs.cohorts import cohort_state_codes
1550
+
1551
+ def _load() -> CohortsResponse:
1552
+ conn = get_db_connection()
1553
+ try:
1554
+ return CohortsResponse(
1555
+ priority=cohort_state_codes("priority"),
1556
+ data_centers=cohort_state_codes("data_centers", conn=conn),
1557
+ all=cohort_state_codes("all"),
1558
+ )
1559
+ finally:
1560
+ conn.close()
1561
+
1562
+ try:
1563
+ return await asyncio.to_thread(_load)
1564
+ except Exception as exc:
1565
+ logger.exception("batch-jobs cohorts failed")
1566
+ raise HTTPException(
1567
+ status_code=500,
1568
+ detail=f"Batch jobs cohorts failed: {exc}",
1569
+ ) from exc
1570
+
1571
+
1572
+ @router.get("/failed-videos", response_model=FailedVideosListResponse)
1573
+ async def list_failed_videos(
1574
+ batch_id: Optional[str] = Query(
1575
+ None, description="Limit to one batch; omit for recent batches combined"
1576
+ ),
1577
+ limit: int = Query(500, ge=1, le=2000),
1578
+ batch_limit: int = Query(25, ge=1, le=100),
1579
+ ) -> FailedVideosListResponse:
1580
+ """Per-video failure log extracted from batch payloads (not summary counts only)."""
1581
+ from api.batch_jobs.batch_job_db import list_failed_videos_from_db
1582
+
1583
+ try:
1584
+ payload = await asyncio.to_thread(
1585
+ list_failed_videos_from_db,
1586
+ batch_id=batch_id,
1587
+ limit=limit,
1588
+ batch_limit=batch_limit,
1589
+ )
1590
+ except Exception as exc:
1591
+ logger.exception("list failed videos failed")
1592
+ raise HTTPException(
1593
+ status_code=500,
1594
+ detail=f"Failed videos list failed: {exc}",
1595
+ ) from exc
1596
+ rows = payload.get("rows") or []
1597
+ return FailedVideosListResponse(
1598
+ rows=[FailedVideoRowModel(**r) for r in rows],
1599
+ total_fail_in_summaries=int(payload.get("total_fail_in_summaries") or 0),
1600
+ truncated=bool(payload.get("truncated")),
1601
+ )
1602
+
1603
+
1604
+ class FailureReasonItem(BaseModel):
1605
+ reason: str
1606
+ reason_id: str = ""
1607
+ count: int
1608
+ example: str = ""
1609
+ example_video_id: Optional[str] = None
1610
+
1611
+
1612
+ class FailureReasonGroup(BaseModel):
1613
+ key: str
1614
+ label: str
1615
+ advice: str
1616
+ retryable: bool = False
1617
+ count: int
1618
+ reasons: List[FailureReasonItem] = Field(default_factory=list)
1619
+
1620
+
1621
+ class FailureReasonsResponse(BaseModel):
1622
+ stage: str
1623
+ cohort: str
1624
+ state: str = ""
1625
+ total: int = 0
1626
+ truncated: bool = False
1627
+ groups: List[FailureReasonGroup] = Field(default_factory=list)
1628
+
1629
+
1630
+ class FailureRow(BaseModel):
1631
+ video_id: str
1632
+ title: str = ""
1633
+ jurisdiction_id: str = ""
1634
+ jurisdiction_name: str = ""
1635
+ state_code: str = ""
1636
+ error: str = ""
1637
+
1638
+
1639
+ class FailureRowsResponse(BaseModel):
1640
+ stage: str
1641
+ reason_id: str = ""
1642
+ total: int = 0
1643
+ rows: List[FailureRow] = Field(default_factory=list)
1644
+
1645
+
1646
+ def _failure_stage(stage: str) -> str:
1647
+ from api.batch_jobs.failure_reasons import STAGES
1648
+
1649
+ st = (stage or "").strip().lower()
1650
+ if st not in STAGES:
1651
+ raise HTTPException(
1652
+ status_code=422,
1653
+ detail=f"No failure breakdown for stage {stage!r}; supported: {', '.join(STAGES)}",
1654
+ )
1655
+ return st
1656
+
1657
+
1658
+ @router.get("/failure-reasons", response_model=FailureReasonsResponse)
1659
+ async def list_failure_reasons(
1660
+ stage: str = Query("transcripts", description="videos or transcripts (both count the same rows)"),
1661
+ cohort: Optional[str] = Query(None, description="all | priority | data_centers"),
1662
+ state: Optional[str] = Query(None, description="2-letter state code; omit for the whole cohort"),
1663
+ ) -> FailureReasonsResponse:
1664
+ """Failed videos for a stage, grouped by the reason stored in ``transcript_file_error`` (#792).
1665
+
1666
+ The group counts sum to ``total``, which is the number on the stage row's failed badge for the
1667
+ same cohort and state.
1668
+ """
1669
+ st = _failure_stage(stage)
1670
+ from api.batch_jobs.failure_reasons import failure_reasons
1671
+
1672
+ def _run() -> Dict[str, Any]:
1673
+ from api.batch_jobs.batch_job_db import get_db_connection
1674
+
1675
+ with get_db_connection() as conn:
1676
+ return failure_reasons(conn, stage=st, cohort=cohort, state=state)
1677
+
1678
+ try:
1679
+ payload = await asyncio.to_thread(_run)
1680
+ except Exception as exc:
1681
+ logger.exception("failure reasons failed")
1682
+ raise HTTPException(status_code=500, detail=f"Failure reasons failed: {exc}") from exc
1683
+ return FailureReasonsResponse(**payload)
1684
+
1685
+
1686
+ @router.get("/failures", response_model=FailureRowsResponse)
1687
+ async def list_failures(
1688
+ reason_id: str = Query(
1689
+ ..., pattern=r"^[0-9a-f]{32}$", description="A reason_id, as returned by /failure-reasons"
1690
+ ),
1691
+ stage: str = Query("transcripts"),
1692
+ cohort: Optional[str] = Query(None),
1693
+ state: Optional[str] = Query(None),
1694
+ limit: int = Query(50, ge=1, le=200),
1695
+ offset: int = Query(0, ge=0),
1696
+ ) -> FailureRowsResponse:
1697
+ """The failed videos behind one reason (paged)."""
1698
+ st = _failure_stage(stage)
1699
+ from api.batch_jobs.failure_reasons import failure_rows
1700
+
1701
+ def _run() -> Dict[str, Any]:
1702
+ from api.batch_jobs.batch_job_db import get_db_connection
1703
+
1704
+ with get_db_connection() as conn:
1705
+ return failure_rows(
1706
+ conn, stage=st, cohort=cohort, state=state, reason_id=reason_id, limit=limit, offset=offset
1707
+ )
1708
+
1709
+ try:
1710
+ payload = await asyncio.to_thread(_run)
1711
+ except Exception as exc:
1712
+ logger.exception("failure rows failed")
1713
+ raise HTTPException(status_code=500, detail=f"Failure rows failed: {exc}") from exc
1714
+ return FailureRowsResponse(**payload)
1715
+
1716
+
1717
+ class FailureGridColumn(BaseModel):
1718
+ key: str
1719
+ label: str
1720
+ sortable: bool = False
1721
+
1722
+
1723
+ class FailureGridRow(BaseModel):
1724
+ video_id: str = ""
1725
+ title: str = ""
1726
+ jurisdiction_id: str = ""
1727
+ jurisdiction_name: str = ""
1728
+ state_code: str = ""
1729
+ channel_id: str = ""
1730
+ channel_url: str = ""
1731
+ event_date: str = ""
1732
+ meeting_type: str = ""
1733
+ error: str = ""
1734
+ group: str = ""
1735
+ group_label: str = ""
1736
+ advice: str = ""
1737
+ retryable: bool = False
1738
+ last_updated: str = ""
1739
+ event_id: str = ""
1740
+
1741
+
1742
+ class FailureGridResponse(BaseModel):
1743
+ stage: str
1744
+ cohort: str
1745
+ state: str = ""
1746
+ error_column: str = ""
1747
+ where_to_look: str = ""
1748
+ total: int = 0
1749
+ columns: List[FailureGridColumn] = Field(default_factory=list)
1750
+ rows: List[FailureGridRow] = Field(default_factory=list)
1751
+
1752
+
1753
+ @router.get("/failure-grid", response_model=FailureGridResponse)
1754
+ async def failure_grid_route(
1755
+ stage: str = Query("transcripts", description="videos, transcripts, analyses_light, reports_light, analyses_full or reports_full"),
1756
+ cohort: Optional[str] = Query(None, description="all | priority | data_centers"),
1757
+ state: Optional[str] = Query(None, description="2-letter state code; omit for the whole cohort"),
1758
+ q: Optional[str] = Query(None, max_length=200, description="Text search over title, video id, jurisdiction and error"),
1759
+ group: Optional[str] = Query(None, description="Reason group key, e.g. rate_limit"),
1760
+ sort: str = Query("last_updated", description="video_id, title, state_code, jurisdiction_name, error, last_updated, event_date or meeting_type"),
1761
+ dir: str = Query("desc", pattern="^(asc|desc)$"),
1762
+ limit: int = Query(50, ge=1, le=100),
1763
+ offset: int = Query(0, ge=0),
1764
+ ) -> FailureGridResponse:
1765
+ """Failed items for any stage, sortable and pageable (#800).
1766
+
1767
+ ``total`` equals the failed badge on the stage row for the same cohort and state when no ``q``
1768
+ or ``group`` is set. The sort key comes from a fixed allow-list; no request text reaches SQL.
1769
+ """
1770
+ from api.batch_jobs.failure_reasons import GRID_STAGES, failure_grid
1771
+
1772
+ st = (stage or "").strip().lower()
1773
+ if st not in GRID_STAGES:
1774
+ raise HTTPException(status_code=422, detail=f"Unknown stage {stage!r}; supported: {', '.join(GRID_STAGES)}")
1775
+
1776
+ def _run() -> Dict[str, Any]:
1777
+ from api.batch_jobs.batch_job_db import get_db_connection
1778
+
1779
+ with get_db_connection() as conn:
1780
+ return failure_grid(
1781
+ conn, stage=st, cohort=cohort, state=state, q=q, group=group,
1782
+ sort=sort, direction=dir, limit=limit, offset=offset,
1783
+ )
1784
+
1785
+ try:
1786
+ payload = await asyncio.to_thread(_run)
1787
+ except ValueError as exc:
1788
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
1789
+ except Exception as exc:
1790
+ logger.exception("failure grid failed")
1791
+ raise HTTPException(status_code=500, detail=f"Failure grid failed: {exc}") from exc
1792
+ return FailureGridResponse(**payload)
1793
+
1794
+
1795
+ class RetryFailuresRequest(BaseModel):
1796
+ stage: str = "transcripts"
1797
+ cohort: Optional[str] = None
1798
+ state: Optional[str] = None
1799
+ group: Optional[str] = None
1800
+ reason_id: Optional[str] = Field(None, pattern=r"^[0-9a-f]{32}$")
1801
+ dry_run: bool = False
1802
+
1803
+
1804
+ class RetryFailuresResponse(BaseModel):
1805
+ stage: str
1806
+ group: str = ""
1807
+ reason_id: str = ""
1808
+ dry_run: bool = False
1809
+ matched: int = 0
1810
+ made_due: int = 0
1811
+ already_due: int = 0
1812
+
1813
+
1814
+ @router.post(
1815
+ "/failures/retry",
1816
+ response_model=RetryFailuresResponse,
1817
+ dependencies=[Depends(require_admin)],
1818
+ )
1819
+ async def retry_failures_route(req: RetryFailuresRequest) -> RetryFailuresResponse:
1820
+ """Make the failed videos of one retryable group or reason due for the next caption fetch (#802).
1821
+
1822
+ Deletes nothing. The next Backfill (Transcripts row) fetches them. ``dry_run`` only counts.
1823
+ """
1824
+ st = _failure_stage(req.stage)
1825
+ from api.batch_jobs.failure_reasons import retry_failures
1826
+
1827
+ def _run() -> Dict[str, Any]:
1828
+ from api.batch_jobs.batch_job_db import get_db_connection
1829
+
1830
+ with get_db_connection() as conn:
1831
+ return retry_failures(
1832
+ conn,
1833
+ stage=st,
1834
+ cohort=req.cohort,
1835
+ state=req.state,
1836
+ group=req.group,
1837
+ reason_id=req.reason_id,
1838
+ dry_run=req.dry_run,
1839
+ )
1840
+
1841
+ try:
1842
+ payload = await asyncio.to_thread(_run)
1843
+ except ValueError as exc:
1844
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
1845
+ except Exception as exc:
1846
+ logger.exception("retry failures failed")
1847
+ raise HTTPException(status_code=500, detail=f"Retry failed: {exc}") from exc
1848
+ return RetryFailuresResponse(**payload)
1849
+
1850
+
1851
+ @router.get("/{batch_id}/jurisdictions", response_model=BatchJurisdictionsResponse)
1852
+ async def list_batch_jurisdictions(
1853
+ batch_id: str,
1854
+ state: str = Query(..., min_length=2, max_length=2, description="USPS state code"),
1855
+ ) -> BatchJurisdictionsResponse:
1856
+ """Slim jurisdiction rows for one state (loaded on demand; no per-video arrays)."""
1857
+ from api.batch_jobs.batch_job_dashboard import (
1858
+ build_batch_state_jurisdictions,
1859
+ )
1860
+
1861
+ st = state.strip().upper()
1862
+ try:
1863
+ rows = await asyncio.to_thread(
1864
+ build_batch_state_jurisdictions,
1865
+ batch_id=batch_id,
1866
+ state_code=st,
1867
+ )
1868
+ except Exception as exc:
1869
+ logger.exception("batch jurisdictions failed for %s %s", batch_id, st)
1870
+ raise HTTPException(
1871
+ status_code=500,
1872
+ detail=f"Batch jurisdictions failed: {exc}",
1873
+ ) from exc
1874
+ if not rows:
1875
+ from api.batch_jobs.batch_job_db import load_batch_job_from_db
1876
+
1877
+ if await asyncio.to_thread(load_batch_job_from_db, batch_id) is None:
1878
+ raise HTTPException(status_code=404, detail=f"Batch not found: {batch_id}")
1879
+ payload = _sanitize_dashboard_payload({"batches": [{"jurisdictions": rows}]})
1880
+ jurs = payload.get("batches", [{}])[0].get("jurisdictions") or []
1881
+ return BatchJurisdictionsResponse(
1882
+ batch_id=batch_id,
1883
+ state_code=st,
1884
+ jurisdictions=[JurisdictionRunModel(**j) for j in jurs],
1885
+ )
1886
+
1887
+
1888
+ @router.get("/{batch_id}", response_model=BatchJobModel)
1889
+ async def get_batch_job(
1890
+ batch_id: str,
1891
+ refresh_files: bool = Query(False),
1892
+ enrich_bronze: bool = Query(False),
1893
+ include_videos: str = Query(
1894
+ "all",
1895
+ description="all | failed_only | none — per-video rows for drill-down",
1896
+ ),
1897
+ ) -> BatchJobModel:
1898
+ def _build_job() -> Dict[str, Any]:
1899
+ from api.batch_jobs.batch_job_db import (
1900
+ enrich_jobs_from_bronze,
1901
+ load_batch_job_from_db,
1902
+ )
1903
+ from api.batch_jobs.batch_job_status import (
1904
+ BatchJobStore,
1905
+ _recompute_summary,
1906
+ apply_batch_lifecycle,
1907
+ count_policy_files_for_jurisdiction,
1908
+ expand_batch_job_plan,
1909
+ )
1910
+ from api.batch_jobs.batch_job_dashboard import _POLICY_CACHE
1911
+
1912
+ job = load_batch_job_from_db(batch_id)
1913
+ if job is None:
1914
+ try:
1915
+ job = BatchJobStore(batch_id).load()
1916
+ except FileNotFoundError as exc:
1917
+ raise HTTPException(
1918
+ status_code=404, detail=f"Batch not found: {batch_id}"
1919
+ ) from exc
1920
+
1921
+ apply_batch_lifecycle(job)
1922
+ _recompute_summary(job)
1923
+ if enrich_bronze:
1924
+ enrich_jobs_from_bronze([job])
1925
+ expand_batch_job_plan(job)
1926
+ _recompute_summary(job)
1927
+ elif refresh_files:
1928
+ for j in job.jurisdictions:
1929
+ j.file_counts = count_policy_files_for_jurisdiction(
1930
+ _POLICY_CACHE,
1931
+ state_code=j.state_code,
1932
+ jurisdiction_id=j.jurisdiction_id,
1933
+ )
1934
+ d = job.to_dict()
1935
+ if include_videos in ("none", "failed_only", "running"):
1936
+ from api.batch_jobs.batch_job_dashboard import slim_batch_dict
1937
+
1938
+ mode = include_videos if include_videos != "running" else "running"
1939
+ d = slim_batch_dict(d, video_mode=mode) # type: ignore[arg-type]
1940
+ elif include_videos != "all":
1941
+ raise HTTPException(
1942
+ status_code=400,
1943
+ detail="include_videos must be all, failed_only, none, or running",
1944
+ )
1945
+ return d
1946
+
1947
+ try:
1948
+ d = await asyncio.to_thread(_build_job)
1949
+ except HTTPException:
1950
+ raise
1951
+ except Exception as exc:
1952
+ logger.exception("batch job detail failed for %s", batch_id)
1953
+ raise HTTPException(
1954
+ status_code=500, detail=f"Batch job load failed: {exc}"
1955
+ ) from exc
1956
+ return BatchJobModel(**d)
api/routes/bills_neon.py ADDED
@@ -0,0 +1,861 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Bills API Routes — Postgres-backed (public serving layer).
3
+
4
+ All endpoints read the `bills` / `bill_sponsorship` marts and the
5
+ `rpt_bill_map_aggregate` mart from the public schema (thin views over gold,
6
+ published by the publish_public_serving dbt macro). Parquet/DuckDB reads were
7
+ retired — only bronze ingestion should ever touch parquet.
8
+
9
+ Column mapping (gold.bills mart -> legacy API field names kept for the frontend):
10
+ identifier -> bill_number
11
+ session_identifier -> session
12
+ latest_action_description -> latest_action
13
+ bill_uid -> bill_id
14
+ `first_action_date`, `abstract`, `source_url`, and per-bill `actions` are not
15
+ present in the current marts and surface as null/empty (the frontend renders
16
+ them conditionally).
17
+ """
18
+ from fastapi import APIRouter, Query, HTTPException
19
+ from fastapi.responses import JSONResponse
20
+ from typing import Optional, List, Dict, Any
21
+ import asyncpg
22
+ import json
23
+ from loguru import logger
24
+ import os
25
+ from datetime import datetime, timedelta
26
+
27
+ from api.errors import parse_error
28
+ from api.database import DATA_SEARCH_PATH
29
+
30
+ router = APIRouter(prefix="/bills", tags=["bills"])
31
+
32
+ # Database configuration
33
+ NEON_DATABASE_URL_DEV = os.getenv("NEON_DATABASE_URL_DEV")
34
+ NEON_DATABASE_URL = os.getenv("NEON_DATABASE_URL")
35
+ DATABASE_URL = NEON_DATABASE_URL_DEV or NEON_DATABASE_URL
36
+
37
+ if DATABASE_URL:
38
+ logger.info(f"🗄️ Bills using: {'DEV' if NEON_DATABASE_URL_DEV else 'PROD'} Postgres (public schema)")
39
+ else:
40
+ logger.warning("⚠️ No database URL configured. Bills endpoints will not work.")
41
+
42
+ # Connection pool
43
+ _pool = None
44
+
45
+ # Cache for map data (TTL: 5 minutes)
46
+ _map_cache = {}
47
+ _map_cache_time = None
48
+ MAP_CACHE_DURATION = timedelta(minutes=5)
49
+
50
+
51
+ async def get_pool():
52
+ """Get or create asyncpg connection pool (search_path = data schema, public)."""
53
+ global _pool
54
+ if _pool is None and DATABASE_URL:
55
+ _pool = await asyncpg.create_pool(
56
+ DATABASE_URL,
57
+ min_size=1,
58
+ max_size=10,
59
+ command_timeout=60,
60
+ server_settings={"search_path": DATA_SEARCH_PATH},
61
+ )
62
+ return _pool
63
+
64
+
65
+ def _maybe_json(value: Any) -> Any:
66
+ """Decode a JSONB column that the pool returns as TEXT (no jsonb codec)."""
67
+ if value is None:
68
+ return None
69
+ if isinstance(value, str):
70
+ try:
71
+ return json.loads(value)
72
+ except (ValueError, TypeError):
73
+ return value
74
+ return value
75
+
76
+
77
+ def _classification_list(value: Any) -> List[str]:
78
+ decoded = _maybe_json(value)
79
+ if isinstance(decoded, list):
80
+ return decoded
81
+ if decoded is None:
82
+ return []
83
+ return [decoded]
84
+
85
+
86
+ # Chamber / bill-type prefix predicates operate on the `identifier` column
87
+ # (e.g. "SB 180", "HB 12"). Kept identical to the prior parquet logic.
88
+ _CHAMBER_PREDICATES = {
89
+ "house": "(identifier LIKE 'HB%' OR identifier LIKE 'HR%' OR identifier LIKE 'HJR%' OR identifier LIKE 'HCR%' OR identifier LIKE 'HJM%' OR identifier LIKE 'H %')",
90
+ "senate": "(identifier LIKE 'SB%' OR identifier LIKE 'SR%' OR identifier LIKE 'SJR%' OR identifier LIKE 'SCR%' OR identifier LIKE 'SJM%' OR identifier LIKE 'S %')",
91
+ "joint": "(identifier LIKE '%JR%' OR identifier LIKE '%JM%')",
92
+ }
93
+
94
+ _TYPE_PREDICATES = {
95
+ "bill": "(identifier LIKE 'HB%' OR identifier LIKE 'SB%' OR identifier LIKE 'AB%')",
96
+ "resolution": "(identifier LIKE 'HR%' OR identifier LIKE 'SR%' OR identifier LIKE 'AR%')",
97
+ "joint_resolution": "(identifier LIKE 'HJR%' OR identifier LIKE 'SJR%' OR identifier LIKE 'AJR%')",
98
+ "concurrent_resolution": "(identifier LIKE 'HCR%' OR identifier LIKE 'SCR%')",
99
+ "memorial": "(identifier LIKE 'HJM%' OR identifier LIKE 'SJM%')",
100
+ }
101
+
102
+ _TOPIC_KEYWORDS = {
103
+ 'fluoride': ['fluorid'],
104
+ 'dental': ['dental'],
105
+ 'medicaid': ['medicaid'],
106
+ 'oral health': ['oral', 'dental', 'teeth'],
107
+ 'health': ['health'],
108
+ 'education': ['education', 'school'],
109
+ }
110
+
111
+ _STATUS_KEYWORDS = {
112
+ 'enacted': ['Enacted'],
113
+ 'passed': ['passed', 'Passed'],
114
+ 'adopted': ['Adopted', 'adopted'],
115
+ 'failed': ['Failed', 'failed'],
116
+ 'introduced': ['Introduced', 'introduced'],
117
+ 'referred': ['referred', 'Referred'],
118
+ 'reported': ['reported', 'Reported'],
119
+ }
120
+
121
+
122
+ class _Filters:
123
+ """Accumulates an asyncpg ($1, $2, …) WHERE clause for the bills mart."""
124
+
125
+ def __init__(self, state: str):
126
+ self.clauses = ["state_code = $1"]
127
+ self.params: List[Any] = [state]
128
+
129
+ def _ph(self) -> str:
130
+ return f"${len(self.params) + 1}"
131
+
132
+ def add(
133
+ self,
134
+ q: Optional[str] = None,
135
+ sessions: Optional[List[str]] = None,
136
+ topic: Optional[str] = None,
137
+ chambers: Optional[List[str]] = None,
138
+ bill_types: Optional[List[str]] = None,
139
+ statuses: Optional[List[str]] = None,
140
+ ) -> "_Filters":
141
+ if topic:
142
+ keywords = _TOPIC_KEYWORDS.get(topic.lower(), [topic])
143
+ parts = []
144
+ for kw in keywords:
145
+ parts.append(f"LOWER(title) LIKE LOWER({self._ph()})")
146
+ self.params.append(f"%{kw}%")
147
+ self.clauses.append(f"({' OR '.join(parts)})")
148
+
149
+ if q:
150
+ p1 = self._ph()
151
+ self.params.append(f"%{q}%")
152
+ p2 = self._ph()
153
+ self.params.append(f"%{q}%")
154
+ self.clauses.append(f"(LOWER(title) LIKE LOWER({p1}) OR LOWER(identifier) LIKE LOWER({p2}))")
155
+
156
+ if sessions:
157
+ phs = []
158
+ for s in sessions:
159
+ phs.append(self._ph())
160
+ self.params.append(s)
161
+ self.clauses.append(f"session_identifier IN ({','.join(phs)})")
162
+
163
+ if chambers:
164
+ preds = [_CHAMBER_PREDICATES[c.lower()] for c in chambers if c.lower() in _CHAMBER_PREDICATES]
165
+ if preds:
166
+ self.clauses.append(f"({' OR '.join(preds)})")
167
+
168
+ if bill_types:
169
+ preds = [_TYPE_PREDICATES[b.lower()] for b in bill_types if b.lower() in _TYPE_PREDICATES]
170
+ if preds:
171
+ self.clauses.append(f"({' OR '.join(preds)})")
172
+
173
+ if statuses:
174
+ status_conds = []
175
+ for status in statuses:
176
+ keywords = _STATUS_KEYWORDS.get(status.lower(), [status])
177
+ kw_parts = []
178
+ for kw in keywords:
179
+ kw_parts.append(f"LOWER(latest_action_description) LIKE LOWER({self._ph()})")
180
+ self.params.append(f"%{kw}%")
181
+ status_conds.append(f"({' OR '.join(kw_parts)})")
182
+ if status_conds:
183
+ self.clauses.append(f"({' OR '.join(status_conds)})")
184
+
185
+ return self
186
+
187
+ @property
188
+ def where(self) -> str:
189
+ return " AND ".join(self.clauses)
190
+
191
+
192
+ async def fetch_bills_from_db(
193
+ state: str,
194
+ q: Optional[str] = None,
195
+ sessions: Optional[List[str]] = None,
196
+ topic: Optional[str] = None,
197
+ chambers: Optional[List[str]] = None,
198
+ bill_types: Optional[List[str]] = None,
199
+ statuses: Optional[List[str]] = None,
200
+ limit: int = 50,
201
+ offset: int = 0,
202
+ ) -> Dict[str, Any]:
203
+ """Fetch bills from the Postgres `bills` mart (detailed drill-down)."""
204
+ pool = await get_pool()
205
+ if pool is None:
206
+ raise HTTPException(status_code=503, detail="Database not configured")
207
+
208
+ f = _Filters(state).add(q=q, sessions=sessions, topic=topic,
209
+ chambers=chambers, bill_types=bill_types, statuses=statuses)
210
+
211
+ count_sql = f"SELECT COUNT(*) FROM bills WHERE {f.where}"
212
+
213
+ limit_ph = f"${len(f.params) + 1}"
214
+ offset_ph = f"${len(f.params) + 2}"
215
+ rows_sql = f"""
216
+ SELECT
217
+ b.bill_uid,
218
+ b.identifier,
219
+ b.title,
220
+ b.classification,
221
+ b.session_identifier,
222
+ b.session_name,
223
+ b.latest_action_date,
224
+ b.latest_action_description,
225
+ b.jurisdiction_id,
226
+ j.name AS jurisdiction_name
227
+ FROM bills b
228
+ LEFT JOIN jurisdictions j ON j.jurisdiction_id = b.jurisdiction_id
229
+ WHERE {f.where.replace('state_code', 'b.state_code')}
230
+ ORDER BY b.latest_action_date DESC NULLS LAST, b.identifier DESC
231
+ LIMIT {limit_ph} OFFSET {offset_ph}
232
+ """
233
+
234
+ async with pool.acquire() as conn:
235
+ total = await conn.fetchval(count_sql, *f.params)
236
+ rows = await conn.fetch(rows_sql, *f.params, limit, offset)
237
+
238
+ bills = [
239
+ {
240
+ "bill_id": r["bill_uid"],
241
+ "bill_number": r["identifier"],
242
+ "title": r["title"],
243
+ "classification": _classification_list(r["classification"]),
244
+ "session": r["session_identifier"],
245
+ "session_name": r["session_name"],
246
+ "first_action_date": None,
247
+ "latest_action_date": str(r["latest_action_date"]) if r["latest_action_date"] else None,
248
+ "latest_action": r["latest_action_description"],
249
+ "jurisdiction_name": r["jurisdiction_name"],
250
+ "abstract": None,
251
+ "source_url": None,
252
+ }
253
+ for r in rows
254
+ ]
255
+
256
+ return {
257
+ "state": state,
258
+ "query": q,
259
+ "topic": topic,
260
+ "chambers": chambers,
261
+ "bill_types": bill_types,
262
+ "statuses": statuses,
263
+ "sessions": sessions,
264
+ "bills": bills,
265
+ "total": total,
266
+ "limit": limit,
267
+ "offset": offset,
268
+ "source": "postgres",
269
+ }
270
+
271
+
272
+ async def fetch_sessions_from_db(
273
+ state: str,
274
+ topic: Optional[str] = None,
275
+ chambers: Optional[List[str]] = None,
276
+ bill_types: Optional[List[str]] = None,
277
+ statuses: Optional[List[str]] = None,
278
+ q: Optional[str] = None,
279
+ ) -> Dict[str, Any]:
280
+ """Aggregate sessions from the Postgres `bills` mart, filtered by active filters."""
281
+ pool = await get_pool()
282
+ if pool is None:
283
+ raise HTTPException(status_code=503, detail="Database not configured")
284
+
285
+ f = _Filters(state).add(q=q, topic=topic, chambers=chambers,
286
+ bill_types=bill_types, statuses=statuses)
287
+
288
+ sql = f"""
289
+ SELECT
290
+ session_identifier AS session,
291
+ MAX(session_name) AS session_name,
292
+ MAX(latest_action_date) AS end_date,
293
+ COUNT(*) AS bill_count
294
+ FROM bills
295
+ WHERE {f.where}
296
+ GROUP BY session_identifier
297
+ ORDER BY MAX(latest_action_date) DESC NULLS LAST, session_identifier DESC
298
+ """
299
+
300
+ async with pool.acquire() as conn:
301
+ rows = await conn.fetch(sql, *f.params)
302
+
303
+ sessions = [
304
+ {
305
+ "session": r["session"],
306
+ "session_name": r["session_name"],
307
+ "start_date": None,
308
+ "end_date": str(r["end_date"]) if r["end_date"] else None,
309
+ "bill_count": r["bill_count"],
310
+ }
311
+ for r in rows
312
+ ]
313
+
314
+ return {
315
+ "state": state,
316
+ "sessions": sessions,
317
+ "total_sessions": len(sessions),
318
+ "source": "postgres",
319
+ }
320
+
321
+
322
+ async def fetch_map_data_from_neon(
323
+ topic: Optional[str] = None,
324
+ session: Optional[str] = None
325
+ ) -> Dict[str, Any]:
326
+ """Fetch map aggregates from the rpt_bill_map_aggregate mart."""
327
+ pool = await get_pool()
328
+
329
+ # Use cache if available
330
+ global _map_cache, _map_cache_time
331
+ cache_key = f"{topic or 'all'}_{session or 'all'}"
332
+
333
+ now = datetime.now()
334
+ if _map_cache_time and (now - _map_cache_time) < MAP_CACHE_DURATION:
335
+ if cache_key in _map_cache:
336
+ logger.debug(f"🚀 Map cache hit for {cache_key}")
337
+ return _map_cache[cache_key]
338
+
339
+ async with pool.acquire() as conn:
340
+ requested_topic = topic.lower() if topic else 'all'
341
+
342
+ # The serving table `rpt_bill_map_aggregate` was repurposed by the
343
+ # trending-topics dbt mart — its grain is now (jurisdiction_id, subject) and
344
+ # it no longer carries the legacy policy-map columns
345
+ # (topic / type_* / status_* / primary_*). When that schema is live, the old
346
+ # choropleth query below 500s with `column "topic" does not exist`. Detect the
347
+ # legacy schema first and, when it's gone, return a clean empty map instead of
348
+ # erroring. We deliberately do NOT fabricate type/status counts to fill the
349
+ # gap — restoring policy-map shading needs a dedicated aggregate table.
350
+ has_legacy_schema = await conn.fetchval(
351
+ """
352
+ SELECT EXISTS (
353
+ SELECT 1 FROM information_schema.columns
354
+ WHERE table_name = 'rpt_bill_map_aggregate'
355
+ AND column_name = 'topic'
356
+ )
357
+ """
358
+ )
359
+ if not has_legacy_schema:
360
+ logger.warning(
361
+ "📊 rpt_bill_map_aggregate has no legacy policy-map schema "
362
+ "(topic/type/status columns); returning empty map. The table is now "
363
+ "the trending-topics mart — policy-map shading needs its own aggregate."
364
+ )
365
+ return {
366
+ "topic": requested_topic,
367
+ "session": session,
368
+ "states": {},
369
+ "total_states": 0,
370
+ "legend": {
371
+ "types": {},
372
+ "statuses": {
373
+ "enacted": "Enacted",
374
+ "failed": "Failed",
375
+ "pending": "Pending",
376
+ },
377
+ },
378
+ "message": "Policy-map aggregates are not available on this database.",
379
+ "source": "neon",
380
+ }
381
+
382
+ # For now, we only support topic='all' (no topic filtering yet)
383
+ # Session filtering would require aggregating bills on-the-fly
384
+
385
+ sql = """
386
+ SELECT
387
+ state_code,
388
+ topic,
389
+ total_bills,
390
+ type_bill,
391
+ type_resolution,
392
+ type_concurrent_resolution,
393
+ type_joint_resolution,
394
+ type_constitutional_amendment,
395
+ status_enacted,
396
+ status_failed,
397
+ status_pending,
398
+ primary_type,
399
+ primary_status,
400
+ map_category,
401
+ sample_bills,
402
+ last_updated
403
+ FROM rpt_bill_map_aggregate
404
+ WHERE topic = $1
405
+ """
406
+
407
+ rows = await conn.fetch(sql, requested_topic)
408
+
409
+ # If topic-specific data not found, return empty (don't fallback)
410
+ if not rows:
411
+ logger.warning(f"📊 No pre-computed data for topic '{requested_topic}'")
412
+ return {
413
+ "topic": requested_topic,
414
+ "session": session,
415
+ "states": {},
416
+ "total_states": 0,
417
+ "message": f"No data available for topic '{requested_topic}'. Try 'all' or pre-compute aggregates for this topic.",
418
+ "source": "postgres"
419
+ }
420
+
421
+ state_data = {}
422
+ for row in rows:
423
+ state_code = row['state_code']
424
+
425
+ sample_bills = _maybe_json(row['sample_bills']) or []
426
+
427
+ state_data[state_code] = {
428
+ "state": state_code,
429
+ "total_bills": row['total_bills'],
430
+ "type_counts": {
431
+ "bill": row['type_bill'],
432
+ "resolution": row['type_resolution'],
433
+ "concurrent_resolution": row['type_concurrent_resolution'],
434
+ "joint_resolution": row['type_joint_resolution'],
435
+ "constitutional_amendment": row['type_constitutional_amendment']
436
+ },
437
+ "status_counts": {
438
+ "enacted": row['status_enacted'] or 0,
439
+ "failed": row['status_failed'] or 0,
440
+ "pending": row['status_pending'] or 0
441
+ },
442
+ "primary_type": row['primary_type'],
443
+ "primary_status": row['primary_status'],
444
+ "map_category": row['map_category'],
445
+ "sample_bills": sample_bills,
446
+ "last_updated": row['last_updated'].isoformat() if row['last_updated'] else None
447
+ }
448
+
449
+ # Build dynamic legend based on actual data
450
+ unique_types = set()
451
+ for state in state_data.values():
452
+ if state['primary_type']:
453
+ unique_types.add(state['primary_type'])
454
+
455
+ type_labels = {
456
+ 'mandate': 'Mandate',
457
+ 'removal': 'Removal',
458
+ 'study': 'Study',
459
+ 'funding': 'Funding',
460
+ 'coverage_expansion': 'Coverage Expansion',
461
+ 'screening': 'Screening',
462
+ 'provider_access': 'Provider Access',
463
+ 'expansion': 'Expansion',
464
+ 'coverage': 'Coverage',
465
+ 'reimbursement': 'Reimbursement',
466
+ 'eligibility': 'Eligibility',
467
+ 'requirement': 'Requirement',
468
+ 'curriculum': 'Curriculum',
469
+ 'reform': 'Reform',
470
+ 'protection': 'Protection',
471
+ 'restriction': 'Restriction',
472
+ 'other': 'Other'
473
+ }
474
+
475
+ legend_types = {t: type_labels.get(t, t.replace('_', ' ').title()) for t in unique_types}
476
+
477
+ result = {
478
+ "topic": requested_topic,
479
+ "session": session,
480
+ "states": state_data,
481
+ "total_states": len(state_data),
482
+ "legend": {
483
+ "types": legend_types,
484
+ "statuses": {
485
+ "enacted": "Enacted",
486
+ "failed": "Failed",
487
+ "pending": "Pending"
488
+ }
489
+ },
490
+ "cached": True,
491
+ "source": "postgres"
492
+ }
493
+
494
+ _map_cache[cache_key] = result
495
+ _map_cache_time = now
496
+
497
+ return result
498
+
499
+
500
+ @router.get("")
501
+ async def get_bills(
502
+ state: str = Query(..., description="State abbreviation (e.g., MA, AL)"),
503
+ q: Optional[str] = Query(None, description="Search query (bill number or title)"),
504
+ sessions: Optional[str] = Query(None, description="Comma-separated session IDs"),
505
+ topic: Optional[str] = Query(None, description="Policy topic (e.g., fluoride, dental, medicaid)"),
506
+ chambers: Optional[str] = Query(None, description="Comma-separated chambers (house, senate, joint)"),
507
+ bill_types: Optional[str] = Query(None, description="Comma-separated bill types"),
508
+ statuses: Optional[str] = Query(None, description="Comma-separated bill statuses"),
509
+ limit: int = Query(50, ge=1, le=500),
510
+ offset: int = Query(0, ge=0)
511
+ ):
512
+ """
513
+ Search legislative bills from the Postgres `bills` mart (detailed drill-down).
514
+ Supports multiple values for sessions, chambers, bill_types, and statuses via comma separation.
515
+
516
+ **Examples:**
517
+ - `/api/bills?state=AL&q=dental` - Search Alabama bills for "dental"
518
+ - `/api/bills?state=AL&sessions=2024rs,2023rs` - Get bills from multiple sessions
519
+ - `/api/bills?state=AL&chambers=house,senate` - Get House and Senate bills
520
+ - `/api/bills?state=AL&bill_types=bill,resolution` - Get bills and resolutions
521
+ - `/api/bills?state=AL&statuses=enacted,passed` - Get enacted and passed bills
522
+ """
523
+ try:
524
+ session_list = sessions.split(',') if sessions else None
525
+ chamber_list = chambers.split(',') if chambers else None
526
+ bill_type_list = bill_types.split(',') if bill_types else None
527
+ status_list = statuses.split(',') if statuses else None
528
+
529
+ logger.info(f"📊 Bills request: state={state}, q={q}, sessions={session_list}, topic={topic}, chambers={chamber_list}, bill_types={bill_type_list}, statuses={status_list}")
530
+
531
+ return await fetch_bills_from_db(
532
+ state=state.upper(),
533
+ q=q,
534
+ sessions=session_list,
535
+ topic=topic,
536
+ chambers=chamber_list,
537
+ bill_types=bill_type_list,
538
+ statuses=status_list,
539
+ limit=limit,
540
+ offset=offset
541
+ )
542
+
543
+ except HTTPException:
544
+ raise
545
+ except Exception as e:
546
+ logger.error(f"Bills query error for state={state}: {e}")
547
+ error_detail = parse_error(e, context={"state": state, "query": q})
548
+ return JSONResponse(status_code=500, content=error_detail.model_dump())
549
+
550
+
551
+ @router.get("/sessions")
552
+ async def get_sessions(
553
+ state: str = Query(..., description="State abbreviation (e.g., MA, AL)"),
554
+ topic: Optional[str] = Query(None, description="Topic filter (e.g., fluoride, dental)"),
555
+ chambers: Optional[str] = Query(None, description="Comma-separated chambers (house, senate, joint)"),
556
+ bill_types: Optional[str] = Query(None, description="Comma-separated bill types"),
557
+ statuses: Optional[str] = Query(None, description="Comma-separated statuses"),
558
+ q: Optional[str] = Query(None, description="Search query")
559
+ ):
560
+ """
561
+ Get legislative sessions for a state from the Postgres `bills` mart, filtered
562
+ by active search criteria. Supports multiple values via comma separation.
563
+
564
+ **Examples:**
565
+ - `/api/bills/sessions?state=MA` - Get all Massachusetts sessions
566
+ - `/api/bills/sessions?state=MA&topic=dental` - Get sessions with dental bills
567
+ - `/api/bills/sessions?state=MA&chambers=house,senate` - Filter by House and Senate
568
+ """
569
+ try:
570
+ chamber_list = chambers.split(',') if chambers else None
571
+ bill_type_list = bill_types.split(',') if bill_types else None
572
+ status_list = statuses.split(',') if statuses else None
573
+
574
+ logger.info(f"📊 Sessions request: state={state}, topic={topic}, chambers={chamber_list}, bill_types={bill_type_list}, statuses={status_list}, q={q}")
575
+
576
+ result = await fetch_sessions_from_db(
577
+ state=state.upper(),
578
+ topic=topic,
579
+ chambers=chamber_list,
580
+ bill_types=bill_type_list,
581
+ statuses=status_list,
582
+ q=q
583
+ )
584
+
585
+ logger.info(f"✅ Returning {len(result.get('sessions', []))} sessions for {state}")
586
+ return result
587
+
588
+ except HTTPException:
589
+ raise
590
+ except Exception as e:
591
+ logger.error(f"Sessions query error for state={state}: {e}")
592
+ error_detail = parse_error(e, context={"state": state})
593
+ return JSONResponse(status_code=500, content=error_detail.model_dump())
594
+
595
+
596
+ @router.get("/map")
597
+ async def get_bill_map_data(
598
+ topic: Optional[str] = Query(None, description="Topic to filter (e.g., dental, health, education)"),
599
+ session: Optional[str] = Query(None, description="Legislative session")
600
+ ):
601
+ """
602
+ Get aggregated bill data for choropleth map from the rpt_bill_map_aggregate mart.
603
+
604
+ Returns pre-computed state-level aggregates for instant visualization.
605
+
606
+ **Examples:**
607
+ - `/api/bills/map` - Get national bill map data
608
+ - `/api/bills/map?topic=dental` - Map dental legislation (not yet implemented)
609
+ """
610
+ try:
611
+ if not DATABASE_URL:
612
+ raise HTTPException(status_code=503, detail="Database not configured")
613
+
614
+ return await fetch_map_data_from_neon(topic=topic, session=session)
615
+
616
+ except HTTPException:
617
+ raise
618
+ except Exception as e:
619
+ logger.error(f"Map data query error: {e}")
620
+ error_detail = parse_error(e, context={"topic": topic, "session": session})
621
+ return JSONResponse(status_code=500, content=error_detail.model_dump())
622
+
623
+
624
+ @router.get("/filter-options")
625
+ async def get_filter_options(
626
+ state: str = Query(..., description="State abbreviation (e.g., AL, GA)"),
627
+ topic: Optional[str] = Query(None, description="Topic filter"),
628
+ q: Optional[str] = Query(None, description="Search query")
629
+ ):
630
+ """
631
+ Get available filter options for a state based on actual data in the `bills` mart.
632
+ Returns only bill types, chambers, and statuses that exist for the selected state/topic.
633
+ """
634
+ try:
635
+ pool = await get_pool()
636
+ if pool is None:
637
+ raise HTTPException(status_code=503, detail="Database not configured")
638
+
639
+ f = _Filters(state.upper()).add(q=q, topic=topic)
640
+ where = f.where
641
+
642
+ # CASE expression for bill type, reused in SELECT + HAVING.
643
+ type_case = (
644
+ "CASE "
645
+ "WHEN identifier LIKE 'HB%' OR identifier LIKE 'SB%' OR identifier LIKE 'AB%' THEN 'bill' "
646
+ "WHEN identifier LIKE 'HR%' OR identifier LIKE 'SR%' OR identifier LIKE 'AR%' THEN 'resolution' "
647
+ "WHEN identifier LIKE 'HJR%' OR identifier LIKE 'SJR%' OR identifier LIKE 'AJR%' THEN 'joint_resolution' "
648
+ "WHEN identifier LIKE 'HCR%' OR identifier LIKE 'SCR%' THEN 'concurrent_resolution' "
649
+ "WHEN identifier LIKE 'HJM%' OR identifier LIKE 'SJM%' THEN 'memorial' "
650
+ "END"
651
+ )
652
+ chamber_case = (
653
+ "CASE "
654
+ "WHEN identifier LIKE 'HB%' OR identifier LIKE 'HR%' OR identifier LIKE 'HJR%' OR "
655
+ "identifier LIKE 'HCR%' OR identifier LIKE 'HJM%' OR identifier LIKE 'H %' THEN 'house' "
656
+ "WHEN identifier LIKE 'SB%' OR identifier LIKE 'SR%' OR identifier LIKE 'SJR%' OR "
657
+ "identifier LIKE 'SCR%' OR identifier LIKE 'SJM%' OR identifier LIKE 'S %' THEN 'senate' "
658
+ "WHEN identifier LIKE '%JR%' OR identifier LIKE '%JM%' THEN 'joint' "
659
+ "END"
660
+ )
661
+ status_case = (
662
+ "CASE "
663
+ "WHEN LOWER(latest_action_description) LIKE '%enact%' THEN 'enacted' "
664
+ "WHEN LOWER(latest_action_description) LIKE '%pass%' THEN 'passed' "
665
+ "WHEN LOWER(latest_action_description) LIKE '%adopt%' THEN 'adopted' "
666
+ "WHEN LOWER(latest_action_description) LIKE '%fail%' THEN 'failed' "
667
+ "WHEN LOWER(latest_action_description) LIKE '%introduc%' THEN 'introduced' "
668
+ "WHEN LOWER(latest_action_description) LIKE '%refer%' THEN 'referred' "
669
+ "WHEN LOWER(latest_action_description) LIKE '%report%' THEN 'reported' "
670
+ "END"
671
+ )
672
+
673
+ sql_types = f"""
674
+ SELECT {type_case} AS bill_type, COUNT(*) AS count
675
+ FROM bills WHERE {where}
676
+ GROUP BY bill_type
677
+ HAVING ({type_case}) IS NOT NULL
678
+ ORDER BY count DESC
679
+ """
680
+ sql_chambers = f"""
681
+ SELECT {chamber_case} AS chamber, COUNT(*) AS count
682
+ FROM bills WHERE {where}
683
+ GROUP BY chamber
684
+ HAVING ({chamber_case}) IS NOT NULL
685
+ ORDER BY count DESC
686
+ """
687
+ sql_statuses = f"""
688
+ SELECT {status_case} AS status, COUNT(*) AS count
689
+ FROM bills WHERE {where} AND latest_action_description IS NOT NULL
690
+ GROUP BY status
691
+ HAVING ({status_case}) IS NOT NULL
692
+ ORDER BY count DESC
693
+ """
694
+
695
+ async with pool.acquire() as conn:
696
+ type_rows = await conn.fetch(sql_types, *f.params)
697
+ chamber_rows = await conn.fetch(sql_chambers, *f.params)
698
+ status_rows = await conn.fetch(sql_statuses, *f.params)
699
+
700
+ type_labels = {
701
+ 'bill': 'Bill (HB/SB)',
702
+ 'resolution': 'Resolution (HR/SR)',
703
+ 'joint_resolution': 'Joint Resolution (HJR/SJR)',
704
+ 'concurrent_resolution': 'Concurrent Resolution (HCR/SCR)',
705
+ 'memorial': 'Memorial (HJM/SJM)'
706
+ }
707
+ chamber_labels = {'house': 'House', 'senate': 'Senate', 'joint': 'Joint'}
708
+ status_labels = {
709
+ 'enacted': 'Enacted',
710
+ 'passed': 'Passed',
711
+ 'adopted': 'Adopted',
712
+ 'failed': 'Failed',
713
+ 'introduced': 'Introduced',
714
+ 'referred': 'Referred to Committee',
715
+ 'reported': 'Reported from Committee'
716
+ }
717
+
718
+ return {
719
+ "state": state,
720
+ "topic": topic,
721
+ "bill_types": [
722
+ {"value": r["bill_type"], "label": type_labels.get(r["bill_type"], r["bill_type"]), "count": r["count"]}
723
+ for r in type_rows
724
+ ],
725
+ "chambers": [
726
+ {"value": r["chamber"], "label": chamber_labels.get(r["chamber"], r["chamber"]), "count": r["count"]}
727
+ for r in chamber_rows
728
+ ],
729
+ "statuses": [
730
+ {"value": r["status"], "label": status_labels.get(r["status"], r["status"]), "count": r["count"]}
731
+ for r in status_rows
732
+ ]
733
+ }
734
+
735
+ except HTTPException:
736
+ raise
737
+ except Exception as e:
738
+ logger.error(f"Filter options query error for state={state}: {e}")
739
+ error_detail = parse_error(e, context={"state": state, "topic": topic, "q": q})
740
+ return JSONResponse(status_code=500, content=error_detail.model_dump())
741
+
742
+
743
+ @router.get("/versions")
744
+ async def get_bill_versions(
745
+ bill_id: str = Query(..., description="Bill ID (e.g., ocd-bill/...)")
746
+ ):
747
+ """
748
+ Get all text versions for a specific bill.
749
+
750
+ Bill text versions are not part of the current Postgres marts, so this returns
751
+ an explicit empty result rather than fabricating data.
752
+ """
753
+ return {
754
+ "bill_id": bill_id,
755
+ "total": 0,
756
+ "versions": [],
757
+ "message": "Bill versions data not available"
758
+ }
759
+
760
+
761
+ @router.get("/{bill_id}")
762
+ async def get_bill_details(bill_id: str):
763
+ """
764
+ Get detailed information about a specific bill from the Postgres `bills` mart.
765
+
766
+ Args:
767
+ bill_id: Bill identifier in format {state}-{bill_number} (e.g., "mo-SB 1548")
768
+
769
+ Returns:
770
+ Detailed bill information including sponsors.
771
+
772
+ Examples:
773
+ - `/api/bills/ga-HB 123` - Georgia House Bill 123
774
+ - `/api/bills/mo-SB 1548` - Missouri Senate Bill 1548
775
+ """
776
+ try:
777
+ if '-' not in bill_id:
778
+ raise HTTPException(status_code=400, detail="Invalid bill ID format. Expected: STATE-BILLNUMBER")
779
+
780
+ parts = bill_id.split('-', 1)
781
+ state = parts[0].upper()
782
+ bill_number = parts[1]
783
+
784
+ pool = await get_pool()
785
+ if pool is None:
786
+ raise HTTPException(status_code=503, detail="Database not configured")
787
+
788
+ bill_sql = """
789
+ SELECT
790
+ b.bill_uid,
791
+ b.identifier,
792
+ b.title,
793
+ b.classification,
794
+ b.latest_action_description,
795
+ b.latest_action_date,
796
+ b.session_identifier,
797
+ b.session_name,
798
+ b.jurisdiction_id,
799
+ j.name AS jurisdiction_name
800
+ FROM bills b
801
+ LEFT JOIN jurisdictions j ON j.jurisdiction_id = b.jurisdiction_id
802
+ WHERE b.state_code = $1 AND b.identifier = $2
803
+ ORDER BY b.latest_action_date DESC NULLS LAST
804
+ LIMIT 1
805
+ """
806
+
807
+ async with pool.acquire() as conn:
808
+ row = await conn.fetchrow(bill_sql, state, bill_number)
809
+
810
+ if not row:
811
+ raise HTTPException(
812
+ status_code=404,
813
+ detail=f"Bill {bill_number} not found in {state}."
814
+ )
815
+
816
+ bill_uid = row["bill_uid"]
817
+ bill_data = {
818
+ "bill_id": bill_uid or bill_id,
819
+ "bill_number": row["identifier"],
820
+ "title": row["title"],
821
+ "classification": _classification_list(row["classification"]),
822
+ "latest_action": row["latest_action_description"],
823
+ "latest_action_date": str(row["latest_action_date"]) if row["latest_action_date"] else None,
824
+ "first_action_date": None,
825
+ "session": row["session_identifier"],
826
+ "session_name": row["session_name"],
827
+ "jurisdiction": row["jurisdiction_name"],
828
+ "state": state,
829
+ }
830
+
831
+ sponsor_rows = await conn.fetch(
832
+ """
833
+ SELECT sponsor_name, is_primary, classification
834
+ FROM bill_sponsorship
835
+ WHERE bill_uid = $1
836
+ ORDER BY is_primary DESC NULLS LAST
837
+ """,
838
+ bill_uid,
839
+ )
840
+ bill_data["sponsors"] = [
841
+ {
842
+ "name": s["sponsor_name"],
843
+ "primary": bool(s["is_primary"]),
844
+ "classification": s["classification"],
845
+ }
846
+ for s in sponsor_rows
847
+ ]
848
+
849
+ # Per-bill action history is not in the current marts.
850
+ bill_data["actions"] = []
851
+ bill_data["sources"] = []
852
+
853
+ return bill_data
854
+
855
+ except HTTPException:
856
+ raise
857
+ except Exception as e:
858
+ logger.error(f"Bill details error: {e}")
859
+ import traceback
860
+ logger.error(traceback.format_exc())
861
+ raise HTTPException(status_code=500, detail=str(e))
api/routes/browse.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Homepage "Browse" card directory API.
3
+
4
+ Serves the four browse categories (place / topic / question / cause) for the
5
+ homepage Browse cards, plus a per-category top-items list, both backed by two
6
+ published serving views over gold:
7
+
8
+ - public.browse_directory_summary — one national row (state_code IS NULL) per
9
+ entity_type plus per-state rows for place/topic. Used by GET /summary.
10
+ - public.browse_transcript_count — item grain (PK entity_type, entity_id) with a
11
+ genuine distinct-transcript count per entity. Used by GET /top-items.
12
+
13
+ Both resolve as bare table names via the connection search_path (matching the
14
+ other routes — see topics.py / search_postgres.py). The columns are plain
15
+ text/int, so the pool's missing JSONB codec is irrelevant here.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ from typing import Dict, List, Optional
20
+
21
+ from fastapi import APIRouter, Query
22
+ from loguru import logger
23
+ from opentelemetry import trace
24
+ from pydantic import BaseModel
25
+
26
+ from api.routes.search_postgres import get_db_pool
27
+
28
+ router = APIRouter(prefix="/api/browse", tags=["browse"])
29
+ tracer = trace.get_tracer(__name__)
30
+
31
+ # The four browse entity types and their card labels (plural noun). Order here is
32
+ # the canonical fallback order; the served list is re-sorted by transcript_count
33
+ # but `cause` is always forced last (it is genuinely 0 transcripts).
34
+ _LABELS: Dict[str, str] = {
35
+ "place": "places",
36
+ "topic": "topics",
37
+ "question": "questions",
38
+ "cause": "causes",
39
+ }
40
+
41
+
42
+ class BrowseCategory(BaseModel):
43
+ entity_type: str
44
+ label: str
45
+ transcript_count: int
46
+ entity_count: int
47
+ has_transcripts: bool
48
+
49
+
50
+ class BrowseSummary(BaseModel):
51
+ categories: List[BrowseCategory]
52
+
53
+
54
+ class BrowseTopItem(BaseModel):
55
+ entity_id: str
56
+ entity_name: str
57
+ transcript_count: int
58
+ # Nullable: question/cause items have no state_code; place/topic carry one.
59
+ state_code: Optional[str] = None
60
+
61
+
62
+ class BrowseTopItems(BaseModel):
63
+ items: List[BrowseTopItem]
64
+
65
+
66
+ class PlaceMapPin(BaseModel):
67
+ """A single map pin for an indexed place (or a state/county rollup of them)."""
68
+ geoid: str
69
+ name: str
70
+ state_code: Optional[str] = None
71
+ latitude: float
72
+ longitude: float
73
+ # Distinct indexed places represented by this pin (1 for an individual
74
+ # place; the rollup count for a state pin).
75
+ place_count: int
76
+ transcript_count: int
77
+
78
+
79
+ class PlaceMapLevel(BaseModel):
80
+ level: str # state | county | city | school_district
81
+ label: str # display label for the filter toggle
82
+ count: int # number of pins at this level
83
+ pins: List[PlaceMapPin]
84
+
85
+
86
+ class PlaceMapResponse(BaseModel):
87
+ levels: List[PlaceMapLevel]
88
+
89
+
90
+ # One round-trip: pull the national row (state_code IS NULL) and, when a state is
91
+ # given, the matching per-state row for each entity_type. We pick the per-state
92
+ # row in Python (preferring it over the national fallback). $1 is the upper-cased
93
+ # state code or NULL.
94
+ _SUMMARY_SQL = """
95
+ SELECT entity_type, state_code, transcript_count, entity_count
96
+ FROM browse_directory_summary
97
+ WHERE state_code IS NULL OR state_code = $1::text
98
+ """
99
+
100
+ # Top items in a category by transcript count, NATIONAL (no place filter).
101
+ # browse_transcript_count is the national rollup (one row per entity, with a
102
+ # representative state_code), so this is correct only when no state is selected.
103
+ _TOP_ITEMS_SQL = """
104
+ SELECT entity_id, entity_name, transcript_count, state_code
105
+ FROM browse_transcript_count
106
+ WHERE entity_type = $1::text
107
+ ORDER BY transcript_count DESC NULLS LAST, entity_name ASC
108
+ LIMIT $2::int
109
+ """
110
+
111
+ # Top items SCOPED TO A STATE (place/topic). Reads the per-state grain mart so a
112
+ # topic that spans many states is ranked by its count IN THIS state — the
113
+ # national rollup above only carries a representative state and would drop most
114
+ # topics under a state filter.
115
+ _TOP_ITEMS_STATE_SQL = """
116
+ SELECT entity_id, entity_name, transcript_count, state_code
117
+ FROM browse_entity_state_transcript_count
118
+ WHERE entity_type = $1::text
119
+ AND state_code = $2::text
120
+ ORDER BY transcript_count DESC NULLS LAST, entity_name ASC
121
+ LIMIT $3::int
122
+ """
123
+
124
+ # Questions are special: they surface from the curated/pinned registry, NOT by
125
+ # transcript count. The homepage "Browse questions" dropdown (and any other
126
+ # top-items question consumer) shows ONLY the featured policy questions, in
127
+ # editorial order (display_order), matching the /policy-questions page. Real
128
+ # distinct-transcript counts are LEFT-joined so a pinned question with no linked
129
+ # transcripts honestly shows 0 rather than being dropped.
130
+ _TOP_QUESTIONS_FEATURED_SQL = """
131
+ SELECT q.question_id AS entity_id,
132
+ q.canonical_text AS entity_name,
133
+ COALESCE(b.transcript_count, 0) AS transcript_count,
134
+ NULL::text AS state_code
135
+ FROM public.policy_question q
136
+ LEFT JOIN browse_transcript_count b
137
+ ON b.entity_type = 'question'
138
+ AND b.entity_id = q.question_id
139
+ WHERE q.is_featured = true
140
+ ORDER BY q.display_order ASC NULLS LAST, q.instances_total DESC NULLS LAST
141
+ LIMIT $1::int
142
+ """
143
+
144
+
145
+ # --- Place map (clustered pins of the places we index) ------------------------
146
+ #
147
+ # The honest "places we index" universe is browse_transcript_count where
148
+ # entity_type='place' (one row per indexed place geoid, with its real distinct
149
+ # transcript_count). We join each place to its census centroid in `jurisdictions`
150
+ # for lat/lon + jurisdiction_type. geoid is NOT unique in `jurisdictions`
151
+ # (city/school_district collisions), so DISTINCT ON (geoid) with a type-priority
152
+ # tiebreaker emits exactly one centroid per place.
153
+ #
154
+ # Individual-place levels (city / county / school_district) are bucketed in
155
+ # Python from this one query by jurisdiction_type. The STATE level is a genuine
156
+ # rollup: one pin per state that has any indexed place, at the real state
157
+ # centroid, sized by the count of distinct indexed places in that state.
158
+ _PLACE_MAP_PLACES_SQL = """
159
+ SELECT DISTINCT ON (b.entity_id)
160
+ b.entity_id AS geoid,
161
+ b.entity_name AS name,
162
+ b.state_code AS state_code,
163
+ j.jurisdiction_type AS jurisdiction_type,
164
+ j.latitude::float8 AS latitude,
165
+ j.longitude::float8 AS longitude,
166
+ b.transcript_count AS transcript_count
167
+ FROM browse_transcript_count b
168
+ JOIN jurisdictions j
169
+ ON j.geoid = b.entity_id
170
+ AND j.latitude IS NOT NULL
171
+ AND j.longitude IS NOT NULL
172
+ WHERE b.entity_type = 'place'
173
+ ORDER BY b.entity_id,
174
+ CASE j.jurisdiction_type
175
+ WHEN 'city' THEN 0 WHEN 'town' THEN 1
176
+ WHEN 'county' THEN 2 WHEN 'school_district' THEN 3 ELSE 4
177
+ END
178
+ """
179
+
180
+ _PLACE_MAP_STATE_SQL = """
181
+ WITH place AS (
182
+ SELECT DISTINCT ON (b.entity_id)
183
+ b.entity_id AS geoid, b.state_code, b.transcript_count
184
+ FROM browse_transcript_count b
185
+ WHERE b.entity_type = 'place' AND b.state_code IS NOT NULL
186
+ )
187
+ SELECT
188
+ s.geoid AS geoid,
189
+ s.name AS name,
190
+ s.state_code AS state_code,
191
+ s.latitude::float8 AS latitude,
192
+ s.longitude::float8 AS longitude,
193
+ count(DISTINCT p.geoid)::int AS place_count,
194
+ sum(p.transcript_count)::int AS transcript_count
195
+ FROM place p
196
+ JOIN jurisdictions s
197
+ ON s.jurisdiction_type = 'state'
198
+ AND s.state_code = p.state_code
199
+ AND s.latitude IS NOT NULL
200
+ AND s.longitude IS NOT NULL
201
+ GROUP BY s.geoid, s.name, s.state_code, s.latitude, s.longitude
202
+ ORDER BY place_count DESC
203
+ """
204
+
205
+ # jurisdiction_type -> (level key, plural label). town folds into the city level
206
+ # (both are sub-county localities); state is built from its own rollup query.
207
+ _PLACE_LEVEL_LABELS: Dict[str, str] = {
208
+ "state": "States",
209
+ "county": "Counties",
210
+ "city": "Cities & towns",
211
+ "school_district": "School districts",
212
+ }
213
+ _TYPE_TO_LEVEL: Dict[str, str] = {
214
+ "city": "city",
215
+ "town": "city",
216
+ "county": "county",
217
+ "school_district": "school_district",
218
+ }
219
+
220
+
221
+ def _normalize_state(state: Optional[str]) -> Optional[str]:
222
+ """Upper-case a 2-letter state code, or None when blank/absent."""
223
+ if state is None:
224
+ return None
225
+ s = state.strip().upper()
226
+ return s or None
227
+
228
+
229
+ @router.get("/summary", response_model=BrowseSummary)
230
+ async def browse_summary(
231
+ state: Optional[str] = Query(
232
+ None, description="Optional 2-letter state code. Scopes place/topic to that state; question/cause stay national."
233
+ ),
234
+ ) -> BrowseSummary:
235
+ """The four homepage Browse cards, sorted by transcript_count desc (cause last)."""
236
+ with tracer.start_as_current_span("browse-summary") as span:
237
+ state_code = _normalize_state(state)
238
+ span.set_attribute("browse.state", state_code or "")
239
+ try:
240
+ pool = await get_db_pool()
241
+ async with pool.acquire() as conn:
242
+ with tracer.start_as_current_span("browse-summary-query"):
243
+ rows = await conn.fetch(_SUMMARY_SQL, state_code)
244
+ except Exception as exc: # noqa: BLE001
245
+ logger.exception("browse summary failed")
246
+ span.record_exception(exc)
247
+ # Empty list over a 500 — the homepage renders an empty Browse state.
248
+ return BrowseSummary(categories=[])
249
+
250
+ # For each entity_type prefer the per-state row over the national one.
251
+ chosen: Dict[str, dict] = {}
252
+ for r in rows:
253
+ et = r["entity_type"]
254
+ is_state_row = r["state_code"] is not None
255
+ existing = chosen.get(et)
256
+ if existing is None or (is_state_row and existing["state_code"] is None):
257
+ chosen[et] = dict(r)
258
+
259
+ categories = [
260
+ BrowseCategory(
261
+ entity_type=et,
262
+ label=_LABELS.get(et, f"{et}s"),
263
+ transcript_count=row["transcript_count"] or 0,
264
+ entity_count=row["entity_count"] or 0,
265
+ has_transcripts=(row["transcript_count"] or 0) > 0,
266
+ )
267
+ for et, row in chosen.items()
268
+ ]
269
+
270
+ # Sort by transcript_count desc, but always pin `place` to the very end so
271
+ # the "Browse places" card sits at the far right of the homepage row (a
272
+ # product choice — places dwarfs the others on transcript count, but we
273
+ # want it last). `cause` (genuinely 0 transcripts) then naturally falls
274
+ # just before place via the descending count.
275
+ categories.sort(
276
+ key=lambda c: (c.entity_type == "place", -c.transcript_count)
277
+ )
278
+
279
+ span.set_attribute("browse.categories", len(categories))
280
+ return BrowseSummary(categories=categories)
281
+
282
+
283
+ @router.get("/top-items", response_model=BrowseTopItems)
284
+ async def browse_top_items(
285
+ entity_type: str = Query(..., description="One of: place, topic, question, cause."),
286
+ state: Optional[str] = Query(
287
+ None, description="Optional 2-letter state code (applies to place/topic; ignored for question/cause)."
288
+ ),
289
+ limit: int = Query(8, ge=1, le=50, description="Max items (default 8, cap 50)."),
290
+ ) -> BrowseTopItems:
291
+ """Top items in a browse category, ranked by transcript_count desc."""
292
+ with tracer.start_as_current_span("browse-top-items") as span:
293
+ et = (entity_type or "").strip().lower()
294
+ span.set_attribute("browse.entity_type", et)
295
+ if et not in _LABELS:
296
+ # Unknown entity_type — empty list rather than a 4xx, matching the
297
+ # forgiving posture of the other browse/topic routes.
298
+ span.set_attribute("browse.unknown_entity_type", True)
299
+ return BrowseTopItems(items=[])
300
+
301
+ state_code = _normalize_state(state)
302
+ # question/cause have no per-state rows; never filter them by state.
303
+ if et in ("question", "cause"):
304
+ state_code = None
305
+ span.set_attribute("browse.state", state_code or "")
306
+
307
+ try:
308
+ pool = await get_db_pool()
309
+ async with pool.acquire() as conn:
310
+ with tracer.start_as_current_span("browse-top-items-query"):
311
+ if et == "question":
312
+ # Pinned/featured registry questions only, editorial order.
313
+ rows = await conn.fetch(_TOP_QUESTIONS_FEATURED_SQL, limit)
314
+ elif state_code:
315
+ # Place/topic scoped to the selected state — per-state mart.
316
+ rows = await conn.fetch(_TOP_ITEMS_STATE_SQL, et, state_code, limit)
317
+ else:
318
+ # National (no place filter) — representative-state rollup.
319
+ rows = await conn.fetch(_TOP_ITEMS_SQL, et, limit)
320
+ except Exception as exc: # noqa: BLE001
321
+ logger.exception("browse top-items failed")
322
+ span.record_exception(exc)
323
+ return BrowseTopItems(items=[])
324
+
325
+ span.set_attribute("browse.items", len(rows))
326
+ return BrowseTopItems(
327
+ items=[
328
+ BrowseTopItem(
329
+ entity_id=r["entity_id"],
330
+ entity_name=r["entity_name"],
331
+ transcript_count=r["transcript_count"] or 0,
332
+ state_code=r["state_code"],
333
+ )
334
+ for r in rows
335
+ ]
336
+ )
337
+
338
+
339
+ @router.get("/place-map", response_model=PlaceMapResponse)
340
+ async def browse_place_map() -> PlaceMapResponse:
341
+ """Clustered map pins for every place we index, grouped into filterable levels.
342
+
343
+ Returns four levels — state (a per-state rollup), county, city (cities +
344
+ towns) and school_district — each an independently toggleable layer of pins
345
+ plotted at real census centroids. Every pin is a place with >=1 transcript;
346
+ no fabricated coordinates or counts.
347
+ """
348
+ with tracer.start_as_current_span("browse-place-map") as span:
349
+ try:
350
+ pool = await get_db_pool()
351
+ async with pool.acquire() as conn:
352
+ with tracer.start_as_current_span("browse-place-map-query"):
353
+ place_rows = await conn.fetch(_PLACE_MAP_PLACES_SQL)
354
+ state_rows = await conn.fetch(_PLACE_MAP_STATE_SQL)
355
+ except Exception as exc: # noqa: BLE001
356
+ logger.exception("browse place-map failed")
357
+ span.record_exception(exc)
358
+ # Empty levels over a 500 — the map renders an empty state.
359
+ return PlaceMapResponse(levels=[])
360
+
361
+ # Bucket the individual indexed places by jurisdiction_type into levels.
362
+ buckets: Dict[str, List[PlaceMapPin]] = {
363
+ "city": [], "county": [], "school_district": [],
364
+ }
365
+ for r in place_rows:
366
+ level = _TYPE_TO_LEVEL.get(r["jurisdiction_type"])
367
+ if level is None:
368
+ continue # an indexed place of an unmapped type — skip, don't guess
369
+ buckets[level].append(
370
+ PlaceMapPin(
371
+ geoid=r["geoid"],
372
+ name=r["name"],
373
+ state_code=r["state_code"],
374
+ latitude=r["latitude"],
375
+ longitude=r["longitude"],
376
+ place_count=1,
377
+ transcript_count=r["transcript_count"] or 0,
378
+ )
379
+ )
380
+
381
+ state_pins = [
382
+ PlaceMapPin(
383
+ geoid=r["geoid"],
384
+ name=r["name"],
385
+ state_code=r["state_code"],
386
+ latitude=r["latitude"],
387
+ longitude=r["longitude"],
388
+ place_count=r["place_count"] or 0,
389
+ transcript_count=r["transcript_count"] or 0,
390
+ )
391
+ for r in state_rows
392
+ ]
393
+
394
+ # Stable level order: state, county, city, school_district.
395
+ ordered = [("state", state_pins)] + [
396
+ (lvl, buckets[lvl]) for lvl in ("county", "city", "school_district")
397
+ ]
398
+ levels = [
399
+ PlaceMapLevel(
400
+ level=lvl,
401
+ label=_PLACE_LEVEL_LABELS[lvl],
402
+ count=len(pins),
403
+ pins=pins,
404
+ )
405
+ for lvl, pins in ordered
406
+ ]
407
+
408
+ span.set_attribute(
409
+ "browse.place_map_pins", sum(len(p) for _, p in ordered)
410
+ )
411
+ return PlaceMapResponse(levels=levels)
api/routes/chat_meetings.py ADDED
@@ -0,0 +1,847 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Public meeting Q&A chat (#630).
3
+
4
+ Normal path: analyzed-meeting search (top 5 summaries) → one model call.
5
+ Detail path: one video's Neon segments → topic passages → one model call.
6
+ The model is Claude Haiku by default (#848); CHAT_PROVIDER=gemini keeps the Flash-Lite path.
7
+ No agent framework; no transcript dump into the prompt.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import os
14
+ import re
15
+ import time
16
+ from dataclasses import dataclass
17
+ from datetime import date, datetime, timezone
18
+ from typing import Any, Dict, List, Optional, Tuple
19
+
20
+ from fastapi import APIRouter, HTTPException, Request, status
21
+ from loguru import logger
22
+ from opentelemetry import trace
23
+ from pydantic import BaseModel, Field
24
+ from starlette.concurrency import run_in_threadpool
25
+
26
+ from api.routes.meetings import TranscriptCue, _coerce_segments
27
+ from api.routes.search_postgres import (
28
+ get_db_pool,
29
+ normalize_state_input,
30
+ resolve_county_city_names,
31
+ )
32
+
33
+ router = APIRouter(prefix="/chat", tags=["chat"])
34
+ tracer = trace.get_tracer(__name__)
35
+
36
+ # Per signed-in user (#1049): the chat requires sign-in, and each user is one bucket across devices.
37
+ _RATE_PER_HOUR = int(os.environ.get("CHAT_RATE_PER_HOUR", "60"))
38
+ _USER_PER_DAY = int(os.environ.get("CHAT_USER_PER_DAY", "200"))
39
+ _BURST_PER_5MIN = int(os.environ.get("CHAT_BURST_PER_5MIN", "20"))
40
+ _MIN_INTERVAL_SECONDS = float(os.environ.get("CHAT_MIN_INTERVAL_SECONDS", "2"))
41
+ _DAILY_SPEND_CAP_USD = float(os.environ.get("CHAT_DAILY_SPEND_CAP_USD", "1.0"))
42
+ _PASSAGE_CHAR_CAP = int(os.environ.get("CHAT_PASSAGE_CHAR_CAP", "12000"))
43
+ _MAX_TRACKED_VISITORS = 2048
44
+
45
+ _HOUR = 3600.0
46
+ _FIVE_MIN = 300.0
47
+
48
+ _visitor_timestamps: Dict[str, List[float]] = {}
49
+ _visitor_last: Dict[str, float] = {}
50
+ _visitor_daily: Dict[str, Dict[str, int]] = {} # utc day -> visitor -> messages
51
+ _spend_by_utc_day: Dict[str, float] = {}
52
+
53
+
54
+ def clear_chat_rate_limits() -> None:
55
+ """Test helper: reset in-memory rate / spend state."""
56
+ _visitor_timestamps.clear()
57
+ _visitor_last.clear()
58
+ _visitor_daily.clear()
59
+ _spend_by_utc_day.clear()
60
+
61
+
62
+ class ChatMeetingsRequest(BaseModel):
63
+ question: str = Field(..., min_length=1, max_length=2000)
64
+ state: Optional[str] = None
65
+ city: Optional[str] = None
66
+ county_fips: Optional[str] = None
67
+ detail_video_id: Optional[str] = Field(
68
+ default=None,
69
+ description="When set with detail_topic, run quote/detail path for one video",
70
+ )
71
+ detail_topic: Optional[str] = None
72
+
73
+
74
+ class ChatCitation(BaseModel):
75
+ title: str
76
+ place: str
77
+ date: str
78
+ url: str
79
+ event_meeting_id: Optional[int] = None
80
+ video_id: Optional[str] = None
81
+
82
+
83
+ class ChatUsage(BaseModel):
84
+ model: str
85
+ input_tokens: Optional[int] = None
86
+ output_tokens: Optional[int] = None
87
+ estimated_usd: Optional[float] = None
88
+
89
+
90
+ class ChatMeetingsResponse(BaseModel):
91
+ answer: str
92
+ citations: List[ChatCitation]
93
+ found: bool
94
+ mode: str
95
+ usage: Optional[ChatUsage] = None
96
+ # How the meetings were matched (#922): the question as typed, all of its content words, or any of them.
97
+ match: Optional[str] = None
98
+
99
+
100
+ @dataclass
101
+ class MeetingContext:
102
+ event_meeting_id: int
103
+ title: str
104
+ place: str
105
+ date: str
106
+ url: str
107
+ video_id: Optional[str]
108
+ summary: str
109
+
110
+
111
+ def _signed_in_user_id(request: Request) -> Optional[str]:
112
+ """The user id in a valid sign-in token (no database read), else None. A bad or expired token counts as a guest."""
113
+ auth = request.headers.get("authorization") or ""
114
+ if not auth.lower().startswith("bearer "):
115
+ return None
116
+ try:
117
+ from api.auth import decode_access_token
118
+
119
+ sub = decode_access_token(auth[7:].strip()).get("sub")
120
+ except Exception: # noqa: BLE001 — any invalid token is simply not signed in
121
+ return None
122
+ return str(sub) if sub not in (None, "") else None
123
+
124
+
125
+ def _visitor_key(request: Request) -> str:
126
+ """Who a chat message counts against (#1049): ``user:<id>``. The chat requires sign-in, so no token is a 401."""
127
+ user_id = _signed_in_user_id(request)
128
+ if not user_id:
129
+ raise HTTPException(
130
+ status_code=status.HTTP_401_UNAUTHORIZED,
131
+ detail="Sign in to use the meeting chat.",
132
+ headers={"WWW-Authenticate": "Bearer"},
133
+ )
134
+ return f"user:{user_id}"
135
+
136
+
137
+ def _check_rate_limit(visitor: str) -> None:
138
+ now = time.monotonic()
139
+ last = _visitor_last.get(visitor)
140
+ if last is not None and (now - last) < _MIN_INTERVAL_SECONDS:
141
+ raise HTTPException(
142
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
143
+ detail="Please wait a moment before sending another message.",
144
+ )
145
+
146
+ if len(_visitor_timestamps) >= _MAX_TRACKED_VISITORS and visitor not in _visitor_timestamps:
147
+ stale = [
148
+ k for k, ts in _visitor_timestamps.items() if not ts or now - ts[-1] >= _HOUR
149
+ ]
150
+ for k in stale:
151
+ _visitor_timestamps.pop(k, None)
152
+ _visitor_last.pop(k, None)
153
+
154
+ day = _utc_day_key()
155
+ for k in [k for k in _visitor_daily if k != day]:
156
+ _visitor_daily.pop(k, None)
157
+ today = _visitor_daily.setdefault(day, {})
158
+ if today.get(visitor, 0) >= _USER_PER_DAY:
159
+ raise HTTPException(
160
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
161
+ detail="Daily chat limit reached. Try again tomorrow.",
162
+ )
163
+
164
+ history = [t for t in _visitor_timestamps.get(visitor, []) if now - t < _HOUR]
165
+ if len(history) >= _RATE_PER_HOUR:
166
+ raise HTTPException(
167
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
168
+ detail="Hourly chat limit reached. Try again later.",
169
+ )
170
+ burst = [t for t in history if now - t < _FIVE_MIN]
171
+ if len(burst) >= _BURST_PER_5MIN:
172
+ raise HTTPException(
173
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
174
+ detail="Too many messages in a short time. Please slow down.",
175
+ )
176
+
177
+ history.append(now)
178
+ _visitor_timestamps[visitor] = history
179
+ _visitor_last[visitor] = now
180
+ today[visitor] = today.get(visitor, 0) + 1
181
+
182
+
183
+ def _utc_day_key() -> str:
184
+ return datetime.now(timezone.utc).strftime("%Y-%m-%d")
185
+
186
+
187
+ def _check_spend_cap() -> None:
188
+ if _spend_by_utc_day.get(_utc_day_key(), 0.0) >= _DAILY_SPEND_CAP_USD:
189
+ raise HTTPException(
190
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
191
+ detail="Daily chat budget reached. Try again tomorrow.",
192
+ )
193
+
194
+
195
+ def _record_spend(usd: Optional[float]) -> None:
196
+ if usd is None or usd <= 0:
197
+ return
198
+ key = _utc_day_key()
199
+ _spend_by_utc_day[key] = _spend_by_utc_day.get(key, 0.0) + usd
200
+ for k in list(_spend_by_utc_day):
201
+ if k != key:
202
+ _spend_by_utc_day.pop(k, None)
203
+
204
+
205
+ def _estimate_cost_usd(
206
+ model: str,
207
+ input_tokens: Optional[int],
208
+ output_tokens: Optional[int],
209
+ *,
210
+ cached_tokens: int = 0,
211
+ ) -> Optional[float]:
212
+ """Cost from the sourced, dated price of ``model`` in prices.yaml; ``None`` when there is none."""
213
+ if input_tokens is None or output_tokens is None:
214
+ return None
215
+ try:
216
+ from llm.usage.prices import call_cost_usd, load_prices
217
+
218
+ return call_cost_usd(
219
+ {
220
+ "model": model,
221
+ "api_mode": "interactive",
222
+ "input_token_count": input_tokens,
223
+ "output_token_count": output_tokens,
224
+ "cached_input_token_count": cached_tokens,
225
+ "thinking_token_count": 0,
226
+ "called_at": datetime.now(timezone.utc).isoformat(),
227
+ },
228
+ load_prices(),
229
+ )
230
+ except Exception as exc: # noqa: BLE001
231
+ # No guessed rate (#848): an unknown cost is reported as unknown.
232
+ logger.warning("chat cost estimate skipped: {}", exc)
233
+ return None
234
+
235
+
236
+ # Words that carry no topic in a question to this chat (#922): question words, glue, and the civic words that
237
+ # appear in nearly every meeting record. What is left is what the search looks for.
238
+ _CHAT_STOP_WORDS = frozenset(
239
+ """a about after all also am an and any are as at be been before but by can could did do does for from had
240
+ has have how i if in into is it its just me my of on or our over should so some than that the their them
241
+ then there these they this to under up us was we were what when where which who whom why will with would
242
+ you your tell show give find know say says said saying talk talks talked talking discuss discusses discussed
243
+ discussing discussion mention mentions mentioned happen happens happened happening think thinks thought
244
+ going get got go please recent recently latest lately today now anything something everything nothing
245
+ council councils board boards commission commissions committee committees meeting meetings city cities
246
+ county counties town towns local government governments official officials member members people public
247
+ resident residents""".split()
248
+ )
249
+ _MAX_CHAT_TERMS = 8
250
+
251
+
252
+ def chat_search_terms(question: str) -> List[str]:
253
+ """The content words of a question, lowercase, with quoted phrases kept whole; at most eight (#922).
254
+
255
+ "What did councils say about data centers?" -> ["data", "centers"]. A question with nothing left
256
+ ("what happened?") gives an empty list, and the caller keeps the typed-question search only.
257
+ """
258
+ text = (question or "").lower()
259
+ terms: List[str] = [p.strip() for p in re.findall(r'"([^"]{2,60})"', text) if p.strip()]
260
+ rest = re.sub(r'"[^"]*"', " ", text)
261
+ for word in re.findall(r"[a-z0-9][a-z0-9'-]*", rest):
262
+ word = word.strip("'-")
263
+ if len(word) > 1 and word not in _CHAT_STOP_WORDS:
264
+ terms.append(word)
265
+ seen: List[str] = []
266
+ for term in terms:
267
+ if term not in seen:
268
+ seen.append(term)
269
+ return seen[:_MAX_CHAT_TERMS]
270
+
271
+
272
+ # One search document per meeting, and whether one term ($n is the term) is in it or in one of its decisions.
273
+ _CHAT_DOC_SQL = (
274
+ "to_tsvector('english', coalesce(em.body_name, '') || ' ' || coalesce(em.jurisdiction_name, '') || ' ' || "
275
+ "coalesce(em.city, '') || ' ' || coalesce(em.meeting_summary, '') || ' ' || coalesce(em.agenda_summary, ''))"
276
+ )
277
+
278
+
279
+ def _chat_terms_tsquery_sql(first_idx: int, count: int, *, every: bool) -> str:
280
+ """One tsquery for the terms held in parameters $first_idx .. $first_idx+count-1 (#926).
281
+
282
+ ``every`` joins them with AND, otherwise OR. Only parameter numbers go into the SQL text. One combined
283
+ query lets Postgres plan the decision lookup as a join and use its text index; a per-term subquery per
284
+ meeting took about a minute on 15,000 meetings.
285
+ """
286
+ joiner = " && " if every else " || "
287
+ return "(" + joiner.join(f"plainto_tsquery('english', ${first_idx + i})" for i in range(count)) + ")"
288
+
289
+
290
+ async def search_meetings_with_match(
291
+ *,
292
+ query: str,
293
+ state: Optional[str] = None,
294
+ city: Optional[str] = None,
295
+ county_fips: Optional[str] = None,
296
+ limit: int = 5,
297
+ ) -> Tuple[List[MeetingContext], Optional[str]]:
298
+ """Meetings for a chat question, and how they matched (#922).
299
+
300
+ Strict first, widening only when nothing is found: the question as typed ("exact"), then every content
301
+ word ("all_terms"), then any content word ranked by how many it matches ("any_term").
302
+ """
303
+ found = await search_analyzed_meetings_for_chat(
304
+ query=query, state=state, city=city, county_fips=county_fips, limit=limit
305
+ )
306
+ if found:
307
+ return found, "exact"
308
+ terms = chat_search_terms(query)
309
+ if not terms:
310
+ return [], None
311
+ for mode in ("all_terms", "any_term"):
312
+ if mode == "any_term" and len(terms) == 1:
313
+ break # one term: "any" is the same search as "all"
314
+ found = await search_analyzed_meetings_for_chat(
315
+ query=query, state=state, city=city, county_fips=county_fips, limit=limit, terms=terms, match=mode
316
+ )
317
+ if found:
318
+ return found, mode
319
+ return [], None
320
+
321
+
322
+ async def search_analyzed_meetings_for_chat(
323
+ *,
324
+ query: str,
325
+ state: Optional[str] = None,
326
+ city: Optional[str] = None,
327
+ county_fips: Optional[str] = None,
328
+ limit: int = 5,
329
+ terms: Optional[List[str]] = None,
330
+ match: str = "exact",
331
+ ) -> List[MeetingContext]:
332
+ """Top matching analyzed meetings with full meeting_summary for the LLM prompt.
333
+
334
+ ``match="exact"`` matches the question as typed. ``"all_terms"`` and ``"any_term"`` match ``terms``
335
+ (from ``chat_search_terms``) and rank by how many a meeting matches. Terms are always parameters.
336
+ """
337
+ state = normalize_state_input(state)
338
+ q = (query or "").strip()
339
+ if not q:
340
+ return []
341
+
342
+ params: List[Any] = []
343
+ hits_sql = ""
344
+ if match == "exact" or not terms:
345
+ params.append(f"%{q}%")
346
+ q_like_idx = len(params)
347
+ params.append(q)
348
+ q_fts_idx = len(params)
349
+ where: List[str] = [
350
+ f"(em.body_name ILIKE ${q_like_idx} OR em.jurisdiction_name ILIKE ${q_like_idx} "
351
+ f"OR em.meeting_summary ILIKE ${q_like_idx} OR em.city ILIKE ${q_like_idx} "
352
+ f"OR EXISTS (SELECT 1 FROM event_decision d "
353
+ f"WHERE d.c1_event_id = em.c1_event_id "
354
+ f"AND d.search_tsv @@ plainto_tsquery('english', ${q_fts_idx})))"
355
+ ]
356
+ else:
357
+ first = len(params) + 1
358
+ params.extend(terms)
359
+ tsq = _chat_terms_tsquery_sql(first, len(terms), every=(match == "all_terms"))
360
+ # The terms are all in the meeting's own text, or all in one of its decisions ("any": at least one).
361
+ where = [
362
+ f"(x.doc @@ {tsq} OR EXISTS (SELECT 1 FROM event_decision d "
363
+ f"WHERE d.c1_event_id = em.c1_event_id AND d.search_tsv @@ {tsq}))"
364
+ ]
365
+ hits_sql = f"ts_rank(x.doc, {tsq})"
366
+
367
+ if state:
368
+ params.append(state.upper())
369
+ where.append(f"em.state_code = ${len(params)}")
370
+
371
+ use_county = bool(county_fips and county_fips.strip())
372
+ if use_county:
373
+ names = await resolve_county_city_names(county_fips)
374
+ if names:
375
+ params.append([n.lower() for n in names])
376
+ where.append(
377
+ f"(lower(em.jurisdiction_name) = ANY(${len(params)}) "
378
+ f"OR lower(em.city) = ANY(${len(params)}))"
379
+ )
380
+ else:
381
+ where.append("FALSE")
382
+ elif city and city.strip():
383
+ params.append(city.strip())
384
+ where.append(
385
+ f"(lower(em.jurisdiction_name) = lower(${len(params)}) "
386
+ f"OR lower(em.city) = lower(${len(params)}))"
387
+ )
388
+
389
+ params.append(max(1, min(limit, 5)))
390
+ limit_idx = len(params)
391
+ em_iso = (
392
+ "(CASE WHEN em.meeting_date ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}' "
393
+ "THEN em.meeting_date END)"
394
+ )
395
+ # Wider matches are ranked by how many terms a meeting has, then by date.
396
+ rank_order = f"{hits_sql} DESC, " if hits_sql else ""
397
+ sql = f"""
398
+ SELECT
399
+ em.event_meeting_id,
400
+ em.body_name,
401
+ em.jurisdiction_name,
402
+ em.state,
403
+ em.state_code,
404
+ em.city,
405
+ {em_iso} AS iso_date,
406
+ em.meeting_summary,
407
+ em.agenda_summary,
408
+ em.video_id
409
+ FROM event_meeting em
410
+ CROSS JOIN LATERAL (SELECT {_CHAT_DOC_SQL} AS doc) x
411
+ WHERE {" AND ".join(where)}
412
+ ORDER BY {rank_order}{em_iso} DESC NULLS LAST, em.event_meeting_id DESC
413
+ LIMIT ${limit_idx}
414
+ """
415
+
416
+ pool = await get_db_pool()
417
+ async with pool.acquire() as conn:
418
+ rows = await conn.fetch(sql, *params)
419
+
420
+ out: List[MeetingContext] = []
421
+ for row in rows:
422
+ place_bits = [p for p in (row["jurisdiction_name"], row["state"]) if p]
423
+ place = ", ".join(place_bits) if place_bits else (row["city"] or "")
424
+ date_str = row["iso_date"] or ""
425
+ if isinstance(date_str, date):
426
+ date_str = date_str.isoformat()
427
+ title = row["body_name"] or row["jurisdiction_name"] or "Meeting"
428
+ summary = (row["meeting_summary"] or row["agenda_summary"] or "").strip()
429
+ mid = int(row["event_meeting_id"])
430
+ out.append(
431
+ MeetingContext(
432
+ event_meeting_id=mid,
433
+ title=title,
434
+ place=place,
435
+ date=str(date_str),
436
+ url=f"/meetings/{mid}",
437
+ video_id=row["video_id"],
438
+ summary=summary,
439
+ )
440
+ )
441
+ return out
442
+
443
+
444
+ def filter_topic_passages(
445
+ cues: List[TranscriptCue],
446
+ topic: str,
447
+ *,
448
+ char_cap: int = _PASSAGE_CHAR_CAP,
449
+ ) -> List[str]:
450
+ """Keep cue texts that mention the topic; cap total characters."""
451
+ terms = [t for t in re.split(r"\W+", (topic or "").lower()) if len(t) >= 3]
452
+ if not terms:
453
+ terms = [(topic or "").strip().lower()]
454
+ terms = [t for t in terms if t]
455
+ passages: List[str] = []
456
+ used = 0
457
+ for cue in cues:
458
+ text = cue.text.strip()
459
+ if not text:
460
+ continue
461
+ low = text.lower()
462
+ if not any(t in low for t in terms):
463
+ continue
464
+ line = f"[{int(cue.start)}s] {text}"
465
+ if used + len(line) > char_cap:
466
+ break
467
+ passages.append(line)
468
+ used += len(line) + 1
469
+ return passages
470
+
471
+
472
+ async def load_segments_for_video(video_id: str) -> List[TranscriptCue]:
473
+ pool = await get_db_pool()
474
+ async with pool.acquire() as conn:
475
+ row = await conn.fetchrow(
476
+ """
477
+ SELECT segments
478
+ FROM public.event_documents
479
+ WHERE video_id = $1 AND document_type = 'transcript'
480
+ LIMIT 1
481
+ """,
482
+ video_id,
483
+ )
484
+ if not row:
485
+ return []
486
+ return _coerce_segments(row["segments"])
487
+
488
+
489
+ # Bumped whenever the system prompts below change (AGENTS.md, "Version and test it").
490
+ # 2026-11-25.1 (#1011): brief Markdown answers, one lead sentence + at most 6 linked bullets.
491
+ CHAT_PROMPT_VERSION = "2026-11-25.1"
492
+
493
+ _SYSTEM_SUMMARIES = """You answer questions about local government meetings using ONLY the meeting summaries provided.
494
+ Rules:
495
+ - Base every claim on those summaries. If they do not cover the question, say you found nothing relevant in the meetings provided.
496
+ - Never invent dollar amounts, vote counts, or other figures that are not in the summaries.
497
+ - Be brief. Format in Markdown, exactly like this:
498
+ - One short lead sentence that answers the question.
499
+ - Then at most 6 bullets, one per place or meeting, each one sentence:
500
+ `- **Place, State**: what happened ([Meeting title, YYYY-MM-DD](Link))`, using that meeting's Link exactly.
501
+ - No headings, no tables, no closing summary.
502
+ - Cite only meetings that are provided; every bullet links its meeting.
503
+ - No JSON wrapper.
504
+ """
505
+
506
+ _SYSTEM_PASSAGES = """You answer using ONLY the transcript passages provided from one meeting.
507
+ Rules:
508
+ - Quote or paraphrase only from those passages; cite the timestamps when useful.
509
+ - If the passages do not answer the question, say so clearly.
510
+ - Never invent figures or quotes that are not in the passages.
511
+ - Be brief: one short lead sentence, then at most 5 bullets ("- "), with **bold** for the key point. No headings.
512
+ """
513
+
514
+
515
+ def _meetings_to_prompt(question: str, meetings: List[MeetingContext]) -> str:
516
+ blocks = []
517
+ for i, m in enumerate(meetings, 1):
518
+ blocks.append(
519
+ f"[{i}] Title: {m.title}\n"
520
+ f"Place: {m.place}\n"
521
+ f"Date: {m.date}\n"
522
+ f"Link: {m.url}\n"
523
+ f"Summary: {m.summary or '(no summary)'}"
524
+ )
525
+ return f"Question: {question}\n\nMeetings:\n\n" + "\n\n".join(blocks)
526
+
527
+
528
+ def _passages_to_prompt(question: str, topic: str, video_id: str, passages: List[str]) -> str:
529
+ body = "\n".join(passages) if passages else "(no matching passages)"
530
+ return (
531
+ f"Question: {question}\n"
532
+ f"Topic filter: {topic}\n"
533
+ f"Video id: {video_id}\n\n"
534
+ f"Passages:\n{body}"
535
+ )
536
+
537
+
538
+ def chat_provider() -> str:
539
+ """``anthropic`` (default) or ``gemini``, from ``CHAT_PROVIDER`` (#848)."""
540
+ name = (os.environ.get("CHAT_PROVIDER") or "anthropic").strip().lower()
541
+ if name not in ("anthropic", "gemini"):
542
+ raise ValueError(f"CHAT_PROVIDER must be 'anthropic' or 'gemini', not {name!r}")
543
+ return name
544
+
545
+
546
+ def _call_claude(
547
+ system: str, user: str
548
+ ) -> Tuple[str, str, Optional[int], Optional[int], Optional[float]]:
549
+ from llm.claude.text_client import DEFAULT_CHAT_MODEL, call_claude_text
550
+
551
+ model = (os.environ.get("CHAT_MODEL") or "").strip() or DEFAULT_CHAT_MODEL
552
+ result = call_claude_text(model=model, system=system, user_text=user)
553
+ usd = _estimate_cost_usd(
554
+ model, result.input_tokens, result.output_tokens, cached_tokens=result.cached_input_tokens
555
+ )
556
+ return result.text, model, result.input_tokens, result.output_tokens, usd
557
+
558
+
559
+ def _call_gemini(
560
+ system: str, user: str
561
+ ) -> Tuple[str, str, Optional[int], Optional[int], Optional[float]]:
562
+ from llm.gemini.genai_text_client import (
563
+ call_gemini_text,
564
+ default_flash_lite_model,
565
+ resolve_gemini_api_key,
566
+ )
567
+
568
+ model = (os.environ.get("CHAT_MODEL") or "").strip() or default_flash_lite_model()
569
+ result = call_gemini_text(
570
+ api_key=resolve_gemini_api_key(),
571
+ model=model,
572
+ user_text=user,
573
+ system_instruction=system,
574
+ temperature=0.2,
575
+ max_output_tokens=1024,
576
+ thinking_budget=0,
577
+ )
578
+ usage = result.usage
579
+ in_tok = getattr(usage, "input_token_count", None) if usage else None
580
+ out_tok = getattr(usage, "output_token_count", None) if usage else None
581
+ usd = _estimate_cost_usd(model, in_tok, out_tok)
582
+ return (result.text or "").strip(), model, in_tok, out_tok, usd
583
+
584
+
585
+ def _call_chat_model(
586
+ system: str, user: str
587
+ ) -> Tuple[str, str, Optional[int], Optional[int], Optional[float]]:
588
+ """The chat's one model call: Claude Haiku by default, Gemini when ``CHAT_PROVIDER=gemini``."""
589
+ if chat_provider() == "gemini":
590
+ return _call_gemini(system, user)
591
+ return _call_claude(system, user)
592
+
593
+
594
+ CHAT_NOT_SET_UP = "Chat is not set up on this site yet."
595
+
596
+
597
+ def chat_model_name() -> str:
598
+ """The model the chat would call, without calling it."""
599
+ override = (os.environ.get("CHAT_MODEL") or "").strip()
600
+ if override:
601
+ return override
602
+ if chat_provider() == "gemini":
603
+ from llm.gemini.genai_text_client import default_flash_lite_model
604
+
605
+ return default_flash_lite_model()
606
+ from llm.claude.text_client import DEFAULT_CHAT_MODEL
607
+
608
+ return DEFAULT_CHAT_MODEL
609
+
610
+
611
+ def chat_missing_setting() -> Optional[str]:
612
+ """The name of the key variable the chat's provider needs and does not have, or None (#916).
613
+
614
+ Only names are returned and logged; a key's value is never read into a message.
615
+ """
616
+ if chat_provider() == "gemini":
617
+ from llm.gemini.genai_text_client import resolve_gemini_api_key
618
+
619
+ try:
620
+ return None if (resolve_gemini_api_key() or "").strip() else "GEMINI_API_KEY"
621
+ except Exception: # noqa: BLE001 - the resolver raises when no key is configured
622
+ return "GEMINI_API_KEY"
623
+ return None if (os.environ.get("ANTHROPIC_API_KEY") or "").strip() else "ANTHROPIC_API_KEY"
624
+
625
+
626
+ def _require_chat_configured() -> None:
627
+ """Answer 503 before any model call when the provider's key is not set (#916)."""
628
+ missing = chat_missing_setting()
629
+ if missing:
630
+ logger.error("chat is not set up: provider={} needs {} and it is not set", chat_provider(), missing)
631
+ raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=CHAT_NOT_SET_UP)
632
+
633
+
634
+ def _log_model_failure(where: str, exc: Exception) -> None:
635
+ """One error line that says what was called and how it failed, for the operator (#916)."""
636
+ try:
637
+ provider, model = chat_provider(), chat_model_name()
638
+ except Exception: # noqa: BLE001
639
+ provider, model = "unknown", "unknown"
640
+ logger.error(
641
+ "{} model call failed: provider={} model={} error={} status={} detail={}",
642
+ where,
643
+ provider,
644
+ model,
645
+ type(exc).__name__,
646
+ getattr(exc, "status_code", None),
647
+ exc,
648
+ )
649
+
650
+
651
+ class ChatStatus(BaseModel):
652
+ provider: str
653
+ model: str
654
+ configured: bool
655
+
656
+
657
+ @router.get("/status", response_model=ChatStatus)
658
+ async def chat_status() -> ChatStatus:
659
+ """Whether the chat can answer on this site: provider, model and whether its key is set. No secrets."""
660
+ return ChatStatus(
661
+ provider=chat_provider(), model=chat_model_name(), configured=chat_missing_setting() is None
662
+ )
663
+
664
+
665
+ def _answer_looks_empty(text: str) -> bool:
666
+ low = (text or "").lower()
667
+ if not text.strip():
668
+ return True
669
+ markers = (
670
+ "nothing relevant",
671
+ "no relevant",
672
+ "not find",
673
+ "don't have enough",
674
+ "do not have enough",
675
+ "no meetings",
676
+ "couldn't find",
677
+ "could not find",
678
+ )
679
+ return any(m in low for m in markers)
680
+
681
+
682
+ def _log_zero_result(question: str, *, mode: str, filters: dict) -> None:
683
+ q_hash = hashlib.sha256(question.encode()).hexdigest()[:16]
684
+ logger.info(
685
+ "chat.zero_result mode={} q_hash={} q_len={} filters={}",
686
+ mode,
687
+ q_hash,
688
+ len(question),
689
+ json.dumps(filters, sort_keys=True),
690
+ )
691
+
692
+
693
+ @router.post("/meetings", response_model=ChatMeetingsResponse)
694
+ async def chat_meetings(body: ChatMeetingsRequest, request: Request) -> ChatMeetingsResponse:
695
+ with tracer.start_as_current_span("chat.meetings") as span:
696
+ visitor = _visitor_key(request)
697
+ _check_rate_limit(visitor)
698
+ _check_spend_cap()
699
+
700
+ question = body.question.strip()
701
+ filters = {"state": body.state, "city": body.city, "county_fips": body.county_fips}
702
+ span.set_attribute("chat.question_len", len(question))
703
+
704
+ if body.detail_video_id and body.detail_topic:
705
+ return await _chat_passages(
706
+ question=question,
707
+ video_id=body.detail_video_id.strip(),
708
+ topic=body.detail_topic.strip(),
709
+ filters=filters,
710
+ span=span,
711
+ )
712
+
713
+ meetings, match = await search_meetings_with_match(
714
+ query=question,
715
+ state=body.state,
716
+ city=body.city,
717
+ county_fips=body.county_fips,
718
+ limit=5,
719
+ )
720
+ span.set_attribute("chat.meeting_hits", len(meetings))
721
+ span.set_attribute("chat.match", match or "none")
722
+
723
+ citations = [
724
+ ChatCitation(
725
+ title=m.title,
726
+ place=m.place,
727
+ date=m.date,
728
+ url=m.url,
729
+ event_meeting_id=m.event_meeting_id,
730
+ video_id=m.video_id,
731
+ )
732
+ for m in meetings
733
+ ]
734
+
735
+ if not meetings:
736
+ _log_zero_result(question, mode="summaries", filters=filters)
737
+ return ChatMeetingsResponse(
738
+ answer=(
739
+ "No matching analyzed meetings were found for that question "
740
+ "in the current scope. Try different wording or broaden the place filter."
741
+ ),
742
+ citations=[],
743
+ found=False,
744
+ mode="summaries",
745
+ )
746
+
747
+ _require_chat_configured()
748
+ prompt = _meetings_to_prompt(question, meetings)
749
+ if match == "any_term":
750
+ # Tell the model the match was loose, so it says so and does not stretch a weak meeting into an answer.
751
+ prompt += (
752
+ "\n\nNote: no meeting matched every word of the question. These meetings mention at least one of: "
753
+ + ", ".join(chat_search_terms(question))
754
+ + ". Say which of these terms each meeting you use is about, and say plainly if none answers the question."
755
+ )
756
+ try:
757
+ text, model, in_tok, out_tok, usd = await run_in_threadpool(
758
+ _call_chat_model, _SYSTEM_SUMMARIES, prompt
759
+ )
760
+ except Exception as exc: # noqa: BLE001
761
+ span.record_exception(exc)
762
+ _log_model_failure("chat", exc)
763
+ raise HTTPException(
764
+ status_code=status.HTTP_502_BAD_GATEWAY,
765
+ detail="The answer service is temporarily unavailable.",
766
+ ) from exc
767
+
768
+ _record_spend(usd)
769
+ found = not _answer_looks_empty(text)
770
+ if not found:
771
+ _log_zero_result(question, mode="summaries", filters=filters)
772
+
773
+ return ChatMeetingsResponse(
774
+ answer=text or "No answer was returned.",
775
+ citations=citations,
776
+ found=found,
777
+ mode="summaries",
778
+ usage=ChatUsage(
779
+ model=model, input_tokens=in_tok, output_tokens=out_tok, estimated_usd=usd
780
+ ),
781
+ match=match,
782
+ )
783
+
784
+
785
+ async def _chat_passages(
786
+ *,
787
+ question: str,
788
+ video_id: str,
789
+ topic: str,
790
+ filters: dict,
791
+ span: Any,
792
+ ) -> ChatMeetingsResponse:
793
+ span.set_attribute("chat.mode", "passages")
794
+ span.set_attribute("chat.video_id", video_id)
795
+ cues = await load_segments_for_video(video_id)
796
+ passages = filter_topic_passages(cues, topic)
797
+ span.set_attribute("chat.passage_count", len(passages))
798
+
799
+ if not passages:
800
+ _log_zero_result(question, mode="passages", filters={**filters, "video_id": video_id})
801
+ return ChatMeetingsResponse(
802
+ answer=(
803
+ "No transcript passages mentioning that topic were found for this meeting. "
804
+ "The recording may lack cues, or the topic wording may not appear in the transcript."
805
+ ),
806
+ citations=[],
807
+ found=False,
808
+ mode="passages",
809
+ )
810
+
811
+ _require_chat_configured()
812
+ try:
813
+ text, model, in_tok, out_tok, usd = await run_in_threadpool(
814
+ _call_chat_model,
815
+ _SYSTEM_PASSAGES,
816
+ _passages_to_prompt(question, topic, video_id, passages),
817
+ )
818
+ except Exception as exc: # noqa: BLE001
819
+ span.record_exception(exc)
820
+ _log_model_failure("chat passages", exc)
821
+ raise HTTPException(
822
+ status_code=status.HTTP_502_BAD_GATEWAY,
823
+ detail="The answer service is temporarily unavailable.",
824
+ ) from exc
825
+
826
+ _record_spend(usd)
827
+ found = not _answer_looks_empty(text)
828
+ if not found:
829
+ _log_zero_result(question, mode="passages", filters={**filters, "video_id": video_id})
830
+
831
+ return ChatMeetingsResponse(
832
+ answer=text or "No answer was returned.",
833
+ citations=[
834
+ ChatCitation(
835
+ title="Meeting transcript",
836
+ place="",
837
+ date="",
838
+ url=f"https://www.youtube.com/watch?v={video_id}",
839
+ video_id=video_id,
840
+ )
841
+ ],
842
+ found=found,
843
+ mode="passages",
844
+ usage=ChatUsage(
845
+ model=model, input_tokens=in_tok, output_tokens=out_tok, estimated_usd=usd
846
+ ),
847
+ )
api/routes/contact.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Contact routes for submitting feedback and issues via GitHub.
3
+ """
4
+ import hashlib
5
+ import os
6
+ import re
7
+ import time
8
+ from typing import Dict, List, Optional
9
+
10
+ import httpx
11
+ from fastapi import APIRouter, HTTPException, status
12
+ from loguru import logger
13
+ from opentelemetry import trace
14
+ from pydantic import BaseModel, EmailStr, Field
15
+ from sqlalchemy.orm import Session
16
+ from starlette.concurrency import run_in_threadpool
17
+
18
+ from api.models import ContactSubmission
19
+
20
+ router = APIRouter(prefix="/contact", tags=["contact"])
21
+ tracer = trace.get_tracer(__name__)
22
+
23
+ CATEGORY_LABELS: Dict[str, str] = {
24
+ "bug": "bug",
25
+ "feature": "enhancement",
26
+ "question": "question",
27
+ "feedback": "feedback",
28
+ }
29
+
30
+ _CONTROL_CHARS_RE = re.compile(r"[\r\n\t\x00-\x1f\x7f]+")
31
+
32
+ # Bounded in-memory rate-limiting and duplicate suppression state
33
+ _RATE_WINDOW_SECONDS: float = 300.0
34
+ _MAX_SUBMISSIONS_PER_SENDER: int = 5
35
+ _MAX_GLOBAL_SUBMISSIONS: int = 30
36
+ _DEDUP_WINDOW_SECONDS: float = 60.0
37
+ _MAX_TRACKED_SENDERS: int = 512
38
+
39
+ _sender_timestamps: Dict[str, List[float]] = {}
40
+ _global_timestamps: List[float] = []
41
+ _recent_fingerprints: Dict[str, float] = {}
42
+
43
+
44
+ def clear_contact_rate_limits() -> None:
45
+ """Clear in-memory contact form rate-limit and deduplication state."""
46
+ _sender_timestamps.clear()
47
+ _global_timestamps.clear()
48
+ _recent_fingerprints.clear()
49
+
50
+
51
+ def _sanitize_single_line(value: str) -> str:
52
+ return _CONTROL_CHARS_RE.sub(" ", value or "").strip()
53
+
54
+
55
+ def _check_and_record_rate_limit(sender_key: str, fingerprint: str) -> float:
56
+ """Check the limits and reserve this submission; return its timestamp.
57
+
58
+ The fingerprint is reserved before the GitHub call so two identical concurrent
59
+ submissions cannot both create issues. If the call fails, the caller must call
60
+ ``_release_fingerprint`` so the user can retry the same message right away.
61
+ """
62
+ now = time.monotonic()
63
+
64
+ # Prune expired fingerprints
65
+ expired_fp = [fp for fp, ts in _recent_fingerprints.items() if now - ts >= _DEDUP_WINDOW_SECONDS]
66
+ for fp in expired_fp:
67
+ _recent_fingerprints.pop(fp, None)
68
+
69
+ if fingerprint in _recent_fingerprints:
70
+ raise HTTPException(
71
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
72
+ detail="Duplicate submission detected. Please wait before submitting the same message again.",
73
+ )
74
+
75
+ # Prune global window
76
+ _global_timestamps[:] = [ts for ts in _global_timestamps if now - ts < _RATE_WINDOW_SECONDS]
77
+ if len(_global_timestamps) >= _MAX_GLOBAL_SUBMISSIONS:
78
+ raise HTTPException(
79
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
80
+ detail="Too many contact requests. Please try again later.",
81
+ )
82
+
83
+ # Prune sender window and bound tracked sender map
84
+ if len(_sender_timestamps) >= _MAX_TRACKED_SENDERS and sender_key not in _sender_timestamps:
85
+ stale_senders = [
86
+ k for k, timestamps in _sender_timestamps.items()
87
+ if not timestamps or now - timestamps[-1] >= _RATE_WINDOW_SECONDS
88
+ ]
89
+ for k in stale_senders:
90
+ _sender_timestamps.pop(k, None)
91
+ if len(_sender_timestamps) >= _MAX_TRACKED_SENDERS:
92
+ oldest_sender = min(
93
+ _sender_timestamps,
94
+ key=lambda k: _sender_timestamps[k][-1] if _sender_timestamps[k] else 0.0,
95
+ )
96
+ _sender_timestamps.pop(oldest_sender, None)
97
+
98
+ sender_history = [
99
+ ts for ts in _sender_timestamps.get(sender_key, []) if now - ts < _RATE_WINDOW_SECONDS
100
+ ]
101
+ if len(sender_history) >= _MAX_SUBMISSIONS_PER_SENDER:
102
+ raise HTTPException(
103
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
104
+ detail="Rate limit exceeded for contact submissions. Please wait a few minutes and try again.",
105
+ )
106
+
107
+ sender_history.append(now)
108
+ _sender_timestamps[sender_key] = sender_history
109
+ _global_timestamps.append(now)
110
+ _recent_fingerprints[fingerprint] = now
111
+ return now
112
+
113
+
114
+ def _release_fingerprint(fingerprint: str, recorded_at: float) -> None:
115
+ """Drop a duplicate-suppression reservation after a failed submission.
116
+
117
+ The per-sender and global counters keep the attempt, so a failing upstream
118
+ still cannot be hammered without limit. Only the reservation made by this
119
+ request is removed (matched by its timestamp).
120
+ """
121
+ if _recent_fingerprints.get(fingerprint) == recorded_at:
122
+ _recent_fingerprints.pop(fingerprint, None)
123
+
124
+
125
+ def _open_session() -> Session:
126
+ """Open an ORM session on the API's own database (patched in tests)."""
127
+ from api.database import SessionLocal
128
+
129
+ return SessionLocal()
130
+
131
+
132
+ def _save_submission(sender_name: str, sender_email: str, subject: str) -> Optional[int]:
133
+ """Store the sender privately; return the new ``contact_submission_id``.
134
+
135
+ Returns ``None`` when the database is unavailable, so the submission can still
136
+ go through. Never logs the email (#448).
137
+ """
138
+ with tracer.start_as_current_span("contact.save_submission") as span:
139
+ db = None
140
+ try:
141
+ db = _open_session()
142
+ row = ContactSubmission(
143
+ sender_name=sender_name,
144
+ sender_email=sender_email,
145
+ subject=subject,
146
+ )
147
+ db.add(row)
148
+ db.commit()
149
+ db.refresh(row)
150
+ span.set_attribute("contact_submission_id", row.contact_submission_id)
151
+ return row.contact_submission_id
152
+ except Exception as exc:
153
+ if db is not None:
154
+ db.rollback()
155
+ span.record_exception(exc)
156
+ logger.warning(
157
+ "Could not save contact submission privately ({}); "
158
+ "creating the issue without a reply address",
159
+ type(exc).__name__,
160
+ )
161
+ return None
162
+ finally:
163
+ if db is not None:
164
+ db.close()
165
+
166
+
167
+ def _attach_issue(submission_id: int, issue_number: Optional[int], issue_url: Optional[str]) -> None:
168
+ """Record the created GitHub issue on its submission row (best effort)."""
169
+ with tracer.start_as_current_span("contact.attach_issue") as span:
170
+ span.set_attribute("contact_submission_id", submission_id)
171
+ db = None
172
+ try:
173
+ db = _open_session()
174
+ row = db.get(ContactSubmission, submission_id)
175
+ if row is None:
176
+ logger.warning("Contact submission #{} not found to attach its issue", submission_id)
177
+ return
178
+ row.github_issue_number = issue_number
179
+ row.github_issue_url = issue_url
180
+ db.commit()
181
+ except Exception as exc:
182
+ if db is not None:
183
+ db.rollback()
184
+ span.record_exception(exc)
185
+ logger.warning(
186
+ "Could not attach issue {} to contact submission #{} ({})",
187
+ issue_url,
188
+ submission_id,
189
+ type(exc).__name__,
190
+ )
191
+ finally:
192
+ if db is not None:
193
+ db.close()
194
+
195
+
196
+ def _discard_submission(submission_id: int) -> None:
197
+ """Delete a stored submission whose issue was never created (best effort).
198
+
199
+ The user saw an error and will retry, so keeping the email would only hold
200
+ personal data for a message that never arrived.
201
+ """
202
+ with tracer.start_as_current_span("contact.discard_submission") as span:
203
+ span.set_attribute("contact_submission_id", submission_id)
204
+ db = None
205
+ try:
206
+ db = _open_session()
207
+ row = db.get(ContactSubmission, submission_id)
208
+ if row is not None:
209
+ db.delete(row)
210
+ db.commit()
211
+ except Exception as exc:
212
+ if db is not None:
213
+ db.rollback()
214
+ span.record_exception(exc)
215
+ logger.warning(
216
+ "Could not discard unsent contact submission #{} ({})",
217
+ submission_id,
218
+ type(exc).__name__,
219
+ )
220
+ finally:
221
+ if db is not None:
222
+ db.close()
223
+
224
+
225
+ class ContactRequest(BaseModel):
226
+ """Contact form submission"""
227
+ name: str = Field(..., min_length=1, max_length=100, description="Name of the person contacting")
228
+ email: EmailStr = Field(..., description="Email address for follow-up")
229
+ subject: str = Field(..., min_length=1, max_length=200, description="Subject of the message")
230
+ message: str = Field(..., min_length=10, max_length=5000, description="Detailed message")
231
+ category: Optional[str] = Field(default="feedback", description="Type of contact: feedback, bug, feature, question")
232
+
233
+
234
+ class ContactResponse(BaseModel):
235
+ """Response after submitting contact form"""
236
+ success: bool
237
+ message: str
238
+ issue_url: Optional[str] = None
239
+
240
+
241
+ @router.post("/submit", response_model=ContactResponse, status_code=status.HTTP_201_CREATED)
242
+ async def submit_contact(request: ContactRequest):
243
+ """
244
+ Submit a contact form message as a GitHub issue.
245
+
246
+ Creates an issue in the GitHub repository with the contact information.
247
+ Requires GITHUB_TOKEN and GITHUB_REPO environment variables.
248
+ """
249
+ clean_name = _sanitize_single_line(request.name)
250
+ clean_subject = _sanitize_single_line(request.subject)
251
+ clean_message = (request.message or "").replace("\x00", "").strip()
252
+ if not clean_name or not clean_subject or len(clean_message) < 10:
253
+ raise HTTPException(
254
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
255
+ detail="Name, subject, and message (at least 10 non-whitespace characters) are required.",
256
+ )
257
+
258
+ github_token = (os.getenv("GITHUB_TOKEN") or "").strip()
259
+ github_repo = (os.getenv("GITHUB_REPO") or "getcommunityone/open-navigator").strip()
260
+
261
+ if not github_token:
262
+ logger.warning("GitHub token not configured - contact form submission failed")
263
+ raise HTTPException(
264
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
265
+ detail="Contact form is not configured. Please email us directly or submit an issue on GitHub.",
266
+ )
267
+
268
+ sender_key = str(request.email).strip().lower()
269
+ fingerprint = hashlib.sha256(
270
+ f"{sender_key}|{clean_subject.lower()}|{clean_message}".encode("utf-8")
271
+ ).hexdigest()
272
+ recorded_at = _check_and_record_rate_limit(sender_key, fingerprint)
273
+
274
+ norm_category = _sanitize_single_line(request.category or "feedback").lower()
275
+ safe_category = norm_category if norm_category in CATEGORY_LABELS else "feedback"
276
+ label = CATEGORY_LABELS[safe_category]
277
+
278
+ # The repository is public: the email goes to the private contact_submission
279
+ # table, never into the issue (#448). No fallback puts it in the issue.
280
+ submission_id = await run_in_threadpool(
281
+ _save_submission, clean_name, str(request.email), clean_subject
282
+ )
283
+ if submission_id is not None:
284
+ # Code span so GitHub does not auto-link "#<id>" to an unrelated issue.
285
+ reply_line = f"Reply address kept privately (submission `#{submission_id}`)"
286
+ else:
287
+ reply_line = "Reply address not kept (private store unavailable)"
288
+
289
+ issue_title = f"[Contact Form] {clean_subject}"
290
+ issue_body = f"""**From:** {clean_name}
291
+ **Reply:** {reply_line}
292
+ **Category:** {safe_category}
293
+
294
+ ---
295
+
296
+ {clean_message}
297
+
298
+ ---
299
+ *This issue was automatically created from the contact form.*
300
+ """
301
+
302
+ github_api_url = f"https://api.github.com/repos/{github_repo}/issues"
303
+ headers = {
304
+ "Authorization": f"Bearer {github_token}",
305
+ "Accept": "application/vnd.github+json",
306
+ "X-GitHub-Api-Version": "2022-11-28",
307
+ }
308
+ payload = {
309
+ "title": issue_title,
310
+ "body": issue_body,
311
+ "labels": [label, "contact-form"],
312
+ }
313
+
314
+ submitted = False
315
+ try:
316
+ async with httpx.AsyncClient() as client:
317
+ response = await client.post(
318
+ github_api_url,
319
+ json=payload,
320
+ headers=headers,
321
+ timeout=10.0,
322
+ )
323
+
324
+ if response.status_code == 201:
325
+ issue_data = response.json()
326
+ issue_url = issue_data.get("html_url")
327
+ raw_number = issue_data.get("number")
328
+ issue_number = raw_number if isinstance(raw_number, int) else None
329
+ submitted = True
330
+ logger.info(f"Contact form submitted successfully: {issue_url}")
331
+ if submission_id is not None:
332
+ await run_in_threadpool(_attach_issue, submission_id, issue_number, issue_url)
333
+ return ContactResponse(
334
+ success=True,
335
+ message="Thank you for contacting us! We've received your message and will get back to you soon.",
336
+ issue_url=issue_url,
337
+ )
338
+ if response.status_code in (403, 429):
339
+ logger.error(f"GitHub API rate limit / auth error: {response.status_code}")
340
+ raise HTTPException(
341
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
342
+ detail="Contact submission service is temporarily rate-limited. Please try again later.",
343
+ )
344
+ logger.error(f"GitHub API error: {response.status_code} - {response.text}")
345
+ raise HTTPException(
346
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
347
+ detail="Failed to submit contact form. Please try again later.",
348
+ )
349
+
350
+ except HTTPException:
351
+ raise
352
+ except httpx.TimeoutException as exc:
353
+ logger.error("GitHub API timeout")
354
+ raise HTTPException(
355
+ status_code=status.HTTP_504_GATEWAY_TIMEOUT,
356
+ detail="Request timed out. Please try again.",
357
+ ) from exc
358
+ except httpx.RequestError as exc:
359
+ logger.error(f"GitHub API request error: {exc}")
360
+ raise HTTPException(
361
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
362
+ detail="Failed to submit contact form. Please try again later.",
363
+ ) from exc
364
+ finally:
365
+ if not submitted:
366
+ _release_fingerprint(fingerprint, recorded_at)
367
+ if submission_id is not None:
368
+ await run_in_threadpool(_discard_submission, submission_id)
api/routes/cpi.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPI (Bureau of Labor Statistics) read endpoint for the frontend inflation toggle.
2
+
3
+ Reads ``public.cpi_annual`` (the civic serving mart over
4
+ ``staging.stg_bls__cpi_annual`` -> ``bronze.bronze_bls_cpi``, loaded by
5
+ ``ingestion.bls.cpi``) and returns a flat
6
+ ``{year: index_value}`` map plus the latest year — exactly the shape the
7
+ frontend ``useInflationToggle`` / ``deflate()`` utility consumes to convert
8
+ nominal dollars to constant dollars of the latest year.
9
+
10
+ One national series is intentional: the same yardstick is applied to every
11
+ geography so cross-place "real dollar" comparisons stay comparable.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import asyncio
16
+ import os
17
+ import re
18
+ import time
19
+ from typing import Any, Dict, Optional
20
+
21
+ import psycopg2
22
+ from fastapi import APIRouter, HTTPException, Query
23
+ from loguru import logger
24
+
25
+ router = APIRouter()
26
+
27
+ _DEFAULT_LOCAL_DB_URL = "postgresql://postgres:password@localhost:5433/open_navigator"
28
+ _DB_ENV_PRIORITY = (
29
+ "NEON_DATABASE_URL_DEV",
30
+ "NEON_DATABASE_URL",
31
+ "OPEN_NAVIGATOR_DATABASE_URL",
32
+ "DATABASE_URL",
33
+ )
34
+ _SERIES_ID_PATTERN = r"^[A-Za-z0-9_-]{3,32}$"
35
+ _SERIES_ID_RE = re.compile(_SERIES_ID_PATTERN)
36
+
37
+
38
+ def resolve_db_url() -> str:
39
+ """Resolve database URL across dev, Neon production, and standard env vars."""
40
+ for env_key in _DB_ENV_PRIORITY:
41
+ raw = (os.getenv(env_key) or "").strip()
42
+ if raw:
43
+ if raw.startswith("postgres://"):
44
+ return raw.replace("postgres://", "postgresql://", 1)
45
+ return raw
46
+ return _DEFAULT_LOCAL_DB_URL
47
+
48
+
49
+ DB_URL = resolve_db_url()
50
+ _INITIAL_DB_URL = DB_URL
51
+
52
+ # CPI updates monthly; a 6-hour TTL keeps cost-per-request negligible while
53
+ # bounding cached entries and avoiding stale/empty cache pollution.
54
+ _CACHE_TTL_S: float = 6 * 3600.0
55
+ _MAX_CACHE_ENTRIES: int = 32
56
+ _CACHE: Dict[str, Dict[str, Any]] = {}
57
+ _inflight_locks: Dict[str, asyncio.Lock] = {}
58
+
59
+
60
+ def clear_cpi_cache() -> None:
61
+ """Clear in-memory CPI cache and inflight locks."""
62
+ _CACHE.clear()
63
+ _inflight_locks.clear()
64
+
65
+
66
+ def _active_db_url() -> str:
67
+ if DB_URL != _INITIAL_DB_URL:
68
+ if DB_URL.startswith("postgres://"):
69
+ return DB_URL.replace("postgres://", "postgresql://", 1)
70
+ return DB_URL
71
+ return resolve_db_url()
72
+
73
+
74
+ def _get_cached(series_id: str) -> Optional[Dict[str, Any]]:
75
+ cached = _CACHE.get(series_id)
76
+ if not cached:
77
+ return None
78
+ if time.monotonic() - cached["fetched_at"] >= _CACHE_TTL_S:
79
+ _CACHE.pop(series_id, None)
80
+ return None
81
+ return cached["payload"]
82
+
83
+
84
+ def _set_cached(series_id: str, payload: Dict[str, Any]) -> None:
85
+ now = time.monotonic()
86
+ if len(_CACHE) >= _MAX_CACHE_ENTRIES and series_id not in _CACHE:
87
+ expired = [k for k, v in _CACHE.items() if now - v["fetched_at"] >= _CACHE_TTL_S]
88
+ for k in expired:
89
+ _CACHE.pop(k, None)
90
+ if len(_CACHE) >= _MAX_CACHE_ENTRIES:
91
+ oldest_key = min(_CACHE, key=lambda k: _CACHE[k]["fetched_at"])
92
+ _CACHE.pop(oldest_key, None)
93
+ _CACHE[series_id] = {"fetched_at": now, "payload": payload}
94
+
95
+
96
+ def _fetch_cpi_series_sync(series_id: str) -> list[tuple[Any, Any, Any]]:
97
+ conn = psycopg2.connect(_active_db_url())
98
+ try:
99
+ cur = conn.cursor()
100
+ # public.cpi_annual is the civic serving relation (mirrored to Neon
101
+ # prod); the staging view is gold/dev-only and never reaches Neon.
102
+ cur.execute(
103
+ """
104
+ SELECT year, index_value, from_official_annual
105
+ FROM public.cpi_annual
106
+ WHERE series_id = %s
107
+ ORDER BY year
108
+ """,
109
+ (series_id,),
110
+ )
111
+ return cur.fetchall()
112
+ finally:
113
+ conn.close()
114
+
115
+
116
+ @router.get("/cpi/annual")
117
+ async def cpi_annual(
118
+ series_id: str = Query(
119
+ "CUUR0000SA0",
120
+ pattern=_SERIES_ID_PATTERN,
121
+ description=(
122
+ "BLS series identifier. Default CUUR0000SA0 = CPI-U NSA, "
123
+ "all items, U.S. city average — the standard deflator the "
124
+ "frontend real-dollar toggle uses across every geography."
125
+ ),
126
+ ),
127
+ ) -> Dict[str, Any]:
128
+ clean_series_id = (series_id or "").strip().upper()
129
+ if not _SERIES_ID_RE.match(clean_series_id):
130
+ raise HTTPException(status_code=400, detail="Invalid BLS series_id format")
131
+
132
+ cached = _get_cached(clean_series_id)
133
+ if cached is not None:
134
+ return cached
135
+
136
+ lock = _inflight_locks.setdefault(clean_series_id, asyncio.Lock())
137
+ try:
138
+ async with lock:
139
+ cached = _get_cached(clean_series_id)
140
+ if cached is not None:
141
+ return cached
142
+
143
+ try:
144
+ rows = await asyncio.to_thread(_fetch_cpi_series_sync, clean_series_id)
145
+ except psycopg2.Error as e:
146
+ logger.exception("CPI query failed for series={}", clean_series_id)
147
+ raise HTTPException(status_code=500, detail="CPI query failed") from e
148
+
149
+ by_year: Dict[str, float] = {}
150
+ from_official: Dict[str, bool] = {}
151
+ for year, index_value, official in rows:
152
+ key = str(int(year))
153
+ by_year[key] = float(index_value)
154
+ from_official[key] = bool(official)
155
+
156
+ latest_year = max((int(y) for y in by_year), default=None)
157
+ payload = {
158
+ "series_id": clean_series_id,
159
+ "latest_year": latest_year,
160
+ "by_year": by_year,
161
+ "from_official_annual": from_official,
162
+ }
163
+ if by_year:
164
+ _set_cached(clean_series_id, payload)
165
+ return payload
166
+ finally:
167
+ if not lock.locked():
168
+ _inflight_locks.pop(clean_series_id, None)
api/routes/data_center_comments.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Comment-level data-center metrics from our own transcripts (#1233, epic #1232).
2
+
3
+ ``GET /api/data-centers/comment-metrics?year=2026&state=AL&city=`` returns the free numbers
4
+ that ``public.data_center_comment`` (dbt) supports: how many public comments, at how many local
5
+ governments and meetings, the concerns they raise (multi-label), the companies and public
6
+ figures they name, how many mention AI, how speakers describe themselves, the places they
7
+ name, and data-center mentions per meeting by quarter.
8
+
9
+ Metrics that need a per-comment stance (opposed / in favor / question) are returned as
10
+ ``null`` with a reason: stance needs the classifier pass that is on hold (epic #1232, phase 2).
11
+ Nothing is defaulted to 0 or invented (CLAUDE.md, No Fabricated Data). The response echoes the
12
+ applied scope so the UI label matches the data (CLAUDE.md, scope label rule).
13
+
14
+ All shaping lives in dbt; this route only counts rows of the served marts.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Any
20
+
21
+ import asyncpg
22
+ from fastapi import APIRouter, HTTPException, Query
23
+ from loguru import logger
24
+ from opentelemetry import trace
25
+ from pydantic import BaseModel, Field
26
+
27
+ from api.routes.data_centers import JobClaimScope, build_scope
28
+ from api.routes.search_postgres import get_db_pool
29
+
30
+ router = APIRouter(prefix="/data-centers", tags=["data-centers"])
31
+ tracer = trace.get_tracer(__name__)
32
+
33
+ STANCE_REASON = (
34
+ "Needs a per-comment stance (opposed / in favor / question). That classifier pass is on hold "
35
+ "by the owner (epic #1232, phase 2); until it runs, this number is unknown."
36
+ )
37
+ BASIS = (
38
+ "Public comments segmented from our own meeting captions (self-introductions and the chair calling "
39
+ "speakers), kept when the speaker isn't staff or the applicant and the comment is about a data center. "
40
+ "Concerns, companies, people, AI and roles are keyword matches (dbt seeds), not a model's reading."
41
+ )
42
+
43
+
44
+ class CountItem(BaseModel):
45
+ key: str
46
+ label: str
47
+ count: int
48
+ share: float | None = Field(None, description="count / comments; null when there are no comments.")
49
+
50
+
51
+ class QuarterItem(BaseModel):
52
+ quarter: str = Field(..., description="e.g. '2026-Q1' (a string, not a number).")
53
+ meetings_with_mention: int = Field(..., description="Meetings whose captions say 'data center'.")
54
+ mention_passages: int = Field(..., description="3-minute caption passages that say it.")
55
+ passages_per_meeting: float | None
56
+ comments: int = Field(..., description="Data-center public comments segmented in those meetings.")
57
+
58
+
59
+ class CommentMetricsResponse(BaseModel):
60
+ year: str | None = Field(None, description="Calendar year filter as a string; null for all years.")
61
+ scope: JobClaimScope
62
+ comments: int
63
+ governments: int
64
+ meetings: int
65
+ meetings_segmented: int = Field(..., description="Meetings in scope with any segmented comment (all topics).")
66
+ meetings_with_no_supporters: int | None = None
67
+ no_supporters_reason: str = STANCE_REASON
68
+ positions: dict[str, int] | None = None
69
+ positions_reason: str = STANCE_REASON
70
+ concerns: list[CountItem]
71
+ multi_concern_share: float | None = Field(
72
+ None, description="Share of comments raising 2+ concerns on the reference list."
73
+ )
74
+ companies: list[CountItem]
75
+ people: list[CountItem]
76
+ ai_mentions: CountItem | None
77
+ roles: list[CountItem]
78
+ places: list[CountItem] = Field(default_factory=list, description="Place kinds named (roads, schools, ...).")
79
+ mentions_per_meeting_by_quarter: list[QuarterItem] = Field(
80
+ ..., description="The trend since 2022-Q1 for the place scope; it ignores `year` on purpose (it is a trend)."
81
+ )
82
+ basis: str = BASIS
83
+
84
+
85
+ def _where(scope: JobClaimScope, year: int | None, alias: str = "") -> tuple[str, list[Any]]:
86
+ a = f"{alias}." if alias else ""
87
+ clauses: list[str] = []
88
+ params: list[Any] = []
89
+ if year is not None:
90
+ params.append(year)
91
+ n = len(params)
92
+ # A range on the date (not extract(year ...)) so the (state_code, meeting_date) index applies.
93
+ clauses.append(f"{a}meeting_date >= make_date(${n}, 1, 1) AND {a}meeting_date < make_date(${n} + 1, 1, 1)")
94
+ if scope.state_code:
95
+ params.append(scope.state_code)
96
+ clauses.append(f"{a}state_code = ${len(params)}")
97
+ if scope.city:
98
+ params.append(f"%{scope.city}%")
99
+ clauses.append(f"{a}jurisdiction_name ILIKE ${len(params)}")
100
+ if scope.jurisdiction_id:
101
+ params.append(scope.jurisdiction_id)
102
+ clauses.append(f"{a}jurisdiction_id = ${len(params)}")
103
+ return (" WHERE " + " AND ".join(clauses)) if clauses else "", params
104
+
105
+
106
+ def build_metric_queries(scope: JobClaimScope, year: int | None) -> dict[str, tuple[str, list[Any]]]:
107
+ """SQL per metric block. Every query reads only served relations."""
108
+ where, params = _where(scope, year)
109
+ where_d, params_d = _where(scope, year, "d")
110
+ totals = (
111
+ "SELECT count(*) AS comments, count(DISTINCT jurisdiction_id) AS governments, "
112
+ "count(DISTINCT video_id) AS meetings, "
113
+ "count(*) FILTER (WHERE reference_concern_count >= 2) AS multi_concern, "
114
+ "count(*) FILTER (WHERE mentions_ai) AS ai "
115
+ f"FROM data_center_comment{where}"
116
+ )
117
+ unnest_sql = (
118
+ "SELECT k AS key, count(*) AS n FROM data_center_comment, unnest({col}) AS k"
119
+ f"{where} GROUP BY k ORDER BY n DESC, k"
120
+ )
121
+ places = (
122
+ "SELECT p.place_kind AS key, count(DISTINCT p.data_center_comment_id) AS n "
123
+ "FROM data_center_comment_place p JOIN data_center_comment d "
124
+ f"ON d.data_center_comment_id = p.data_center_comment_id{where_d} GROUP BY 1 ORDER BY 2 DESC"
125
+ )
126
+ seg_where, seg_params = _where(scope, year)
127
+ segmented = f"SELECT count(*) AS n FROM segmented_meeting{seg_where}"
128
+ q_where, q_params = _where(scope, None)
129
+ q_extra = " AND " if q_where else " WHERE "
130
+ quarters = (
131
+ "WITH m AS (SELECT video_id, meeting_date FROM data_center_meeting_mention"
132
+ f"{q_where}{q_extra}meeting_date >= DATE '2022-01-01'), "
133
+ "q AS (SELECT to_char(meeting_date, 'YYYY') || '-Q' || extract(quarter FROM meeting_date)::int AS quarter, "
134
+ "count(DISTINCT video_id) AS meetings, count(*) AS passages FROM m GROUP BY 1), "
135
+ "c AS (SELECT to_char(meeting_date, 'YYYY') || '-Q' || extract(quarter FROM meeting_date)::int AS quarter, "
136
+ f"count(*) AS comments FROM data_center_comment{q_where}{q_extra}meeting_date >= DATE '2022-01-01' GROUP BY 1) "
137
+ "SELECT q.quarter, q.meetings, q.passages, coalesce(c.comments, 0) AS comments "
138
+ "FROM q LEFT JOIN c USING (quarter) ORDER BY q.quarter"
139
+ )
140
+ return {
141
+ "totals": (totals, params),
142
+ "concerns": (unnest_sql.format(col="concern_keys"), params),
143
+ "companies": (unnest_sql.format(col="company_keys"), params),
144
+ "people": (unnest_sql.format(col="person_keys"), params),
145
+ "roles": (unnest_sql.format(col="role_keys"), params),
146
+ "places": (places, params_d),
147
+ "segmented": (segmented, seg_params),
148
+ "quarters": (quarters, q_params),
149
+ }
150
+
151
+
152
+ # Labels mirror the dbt seeds (comment_concern_terms, comment_entity_terms, comment_role_terms);
153
+ # an unknown key falls back to the key itself, never to an invented label.
154
+ CONCERN_LABELS = {
155
+ "water_use": "Water use", "quality_of_life": "Quality of life", "lack_of_transparency": "Lack of transparency",
156
+ "company_distrust": "Company distrust", "rushed_review": "Rushed review",
157
+ "limited_community_benefit": "Limited community benefit", "few_jobs": "Few jobs",
158
+ "taxpayer_subsidies": "Taxpayer subsidies", "community_character": "Community character",
159
+ "farmland_wildlife_loss": "Farmland / wildlife loss", "property_rights": "Property rights",
160
+ "energy_costs_grid": "Electricity costs / grid",
161
+ }
162
+ ENTITY_LABELS = {
163
+ "google": "Google / Alphabet", "amazon": "Amazon / AWS", "meta": "Meta / Facebook", "microsoft": "Microsoft",
164
+ "openai": "OpenAI / ChatGPT", "xai": "xAI / Grok", "anthropic": "Anthropic / Claude", "nvidia": "Nvidia",
165
+ "oracle": "Oracle", "apple": "Apple", "tesla": "Tesla", "blackstone_qts": "Blackstone / QTS",
166
+ "coreweave": "CoreWeave", "elon_musk": "Elon Musk", "sam_altman": "Sam Altman", "peter_thiel": "Peter Thiel",
167
+ "mark_zuckerberg": "Mark Zuckerberg", "jeff_bezos": "Jeff Bezos", "bill_gates": "Bill Gates",
168
+ "kevin_oleary": "Kevin O'Leary", "jensen_huang": "Jensen Huang", "larry_ellison": "Larry Ellison",
169
+ "sundar_pichai": "Sundar Pichai", "satya_nadella": "Satya Nadella",
170
+ }
171
+ ROLE_LABELS = {
172
+ "resident": "Resident", "property_owner": "Property owner", "union_worker": "Union worker",
173
+ "business": "Business owner / chamber", "farmer": "Farmer", "advocacy_group": "Advocacy or community group",
174
+ "elected_official": "Elected official",
175
+ }
176
+ PLACE_LABELS = {
177
+ "road": "Roads and routes", "school": "Schools", "county": "Counties and townships",
178
+ "neighborhood": "Neighborhoods", "district": "Districts and wards", "site": "Named sites",
179
+ "jurisdiction": "Towns and cities", "project": "Tracked data center projects",
180
+ }
181
+
182
+
183
+ def _items(rows: list[Any], labels: dict[str, str], total: int) -> list[CountItem]:
184
+ return [
185
+ CountItem(
186
+ key=r["key"],
187
+ label=labels.get(r["key"], r["key"]),
188
+ count=int(r["n"]),
189
+ share=round(int(r["n"]) / total, 4) if total else None,
190
+ )
191
+ for r in rows
192
+ ]
193
+
194
+
195
+ def shape_response(
196
+ year: int | None, scope: JobClaimScope, results: dict[str, list[Any]]
197
+ ) -> CommentMetricsResponse:
198
+ t = results["totals"][0] if results["totals"] else {}
199
+ total = int(t.get("comments") or 0)
200
+ quarters = [
201
+ QuarterItem(
202
+ quarter=r["quarter"],
203
+ meetings_with_mention=int(r["meetings"]),
204
+ mention_passages=int(r["passages"]),
205
+ passages_per_meeting=round(int(r["passages"]) / int(r["meetings"]), 2) if r["meetings"] else None,
206
+ comments=int(r["comments"]),
207
+ )
208
+ for r in results["quarters"]
209
+ ]
210
+ return CommentMetricsResponse(
211
+ year=str(year) if year is not None else None,
212
+ scope=scope,
213
+ comments=total,
214
+ governments=int(t.get("governments") or 0),
215
+ meetings=int(t.get("meetings") or 0),
216
+ meetings_segmented=int(results["segmented"][0]["n"]) if results["segmented"] else 0,
217
+ concerns=_items(results["concerns"], CONCERN_LABELS, total),
218
+ multi_concern_share=round(int(t["multi_concern"]) / total, 4) if total else None,
219
+ companies=_items(results["companies"], ENTITY_LABELS, total),
220
+ people=_items(results["people"], ENTITY_LABELS, total),
221
+ ai_mentions=(
222
+ CountItem(key="ai", label="Any mention of AI", count=int(t["ai"]), share=round(int(t["ai"]) / total, 4))
223
+ if total
224
+ else None
225
+ ),
226
+ roles=_items(results["roles"], ROLE_LABELS, total),
227
+ places=_items(results["places"], PLACE_LABELS, total),
228
+ mentions_per_meeting_by_quarter=quarters,
229
+ )
230
+
231
+
232
+ @router.get("/comment-metrics", response_model=CommentMetricsResponse)
233
+ async def data_center_comment_metrics(
234
+ year: int = Query(2026, ge=0, le=2100, description="Meeting year (default 2026); 0 for all years."),
235
+ state: str | None = Query(None, description="2-letter code or full state name."),
236
+ city: str | None = Query(None, description="City / jurisdiction name (substring)."),
237
+ jurisdiction_id: str | None = Query(None),
238
+ ) -> CommentMetricsResponse:
239
+ scope = build_scope(state, city, jurisdiction_id)
240
+ year_filter = year or None
241
+ queries = build_metric_queries(scope, year_filter)
242
+ with tracer.start_as_current_span("data_center_comment_metrics") as span:
243
+ span.set_attribute("scope.level", scope.level)
244
+ pool = await get_db_pool()
245
+ results: dict[str, list[Any]] = {}
246
+ try:
247
+ async with pool.acquire() as conn:
248
+ for name, (sql, params) in queries.items():
249
+ results[name] = [dict(r) for r in await conn.fetch(sql, *params)]
250
+ except asyncpg.UndefinedTableError as exc:
251
+ # The marts are new; before the first dbt build there is nothing to count.
252
+ logger.warning("comment-metrics: {}", exc)
253
+ raise HTTPException(status_code=503, detail="Comment-level data isn't built yet.") from exc
254
+ return shape_response(year_filter, scope, results)
api/routes/data_center_drill.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The records behind each "Who spoke up" number on the data center story (#1288).
2
+
3
+ Each list endpoint here returns the rows one story KPI counts, with the same filter the KPI's own
4
+ endpoint uses, so the list's total equals the number on the tile:
5
+
6
+ * ``GET /api/data-centers/speakers?side=for|against|question`` — the counted public speakers behind
7
+ "spoke for / against / asked a question" (``/positions`` sums ``data_center_meeting_position``,
8
+ whose per-meeting counts are these ``data_center_public_comment`` rows).
9
+ * ``GET /api/data-centers/vote-decisions?side=for|against`` — the decisions with a recorded tally behind
10
+ "votes for / against"; ``total_votes`` is the tile (a sum of votes), ``total_decisions`` the rows.
11
+ * ``GET /api/data-centers/comments`` — the caption-segmented public comments behind the
12
+ ``/comment-metrics`` counts (all, ``ai=true``, or ``company=<key>``). The mart carries no comment text
13
+ (privacy by construction, #1233), so these rows link to the moment in the recording instead of quoting.
14
+
15
+ Every row is a real row of a ``public`` mart; nothing is invented or defaulted (CLAUDE.md, No Fabricated
16
+ Data). Residents appear only as the mart's "First L." (``speaker_display_name``); a comment flagged as a
17
+ possible minor is listed (so the count still adds up) with its name, link and keywords withheld (AGENTS.md,
18
+ Privacy). Each response echoes the applied scope so the list's label matches the data.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import re
24
+ from datetime import date
25
+ from typing import Any, Literal
26
+
27
+ import asyncpg
28
+ from fastapi import APIRouter, HTTPException, Query
29
+ from loguru import logger
30
+ from opentelemetry import trace
31
+ from pydantic import BaseModel, Field
32
+
33
+ from api.routes.data_center_comments import _where as comment_where
34
+ from api.routes.data_centers import JobClaimScope, build_scope, jump_url
35
+ from api.routes.search_postgres import get_db_pool
36
+
37
+ router = APIRouter(prefix="/data-centers", tags=["data-centers"])
38
+ tracer = trace.get_tracer(__name__)
39
+
40
+ PAGE_DEFAULT = 25
41
+ PAGE_MAX = 100
42
+
43
+ # The dbt macro data_center_regex() in Python, to mark the data center words inside a verbatim quote.
44
+ DATA_CENTER_RE = re.compile(r"\b(data[ -]?cent(?:er|re)s?|datacent(?:er|re)s?|hyperscal(?:e|er|ers)?)\b", re.IGNORECASE)
45
+
46
+ WITHHELD_MINOR = "The speaker may be a minor, so the name, the link and the keywords are withheld."
47
+ NO_TEXT_NOTE = (
48
+ "Comments segmented from our captions are stored without their words (privacy by construction, #1233): "
49
+ "each one links to its moment in the recording instead of being quoted."
50
+ )
51
+
52
+
53
+ def mark_terms(quote: str | None) -> str | None:
54
+ """The quote with each data center word wrapped in <mark> (for highlightSnippet); any <mark> already in the
55
+ text is removed first so only our marks remain. The words themselves are unchanged."""
56
+ if quote is None:
57
+ return None
58
+ clean = re.sub(r"</?mark>", "", quote)
59
+ return DATA_CENTER_RE.sub(lambda m: f"<mark>{m.group(0)}</mark>", clean)
60
+
61
+
62
+ def applied_scope(state: str | None, city: str | None) -> JobClaimScope:
63
+ """The scope ``/positions`` and ``/decisions`` apply: state, then city as a jurisdiction-name substring."""
64
+ s = build_scope(state, city, None)
65
+ return JobClaimScope(
66
+ level="city" if s.city else ("state" if s.state_code else "national"),
67
+ state_code=s.state_code,
68
+ state=s.state,
69
+ city=s.city,
70
+ )
71
+
72
+
73
+ def position_where(scope: JobClaimScope, params: list[Any]) -> str:
74
+ """The ``/positions`` totals filter, on the joined ``data_center_meeting_position p``."""
75
+ where: list[str] = []
76
+ if scope.state_code:
77
+ params.append(scope.state_code)
78
+ where.append(f"p.state_code = ${len(params)}")
79
+ if scope.city:
80
+ params.append(f"%{scope.city}%")
81
+ where.append(f"p.jurisdiction_name ILIKE ${len(params)}")
82
+ return " AND ".join(where) or "TRUE"
83
+
84
+
85
+ # --- speakers -----------------------------------------------------------------------------------------------------
86
+
87
+
88
+ class Speaker(BaseModel):
89
+ public_comment_id: str
90
+ quote: str | None = Field(None, description="The speaker's own words, verbatim from the transcript.")
91
+ quote_highlighted: str | None = Field(None, description="The same words with data center terms in <mark>.")
92
+ speaker_display_name: str | None = Field(None, description='"First L."; null when no name was heard.')
93
+ speaker_role: str | None = None
94
+ match_basis: str | None = Field(
95
+ None, description="Why it counts: data_center_decision, data_center_item, own_words or same_item."
96
+ )
97
+ decision_headline: str | None = Field(None, description="The item the comment is on, when there is one.")
98
+ event_decision_id: str | None = None
99
+ jurisdiction_name: str | None = None
100
+ state_code: str | None = None
101
+ meeting_date: date | None = None
102
+ video_url: str | None = None
103
+ start_seconds: float | None = None
104
+ jump_url: str | None = None
105
+
106
+
107
+ class SpeakersResponse(BaseModel):
108
+ scope: JobClaimScope
109
+ side: Literal["for", "against", "question"]
110
+ available: bool = True
111
+ total: int | None = Field(None, description="Every counted speaker on this side in scope (the tile's number).")
112
+ limit: int
113
+ offset: int
114
+ items: list[Speaker] = Field(default_factory=list)
115
+
116
+
117
+ def build_speaker_queries(
118
+ scope: JobClaimScope, side: str, limit: int, offset: int
119
+ ) -> tuple[str, list[Any], str, list[Any]]:
120
+ """(count SQL, params, page SQL, params). The rows the ``data_center_meeting_position`` speaker counts are made
121
+ of: counted comments on the side, scoped on their meeting's position row exactly as ``/positions`` scopes."""
122
+ params: list[Any] = [side]
123
+ where = position_where(scope, params)
124
+ base = (
125
+ "FROM data_center_public_comment c "
126
+ "JOIN data_center_meeting_position p ON p.data_center_meeting_position_id = c.data_center_meeting_position_id "
127
+ f"WHERE c.is_counted AND c.stance_bucket = $1 AND {where}"
128
+ )
129
+ count_sql = f"SELECT count(*)::int AS n {base}"
130
+ page_params = [*params, limit, offset]
131
+ page_sql = (
132
+ "SELECT c.public_comment_id, c.quote, c.speaker_display_name, c.speaker_role, c.match_basis, "
133
+ "c.decision_headline, c.event_decision_id, p.jurisdiction_name, p.state_code, "
134
+ "coalesce(c.meeting_date, p.meeting_date) AS meeting_date, c.video_url, c.start_seconds::float8 AS start_seconds "
135
+ f"{base} "
136
+ "ORDER BY coalesce(c.meeting_date, p.meeting_date) DESC NULLS LAST, c.event_meeting_id, "
137
+ "c.start_seconds NULLS LAST, c.public_comment_id "
138
+ f"LIMIT ${len(page_params) - 1} OFFSET ${len(page_params)}"
139
+ )
140
+ return count_sql, params, page_sql, page_params
141
+
142
+
143
+ @router.get("/speakers", response_model=SpeakersResponse)
144
+ async def data_center_speakers(
145
+ side: Literal["for", "against", "question"] = Query(..., description="The tile: for, against or question."),
146
+ state: str | None = Query(None, description="2-letter state code (a full name is normalized)."),
147
+ city: str | None = Query(None, description="City; case-insensitive substring of the jurisdiction name."),
148
+ limit: int = Query(PAGE_DEFAULT, ge=1, le=PAGE_MAX),
149
+ offset: int = Query(0, ge=0),
150
+ ) -> SpeakersResponse:
151
+ """
152
+ The public speakers behind "spoke for", "spoke against" or "asked a question" on the story's "Who spoke up"
153
+ screen, each with their own words and the moment in the recording. ``total`` equals the tile.
154
+
155
+ Example:
156
+ GET /api/data-centers/speakers?side=against&state=AZ
157
+ """
158
+ scope = applied_scope(state, city)
159
+ count_sql, params, page_sql, page_params = build_speaker_queries(scope, side, limit, offset)
160
+ with tracer.start_as_current_span("data-centers.speakers") as span:
161
+ span.set_attribute("drill.side", side)
162
+ span.set_attribute("drill.scope_level", scope.level)
163
+ try:
164
+ pool = await get_db_pool()
165
+ async with pool.acquire() as conn:
166
+ count_rows = await conn.fetch(count_sql, *params)
167
+ rows = await conn.fetch(page_sql, *page_params)
168
+ except asyncpg.exceptions.UndefinedTableError as e:
169
+ logger.warning("data-centers speakers: mart not loaded ({})", e)
170
+ return SpeakersResponse(scope=scope, side=side, available=False, limit=limit, offset=offset)
171
+ except Exception as e: # noqa: BLE001
172
+ span.record_exception(e)
173
+ logger.error("data-centers speakers error (scope={}): {}", scope.model_dump(), e)
174
+ raise HTTPException(status_code=500, detail="Failed to load the speakers")
175
+ items: list[Speaker] = []
176
+ for r in rows:
177
+ row = dict(r)
178
+ row["quote_highlighted"] = mark_terms(row.get("quote"))
179
+ row["jump_url"] = jump_url(row["video_url"], row.get("start_seconds")) if row.get("video_url") else None
180
+ items.append(Speaker(**row))
181
+ total = int(count_rows[0]["n"]) if count_rows else 0
182
+ span.set_attribute("drill.total", total)
183
+ return SpeakersResponse(scope=scope, side=side, total=total, limit=limit, offset=offset, items=items)
184
+
185
+
186
+ # --- votes --------------------------------------------------------------------------------------------------------
187
+
188
+
189
+ class VoteDecision(BaseModel):
190
+ data_center_decision_id: str
191
+ headline: str | None = None
192
+ outcome: str | None = None
193
+ votes_for: int
194
+ votes_against: int
195
+ meeting_date: date | None = None
196
+ jurisdiction_name: str | None = None
197
+ state_code: str | None = None
198
+ video_url: str | None = None
199
+ decision_url: str | None = Field(None, description="Site path of the decision's page (/decisions/:id).")
200
+
201
+
202
+ class VoteDecisionsResponse(BaseModel):
203
+ scope: JobClaimScope
204
+ side: Literal["for", "against"]
205
+ available: bool = True
206
+ total_decisions: int | None = Field(None, description="Decisions with a recorded tally and a vote on this side.")
207
+ total_votes: int | None = Field(None, description="Their votes on this side summed: the tile's number.")
208
+ limit: int
209
+ offset: int
210
+ items: list[VoteDecision] = Field(default_factory=list)
211
+
212
+
213
+ def build_vote_queries(
214
+ scope: JobClaimScope, side: str, limit: int, offset: int
215
+ ) -> tuple[str, list[Any], str, list[Any]]:
216
+ """(totals SQL, params, page SQL, params). ``data_center_meeting_position`` sums the tallies of the meeting's data
217
+ center decisions where both sides parse; ``data_center_decision`` carries votes_for / votes_against only for
218
+ those. Decisions with 0 votes on the side add nothing to the tile and are left out of its list."""
219
+ col = "votes_for" if side == "for" else "votes_against"
220
+ params: list[Any] = []
221
+ where = position_where(scope, params)
222
+ base = (
223
+ "FROM data_center_decision d "
224
+ "JOIN data_center_meeting_position p ON p.event_meeting_id = d.event_meeting_id "
225
+ f"WHERE d.votes_for IS NOT NULL AND d.votes_against IS NOT NULL AND d.{col} > 0 AND {where}"
226
+ )
227
+ totals_sql = f"SELECT count(*)::int AS decisions, coalesce(sum(d.{col}), 0)::int AS votes {base}"
228
+ page_params = [*params, limit, offset]
229
+ page_sql = (
230
+ "SELECT d.data_center_decision_id, d.headline, d.outcome, d.votes_for, d.votes_against, d.meeting_date, "
231
+ "p.jurisdiction_name, p.state_code, d.video_url, d.decision_url "
232
+ f"{base} ORDER BY d.meeting_date DESC NULLS LAST, d.data_center_decision_id "
233
+ f"LIMIT ${len(page_params) - 1} OFFSET ${len(page_params)}"
234
+ )
235
+ return totals_sql, params, page_sql, page_params
236
+
237
+
238
+ @router.get("/vote-decisions", response_model=VoteDecisionsResponse)
239
+ async def data_center_vote_decisions(
240
+ side: Literal["for", "against"] = Query(..., description="The tile: for or against."),
241
+ state: str | None = Query(None, description="2-letter state code (a full name is normalized)."),
242
+ city: str | None = Query(None, description="City; case-insensitive substring of the jurisdiction name."),
243
+ limit: int = Query(PAGE_DEFAULT, ge=1, le=PAGE_MAX),
244
+ offset: int = Query(0, ge=0),
245
+ ) -> VoteDecisionsResponse:
246
+ """
247
+ The decisions behind "votes for" or "votes against": each data center decision with a recorded tally and at
248
+ least one vote on that side, newest first. ``total_votes`` equals the tile.
249
+
250
+ Example:
251
+ GET /api/data-centers/vote-decisions?side=for&state=AL
252
+ """
253
+ scope = applied_scope(state, city)
254
+ totals_sql, params, page_sql, page_params = build_vote_queries(scope, side, limit, offset)
255
+ with tracer.start_as_current_span("data-centers.vote-decisions") as span:
256
+ span.set_attribute("drill.side", side)
257
+ span.set_attribute("drill.scope_level", scope.level)
258
+ try:
259
+ pool = await get_db_pool()
260
+ async with pool.acquire() as conn:
261
+ totals = await conn.fetch(totals_sql, *params)
262
+ rows = await conn.fetch(page_sql, *page_params)
263
+ except asyncpg.exceptions.UndefinedTableError as e:
264
+ logger.warning("data-centers vote-decisions: mart not loaded ({})", e)
265
+ return VoteDecisionsResponse(scope=scope, side=side, available=False, limit=limit, offset=offset)
266
+ except Exception as e: # noqa: BLE001
267
+ span.record_exception(e)
268
+ logger.error("data-centers vote-decisions error (scope={}): {}", scope.model_dump(), e)
269
+ raise HTTPException(status_code=500, detail="Failed to load the decisions")
270
+ t = dict(totals[0]) if totals else {"decisions": 0, "votes": 0}
271
+ return VoteDecisionsResponse(
272
+ scope=scope,
273
+ side=side,
274
+ total_decisions=int(t["decisions"]),
275
+ total_votes=int(t["votes"]),
276
+ limit=limit,
277
+ offset=offset,
278
+ items=[VoteDecision(**dict(r)) for r in rows],
279
+ )
280
+
281
+
282
+ # --- caption comments ---------------------------------------------------------------------------------------------
283
+
284
+
285
+ class CaptionComment(BaseModel):
286
+ data_center_comment_id: str
287
+ speaker_display_name: str | None = Field(None, description='"First L."; null when unknown or withheld.')
288
+ possible_minor: bool = False
289
+ withheld_reason: str | None = None
290
+ jurisdiction_name: str | None = None
291
+ state_code: str | None = None
292
+ meeting_date: date | None = None
293
+ start_seconds: float | None = None
294
+ jump_url: str | None = Field(None, description="The recording at the comment's start; null for a possible minor.")
295
+ concern_keys: list[str] = Field(default_factory=list)
296
+ company_keys: list[str] = Field(default_factory=list)
297
+ mentions_ai: bool | None = None
298
+
299
+
300
+ class CaptionCommentsResponse(BaseModel):
301
+ scope: JobClaimScope
302
+ year: str | None = Field(None, description="Calendar year filter as a string; null for all years.")
303
+ filter: Literal["all", "ai", "company"] = "all"
304
+ company: str | None = None
305
+ available: bool = True
306
+ total: int | None = Field(None, description="Every comment matching the filter in scope (the tile's number).")
307
+ limit: int
308
+ offset: int
309
+ note: str = NO_TEXT_NOTE
310
+ items: list[CaptionComment] = Field(default_factory=list)
311
+
312
+
313
+ def build_comment_queries(
314
+ scope: JobClaimScope, year: int | None, ai: bool, company: str | None, limit: int, offset: int
315
+ ) -> tuple[str, list[Any], str, list[Any]]:
316
+ """(count SQL, params, page SQL, params) over ``data_center_comment`` with ``/comment-metrics``' own filter (its
317
+ ``_where``), plus ``mentions_ai`` or the company key when the tile is one of those."""
318
+ where, params = comment_where(scope, year)
319
+ extra: list[str] = []
320
+ if ai:
321
+ extra.append("mentions_ai")
322
+ if company:
323
+ params = [*params, company]
324
+ extra.append(f"${len(params)} = ANY(company_keys)")
325
+ if extra:
326
+ where = f"{where} AND {' AND '.join(extra)}" if where else f" WHERE {' AND '.join(extra)}"
327
+ count_sql = f"SELECT count(*)::int AS n FROM data_center_comment{where}"
328
+ page_params = [*params, limit, offset]
329
+ page_sql = (
330
+ "SELECT data_center_comment_id, speaker_display_name, coalesce(possible_minor, false) AS possible_minor, "
331
+ "jurisdiction_name, state_code, meeting_date, start_seconds::float8 AS start_seconds, video_id, "
332
+ "coalesce(concern_keys, '{}') AS concern_keys, coalesce(company_keys, '{}') AS company_keys, mentions_ai "
333
+ f"FROM data_center_comment{where} "
334
+ "ORDER BY meeting_date DESC NULLS LAST, jurisdiction_name, video_id, start_seconds NULLS LAST, data_center_comment_id "
335
+ f"LIMIT ${len(page_params) - 1} OFFSET ${len(page_params)}"
336
+ )
337
+ return count_sql, params, page_sql, page_params
338
+
339
+
340
+ def shape_comment(row: dict[str, Any]) -> CaptionComment:
341
+ video_id = row.pop("video_id", None)
342
+ if row.get("possible_minor"):
343
+ return CaptionComment(
344
+ data_center_comment_id=row["data_center_comment_id"],
345
+ possible_minor=True,
346
+ withheld_reason=WITHHELD_MINOR,
347
+ jurisdiction_name=row.get("jurisdiction_name"),
348
+ state_code=row.get("state_code"),
349
+ meeting_date=row.get("meeting_date"),
350
+ )
351
+ url = f"https://www.youtube.com/watch?v={video_id}" if video_id else None
352
+ row["jump_url"] = jump_url(url, row.get("start_seconds")) if url else None
353
+ return CaptionComment(**row)
354
+
355
+
356
+ @router.get("/comments", response_model=CaptionCommentsResponse)
357
+ async def data_center_caption_comments(
358
+ year: int = Query(2026, ge=0, le=2100, description="Meeting year (default 2026); 0 for all years."),
359
+ state: str | None = Query(None, description="2-letter code or full state name."),
360
+ city: str | None = Query(None, description="City / jurisdiction name (substring)."),
361
+ ai: bool = Query(False, description="Only comments that mention AI (the 'Mention AI' tile)."),
362
+ company: str | None = Query(None, max_length=64, description="Only comments naming this company key."),
363
+ limit: int = Query(PAGE_DEFAULT, ge=1, le=PAGE_MAX),
364
+ offset: int = Query(0, ge=0),
365
+ ) -> CaptionCommentsResponse:
366
+ """
367
+ The public comments behind the caption counts under "Who spoke up" ("60 public comments", "Mention AI",
368
+ "Name Google"): each comment's place, date, speaker ("First L." when known) and the link to its moment in
369
+ the recording. ``total`` equals the tile. No comment text is served (see ``note``).
370
+
371
+ Example:
372
+ GET /api/data-centers/comments?year=2026&state=AL
373
+ """
374
+ scope = build_scope(state, city, None)
375
+ year_filter = year or None
376
+ company_key = company.strip() if company and company.strip() else None
377
+ count_sql, params, page_sql, page_params = build_comment_queries(
378
+ scope, year_filter, ai, company_key, limit, offset
379
+ )
380
+ flt: Literal["all", "ai", "company"] = "ai" if ai else ("company" if company_key else "all")
381
+ with tracer.start_as_current_span("data-centers.comments") as span:
382
+ span.set_attribute("drill.filter", flt)
383
+ span.set_attribute("drill.scope_level", scope.level)
384
+ try:
385
+ pool = await get_db_pool()
386
+ async with pool.acquire() as conn:
387
+ count_rows = await conn.fetch(count_sql, *params)
388
+ rows = await conn.fetch(page_sql, *page_params)
389
+ except asyncpg.exceptions.UndefinedTableError as e:
390
+ logger.warning("data-centers comments: mart not loaded ({})", e)
391
+ return CaptionCommentsResponse(
392
+ scope=scope, year=str(year_filter) if year_filter else None, filter=flt, company=company_key,
393
+ available=False, limit=limit, offset=offset,
394
+ )
395
+ except Exception as e: # noqa: BLE001
396
+ span.record_exception(e)
397
+ logger.error("data-centers comments error (scope={}): {}", scope.model_dump(), e)
398
+ raise HTTPException(status_code=500, detail="Failed to load the comments")
399
+ return CaptionCommentsResponse(
400
+ scope=scope,
401
+ year=str(year_filter) if year_filter else None,
402
+ filter=flt,
403
+ company=company_key,
404
+ total=int(count_rows[0]["n"]) if count_rows else 0,
405
+ limit=limit,
406
+ offset=offset,
407
+ items=[shape_comment(dict(r)) for r in rows],
408
+ )
api/routes/data_centers.py ADDED
The diff for this file is too large to render. See raw diff
 
api/routes/data_deletion.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Data deletion endpoints for OAuth provider compliance (Facebook, etc.)
3
+ """
4
+ import base64
5
+ import hashlib
6
+ import hmac
7
+ import json
8
+ import os
9
+ import re
10
+ from datetime import datetime, timezone
11
+ from typing import Optional
12
+ from urllib.parse import urlencode
13
+
14
+ from fastapi import APIRouter, Depends, HTTPException, Request
15
+ from loguru import logger
16
+ from pydantic import BaseModel
17
+ from sqlalchemy.orm import Session
18
+
19
+ from api.database import get_db
20
+ from api.models import User
21
+
22
+ router = APIRouter()
23
+
24
+ _SAFE_USER_ID_RE = re.compile(r"^[A-Za-z0-9._-]{1,128}$")
25
+
26
+
27
+ class DataDeletionRequest(BaseModel):
28
+ """Data deletion request from OAuth provider"""
29
+ signed_request: str # Facebook's signed request
30
+
31
+
32
+ class DataDeletionResponse(BaseModel):
33
+ """Response to data deletion request"""
34
+ url: str
35
+ confirmation_code: str
36
+
37
+
38
+ def _b64url_decode(segment: str) -> bytes:
39
+ cleaned = (segment or "").strip()
40
+ if not cleaned:
41
+ raise ValueError("Empty base64url segment")
42
+ padding = "=" * (-len(cleaned) % 4)
43
+ return base64.urlsafe_b64decode(cleaned + padding)
44
+
45
+
46
+ def parse_signed_request(signed_request: str, app_secret: str) -> dict:
47
+ """
48
+ Parse and validate Facebook's signed_request parameter.
49
+
50
+ Format: base64url(signature).base64url(payload)
51
+ Uses constant-time HMAC comparison and verifies HMAC-SHA256 algorithm header.
52
+ """
53
+ try:
54
+ if not signed_request or "." not in signed_request or not app_secret:
55
+ raise ValueError("Malformed signed_request or empty secret")
56
+
57
+ encoded_sig, payload = signed_request.split(".", 1)
58
+ sig = _b64url_decode(encoded_sig)
59
+ raw_payload = _b64url_decode(payload)
60
+ data = json.loads(raw_payload.decode("utf-8"))
61
+ if not isinstance(data, dict):
62
+ raise ValueError("Signed request payload must be a JSON object")
63
+
64
+ algorithm = data.get("algorithm")
65
+ if algorithm is None or str(algorithm).upper() != "HMAC-SHA256":
66
+ raise ValueError(f"Unsupported signed_request algorithm: {algorithm}")
67
+
68
+ expected_sig = hmac.new(
69
+ app_secret.encode("utf-8"),
70
+ msg=payload.encode("utf-8"),
71
+ digestmod=hashlib.sha256,
72
+ ).digest()
73
+
74
+ if not hmac.compare_digest(sig, expected_sig):
75
+ raise ValueError("Invalid signature")
76
+
77
+ return data
78
+ except Exception as e:
79
+ logger.error(f"Error parsing signed_request: {e}")
80
+ raise HTTPException(status_code=400, detail="Invalid signed request") from e
81
+
82
+
83
+ async def _extract_signed_request(request: Request) -> Optional[str]:
84
+ content_type = (request.headers.get("content-type") or "").lower()
85
+ if "application/json" in content_type:
86
+ try:
87
+ body = await request.json()
88
+ if isinstance(body, dict):
89
+ parsed = DataDeletionRequest(**body)
90
+ return parsed.signed_request
91
+ except Exception:
92
+ return None
93
+ try:
94
+ form = await request.form()
95
+ val = form.get("signed_request")
96
+ return str(val) if val is not None else None
97
+ except Exception:
98
+ return None
99
+
100
+
101
+ @router.post("/data-deletion/facebook", response_model=DataDeletionResponse)
102
+ async def facebook_data_deletion_callback(
103
+ request: Request,
104
+ db: Session = Depends(get_db),
105
+ ):
106
+ """
107
+ Facebook Data Deletion Request Callback
108
+
109
+ Facebook requires apps to provide a data deletion callback URL.
110
+ This endpoint receives deletion requests and processes them.
111
+
112
+ Docs: https://developers.facebook.com/docs/development/create-an-app/app-dashboard/data-deletion-callback
113
+ """
114
+ signed_request = await _extract_signed_request(request)
115
+ if not signed_request or not signed_request.strip():
116
+ raise HTTPException(status_code=400, detail="Missing signed_request")
117
+
118
+ app_secret = os.getenv("FACEBOOK_APP_SECRET")
119
+ if not app_secret:
120
+ logger.error("FACEBOOK_APP_SECRET not configured")
121
+ raise HTTPException(status_code=500, detail="Server configuration error")
122
+
123
+ data = parse_signed_request(signed_request.strip(), app_secret)
124
+ raw_user_id = data.get("user_id")
125
+ user_id = str(raw_user_id).strip() if raw_user_id is not None else ""
126
+
127
+ if not user_id or not _SAFE_USER_ID_RE.match(user_id):
128
+ raise HTTPException(status_code=400, detail="Missing or invalid user_id in signed request")
129
+
130
+ logger.info(f"Data deletion request from Facebook user: {user_id}")
131
+
132
+ user = db.query(User).filter(
133
+ User.oauth_provider == "facebook",
134
+ User.oauth_id == user_id,
135
+ ).first()
136
+
137
+ if user:
138
+ try:
139
+ # Never log the email: this request exists to erase it (#448).
140
+ logger.info(
141
+ "Deleting user account: user_id={} (Facebook ID: {})",
142
+ getattr(user, "user_id", None),
143
+ user_id,
144
+ )
145
+ db.delete(user)
146
+ db.commit()
147
+ deletion_status = "deleted"
148
+ except Exception as exc:
149
+ db.rollback()
150
+ # Exception text can echo row values (bound parameters), so log only its type.
151
+ logger.error(
152
+ "Database error deleting Facebook user {}: {}", user_id, type(exc).__name__
153
+ )
154
+ raise HTTPException(status_code=500, detail="Failed to process data deletion") from exc
155
+ else:
156
+ logger.info(f"No user found for Facebook ID: {user_id}")
157
+ deletion_status = "not_found"
158
+
159
+ now_utc = datetime.now(timezone.utc)
160
+ confirmation_code = f"DEL-{user_id}-{int(now_utc.timestamp())}"
161
+
162
+ base_url = os.getenv("FRONTEND_URL", "https://www.communityone.com").rstrip("/")
163
+ query_str = urlencode({"code": confirmation_code, "status": deletion_status})
164
+ status_url = f"{base_url}/data-deletion-status?{query_str}"
165
+
166
+ logger.info(f"Data deletion request processed: {confirmation_code}")
167
+
168
+ return DataDeletionResponse(
169
+ url=status_url,
170
+ confirmation_code=confirmation_code,
171
+ )
172
+
173
+
174
+ @router.get("/data-deletion/status")
175
+ async def data_deletion_status(code: str = None, status: str = None):
176
+ """
177
+ Data deletion status page (informational)
178
+
179
+ Users are redirected here after Facebook processes their deletion request.
180
+ """
181
+ return {
182
+ "confirmation_code": code,
183
+ "status": status,
184
+ "message": "Your data deletion request has been processed." if status == "deleted" else "No account found.",
185
+ "timestamp": datetime.now(timezone.utc).isoformat(),
186
+ }