Files
FabledCurator/backend/app/api/suggestions.py
T
bvandeusen a444cf82d1
CI / backend-lint-and-test (push) Successful in 36s
CI / lint (push) Successful in 3s
CI / frontend-build (push) Successful in 20s
CI / integration (push) Successful in 3m45s
refactor(tags): unify suggestion source — one canonical DB-tag dropdown, drop dead raw/alias machinery (#154)
Every tag suggestion is a canonical DB tag now (tagging-v2 #114: heads + CCIP
score EXISTING concept tags). The pre-heads apparatus for model-predicted tags
that didn't exist in the DB — creates_new_tag / raw_name / via_alias, the
/suggestions/alias endpoint + add_alias_and_accept, AliasPickerDialog, and the
store's aliasAccept/removeAlias — was dead and is removed.

The type-to-add dropdown was TWO row sources (server autocomplete + the image's
ML suggestions) merged with a dedup that dropped the %-bearing suggestion row
when the debounced server hit landed — the operator's "confidence % flickers
then vanishes". Now it's ONE list of DB-tag matches, each annotated with the
model's confidence (join by canonical_tag_id) when the tag was scored for this
image. No dedup, no flicker; picking a suggested tag still records acceptance
via TagPanel.findPending.

Single per-image fetch: score_image now reports above_threshold per row
(computed vs the head's own suggest cut, separate from the inclusion floor), so
the rail makes ONE min=0 request and derives the panel (above_threshold) and the
dropdown (all, text-filtered) client-side — the two /suggestions calls collapse
to one. Manual "Create 'X' as <kind>" (novel typed names) is unchanged; the
alias table + tag-side alias admin + auto-apply alias matching are untouched.

Tests: gate/serializer assertions updated (above_threshold; dropped dead-field
+ alias-endpoint checks); frontend spec seeds via the single load and covers the
byCategory/aboveByCategory split.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CgZP9v2otxVJymiYsnVuMy
2026-07-10 15:22:51 -04:00

134 lines
5.2 KiB
Python

"""Suggestions API: per-image ranked suggestions + accept/alias/dismiss."""
from quart import Blueprint, jsonify, request
from ..extensions import get_session
from ..services.ml.allowlist import AllowlistService
from ..services.ml.suggestions import SuggestionService
suggestions_bp = Blueprint("suggestions", __name__, url_prefix="/api")
@suggestions_bp.route("/images/<int:image_id>/suggestions", methods=["GET"])
async def get_suggestions(image_id: int):
# ?min=<float> overrides the per-head suggest thresholds for INCLUSION. The
# rail sends min=0 in its single per-image fetch to get EVERY head (each row
# still carries above_threshold vs its natural cut), then derives the panel
# (above_threshold) and the typed dropdown (all, filtered by text) client-side
# — no second request. Omitted → only above-threshold rows.
override = None
raw_min = request.args.get("min")
if raw_min is not None:
try:
override = min(1.0, max(0.0, float(raw_min)))
except ValueError:
return jsonify({"error": "min must be a float in [0,1]"}), 400
async with get_session() as session:
sl = await SuggestionService(session).for_image(
image_id, threshold_override=override
)
return jsonify(
{
"by_category": {
cat: [
{
"canonical_tag_id": s.canonical_tag_id,
"display_name": s.display_name,
"category": s.category,
"score": round(s.score, 4),
"source": s.source,
# whether the score cleared the head's own suggest cut.
# The single min=0 fetch returns every head; the panel
# shows above_threshold, the typed dropdown shows all and
# annotates each match with its score.
"above_threshold": s.above_threshold,
# operator dismissed this tag for this image — surfaced
# (not dropped) so the rail can show it rejected + offer
# one-click un-reject.
"rejected": s.rejected,
# the crop region that produced this tag (#1206) —
# {bbox,kind,detector} or null (whole-image won). Drives
# the hover→overlay highlight.
"grounding": s.grounding,
}
for s in items
]
for cat, items in sl.by_category.items()
}
}
)
@suggestions_bp.route(
"/images/<int:image_id>/suggestions/accept", methods=["POST"]
)
async def accept_suggestion(image_id: int):
body = await request.get_json()
if not body or "tag_id" not in body:
return jsonify({"error": "tag_id required"}), 400
tag_id = body["tag_id"]
async with get_session() as session:
await AllowlistService(session).accept(image_id, tag_id)
await session.commit()
return jsonify({"accepted": True, "tag_id": tag_id})
@suggestions_bp.route(
"/images/<int:image_id>/suggestions/dismiss", methods=["POST"]
)
async def dismiss_suggestion(image_id: int):
body = await request.get_json()
if not body or "tag_id" not in body:
return jsonify({"error": "tag_id required"}), 400
async with get_session() as session:
await AllowlistService(session).dismiss(image_id, body["tag_id"])
await session.commit()
return "", 204
@suggestions_bp.route(
"/images/<int:image_id>/suggestions/undismiss", methods=["POST"]
)
async def undismiss_suggestion(image_id: int):
"""Reverse a per-image dismissal (reject-recovery). Idempotent — undoing a
tag that isn't rejected is a no-op delete."""
body = await request.get_json()
if not body or "tag_id" not in body:
return jsonify({"error": "tag_id required"}), 400
async with get_session() as session:
await AllowlistService(session).undismiss(image_id, body["tag_id"])
await session.commit()
return "", 204
@suggestions_bp.route("/suggestions/bulk", methods=["POST"])
async def bulk_suggestions():
body = await request.get_json()
if not body or "image_ids" not in body:
return jsonify({"error": "image_ids required"}), 400
raw = body["image_ids"]
if not isinstance(raw, list) or not raw:
return jsonify({"error": "image_ids must be a non-empty list"}), 400
try:
ids = [int(x) for x in raw]
except (TypeError, ValueError):
return jsonify({"error": "image_ids must be integers"}), 400
if len(ids) > 200:
return jsonify({"error": "selection too large (max 200)"}), 400
try:
threshold = float(body.get("threshold", 0.8))
except (TypeError, ValueError):
threshold = 0.8
threshold = min(1.0, max(0.0, threshold))
async with get_session() as session:
suggestions = await SuggestionService(session).for_selection(
ids, threshold=threshold
)
return jsonify(
{
"suggestions": suggestions,
"evaluated": len(ids),
"threshold": threshold,
}
)