feat(fc2c-i): showcase random-sample service and endpoint
This commit is contained in:
@@ -20,12 +20,14 @@ def all_blueprints() -> list[Blueprint]:
|
||||
from .import_admin import import_admin_bp
|
||||
from .ml_admin import ml_admin_bp
|
||||
from .settings import settings_bp
|
||||
from .showcase import showcase_bp
|
||||
from .suggestions import suggestions_bp
|
||||
from .tags import tags_bp
|
||||
return [
|
||||
api_bp,
|
||||
gallery_bp,
|
||||
tags_bp,
|
||||
showcase_bp,
|
||||
settings_bp,
|
||||
import_admin_bp,
|
||||
suggestions_bp,
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Showcase API: scalable random sample of images."""
|
||||
|
||||
from quart import Blueprint, jsonify, request
|
||||
|
||||
from ..extensions import get_session
|
||||
from ..services.showcase_service import ShowcaseService
|
||||
|
||||
showcase_bp = Blueprint("showcase", __name__, url_prefix="/api/showcase")
|
||||
|
||||
|
||||
@showcase_bp.route("", methods=["GET"])
|
||||
async def random_showcase():
|
||||
try:
|
||||
limit = int(request.args.get("limit", "60"))
|
||||
except ValueError:
|
||||
return jsonify({"error": "limit must be an integer"}), 400
|
||||
async with get_session() as session:
|
||||
svc = ShowcaseService(session)
|
||||
try:
|
||||
images = await svc.random_sample(limit=limit)
|
||||
except ValueError as exc:
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
return jsonify({"images": images})
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Random-sample query for the showcase.
|
||||
|
||||
Uses the tsm_system_rows TABLESAMPLE method (migration 0004) instead of
|
||||
ORDER BY random(): sampling cost scales with the sample size, not the table,
|
||||
so it stays fast as the collection grows. SYSTEM_ROWS(n) returns up to n
|
||||
rows; an empty table yields none.
|
||||
"""
|
||||
|
||||
from sqlalchemy import select, text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from ..models import ImageRecord
|
||||
from .gallery_service import thumbnail_url
|
||||
|
||||
|
||||
class ShowcaseService:
|
||||
def __init__(self, session: AsyncSession):
|
||||
self.session = session
|
||||
|
||||
async def random_sample(self, limit: int = 60) -> list[dict]:
|
||||
if limit < 1 or limit > 200:
|
||||
raise ValueError("limit must be between 1 and 200")
|
||||
stmt = select(ImageRecord).from_statement(
|
||||
text(
|
||||
"SELECT * FROM image_record "
|
||||
"TABLESAMPLE SYSTEM_ROWS(:n)"
|
||||
).bindparams(n=limit)
|
||||
)
|
||||
rows = (await self.session.execute(stmt)).scalars().all()
|
||||
return [
|
||||
{
|
||||
"id": r.id,
|
||||
"sha256": r.sha256,
|
||||
"mime": r.mime,
|
||||
"width": r.width,
|
||||
"height": r.height,
|
||||
"thumbnail_url": thumbnail_url(r.sha256, r.mime),
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
Reference in New Issue
Block a user