Compare commits
7
Commits
ccb53d87a2
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4ac890432 | ||
|
|
56656be597 | ||
|
|
285add0b98 | ||
|
|
454e14b9fb | ||
|
|
0329d5f588 | ||
|
|
be72b5cbf3 | ||
|
|
6aafe3ff6f |
No files matched your search
@@ -0,0 +1,19 @@
|
|||||||
|
# PostgreSQL Database Configuration
|
||||||
|
POSTGRES_USER=postgres
|
||||||
|
POSTGRES_PASSWORD=postgres
|
||||||
|
POSTGRES_DB=novias_db
|
||||||
|
DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/novias_db
|
||||||
|
|
||||||
|
# PGAdmin Configuration
|
||||||
|
PGADMIN_EMAIL=admin@example.com
|
||||||
|
PGADMIN_PASSWORD=admin
|
||||||
|
|
||||||
|
# JWT & Authentication
|
||||||
|
JWT_SECRET=development_insecure_jwt_secret_change_me
|
||||||
|
JWT_ALGORITHM=HS256
|
||||||
|
ACCESS_TOKEN_EXPIRE_MINUTES=1440
|
||||||
|
|
||||||
|
# SSO Google OAuth (Optional in development / MockDevAdapter active)
|
||||||
|
GOOGLE_CLIENT_ID=
|
||||||
|
GOOGLE_CLIENT_SECRET=
|
||||||
|
GOOGLE_REDIRECT_URI=http://localhost:8000/v1/auth/callback
|
||||||
+2
-2
@@ -7,8 +7,8 @@ __pycache__/
|
|||||||
.mypy_cache/
|
.mypy_cache/
|
||||||
|
|
||||||
.env
|
.env
|
||||||
.env.*
|
# Keep templates tracked
|
||||||
!.env.example # Keep templates tracked
|
!.env.example
|
||||||
*.pem
|
*.pem
|
||||||
*.key
|
*.key
|
||||||
client_secret*.json
|
client_secret*.json
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ This document specifies the mandatory workflows, constraints, and quality gates
|
|||||||
- **Session Modes**:
|
- **Session Modes**:
|
||||||
- `learning`: The user drives and writes the reasoning, the agent asks guiding questions.
|
- `learning`: The user drives and writes the reasoning, the agent asks guiding questions.
|
||||||
- `delivery`: The agent may draft code and plans, presenting rationale and trade-offs.
|
- `delivery`: The agent may draft code and plans, presenting rationale and trade-offs.
|
||||||
|
- **Live Task Tracking (`todo.txt`)**: Keep `todo.txt` synchronized with code reality. When a deliverable or milestone is implemented and verified, mark it as completed (`x YYYY-MM-DD ...`) immediately. Never leave verified work marked as pending or untracked.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -54,3 +55,13 @@ No commit may be generated if any of these checks fail or report unhandled error
|
|||||||
When working on specialized sub-domains:
|
When working on specialized sub-domains:
|
||||||
- **Anne Droid** (`profile/agents/anne-droid.md`): Consult for UX flow, client accessibility, or backend API contract changes that impact the UI. Delegate to Anne for frontend component styling, PWA camera/canvas interaction, or client-side tests on `feat/anne/*` branches.
|
- **Anne Droid** (`profile/agents/anne-droid.md`): Consult for UX flow, client accessibility, or backend API contract changes that impact the UI. Delegate to Anne for frontend component styling, PWA camera/canvas interaction, or client-side tests on `feat/anne/*` branches.
|
||||||
- Do not invoke Anne Droid for backend-only logic, database migrations, or Docker infrastructure.
|
- Do not invoke Anne Droid for backend-only logic, database migrations, or Docker infrastructure.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Live Task Tracking (`todo.txt`)
|
||||||
|
|
||||||
|
For multi-step engineering milestones and deliverables:
|
||||||
|
- Maintain a standard, comment-free `todo.txt` in the repository root formatted for `tuxedo` / `todo.sh`.
|
||||||
|
- Prioritize deliverables using standard priorities (`(A)`, `(B)`, `(C)`), projects (`+<component>`), and contexts (`@<area>`).
|
||||||
|
- Keep `todo.txt` synchronized with code reality: when a deliverable is implemented and verified, mark it completed (`x YYYY-MM-DD ...`) immediately. Never leave verified work marked as pending or untracked.
|
||||||
|
|
||||||
+149
@@ -0,0 +1,149 @@
|
|||||||
|
# A generic, single database configuration.
|
||||||
|
|
||||||
|
[alembic]
|
||||||
|
# path to migration scripts.
|
||||||
|
# this is typically a path given in POSIX (e.g. forward slashes)
|
||||||
|
# format, relative to the token %(here)s which refers to the location of this
|
||||||
|
# ini file
|
||||||
|
script_location = %(here)s/alembic
|
||||||
|
|
||||||
|
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||||
|
# Uncomment the line below if you want the files to be prepended with date and time
|
||||||
|
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||||
|
# for all available tokens
|
||||||
|
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||||
|
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
|
||||||
|
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
|
||||||
|
|
||||||
|
# sys.path path, will be prepended to sys.path if present.
|
||||||
|
# defaults to the current working directory. for multiple paths, the path separator
|
||||||
|
# is defined by "path_separator" below.
|
||||||
|
prepend_sys_path = .
|
||||||
|
|
||||||
|
# timezone to use when rendering the date within the migration file
|
||||||
|
# as well as the filename.
|
||||||
|
# If specified, requires the tzdata library which can be installed by adding
|
||||||
|
# `alembic[tz]` to the pip requirements.
|
||||||
|
# string value is passed to ZoneInfo()
|
||||||
|
# leave blank for localtime
|
||||||
|
# timezone =
|
||||||
|
|
||||||
|
# max length of characters to apply to the "slug" field
|
||||||
|
# truncate_slug_length = 40
|
||||||
|
|
||||||
|
# set to 'true' to run the environment during
|
||||||
|
# the 'revision' command, regardless of autogenerate
|
||||||
|
# revision_environment = false
|
||||||
|
|
||||||
|
# set to 'true' to allow .pyc and .pyo files without
|
||||||
|
# a source .py file to be detected as revisions in the
|
||||||
|
# versions/ directory
|
||||||
|
# sourceless = false
|
||||||
|
|
||||||
|
# version location specification; This defaults
|
||||||
|
# to <script_location>/versions. When using multiple version
|
||||||
|
# directories, initial revisions must be specified with --version-path.
|
||||||
|
# The path separator used here should be the separator specified by "path_separator"
|
||||||
|
# below.
|
||||||
|
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
|
||||||
|
|
||||||
|
# path_separator; This indicates what character is used to split lists of file
|
||||||
|
# paths, including version_locations and prepend_sys_path within configparser
|
||||||
|
# files such as alembic.ini.
|
||||||
|
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
|
||||||
|
# to provide os-dependent path splitting.
|
||||||
|
#
|
||||||
|
# Note that in order to support legacy alembic.ini files, this default does NOT
|
||||||
|
# take place if path_separator is not present in alembic.ini. If this
|
||||||
|
# option is omitted entirely, fallback logic is as follows:
|
||||||
|
#
|
||||||
|
# 1. Parsing of the version_locations option falls back to using the legacy
|
||||||
|
# "version_path_separator" key, which if absent then falls back to the legacy
|
||||||
|
# behavior of splitting on spaces and/or commas.
|
||||||
|
# 2. Parsing of the prepend_sys_path option falls back to the legacy
|
||||||
|
# behavior of splitting on spaces, commas, or colons.
|
||||||
|
#
|
||||||
|
# Valid values for path_separator are:
|
||||||
|
#
|
||||||
|
# path_separator = :
|
||||||
|
# path_separator = ;
|
||||||
|
# path_separator = space
|
||||||
|
# path_separator = newline
|
||||||
|
#
|
||||||
|
# Use os.pathsep. Default configuration used for new projects.
|
||||||
|
path_separator = os
|
||||||
|
|
||||||
|
|
||||||
|
# set to 'true' to search source files recursively
|
||||||
|
# in each "version_locations" directory
|
||||||
|
# new in Alembic version 1.10
|
||||||
|
# recursive_version_locations = false
|
||||||
|
|
||||||
|
# the output encoding used when revision files
|
||||||
|
# are written from script.py.mako
|
||||||
|
# output_encoding = utf-8
|
||||||
|
|
||||||
|
# database URL. This is consumed by the user-maintained env.py script only.
|
||||||
|
# other means of configuring database URLs may be customized within the env.py
|
||||||
|
# file.
|
||||||
|
sqlalchemy.url = driver://user:pass@localhost/dbname
|
||||||
|
|
||||||
|
|
||||||
|
[post_write_hooks]
|
||||||
|
# post_write_hooks defines scripts or Python functions that are run
|
||||||
|
# on newly generated revision scripts. See the documentation for further
|
||||||
|
# detail and examples
|
||||||
|
|
||||||
|
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||||
|
# hooks = black
|
||||||
|
# black.type = console_scripts
|
||||||
|
# black.entrypoint = black
|
||||||
|
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
|
||||||
|
# hooks = ruff
|
||||||
|
# ruff.type = module
|
||||||
|
# ruff.module = ruff
|
||||||
|
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# Alternatively, use the exec runner to execute a binary found on your PATH
|
||||||
|
# hooks = ruff
|
||||||
|
# ruff.type = exec
|
||||||
|
# ruff.executable = ruff
|
||||||
|
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# Logging configuration. This is also consumed by the user-maintained
|
||||||
|
# env.py script only.
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARNING
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARNING
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Generic single-database configuration with an async dbapi.
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import asyncio
|
||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from sqlalchemy import pool
|
||||||
|
from sqlalchemy.engine import Connection
|
||||||
|
from sqlalchemy.ext.asyncio import create_async_engine
|
||||||
|
|
||||||
|
import api.db_models # noqa: F401
|
||||||
|
from alembic import context
|
||||||
|
from api.core.config import settings
|
||||||
|
from api.database.base import Base
|
||||||
|
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
"""Run migrations in 'offline' mode."""
|
||||||
|
url = settings.DATABASE_URL
|
||||||
|
context.configure(
|
||||||
|
url=url,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"},
|
||||||
|
compare_type=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def do_run_migrations(connection: Connection) -> None:
|
||||||
|
context.configure(
|
||||||
|
connection=connection,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
compare_type=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
async def run_async_migrations() -> None:
|
||||||
|
"""Run migrations in 'online' mode using the async engine."""
|
||||||
|
connectable = create_async_engine(
|
||||||
|
settings.DATABASE_URL,
|
||||||
|
poolclass=pool.NullPool,
|
||||||
|
)
|
||||||
|
|
||||||
|
async with connectable.connect() as connection:
|
||||||
|
await connection.run_sync(do_run_migrations)
|
||||||
|
|
||||||
|
await connectable.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
"""Run migrations in 'online' mode."""
|
||||||
|
asyncio.run(run_async_migrations())
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = ${repr(up_revision)}
|
||||||
|
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||||
|
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
"""Upgrade schema."""
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
"""Downgrade schema."""
|
||||||
|
${downgrades if downgrades else "pass"}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
"""initial schema with postgis and pgvector
|
||||||
|
|
||||||
|
Revision ID: 001_initial_schema
|
||||||
|
Revises:
|
||||||
|
Create Date: 2026-10-13 07:05:00.000000
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import geoalchemy2
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from pgvector.sqlalchemy import Vector
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = "001_initial_schema"
|
||||||
|
down_revision: str | None = None
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# 1. Enable required PostgreSQL extensions
|
||||||
|
op.execute("CREATE EXTENSION IF NOT EXISTS postgis;")
|
||||||
|
op.execute("CREATE EXTENSION IF NOT EXISTS vector;")
|
||||||
|
|
||||||
|
# 2. Users table
|
||||||
|
op.create_table(
|
||||||
|
"users",
|
||||||
|
sa.Column("id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("name", sa.String(length=100), nullable=False),
|
||||||
|
sa.Column("email", sa.String(length=255), nullable=False),
|
||||||
|
sa.Column("trust_score", sa.Float(), nullable=False, server_default="0.5"),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_users_email"), "users", ["email"], unique=True)
|
||||||
|
|
||||||
|
# 3. Sculptures table
|
||||||
|
op.create_table(
|
||||||
|
"sculptures",
|
||||||
|
sa.Column("id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("name", sa.String(length=255), nullable=False),
|
||||||
|
sa.Column("artist", sa.String(length=255), nullable=False),
|
||||||
|
sa.Column("year", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("description", sa.Text(), nullable=True),
|
||||||
|
sa.Column("audio_url", sa.String(length=512), nullable=True),
|
||||||
|
sa.Column("unlocked_content", sa.Text(), nullable=True),
|
||||||
|
sa.Column("status", sa.String(length=50), nullable=False, server_default="on-site"),
|
||||||
|
sa.Column(
|
||||||
|
"location",
|
||||||
|
geoalchemy2.types.Geometry(
|
||||||
|
geometry_type="POINT", srid=4326, from_text="ST_GeomFromEWKT", name="geometry"
|
||||||
|
),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("embedding", Vector(1280), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create HNSW index for vector cosine similarity
|
||||||
|
op.execute(
|
||||||
|
"CREATE INDEX idx_sculptures_embedding ON sculptures USING hnsw (embedding vector_cosine_ops);"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4. Check-ins table
|
||||||
|
op.create_table(
|
||||||
|
"check_ins",
|
||||||
|
sa.Column("id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("user_id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("sculpture_id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("captured_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("photo_url", sa.String(length=512), nullable=False),
|
||||||
|
sa.Column("similarity_score", sa.Float(), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(["sculpture_id"], ["sculptures.id"], ondelete="CASCADE"),
|
||||||
|
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.UniqueConstraint("user_id", "sculpture_id", name="uq_user_sculpture_checkin"),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_check_ins_sculpture_id"), "check_ins", ["sculpture_id"], unique=False)
|
||||||
|
op.create_index(op.f("ix_check_ins_user_id"), "check_ins", ["user_id"], unique=False)
|
||||||
|
|
||||||
|
# 5. Tickets table
|
||||||
|
op.create_table(
|
||||||
|
"tickets",
|
||||||
|
sa.Column("id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("reporter_id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("sculpture_id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("reported_status", sa.String(length=50), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"location",
|
||||||
|
geoalchemy2.types.Geometry(
|
||||||
|
geometry_type="POINT", srid=4326, from_text="ST_GeomFromEWKT", name="geometry"
|
||||||
|
),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("photo_url", sa.String(length=512), nullable=True),
|
||||||
|
sa.Column("description", sa.Text(), nullable=True),
|
||||||
|
sa.Column("status", sa.String(length=50), nullable=False, server_default="pending"),
|
||||||
|
sa.Column("reporter_trust_score", sa.Float(), nullable=False),
|
||||||
|
sa.Column("notes", sa.String(length=300), nullable=True),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column("resolved_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(["sculpture_id"], ["sculptures.id"], ondelete="CASCADE"),
|
||||||
|
sa.ForeignKeyConstraint(["reporter_id"], ["users.id"], ondelete="CASCADE"),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_tickets_reporter_id"), "tickets", ["reporter_id"], unique=False)
|
||||||
|
op.create_index(op.f("ix_tickets_sculpture_id"), "tickets", ["sculpture_id"], unique=False)
|
||||||
|
op.create_index(
|
||||||
|
"idx_tickets_sculpture_status", "tickets", ["sculpture_id", "status"], unique=False
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("tickets")
|
||||||
|
op.drop_table("check_ins")
|
||||||
|
op.execute("DROP INDEX IF EXISTS idx_sculptures_embedding;")
|
||||||
|
op.drop_table("sculptures")
|
||||||
|
op.drop_index(op.f("ix_users_email"), table_name="users")
|
||||||
|
op.drop_table("users")
|
||||||
+1
-1
@@ -47,7 +47,7 @@ exclude = ["**/__pycache__", ".venv"]
|
|||||||
asyncio_mode = "auto"
|
asyncio_mode = "auto"
|
||||||
asyncio_default_fixture_loop_scope = "function"
|
asyncio_default_fixture_loop_scope = "function"
|
||||||
testpaths = ["tests"]
|
testpaths = ["tests"]
|
||||||
pythonpath = ["src"]
|
pythonpath = ["src", "."]
|
||||||
|
|
||||||
[build-system]
|
[build-system]
|
||||||
requires = ["hatchling"]
|
requires = ["hatchling"]
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
import asyncio
|
||||||
|
import math
|
||||||
|
import random
|
||||||
|
import uuid
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from geoalchemy2.elements import WKTElement
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from api.database.session import AsyncSessionLocal
|
||||||
|
from api.db_models.sculpture import SculptureDB
|
||||||
|
from api.db_models.user import UserDB
|
||||||
|
|
||||||
|
|
||||||
|
def generate_normalized_embedding(seed_int: int, dimensions: int = 1280) -> list[float]:
|
||||||
|
"""
|
||||||
|
Generate a deterministic, L2-normalized float vector simulating MobileNetV2 output.
|
||||||
|
"""
|
||||||
|
rng = random.Random(seed_int)
|
||||||
|
raw_vals = [rng.gauss(0.0, 1.0) for _ in range(dimensions)]
|
||||||
|
magnitude = math.sqrt(sum(x * x for x in raw_vals))
|
||||||
|
return [round(x / magnitude, 6) for x in raw_vals]
|
||||||
|
|
||||||
|
|
||||||
|
INITIAL_USER = {
|
||||||
|
"id": uuid.UUID("123e4567-e89b-12d3-a456-426614174000"),
|
||||||
|
"name": "Explorador Caleño",
|
||||||
|
"email": "explorer@cali.gov.co",
|
||||||
|
"trust_score": 0.85,
|
||||||
|
}
|
||||||
|
|
||||||
|
INITIAL_SCULPTURES = [
|
||||||
|
{
|
||||||
|
"id": uuid.UUID("234e5678-e89b-12d3-a456-426614174001"),
|
||||||
|
"name": "La Novia Dulce",
|
||||||
|
"artist": "Lorena Espitia",
|
||||||
|
"year": 2006,
|
||||||
|
"latitude": 3.450143,
|
||||||
|
"longitude": -76.533282,
|
||||||
|
"status": "on-site",
|
||||||
|
"description": (
|
||||||
|
"Decorated with sweets and candies representing Cali's culinary traditions. "
|
||||||
|
"This bride is a homage to the traditional 'Macetas' given to godchildren every June."
|
||||||
|
),
|
||||||
|
"unlocked_content": (
|
||||||
|
"Cultural Oracle Insight: Lorena Espitia used bright fiberglass modeling to create a tactile sense "
|
||||||
|
"of Colombian sugar candies. The sculpture is traditionally positioned near the river to evoke "
|
||||||
|
"Cali's warm breeze carrying sweet aromas."
|
||||||
|
),
|
||||||
|
"audio_url": "https://cdn.gatos.cali.gov.co/audio/novia_dulce.mp3",
|
||||||
|
"embedding_seed": 101,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": uuid.UUID("234e5678-e89b-12d3-a456-426614174002"),
|
||||||
|
"name": "La Gata Ceremonial",
|
||||||
|
"artist": "José Horacio Martínez",
|
||||||
|
"year": 2006,
|
||||||
|
"latitude": 3.451600,
|
||||||
|
"longitude": -76.532600,
|
||||||
|
"status": "moved",
|
||||||
|
"description": (
|
||||||
|
"A dark sculpture featuring intricate pre-Columbian gold patterns. "
|
||||||
|
"It represents the ancestral heritage, jaguar spirits, and mythological elements of Southwest Colombia."
|
||||||
|
),
|
||||||
|
"unlocked_content": (
|
||||||
|
"Cultural Oracle Insight: The gold motifs are inspired by Calima culture gold artifacts. "
|
||||||
|
"Its temporary relocation due to civic repairs on the Boulevard has triggered consensus recalculation, "
|
||||||
|
"verifying its new spot 150m north."
|
||||||
|
),
|
||||||
|
"audio_url": "https://cdn.gatos.cali.gov.co/audio/gata_ceremonial.mp3",
|
||||||
|
"embedding_seed": 102,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": uuid.UUID("234e5678-e89b-12d3-a456-426614174003"),
|
||||||
|
"name": "La Gata Ilustrada",
|
||||||
|
"artist": "Lucy Tejada",
|
||||||
|
"year": 2006,
|
||||||
|
"latitude": 3.450800,
|
||||||
|
"longitude": -76.532900,
|
||||||
|
"status": "on-site",
|
||||||
|
"description": (
|
||||||
|
"Covered in birds, trees, and dreamlike childhood imagery by Lucy Tejada, "
|
||||||
|
"sister of master Hernando Tejada."
|
||||||
|
),
|
||||||
|
"unlocked_content": (
|
||||||
|
"Cultural Oracle Insight: Lucy Tejada painted this sculpture as a direct artistic dialogue "
|
||||||
|
"with her brother's bronze cat, symbolizing Cali's natural biodiversity and poetic innocence."
|
||||||
|
),
|
||||||
|
"audio_url": "https://cdn.gatos.cali.gov.co/audio/gata_ilustrada.mp3",
|
||||||
|
"embedding_seed": 103,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
async def seed_data(session: AsyncSession) -> tuple[UserDB, Sequence[SculptureDB]]:
|
||||||
|
"""
|
||||||
|
Idempotently seed the baseline user and cat sculptures into the database.
|
||||||
|
"""
|
||||||
|
# 1. Seed user
|
||||||
|
user = await session.get(UserDB, INITIAL_USER["id"])
|
||||||
|
if not user:
|
||||||
|
user = UserDB(
|
||||||
|
id=INITIAL_USER["id"],
|
||||||
|
name=INITIAL_USER["name"],
|
||||||
|
email=INITIAL_USER["email"],
|
||||||
|
trust_score=INITIAL_USER["trust_score"],
|
||||||
|
)
|
||||||
|
session.add(user)
|
||||||
|
else:
|
||||||
|
user.name = INITIAL_USER["name"]
|
||||||
|
user.trust_score = INITIAL_USER["trust_score"]
|
||||||
|
|
||||||
|
# 2. Seed sculptures
|
||||||
|
seeded_sculptures: list[SculptureDB] = []
|
||||||
|
for item in INITIAL_SCULPTURES:
|
||||||
|
sculpture = await session.get(SculptureDB, item["id"])
|
||||||
|
# PostGIS Point(Longitude Latitude) EPSG:4326
|
||||||
|
point = WKTElement(f"POINT({item['longitude']} {item['latitude']})", srid=4326)
|
||||||
|
embedding = generate_normalized_embedding(item["embedding_seed"])
|
||||||
|
|
||||||
|
if not sculpture:
|
||||||
|
sculpture = SculptureDB(
|
||||||
|
id=item["id"],
|
||||||
|
name=item["name"],
|
||||||
|
artist=item["artist"],
|
||||||
|
year=item["year"],
|
||||||
|
description=item["description"],
|
||||||
|
audio_url=item["audio_url"],
|
||||||
|
unlocked_content=item["unlocked_content"],
|
||||||
|
status=item["status"],
|
||||||
|
location=point,
|
||||||
|
embedding=embedding,
|
||||||
|
)
|
||||||
|
session.add(sculpture)
|
||||||
|
else:
|
||||||
|
sculpture.name = item["name"]
|
||||||
|
sculpture.artist = item["artist"]
|
||||||
|
sculpture.year = item["year"]
|
||||||
|
sculpture.description = item["description"]
|
||||||
|
sculpture.audio_url = item["audio_url"]
|
||||||
|
sculpture.unlocked_content = item["unlocked_content"]
|
||||||
|
sculpture.status = item["status"]
|
||||||
|
sculpture.location = point
|
||||||
|
sculpture.embedding = embedding
|
||||||
|
|
||||||
|
seeded_sculptures.append(sculpture)
|
||||||
|
|
||||||
|
await session.commit()
|
||||||
|
return user, seeded_sculptures
|
||||||
|
|
||||||
|
|
||||||
|
async def run_seed() -> None:
|
||||||
|
"""CLI runner for database seeding."""
|
||||||
|
print("🌱 Starting database seeding...")
|
||||||
|
async with AsyncSessionLocal() as session:
|
||||||
|
user, sculptures = await seed_data(session)
|
||||||
|
print(f"✅ User seeded: {user.name} ({user.email})")
|
||||||
|
for s in sculptures:
|
||||||
|
print(f"✅ Sculpture seeded: {s.name} by {s.artist} [{s.status}]")
|
||||||
|
print("🎉 Database seeding completed successfully!")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(run_seed())
|
||||||
+6
-33
@@ -1,9 +1,8 @@
|
|||||||
from fastapi import FastAPI, HTTPException, status
|
from fastapi import FastAPI
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
from api.core.config import settings
|
from api.core.config import settings
|
||||||
from api.models.auth import DevTokenRequest, LoginResponse
|
from api.routers import auth, sculptures, users
|
||||||
from api.services.auth.service import AuthService
|
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title=settings.PROJECT_NAME,
|
title=settings.PROJECT_NAME,
|
||||||
@@ -20,7 +19,10 @@ app.add_middleware(
|
|||||||
allow_headers=["*"],
|
allow_headers=["*"],
|
||||||
)
|
)
|
||||||
|
|
||||||
auth_service = AuthService()
|
# Register routers
|
||||||
|
app.include_router(auth.router)
|
||||||
|
app.include_router(users.router)
|
||||||
|
app.include_router(sculptures.router)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/health", tags=["System"])
|
@app.get("/health", tags=["System"])
|
||||||
@@ -34,32 +36,3 @@ async def health_check() -> dict[str, str]:
|
|||||||
"version": settings.VERSION,
|
"version": settings.VERSION,
|
||||||
"env": settings.ENV,
|
"env": settings.ENV,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@app.post(
|
|
||||||
"/auth/dev-token",
|
|
||||||
response_model=LoginResponse,
|
|
||||||
tags=["Authentication"],
|
|
||||||
summary="Development SSO Bypass Token Generation",
|
|
||||||
)
|
|
||||||
async def generate_dev_token(payload: DevTokenRequest) -> LoginResponse:
|
|
||||||
"""
|
|
||||||
Generate signed JWT for testing without contacting external OAuth providers.
|
|
||||||
Available only when ENV is not 'production'.
|
|
||||||
"""
|
|
||||||
if settings.ENV == "production":
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_403_FORBIDDEN,
|
|
||||||
detail="Development token generation disabled in production environment.",
|
|
||||||
)
|
|
||||||
|
|
||||||
# Use deterministic mock ID based on email
|
|
||||||
import hashlib
|
|
||||||
import uuid
|
|
||||||
|
|
||||||
deterministic_uuid = uuid.UUID(hashlib.md5(payload.email.encode("utf-8")).hexdigest())
|
|
||||||
|
|
||||||
return auth_service.create_access_token(
|
|
||||||
user_id=str(deterministic_uuid),
|
|
||||||
email=payload.email,
|
|
||||||
)
|
|
||||||
@@ -47,10 +47,14 @@ class SculptureDetails(Sculpture):
|
|||||||
Extended sculpture model containing cultural details, unlocked content, and audio resources.
|
Extended sculpture model containing cultural details, unlocked content, and audio resources.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
description: str = Field(..., description="Public cultural description of the sculpture.")
|
description: str | None = Field(
|
||||||
audio_url: HttpUrl = Field(..., description="Direct link to the audio guide resource.")
|
default=None, description="Public cultural description of the sculpture."
|
||||||
unlocked_content: str = Field(
|
)
|
||||||
..., description="Extended history/curation unlocked upon checking in."
|
audio_url: HttpUrl | None = Field(
|
||||||
|
default=None, description="Direct link to the audio guide resource."
|
||||||
|
)
|
||||||
|
unlocked_content: str | None = Field(
|
||||||
|
default=None, description="Extended history/curation unlocked upon checking in."
|
||||||
)
|
)
|
||||||
|
|
||||||
model_config = {
|
model_config = {
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
"""
|
||||||
|
API routers module.
|
||||||
|
"""
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import hashlib
|
||||||
|
import uuid
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from api.core.config import settings
|
||||||
|
from api.database.session import get_db_session
|
||||||
|
from api.db_models.user import UserDB
|
||||||
|
from api.models.auth import DevTokenRequest, LoginRequest, LoginResponse
|
||||||
|
from api.routers.deps import auth_service
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/auth", tags=["Authentication"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/login",
|
||||||
|
response_model=LoginResponse,
|
||||||
|
summary="Google SSO Authentication",
|
||||||
|
description="Exchange a Google OAuth ID token for a system-issued JWT access token.",
|
||||||
|
)
|
||||||
|
async def login_user(
|
||||||
|
payload: LoginRequest,
|
||||||
|
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||||
|
) -> LoginResponse:
|
||||||
|
try:
|
||||||
|
identity = await auth_service.authenticate_sso(payload.id_token)
|
||||||
|
except ValueError as err:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail=f"Invalid token provided: {err}",
|
||||||
|
) from err
|
||||||
|
|
||||||
|
# Provision or retrieve user
|
||||||
|
result = await db.execute(select(UserDB).where(UserDB.email == identity.email))
|
||||||
|
user = result.scalars().first()
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
user_uuid = uuid.UUID(hashlib.md5(identity.email.encode("utf-8")).hexdigest())
|
||||||
|
user = UserDB(
|
||||||
|
id=user_uuid,
|
||||||
|
name=identity.name,
|
||||||
|
email=identity.email,
|
||||||
|
trust_score=0.5,
|
||||||
|
)
|
||||||
|
db.add(user)
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(user)
|
||||||
|
|
||||||
|
return auth_service.create_access_token(
|
||||||
|
user_id=str(user.id),
|
||||||
|
email=user.email,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/dev-token",
|
||||||
|
response_model=LoginResponse,
|
||||||
|
summary="Development SSO Bypass Token Generation",
|
||||||
|
description="Generate signed JWT for testing without contacting external OAuth providers.",
|
||||||
|
)
|
||||||
|
async def generate_dev_token(
|
||||||
|
payload: DevTokenRequest,
|
||||||
|
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||||
|
) -> LoginResponse:
|
||||||
|
if settings.ENV == "production":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Development token generation disabled in production environment.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Deterministic UUID based on email
|
||||||
|
user_uuid = uuid.UUID(hashlib.md5(payload.email.encode("utf-8")).hexdigest())
|
||||||
|
|
||||||
|
# Ensure user exists in database
|
||||||
|
result = await db.execute(select(UserDB).where(UserDB.email == payload.email))
|
||||||
|
user = result.scalars().first()
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
user = UserDB(
|
||||||
|
id=user_uuid,
|
||||||
|
name=payload.name,
|
||||||
|
email=payload.email,
|
||||||
|
trust_score=0.5,
|
||||||
|
)
|
||||||
|
db.add(user)
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(user)
|
||||||
|
|
||||||
|
return auth_service.create_access_token(
|
||||||
|
user_id=str(user.id),
|
||||||
|
email=user.email,
|
||||||
|
)
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import uuid
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
import jwt
|
||||||
|
from fastapi import Depends, HTTPException, status
|
||||||
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from api.database.session import get_db_session
|
||||||
|
from api.db_models.user import UserDB
|
||||||
|
from api.services.auth.service import AuthService
|
||||||
|
|
||||||
|
security = HTTPBearer(auto_error=False)
|
||||||
|
auth_service = AuthService()
|
||||||
|
|
||||||
|
|
||||||
|
async def get_current_user(
|
||||||
|
credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)],
|
||||||
|
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||||
|
) -> UserDB:
|
||||||
|
"""
|
||||||
|
FastAPI dependency validating Bearer JWT token and returning authenticated UserDB entity.
|
||||||
|
"""
|
||||||
|
if credentials is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Authentication token missing or expired.",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
|
|
||||||
|
token = credentials.credentials
|
||||||
|
try:
|
||||||
|
payload = auth_service.decode_access_token(token)
|
||||||
|
except jwt.PyJWTError as err:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Authentication token missing or expired.",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
) from err
|
||||||
|
|
||||||
|
user_id_str = payload.get("sub")
|
||||||
|
if not user_id_str:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid token payload: missing subject.",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
user_uuid = uuid.UUID(user_id_str)
|
||||||
|
except ValueError as err:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid user ID format in token.",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
) from err
|
||||||
|
|
||||||
|
user = await db.get(UserDB, user_uuid)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="User associated with token not found.",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
|
|
||||||
|
return user
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import struct
|
||||||
|
from typing import Annotated
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from geoalchemy2.elements import WKBElement, WKTElement
|
||||||
|
from pydantic import HttpUrl, TypeAdapter
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from api.database.session import get_db_session
|
||||||
|
from api.db_models.sculpture import SculptureDB
|
||||||
|
from api.models.sculpture import Sculpture, SculptureDetails, SculptureStatus
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/sculptures", tags=["Sculptures"])
|
||||||
|
|
||||||
|
http_url_adapter = TypeAdapter(HttpUrl)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_coordinates(location: object) -> tuple[float, float]:
|
||||||
|
"""
|
||||||
|
Extract (longitude, latitude) from PostGIS WKBElement, WKTElement, or string representation.
|
||||||
|
"""
|
||||||
|
if isinstance(location, WKTElement) or (isinstance(location, str) and "POINT" in location):
|
||||||
|
raw_str = str(location).strip()
|
||||||
|
coords_str = raw_str[raw_str.find("(") + 1 : raw_str.find(")")]
|
||||||
|
lon, lat = map(float, coords_str.split())
|
||||||
|
return lon, lat
|
||||||
|
|
||||||
|
if isinstance(location, WKBElement):
|
||||||
|
raw = location.data
|
||||||
|
b = bytes.fromhex(raw) if isinstance(raw, str) else raw
|
||||||
|
byteorder = "<" if b[0] == 1 else ">"
|
||||||
|
geom_type = struct.unpack(byteorder + "I", b[1:5])[0]
|
||||||
|
# Check for SRID flag (EWKB: 0x20000000)
|
||||||
|
offset = 9 if (geom_type & 0x20000000) else 5
|
||||||
|
lon, lat = struct.unpack(byteorder + "dd", b[offset : offset + 16])
|
||||||
|
return lon, lat
|
||||||
|
|
||||||
|
raise ValueError(f"Unsupported location geometry format: {type(location)}")
|
||||||
|
|
||||||
|
|
||||||
|
def to_sculpture_read(db_item: SculptureDB) -> Sculpture:
|
||||||
|
lon, lat = extract_coordinates(db_item.location)
|
||||||
|
return Sculpture(
|
||||||
|
id=db_item.id,
|
||||||
|
name=db_item.name,
|
||||||
|
artist=db_item.artist,
|
||||||
|
year=db_item.year,
|
||||||
|
latitude=lat,
|
||||||
|
longitude=lon,
|
||||||
|
status=SculptureStatus(db_item.status),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def to_sculpture_details(db_item: SculptureDB) -> SculptureDetails:
|
||||||
|
lon, lat = extract_coordinates(db_item.location)
|
||||||
|
audio_url = http_url_adapter.validate_python(db_item.audio_url) if db_item.audio_url else None
|
||||||
|
return SculptureDetails(
|
||||||
|
id=db_item.id,
|
||||||
|
name=db_item.name,
|
||||||
|
artist=db_item.artist,
|
||||||
|
year=db_item.year,
|
||||||
|
latitude=lat,
|
||||||
|
longitude=lon,
|
||||||
|
status=SculptureStatus(db_item.status),
|
||||||
|
description=db_item.description,
|
||||||
|
audio_url=audio_url,
|
||||||
|
unlocked_content=db_item.unlocked_content,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=list[Sculpture], summary="List All Cat Sculptures")
|
||||||
|
async def list_sculptures(
|
||||||
|
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||||
|
) -> list[Sculpture]:
|
||||||
|
"""
|
||||||
|
Returns list of all sculptures with names, locations, and current status (Single Source of Truth).
|
||||||
|
"""
|
||||||
|
query = select(SculptureDB).order_by(SculptureDB.name)
|
||||||
|
result = await db.execute(query)
|
||||||
|
sculptures_db = result.scalars().all()
|
||||||
|
return [to_sculpture_read(item) for item in sculptures_db]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{id}", response_model=SculptureDetails, summary="Get Sculpture Details")
|
||||||
|
async def get_sculpture_by_id(
|
||||||
|
id: UUID,
|
||||||
|
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||||
|
) -> SculptureDetails:
|
||||||
|
"""
|
||||||
|
Detailed information about a sculpture, historical context, artist, and unlockable audio guides.
|
||||||
|
"""
|
||||||
|
sculpture = await db.get(SculptureDB, id)
|
||||||
|
if not sculpture:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Sculpture not found.",
|
||||||
|
)
|
||||||
|
return to_sculpture_details(sculpture)
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
from pydantic import EmailStr, HttpUrl, TypeAdapter
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from api.database.session import get_db_session
|
||||||
|
from api.db_models.checkin import CheckInDB
|
||||||
|
from api.db_models.user import UserDB
|
||||||
|
from api.models.checkin import CheckInRecord
|
||||||
|
from api.models.user import User
|
||||||
|
from api.routers.deps import get_current_user
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/users", tags=["Users"])
|
||||||
|
|
||||||
|
email_adapter = TypeAdapter(EmailStr)
|
||||||
|
http_url_adapter = TypeAdapter(HttpUrl)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/me",
|
||||||
|
response_model=User,
|
||||||
|
summary="Retrieve Current User Profile",
|
||||||
|
description="Get details about the authenticated user, including their community trust score.",
|
||||||
|
)
|
||||||
|
async def get_my_profile(
|
||||||
|
current_user: Annotated[UserDB, Depends(get_current_user)],
|
||||||
|
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||||
|
) -> User:
|
||||||
|
# Calculate count of unique verified captures
|
||||||
|
count_stmt = select(func.count(CheckInDB.id)).where(CheckInDB.user_id == current_user.id)
|
||||||
|
result = await db.execute(count_stmt)
|
||||||
|
captured_count = result.scalar() or 0
|
||||||
|
|
||||||
|
return User(
|
||||||
|
id=current_user.id,
|
||||||
|
name=current_user.name,
|
||||||
|
email=email_adapter.validate_python(current_user.email),
|
||||||
|
trust_score=current_user.trust_score,
|
||||||
|
captured_count=captured_count,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/me/collection",
|
||||||
|
response_model=list[CheckInRecord],
|
||||||
|
summary="Get User's Unlocked Sculptures",
|
||||||
|
description="Returns the user's progress tracking which cat sculptures they have successfully captured.",
|
||||||
|
)
|
||||||
|
async def get_my_collection(
|
||||||
|
current_user: Annotated[UserDB, Depends(get_current_user)],
|
||||||
|
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||||
|
) -> list[CheckInRecord]:
|
||||||
|
stmt = (
|
||||||
|
select(CheckInDB)
|
||||||
|
.where(CheckInDB.user_id == current_user.id)
|
||||||
|
.order_by(CheckInDB.captured_at.desc())
|
||||||
|
)
|
||||||
|
result = await db.execute(stmt)
|
||||||
|
check_ins = result.scalars().all()
|
||||||
|
|
||||||
|
return [
|
||||||
|
CheckInRecord(
|
||||||
|
sculpture_id=item.sculpture_id,
|
||||||
|
unlocked_at=item.captured_at,
|
||||||
|
checkin_photo_url=(
|
||||||
|
http_url_adapter.validate_python(item.photo_url) if item.photo_url else None
|
||||||
|
),
|
||||||
|
similarity_score=item.similarity_score,
|
||||||
|
)
|
||||||
|
for item in check_ins
|
||||||
|
]
|
||||||
@@ -2,9 +2,39 @@ from collections.abc import AsyncGenerator
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from httpx import ASGITransport, AsyncClient
|
from httpx import ASGITransport, AsyncClient
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||||
|
from sqlalchemy.pool import NullPool
|
||||||
|
|
||||||
|
from api.core.config import settings
|
||||||
|
from api.database.session import get_db_session
|
||||||
from api.main import app
|
from api.main import app
|
||||||
|
|
||||||
|
# Engine with NullPool prevents cross-loop asyncpg connection clashes in pytest
|
||||||
|
test_engine = create_async_engine(
|
||||||
|
settings.DATABASE_URL,
|
||||||
|
poolclass=NullPool,
|
||||||
|
echo=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
TestAsyncSessionLocal = async_sessionmaker(
|
||||||
|
bind=test_engine,
|
||||||
|
class_=AsyncSession,
|
||||||
|
expire_on_commit=False,
|
||||||
|
autocommit=False,
|
||||||
|
autoflush=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def override_get_db_session() -> AsyncGenerator[AsyncSession, None]:
|
||||||
|
async with TestAsyncSessionLocal() as session:
|
||||||
|
try:
|
||||||
|
yield session
|
||||||
|
finally:
|
||||||
|
await session.close()
|
||||||
|
|
||||||
|
|
||||||
|
app.dependency_overrides[get_db_session] = override_get_db_session
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
async def async_client() -> AsyncGenerator[AsyncClient, None]:
|
async def async_client() -> AsyncGenerator[AsyncClient, None]:
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import uuid
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
from api.core.config import settings
|
||||||
|
from api.database.seed import INITIAL_SCULPTURES
|
||||||
|
from api.db_models.checkin import CheckInDB
|
||||||
|
from tests.conftest import TestAsyncSessionLocal
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_auth_login_success(async_client: AsyncClient):
|
||||||
|
payload = {"id_token": "valid-mock-token"}
|
||||||
|
response = await async_client.post("/auth/login", json=payload)
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
data = response.json()
|
||||||
|
assert "access_token" in data
|
||||||
|
assert data["token_type"] == "Bearer"
|
||||||
|
assert data["expires_in"] > 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_auth_login_invalid_token(async_client: AsyncClient):
|
||||||
|
payload = {"id_token": "invalid-token"}
|
||||||
|
response = await async_client.post("/auth/login", json=payload)
|
||||||
|
assert response.status_code == 401
|
||||||
|
assert "Invalid token provided" in response.json()["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_dev_token_production_disabled(async_client: AsyncClient):
|
||||||
|
original_env = settings.ENV
|
||||||
|
try:
|
||||||
|
settings.ENV = "production"
|
||||||
|
payload = {"email": "blocked@cali.gov.co", "name": "Blocked"}
|
||||||
|
response = await async_client.post("/auth/dev-token", json=payload)
|
||||||
|
assert response.status_code == 403
|
||||||
|
assert "disabled in production" in response.json()["detail"]
|
||||||
|
finally:
|
||||||
|
settings.ENV = original_env
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_users_me_unauthorized(async_client: AsyncClient):
|
||||||
|
# Missing header
|
||||||
|
res1 = await async_client.get("/users/me")
|
||||||
|
assert res1.status_code == 401
|
||||||
|
|
||||||
|
# Invalid token
|
||||||
|
res2 = await async_client.get("/users/me", headers={"Authorization": "Bearer bad.token.here"})
|
||||||
|
assert res2.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_users_me_and_collection_flow(async_client: AsyncClient):
|
||||||
|
test_email = f"explorer.{uuid.uuid4().hex[:8]}@example.com"
|
||||||
|
token_resp = await async_client.post(
|
||||||
|
"/auth/dev-token", json={"email": test_email, "name": "Collection Explorer"}
|
||||||
|
)
|
||||||
|
assert token_resp.status_code == 200
|
||||||
|
token = token_resp.json()["access_token"]
|
||||||
|
headers = {"Authorization": f"Bearer {token}"}
|
||||||
|
|
||||||
|
# 1. Profile initially has 0 captures
|
||||||
|
profile_resp = await async_client.get("/users/me", headers=headers)
|
||||||
|
assert profile_resp.status_code == 200
|
||||||
|
profile_data = profile_resp.json()
|
||||||
|
assert profile_data["email"] == test_email
|
||||||
|
assert profile_data["name"] == "Collection Explorer"
|
||||||
|
assert profile_data["captured_count"] == 0
|
||||||
|
user_id = uuid.UUID(profile_data["id"])
|
||||||
|
|
||||||
|
# 2. Collection initially empty
|
||||||
|
col_resp = await async_client.get("/users/me/collection", headers=headers)
|
||||||
|
assert col_resp.status_code == 200
|
||||||
|
assert col_resp.json() == []
|
||||||
|
|
||||||
|
# 3. Add a check-in record directly via DB session
|
||||||
|
sculpture_id = INITIAL_SCULPTURES[0]["id"]
|
||||||
|
async with TestAsyncSessionLocal() as session:
|
||||||
|
check_in = CheckInDB(
|
||||||
|
user_id=user_id,
|
||||||
|
sculpture_id=sculpture_id,
|
||||||
|
photo_url="https://cdn.gatos.cali.gov.co/uploads/test.jpg",
|
||||||
|
similarity_score=0.92,
|
||||||
|
)
|
||||||
|
session.add(check_in)
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
# 4. Collection now has 1 capture
|
||||||
|
col_resp2 = await async_client.get("/users/me/collection", headers=headers)
|
||||||
|
assert col_resp2.status_code == 200
|
||||||
|
items = col_resp2.json()
|
||||||
|
assert len(items) == 1
|
||||||
|
assert items[0]["sculpture_id"] == str(sculpture_id)
|
||||||
|
assert items[0]["similarity_score"] == 0.92
|
||||||
|
assert items[0]["checkin_photo_url"] == "https://cdn.gatos.cali.gov.co/uploads/test.jpg"
|
||||||
|
|
||||||
|
# 5. Profile captured_count reflects the new capture
|
||||||
|
profile_resp2 = await async_client.get("/users/me", headers=headers)
|
||||||
|
assert profile_resp2.status_code == 200
|
||||||
|
assert profile_resp2.json()["captured_count"] == 1
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import pytest
|
import pytest
|
||||||
from httpx import AsyncClient
|
from httpx import AsyncClient
|
||||||
|
|
||||||
from api.main import auth_service
|
from api.routers.deps import auth_service
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import uuid
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from httpx import AsyncClient
|
||||||
|
|
||||||
|
from api.database.seed import INITIAL_SCULPTURES
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_list_sculptures_endpoint(async_client: AsyncClient):
|
||||||
|
response = await async_client.get("/sculptures")
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
data = response.json()
|
||||||
|
assert isinstance(data, list)
|
||||||
|
assert len(data) >= 3
|
||||||
|
|
||||||
|
# Check that our seeded sculptures are present
|
||||||
|
names = {item["name"] for item in data}
|
||||||
|
for seeded in INITIAL_SCULPTURES:
|
||||||
|
assert seeded["name"] in names
|
||||||
|
|
||||||
|
# Verify schema fields and coordinates on each sculpture
|
||||||
|
for item in data:
|
||||||
|
assert "id" in item
|
||||||
|
assert "name" in item
|
||||||
|
assert "artist" in item
|
||||||
|
assert "year" in item
|
||||||
|
assert "latitude" in item
|
||||||
|
assert "longitude" in item
|
||||||
|
assert "status" in item
|
||||||
|
# Cali bounding box check
|
||||||
|
assert 3.30 <= item["latitude"] <= 3.60
|
||||||
|
assert -76.60 <= item["longitude"] <= -76.40
|
||||||
|
assert item["status"] in ("on-site", "moved", "missing")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_get_sculpture_by_id_success(async_client: AsyncClient):
|
||||||
|
target_id = str(INITIAL_SCULPTURES[0]["id"])
|
||||||
|
response = await async_client.get(f"/sculptures/{target_id}")
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
data = response.json()
|
||||||
|
assert data["id"] == target_id
|
||||||
|
assert data["name"] == INITIAL_SCULPTURES[0]["name"]
|
||||||
|
assert data["artist"] == INITIAL_SCULPTURES[0]["artist"]
|
||||||
|
assert data["year"] == INITIAL_SCULPTURES[0]["year"]
|
||||||
|
assert data["description"] == INITIAL_SCULPTURES[0]["description"]
|
||||||
|
assert data["audio_url"] == INITIAL_SCULPTURES[0]["audio_url"]
|
||||||
|
assert data["unlocked_content"] == INITIAL_SCULPTURES[0]["unlocked_content"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_get_sculpture_by_id_not_found(async_client: AsyncClient):
|
||||||
|
non_existent_id = uuid.uuid4()
|
||||||
|
response = await async_client.get(f"/sculptures/{non_existent_id}")
|
||||||
|
assert response.status_code == 404
|
||||||
|
data = response.json()
|
||||||
|
assert data["detail"] == "Sculpture not found."
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_get_sculpture_by_id_invalid_uuid(async_client: AsyncClient):
|
||||||
|
response = await async_client.get("/sculptures/invalid-uuid-1234")
|
||||||
|
assert response.status_code == 422
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import struct
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from geoalchemy2.elements import WKBElement, WKTElement
|
||||||
|
|
||||||
|
from api.db_models.sculpture import SculptureDB
|
||||||
|
from api.routers.sculptures import (
|
||||||
|
extract_coordinates,
|
||||||
|
to_sculpture_details,
|
||||||
|
to_sculpture_read,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_extract_coordinates_from_wkt():
|
||||||
|
wkt = WKTElement("POINT(-76.533282 3.450143)", srid=4326)
|
||||||
|
lon, lat = extract_coordinates(wkt)
|
||||||
|
assert abs(lon - (-76.533282)) < 1e-6
|
||||||
|
assert abs(lat - 3.450143) < 1e-6
|
||||||
|
|
||||||
|
|
||||||
|
def test_extract_coordinates_from_wkb_ewkb():
|
||||||
|
# Build standard EWKB for POINT(-76.533282 3.450143) SRID 4326
|
||||||
|
# byteorder: 1 (little-endian), type: 0x20000001 (Point + EWKB), srid: 4326
|
||||||
|
packed = struct.pack("<bIIdd", 1, 0x20000001, 4326, -76.533282, 3.450143)
|
||||||
|
wkb = WKBElement(packed)
|
||||||
|
lon, lat = extract_coordinates(wkb)
|
||||||
|
assert abs(lon - (-76.533282)) < 1e-6
|
||||||
|
assert abs(lat - 3.450143) < 1e-6
|
||||||
|
|
||||||
|
|
||||||
|
def test_extract_coordinates_unsupported_type():
|
||||||
|
with pytest.raises(ValueError, match="Unsupported location geometry format"):
|
||||||
|
extract_coordinates(12345) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
|
||||||
|
def test_to_sculpture_read_mapping():
|
||||||
|
point = WKTElement("POINT(-76.5329 3.4508)", srid=4326)
|
||||||
|
db_item = SculptureDB(
|
||||||
|
id=uuid.uuid4(),
|
||||||
|
name="La Gata Ilustrada",
|
||||||
|
artist="Lucy Tejada",
|
||||||
|
year=2006,
|
||||||
|
description="A wonderful sculpture",
|
||||||
|
audio_url="https://cdn.gatos.cali.gov.co/audio/test.mp3",
|
||||||
|
unlocked_content="Secret lore",
|
||||||
|
status="on-site",
|
||||||
|
location=point,
|
||||||
|
embedding=[0.0] * 1280,
|
||||||
|
)
|
||||||
|
read_model = to_sculpture_read(db_item)
|
||||||
|
assert read_model.name == "La Gata Ilustrada"
|
||||||
|
assert read_model.year == 2006
|
||||||
|
assert abs(read_model.longitude - (-76.5329)) < 1e-6
|
||||||
|
assert abs(read_model.latitude - 3.4508) < 1e-6
|
||||||
|
|
||||||
|
|
||||||
|
def test_to_sculpture_details_mapping():
|
||||||
|
point = WKTElement("POINT(-76.5326 3.4516)", srid=4326)
|
||||||
|
db_item = SculptureDB(
|
||||||
|
id=uuid.uuid4(),
|
||||||
|
name="La Gata Ceremonial",
|
||||||
|
artist="José Horacio Martínez",
|
||||||
|
year=2006,
|
||||||
|
description="Pre-Columbian motifs",
|
||||||
|
audio_url="https://cdn.gatos.cali.gov.co/audio/ceremonial.mp3",
|
||||||
|
unlocked_content="Gold lore",
|
||||||
|
status="moved",
|
||||||
|
location=point,
|
||||||
|
embedding=[0.0] * 1280,
|
||||||
|
)
|
||||||
|
details_model = to_sculpture_details(db_item)
|
||||||
|
assert details_model.name == "La Gata Ceremonial"
|
||||||
|
assert details_model.status.value == "moved"
|
||||||
|
assert details_model.description == "Pre-Columbian motifs"
|
||||||
|
assert str(details_model.audio_url) == "https://cdn.gatos.cali.gov.co/audio/ceremonial.mp3"
|
||||||
|
assert details_model.unlocked_content == "Gold lore"
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import importlib.util
|
||||||
|
import math
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from api.database.seed import INITIAL_SCULPTURES, INITIAL_USER, generate_normalized_embedding
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalized_embedding_properties():
|
||||||
|
vec = generate_normalized_embedding(seed_int=42, dimensions=1280)
|
||||||
|
assert len(vec) == 1280
|
||||||
|
|
||||||
|
# Verify L2 norm == 1.0
|
||||||
|
l2_norm = math.sqrt(sum(x * x for x in vec))
|
||||||
|
assert math.isclose(l2_norm, 1.0, rel_tol=1e-3)
|
||||||
|
|
||||||
|
# Determinism
|
||||||
|
vec_repeat = generate_normalized_embedding(seed_int=42, dimensions=1280)
|
||||||
|
assert vec == vec_repeat
|
||||||
|
|
||||||
|
|
||||||
|
def test_initial_sculptures_data_validity():
|
||||||
|
assert len(INITIAL_SCULPTURES) == 3
|
||||||
|
|
||||||
|
for item in INITIAL_SCULPTURES:
|
||||||
|
# Geographic bounds for Cali, Colombia
|
||||||
|
assert 3.30 <= item["latitude"] <= 3.60
|
||||||
|
assert -76.60 <= item["longitude"] <= -76.40
|
||||||
|
assert item["year"] >= 1996
|
||||||
|
assert len(item["name"]) > 0
|
||||||
|
assert len(item["artist"]) > 0
|
||||||
|
assert item["status"] in ("on-site", "moved", "missing")
|
||||||
|
|
||||||
|
|
||||||
|
def test_initial_user_data_validity():
|
||||||
|
assert "@" in INITIAL_USER["email"]
|
||||||
|
assert 0.0 <= INITIAL_USER["trust_score"] <= 1.0
|
||||||
|
assert len(INITIAL_USER["name"]) > 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_migration_001_structure():
|
||||||
|
migration_file = Path(__file__).parents[2] / "alembic" / "versions" / "001_initial_schema.py"
|
||||||
|
assert migration_file.is_file()
|
||||||
|
|
||||||
|
spec = importlib.util.spec_from_file_location("migration_001", str(migration_file))
|
||||||
|
assert spec is not None
|
||||||
|
assert spec.loader is not None
|
||||||
|
mod = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(mod)
|
||||||
|
|
||||||
|
assert hasattr(mod, "upgrade")
|
||||||
|
assert callable(mod.upgrade)
|
||||||
|
assert hasattr(mod, "downgrade")
|
||||||
|
assert callable(mod.downgrade)
|
||||||
|
assert mod.revision == "001_initial_schema"
|
||||||
Generated
+3
-3
@@ -92,11 +92,11 @@ wheels = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "certifi"
|
name = "certifi"
|
||||||
version = "2026.7.22"
|
version = "2026.10.23"
|
||||||
source = { registry = "https://pypi.org/simple" }
|
source = { registry = "https://pypi.org/simple" }
|
||||||
sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" }
|
sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" }
|
||||||
wheels = [
|
wheels = [
|
||||||
{ url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" },
|
{ url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
@@ -1,18 +1,10 @@
|
|||||||
FROM postgis/postgis:17-3.5
|
FROM pgvector/pgvector:pg17
|
||||||
|
|
||||||
# Install build dependencies and pgvector
|
# Install official PostGIS 3 for PostgreSQL 17
|
||||||
RUN apt-get update && \
|
RUN apt-get update && \
|
||||||
apt-get install -y --no-install-recommends \
|
apt-get install -y --no-install-recommends \
|
||||||
postgresql-17-pgvector || \
|
postgresql-17-postgis-3 \
|
||||||
(apt-get install -y --no-install-recommends git build-essential postgresql-server-dev-17 && \
|
postgresql-17-postgis-3-scripts && \
|
||||||
cd /tmp && \
|
|
||||||
git clone --branch v0.8.0 https://github.com/pgvector/pgvector.git && \
|
|
||||||
cd pgvector && \
|
|
||||||
make && \
|
|
||||||
make install && \
|
|
||||||
apt-get remove -y git build-essential postgresql-server-dev-17 && \
|
|
||||||
apt-get autoremove -y && \
|
|
||||||
rm -rf /tmp/pgvector) && \
|
|
||||||
rm -rf /var/lib/apt/lists/*
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
COPY docker/postgres/init-extensions.sql /docker-entrypoint-initdb.d/01-init-extensions.sql
|
COPY docker/postgres/init-extensions.sql /docker-entrypoint-initdb.d/01-init-extensions.sql
|
||||||
+11
-3
@@ -49,10 +49,16 @@ Validates "Check-ins" using client-side edge embeddings (MobileNetV2 1280-dimens
|
|||||||
### 4. Interaction & Collection Service
|
### 4. Interaction & Collection Service
|
||||||
Manages the many-to-many relationship between users and sculptures (unlocked achievements, captured photo galleries, and cultural audio/insights).
|
Manages the many-to-many relationship between users and sculptures (unlocked achievements, captured photo galleries, and cultural audio/insights).
|
||||||
|
|
||||||
### 5. Crowdsourcing & Ticket Service
|
### 5. Crowdsourcing & Ticket Service (Cascade Triage)
|
||||||
Manages citizen reports for moved, missing, or altered sculptures:
|
Manages citizen reports for moved, missing, or altered sculptures:
|
||||||
- Accepts coordinates, observed status, verification photo, and optional commentary.
|
- Accepts coordinates, observed status, verification photo, and optional free-form commentary.
|
||||||
- Groups overlapping submissions into spatial clusters ($\le 20\text{ m}$ radius) over a 48-hour window.
|
- **Cascade Triage Architecture**:
|
||||||
|
1. **Tier 1 (Deterministic Math)**: Rejects physical impossibilities via spatio-temporal velocity checks ($v \le 120\text{ km/h}$).
|
||||||
|
2. **Tier 2 (System One Decision Engine - Jev)**: Free-form commentary and report metadata are processed via a pluggable `TriageProvider` adapter (backed by TypeSafe AI's non-autoregressive **Jev** model):
|
||||||
|
- `is_spam` (`noul`): Fast boolean probability filter to eliminate noise before human review.
|
||||||
|
- `category` (`choice`): Categorizes reports into municipal work, temporary festival relocation, vandalism, theft, or empty pedestal.
|
||||||
|
- `credibility` (`score`): Calibrated plausibility scoring used to scale reporter vote weight.
|
||||||
|
3. **Tier 3 (Spatial Clustering & Consensus)**: Groups verified submissions into spatial clusters ($\le 20\text{ m}$ radius) over a 48-hour window.
|
||||||
|
|
||||||
### 6. Location Tracker Service (The Oracle) & Hybrid Consensus Engine
|
### 6. Location Tracker Service (The Oracle) & Hybrid Consensus Engine
|
||||||
Computes the single source of truth (SSOT) location and status of each sculpture:
|
Computes the single source of truth (SSOT) location and status of each sculpture:
|
||||||
@@ -67,4 +73,6 @@ Computes the single source of truth (SSOT) location and status of each sculpture
|
|||||||
* **PWA Priority:** Chosen for immediate access (QR/URL) over the friction of app store downloads, especially for tourists.
|
* **PWA Priority:** Chosen for immediate access (QR/URL) over the friction of app store downloads, especially for tourists.
|
||||||
* **SSO Adapter Pattern:** Isolates authentication provider logic behind a clean contract, allowing local offline testing and easy migration to alternative auth providers (e.g. Authelia) without touching business logic.
|
* **SSO Adapter Pattern:** Isolates authentication provider logic behind a clean contract, allowing local offline testing and easy migration to alternative auth providers (e.g. Authelia) without touching business logic.
|
||||||
* **Hybrid Consensus Threshold:** Combines automated confidence scoring ($\ge 3.0$) with human-in-the-loop moderator verification for ambiguous edge cases, balancing real-time responsiveness with catalog integrity.
|
* **Hybrid Consensus Threshold:** Combines automated confidence scoring ($\ge 3.0$) with human-in-the-loop moderator verification for ambiguous edge cases, balancing real-time responsiveness with catalog integrity.
|
||||||
|
* **Cascade Triage & Non-Autoregressive Decision Engine (Jev):** Free-form crowdsourced reports and device fallback queues are pre-triaged using TypeSafe AI's Jev model via a pluggable `TriageProvider` adapter. By choosing a non-autoregressive decision model over generative LLMs, the system achieves sub-200ms latency, calibrated probabilities, and guaranteed typed responses without heavy server-side GPU/RAM requirements. Code-level velocity math and client-side MobileNetV2 feature embeddings remain untouched.
|
||||||
|
|
||||||
|
|
||||||
@@ -45,8 +45,8 @@ graph TD
|
|||||||
|
|
||||||
### ADR-004: Asynchronous Moderation Queue for Device Failures
|
### ADR-004: Asynchronous Moderation Queue for Device Failures
|
||||||
* **Context:** Some older or budget smartphones may throw exceptions when attempting WebAssembly compilation or WebGL initialization, preventing local vector generation.
|
* **Context:** Some older or budget smartphones may throw exceptions when attempting WebAssembly compilation or WebGL initialization, preventing local vector generation.
|
||||||
* **Decision:** If the PWA catches an ONNX initialization error, it degrades gracefully by falling back to an **Asynchronous Moderation Queue**. It uploads the raw GPS coordinates and the compressed photo to the `/reports` endpoint. The check-in is set to "Pending" until an admin manually approves it.
|
* **Decision:** If the PWA catches an ONNX initialization error, it degrades gracefully by falling back to an **Asynchronous Moderation Queue**. It uploads the raw GPS coordinates and the compressed photo to the `/reports` endpoint. The check-in is set to "Pending" until an admin manually approves it or the pluggable Jev triage engine verifies the report's credibility.
|
||||||
* **Rationale:** Protects the server from loading resource-heavy inference engines (like PyTorch or full onnxruntime) on the backend, maintaining strict memory limits while still ensuring all users can complete check-ins.
|
* **Rationale:** Protects the server from loading resource-heavy inference engines (like PyTorch or full onnxruntime) on the backend, maintaining strict memory limits while still ensuring all users can complete check-ins. Combined with non-autoregressive decision models (Jev), fallback tickets can be pre-scored for credibility without human bottlenecking.
|
||||||
|
|
||||||
### ADR-005: Progressive Dataset Rollout via Admin Seeding Tool
|
### ADR-005: Progressive Dataset Rollout via Admin Seeding Tool
|
||||||
* **Context:** Collecting, photographing, and seeding reference vectors for all 38 cats on day one is a bottleneck that delays MVP deployment.
|
* **Context:** Collecting, photographing, and seeding reference vectors for all 38 cats on day one is a bottleneck that delays MVP deployment.
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
x 2026-10-13 (A) Containerize PostGIS 17 + pgvector in docker-compose.yml with healthcheck +infra @db
|
||||||
|
x 2026-10-13 (A) Implement async SQLAlchemy 2.0 engine and session factory in api/database.py +api @db
|
||||||
|
x 2026-10-13 (A) Define Sculpture, CheckIn, and User ORM models with GeoAlchemy2 and pgvector in api/models.py +api @db
|
||||||
|
x 2026-10-13 (A) Initialize Alembic and create initial schema migration in api/alembic/ +api @db
|
||||||
|
x 2026-10-13 (A) Create seed script and populate 3 historical cat sculptures in api/scripts/seed_sculptures.py +api @db
|
||||||
|
x 2026-10-13 (A) Establish automated test suite with pytest-asyncio and SQLite/Postgres harness in api/tests/ +test @api
|
||||||
|
x 2026-10-13 (A) Draft Architectural Decision Record for Jev Cascade Triage in docs/adr/001-jev-cascade-triage.md +docs @arch
|
||||||
|
x 2026-10-15 (A) Implement Pydantic v2 domain schemas matching openapi_unified.yaml in api/models/ +api @backend
|
||||||
|
x 2026-10-15 (A) Implement IdentityProvider protocol, auth router, and users profile router in api/routers/ +api @auth
|
||||||
|
x 2026-10-13 (A) Implement Sculptures read router with spatial coordinate serialization in api/routers/sculptures.py +api @backend
|
||||||
|
(B) Implement Check-In verification engine with spatial distance threshold and cosine similarity threshold in api/services/checkin.py +api @backend
|
||||||
|
(B) Implement Check-In router with idempotency and streak tracking in api/routers/checkins.py +api @backend
|
||||||
|
(B) Implement Jev lightweight triage adapter protocol and mock fallback in api/services/triage.py +api @ai
|
||||||
|
(C) Implement consensus engine for multi-user spatial cluster voting in api/services/consensus.py +api @backend
|
||||||
|
(C) Implement public catalog and leaderboard endpoints in api/routers/catalog.py +api @backend
|
||||||
|
(C) Write comprehensive integration tests for Check-In flow, edge cases, and spatial rejection in api/tests/test_checkins.py +test @api
|
||||||
|
(D) Consult Anne Droid to review OpenAPI schemas against PWA client camera and canvas contract +pwa @frontend
|
||||||
Reference in new issue
Block a user