Spaces:
Running on T4
Download backend/README.md from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 8.34 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/README.md
- Command line
-
hf download hf://spaces/modventures/baseball-engine/backend/README.md
-
curl -L -o README.md https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/README.md
Cognivision Baseball backend
This is the FastAPI backend for the Cognivision Baseball app. It covers accounts, teams, media, sessions and drills, the coach loop, billing, and the AI coach swing report.
- Design: DESIGN.md
- Rules for contributors: CONTRIBUTING.md
- Swing report output: ../AI-coach-agent/docs/SWING_REPORT_API.md
Setup
Requirements: Python 3.11, and Docker for the local test Postgres.
cd backend
python3.11 -m venv .venv
.venv/bin/pip install -e ".[dev]" -e ../AI-coach-agent
cp .env.example .env # then fill in DATABASE_URL, JWT_SECRET, STORAGE_*, GOOGLE_API_KEY
Run
.venv/bin/alembic upgrade head # create or upgrade the schema
.venv/bin/uvicorn app.main:app --reload # API on http://localhost:8000, docs at /docs (not in prod)
.venv/bin/python -m app.jobs.cleanup # schedule this hourly (uploads, abandoned sessions, media)
Test
docker run -d --name cognivision-backend-pg -e POSTGRES_USER=app -e POSTGRES_PASSWORD=app \
-e POSTGRES_DB=app_test -p 55440:5432 postgres:16-alpine
TEST_DATABASE_NAME=app_test .venv/bin/python -m pytest
.venv/bin/ruff check app tests
- Each run creates a fresh database named by
TEST_DATABASE_NAMEand migrates it with Alembic. - S3 is simulated in-process with moto.
- Gemini is not called: the AI coach falls back to its rule-based text.
Environment
| Variable | Purpose |
|---|---|
ENV |
dev, test or prod. prod hides /docs. |
DATABASE_URL |
postgresql+asyncpg://user:password@host/db (Neon or Supabase) |
JWT_SECRET |
Long random secret for access tokens |
STORAGE_ENDPOINT, STORAGE_REGION, STORAGE_BUCKET, STORAGE_KEY, STORAGE_SECRET |
DigitalOcean Spaces bucket and access keys |
GOOGLE_API_KEY |
Gemini key for the coach text. Without it, rule-based text is used. |
RESEND_API_KEY, EMAIL_FROM, PASSWORD_RESET_URL |
Password reset email (milestone 4) |
FCM_PROJECT_ID, FCM_SERVICE_ACCOUNT_FILE |
Push notifications (milestone 3) |
APPLE_CLIENT_IDS, GOOGLE_CLIENT_IDS |
Social sign-in audiences (JSON lists) |
APPLE_BUNDLE_ID, APPLE_ENVIRONMENT, GOOGLE_PACKAGE_NAME, GOOGLE_SERVICE_ACCOUNT_FILE, GOOGLE_PUBSUB_AUDIENCE, PRO_PRODUCT_IDS |
Billing (milestone 4) |
Docker
docker build -f backend/Dockerfile -t cognivision-backend . # from the repository root
docker run --env-file backend/.env cognivision-backend alembic upgrade head
docker run --env-file backend/.env -p 8000:8000 cognivision-backend
For Firebase on a Hugging Face Docker Space running this backend, set FCM_PROJECT_ID to your Firebase project ID
and FCM_SERVICE_ACCOUNT_FILE to /tmp/firebase-service-account.json in the Space's variables. Add the entire
service account JSON as a secret named FCM_SERVICE_ACCOUNT_JSON. At startup, the container writes that secret
to the configured path with owner-only permissions before starting the API. Keep the JSON out of Git and Docker
build arguments. Without the JSON secret, startup still supports an existing credentials file or disabled push.
The repository's root Dockerfile and existing Hugging Face deployment run the separate GPU analysis API;
this setup requires deploying backend/Dockerfile with Space app_port: 8000.
API request/response diagnostics
Apply alembic upgrade head before deploying this version. The api_request_logs
table records every HTTP call handled by this backend, including failed validation,
authentication failures, unknown routes, health checks, and repeated requests.
The separate GPU API and standalone coach API do not write to this backend table;
the ML payload forwarded to the swing-report endpoint is captured here in full
within the configured JSON size limit.
Each row includes the request ID (also returned as X-Request-Id), timestamp,
method, route/path, authenticated account ID when available, session/analysis ID
and revision, HTTP status, duration, error code/type, service build version,
selected headers, query parameters, and sanitized request/response JSON. For a
swing report this includes event times, measurement values and quality reasons,
benchmarks, scores, chosen focus/drill, provider/fallback metadata, and generated
coaching text. The logger does not change measurement or scoring logic.
request_payload and response_payload contain capture_status,
observed_bytes, and body. JSON bodies up to API_AUDIT_MAX_BODY_BYTES (default
1 MiB per direction) are captured. Larger bodies are marked truncated and their
body is omitted, never stored as an invalid partial JSON document. Malformed JSON,
binary/media bodies, and unread/incomplete streams are explicitly marked. Video
bytes are never buffered for logging. Passwords, tokens, authorization, cookies,
receipts, webhook encoded data, emails, phone numbers, and URLs are redacted;
athlete measurements and report text remain diagnostic data. Restrict database
access to these records; audit browsing is restricted to explicitly allowlisted accounts.
Writes use their own transaction after handling the request, so application
rollbacks do not erase diagnostics. They are best-effort with a bounded timeout
(default two seconds): a database outage or full audit table does not replace the
API response. Such failures emit api_audit_write_failed with request ID and
exception class only. No database logger can guarantee a row during a database
outage or process termination. The hourly cleanup command removes records older
than API_AUDIT_RETENTION_DAYS (default 30). Set SERVICE_VERSION to the deployed
commit/build ID. API_AUDIT_ENABLED=false disables collection.
Find a reported analysis:
SELECT created_at, request_id, session_id, analysis_id, analysis_revision,
status_code, duration_ms, service_version,
request_payload->'body' AS input,
response_payload->'body' AS output
FROM api_request_logs
WHERE analysis_id = 'analysis_001'
ORDER BY created_at DESC;
Trace a request or recent failures:
SELECT * FROM api_request_logs WHERE request_id = 'request-id-from-response';
SELECT created_at, request_id, route, status_code, error_code, response_payload
FROM api_request_logs
WHERE status_code >= 400
ORDER BY created_at DESC LIMIT 100;
A repeated analysis revision can legitimately return an older stored report; the request log retains each submitted payload and the actual returned response so that difference can be investigated.
Read logs through the API
Set API_AUDIT_READER_ACCOUNT_IDS to a JSON array of trusted operator account UUIDs
and restart the backend. The default empty list denies access to everyone. Player
or coach status alone does not grant access. Use the operator's normal access JWT:
API_AUDIT_READER_ACCOUNT_IDS=["YOUR-OPERATOR-ACCOUNT-UUID"]
GET /v1/admin/api-logs: newest-first metadata, withitemsandnext_cursor. Filters:request_id,session_id,analysis_id,account_id,status_code,method(uppercase),route(exact route template),since, anduntil. Date filters apply tocreated_at, are timezone-aware, and use an inclusivesinceand exclusiveuntil.limitdefaults to 50, maximum 200. Passnext_cursorascursorwith the same filters to fetch another page.GET /v1/admin/api-logs/{log_id}: metadata plus saved sanitized request/response bodies, selected headers, and query parameters. Use the log row'sid, not itsrequest_id, for this URL.
curl "$API_BASE_URL/v1/admin/api-logs?analysis_id=analysis_001&limit=20" \
-H "Authorization: Bearer $ACCESS_TOKEN"
curl "$API_BASE_URL/v1/admin/api-logs/$LOG_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN"
Returns 401 without valid authentication, 403 without allowlist access, 400 for
invalid filters, and 404 for a missing/expired log ID. Successful responses use
Cache-Control: no-store. Lists omit payload columns; fetch individual records to
inspect bodies. Log reads are themselves audited, but their response bodies are
marked omitted_audit_read to avoid recursively duplicating saved payloads.
No additional database migration is needed beyond the original audit-log table.