Backend API: auth, projects/images/annotations, R2 presign, tracing, thumbnails, pagination, tests, docs
This commit is contained in:
parent
5c5deed2f5
commit
f8ed08b854
49 changed files with 2626 additions and 0 deletions
0
src/api/__init__.py
Normal file
0
src/api/__init__.py
Normal file
0
src/api/v1/__init__.py
Normal file
0
src/api/v1/__init__.py
Normal file
40
src/api/v1/activities.py
Normal file
40
src/api/v1/activities.py
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
"""Activity feed derived from the action-event tracelog (no separate table)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy import desc, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from models import ActionEvent, User
|
||||
from src.core.db import get_session
|
||||
|
||||
router = APIRouter(prefix="/activities", tags=["activities"])
|
||||
|
||||
_ACTION_TEXT = {
|
||||
"project.create": "đã tạo dự án mới",
|
||||
"image.confirm": "đã tải ảnh mới lên",
|
||||
"image.status": "đã đổi trạng thái ảnh",
|
||||
"annotation.save": "đã lưu nhãn ảnh",
|
||||
"dataset.export": "đã xuất dataset",
|
||||
"image.next": "đã chuyển ảnh",
|
||||
}
|
||||
|
||||
|
||||
def _describe(e: ActionEvent, names: dict) -> str:
|
||||
base = _ACTION_TEXT.get(e.action, f"đã thực hiện {e.action}")
|
||||
who = names.get(e.user_id or "", None) or (e.user_id or "hệ thống")
|
||||
detail = e.image_id or e.project_id or ""
|
||||
return f"{who} {base} {detail}".strip()
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_activities(limit: int = Query(default=30, le=200),
|
||||
db: AsyncSession = Depends(get_session)):
|
||||
rows = (await db.execute(select(ActionEvent).order_by(desc(ActionEvent.created_at)).limit(limit))).scalars().all()
|
||||
users = (await db.execute(select(User))).scalars().all()
|
||||
names = {u.id: u.name for u in users}
|
||||
return [{"id": e.id,
|
||||
"timestamp": e.created_at.isoformat() if e.created_at else "",
|
||||
"userName": names.get(e.user_id or "", e.user_id or "hệ thống"),
|
||||
"actionText": _describe(e, names),
|
||||
"projectId": e.project_id} for e in rows]
|
||||
21
src/api/v1/annotations.py
Normal file
21
src/api/v1/annotations.py
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from shared.schemas import AnnotationUpsert
|
||||
from src.core.db import get_session
|
||||
from src.services import annotations as svc
|
||||
|
||||
router = APIRouter(prefix="/projects/{project_id}/images/{image_id}/annotation", tags=["annotations"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_annotation(project_id: str, image_id: str, db: AsyncSession = Depends(get_session)):
|
||||
return await svc.get_annotation(project_id, image_id, db)
|
||||
|
||||
|
||||
@router.put("")
|
||||
async def upsert_annotation(project_id: str, image_id: str, body: AnnotationUpsert,
|
||||
db: AsyncSession = Depends(get_session)):
|
||||
return await svc.upsert_annotation(project_id, image_id, body, db)
|
||||
73
src/api/v1/auth.py
Normal file
73
src/api/v1/auth.py
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from models import User
|
||||
from src.core.db import get_session
|
||||
from src.core.security import create_token, get_current_user, verify_password
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
class LoginIn(BaseModel):
|
||||
email: str
|
||||
password: str = ""
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
async def login(body: LoginIn, db: AsyncSession = Depends(get_session)):
|
||||
user = (await db.execute(
|
||||
select(User).where(User.email == body.email.strip().lower()))).scalar_one_or_none()
|
||||
if user is None or not verify_password(body.password or "", user.password_hash or ""):
|
||||
raise HTTPException(401, "email hoặc mật khẩu không đúng")
|
||||
access = create_token(user.id, user.role)
|
||||
refresh = create_token(user.id, user.role, expires_minutes=60 * 24 * 7)
|
||||
return {"user": {"id": user.id, "name": user.name, "email": user.email,
|
||||
"avatarInitials": "".join(p[0] for p in user.name.split()[:2]).upper(),
|
||||
"avatarColor": "#3B82F6", "role": user.role, "status": user.status,
|
||||
"isOnline": True, "lastActive": "Đang trực tuyến"},
|
||||
"accessToken": access, "refreshToken": refresh}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def me(user: User = Depends(get_current_user)):
|
||||
return {"id": user.id, "name": user.name, "email": user.email,
|
||||
"avatarInitials": "".join(p[0] for p in user.name.split()[:2]).upper(),
|
||||
"avatarColor": "#3B82F6", "role": user.role, "status": user.status,
|
||||
"isOnline": True, "lastActive": "Đang trực tuyến"}
|
||||
|
||||
|
||||
class InviteIn(BaseModel):
|
||||
email: str
|
||||
role: str = "annotator"
|
||||
projectIds: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class UserPatch(BaseModel):
|
||||
role: str | None = None
|
||||
status: str | None = None
|
||||
projectIds: list[str] | None = None
|
||||
|
||||
|
||||
users_router = APIRouter(prefix="/users", tags=["users"])
|
||||
|
||||
|
||||
@users_router.get("")
|
||||
async def list_users(db: AsyncSession = Depends(get_session)):
|
||||
from src.services import users as svc
|
||||
return await svc.list_users(db)
|
||||
|
||||
|
||||
@users_router.post("", status_code=201)
|
||||
async def invite(body: InviteIn, db: AsyncSession = Depends(get_session)):
|
||||
from src.services import users as svc
|
||||
return await svc.invite_user(body.email, body.role, body.projectIds, db)
|
||||
|
||||
|
||||
@users_router.patch("/{user_id}")
|
||||
async def patch_user(user_id: str, body: UserPatch, db: AsyncSession = Depends(get_session)):
|
||||
from src.services import users as svc
|
||||
return await svc.patch_user(user_id, body.model_dump(), db)
|
||||
39
src/api/v1/events.py
Normal file
39
src/api/v1/events.py
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
"""Client action ingest: operations the backend never sees (UI-only actions).
|
||||
|
||||
Batch format keeps high-frequency UI affordable: the frontend buffers and sends
|
||||
up to 200 events per call. session_id is required — an event without a session
|
||||
cannot be replayed.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from shared import events
|
||||
from shared.tracing import new_id
|
||||
|
||||
router = APIRouter(prefix="/events", tags=["events"])
|
||||
|
||||
|
||||
class ClientEvent(BaseModel):
|
||||
action: str = Field(min_length=1, max_length=64)
|
||||
project_id: str | None = None
|
||||
image_id: str | None = None
|
||||
payload: dict = Field(default_factory=dict)
|
||||
|
||||
|
||||
class EventsIn(BaseModel):
|
||||
session_id: str = Field(min_length=1, max_length=64)
|
||||
events: list[ClientEvent] = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
@router.post("", status_code=202)
|
||||
async def ingest(body: EventsIn):
|
||||
if not body.session_id.strip():
|
||||
raise HTTPException(400, "session_id is required")
|
||||
for e in body.events:
|
||||
await events.emit(e.action, project_id=e.project_id, image_id=e.image_id,
|
||||
payload=e.payload, session_id=body.session_id,
|
||||
trace_id=new_id())
|
||||
return {"accepted": len(body.events)}
|
||||
37
src/api/v1/images.py
Normal file
37
src/api/v1/images.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from shared.schemas import ImageConfirm, PresignRequest
|
||||
from src.core.db import get_session
|
||||
from src.services import images as svc
|
||||
|
||||
router = APIRouter(prefix="/projects/{project_id}/images", tags=["images"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_images(project_id: str, status: str | None = Query(default=None),
|
||||
search: str | None = Query(default=None),
|
||||
assignee: str | None = Query(default=None),
|
||||
limit: int = Query(default=50, ge=1, le=200),
|
||||
offset: int = Query(default=0, ge=0),
|
||||
db: AsyncSession = Depends(get_session)):
|
||||
return await svc.list_images(project_id, status, db, search=search,
|
||||
assignee=assignee, limit=limit, offset=offset)
|
||||
|
||||
|
||||
@router.post("/presign")
|
||||
async def presign_upload(project_id: str, body: PresignRequest):
|
||||
return svc.build_presign(project_id, body.fileName, body.contentType)
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def confirm_image(project_id: str, body: ImageConfirm, db: AsyncSession = Depends(get_session)):
|
||||
return await svc.confirm_image(project_id, body, db)
|
||||
|
||||
|
||||
@router.patch("/{image_id}")
|
||||
async def update_status(project_id: str, image_id: str, status: str,
|
||||
db: AsyncSession = Depends(get_session)):
|
||||
return await svc.update_status(project_id, image_id, status, db)
|
||||
47
src/api/v1/projects.py
Normal file
47
src/api/v1/projects.py
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from shared.schemas import LabelClassIn, ProjectCreate
|
||||
from src.core.db import get_session
|
||||
from src.services import projects as svc
|
||||
|
||||
router = APIRouter(prefix="/projects", tags=["projects"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_projects(db: AsyncSession = Depends(get_session)):
|
||||
return await svc.list_projects(db)
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_project(body: ProjectCreate, db: AsyncSession = Depends(get_session)):
|
||||
return await svc.create_project(body, db)
|
||||
|
||||
|
||||
@router.get("/{project_id}")
|
||||
async def get_project(project_id: str, db: AsyncSession = Depends(get_session)):
|
||||
return await svc.get_project_detail(project_id, db)
|
||||
|
||||
|
||||
@router.patch("/{project_id}")
|
||||
async def patch_project(project_id: str, body: dict, db: AsyncSession = Depends(get_session)):
|
||||
return await svc.patch_project(project_id, body, db)
|
||||
|
||||
|
||||
@router.delete("/{project_id}")
|
||||
async def delete_project(project_id: str, db: AsyncSession = Depends(get_session)):
|
||||
return await svc.delete_project(project_id, db)
|
||||
|
||||
|
||||
@router.post("/{project_id}/classes", status_code=201)
|
||||
async def add_class(project_id: str, body: LabelClassIn, db: AsyncSession = Depends(get_session)):
|
||||
return await svc.add_label_class(project_id, body, db)
|
||||
|
||||
|
||||
@router.put("/{project_id}/classes")
|
||||
async def replace_classes(project_id: str, body: list[dict],
|
||||
db: AsyncSession = Depends(get_session)):
|
||||
"""Bulk replace backing LabelsTab onUpdateClasses (add/edit/delete in one call)."""
|
||||
return await svc.replace_classes(project_id, body, db)
|
||||
60
src/api/v1/system.py
Normal file
60
src/api/v1/system.py
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import select, text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from shared.traffic import get_snapshot
|
||||
from src.core.db import Base, get_engine, get_session, get_session_factory
|
||||
|
||||
router = APIRouter(tags=["system"])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health(db: AsyncSession = Depends(get_session)):
|
||||
await db.execute(text("SELECT 1"))
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/metrics")
|
||||
async def metrics():
|
||||
"""Phase-1 traffic counters (Phase-2: Prometheus export). No auth on dev; protect in prod."""
|
||||
return get_snapshot()
|
||||
|
||||
|
||||
@router.post("/admin/backfill-thumbnails")
|
||||
async def backfill_thumbnails(limit: int = 100, db: AsyncSession = Depends(get_session)):
|
||||
"""Mint thumbs for images uploaded before thumbnailing existed. Dev-only."""
|
||||
from models import Image
|
||||
from shared import thumbnails
|
||||
rows = (await db.execute(
|
||||
select(Image).where(Image.thumbnail_r2_key.is_(None)).limit(limit))).scalars().all()
|
||||
minted = 0
|
||||
for im in rows:
|
||||
keys = await thumbnails.mint_thumbnails_for_image(im.project_id, im.id, im.r2_key)
|
||||
if keys["thumbnail"]:
|
||||
im.thumbnail_r2_key = keys["thumbnail"]
|
||||
if keys["small"]:
|
||||
im.thumbnail_small_r2_key = keys["small"]
|
||||
if keys["thumbnail"] or keys["small"]:
|
||||
minted += 1
|
||||
await db.commit()
|
||||
return {"scanned": len(rows), "minted": minted}
|
||||
|
||||
|
||||
@router.post("/admin/init-db")
|
||||
async def init_db():
|
||||
"""Create tables from models. Replaced by Alembic once migrations exist."""
|
||||
from models import User
|
||||
from src.core.security import hash_password
|
||||
async with get_engine().begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
factory = get_session_factory()
|
||||
async with factory() as s:
|
||||
admin = (await s.execute(select(User).where(User.email == "admin@danable.local"))).scalar_one_or_none()
|
||||
if admin is None:
|
||||
s.add(User(email="admin@danable.local", name="Admin", role="admin",
|
||||
status="active", password_hash=hash_password("Admin123!"),
|
||||
assigned_project_ids=[]))
|
||||
await s.commit()
|
||||
return {"ok": True, "seeded_admin": "admin@danable.local"}
|
||||
Loading…
Add table
Add a link
Reference in a new issue