feat: Enhance tag management with new API endpoints and frontend components

This commit introduces several new features for tag management, including the ability to retrieve tags for specific photos, update tag names, and delete tags through new API endpoints. The frontend has been updated to support these functionalities, allowing users to manage tags more effectively with a user-friendly interface. Additionally, new components for managing photo tags and bulk tagging have been added, improving overall usability. Documentation and tests have been updated to reflect these changes, ensuring reliability and user satisfaction.
This commit is contained in:
tanyar09
2025-11-04 12:16:22 -05:00
parent 91ee2ce8ab
commit 0a960a99ce
5 changed files with 1244 additions and 13 deletions
+93 -1
View File
@@ -14,13 +14,24 @@ from src.web.schemas.tags import (
TagCreateRequest,
TagResponse,
TagsResponse,
TagUpdateRequest,
TagDeleteRequest,
PhotoTagsListResponse,
PhotoTagItem,
PhotosWithTagsResponse,
PhotoWithTagsItem,
)
from src.web.services.tag_service import (
add_tags_to_photos,
get_or_create_tag,
list_tags,
remove_tags_from_photos,
get_photo_tags,
update_tag,
delete_tags,
get_photos_with_tags,
)
from src.web.db.models import Photo
router = APIRouter(prefix="/tags", tags=["tags"])
@@ -59,7 +70,7 @@ def add_tags_to_photos_endpoint(
)
photos_updated, tags_added = add_tags_to_photos(
db, request.photo_ids, request.tag_names
db, request.photo_ids, request.tag_names, request.linkage_type
)
return PhotoTagsResponse(
@@ -95,3 +106,84 @@ def remove_tags_from_photos_endpoint(
tags_removed=tags_removed,
)
@router.get("/photos/{photo_id}", response_model=PhotoTagsListResponse)
def get_photo_tags_endpoint(
photo_id: int, db: Session = Depends(get_db)
) -> PhotoTagsListResponse:
"""Get all tags for a specific photo."""
# Validate photo exists
photo = db.query(Photo).filter(Photo.id == photo_id).first()
if not photo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=f"Photo {photo_id} not found"
)
tags_data = get_photo_tags(db, photo_id)
items = [
PhotoTagItem(tag_id=tag_id, tag_name=tag_name, linkage_type=linkage_type)
for tag_id, tag_name, linkage_type in tags_data
]
return PhotoTagsListResponse(photo_id=photo_id, tags=items, total=len(items))
@router.put("/{tag_id}", response_model=TagResponse)
def update_tag_endpoint(
tag_id: int, request: TagUpdateRequest, db: Session = Depends(get_db)
) -> TagResponse:
"""Update a tag name."""
try:
tag = update_tag(db, tag_id, request.tag_name)
return TagResponse.model_validate(tag)
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)
)
@router.post("/delete", response_model=dict)
def delete_tags_endpoint(
request: TagDeleteRequest, db: Session = Depends(get_db)
) -> dict:
"""Delete tags and all their linkages."""
if not request.tag_ids:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="tag_ids list cannot be empty",
)
deleted_count = delete_tags(db, request.tag_ids)
return {
"message": f"Deleted {deleted_count} tag(s)",
"deleted_count": deleted_count,
}
@router.get("/photos", response_model=PhotosWithTagsResponse)
def get_photos_with_tags_endpoint(db: Session = Depends(get_db)) -> PhotosWithTagsResponse:
"""Get all photos with tags and face counts, matching desktop tag manager query exactly.
Returns all photos with their tags (comma-separated) and face counts,
ordered by date_taken DESC, filename.
"""
photos_data = get_photos_with_tags(db)
items = [
PhotoWithTagsItem(
id=p['id'],
filename=p['filename'],
path=p['path'],
processed=p['processed'],
date_taken=p['date_taken'],
date_added=p['date_added'],
face_count=p['face_count'],
tags=p['tags'],
)
for p in photos_data
]
return PhotosWithTagsResponse(items=items, total=len(items))
+49
View File
@@ -37,6 +37,7 @@ class PhotoTagsRequest(BaseModel):
photo_ids: List[int] = Field(..., description="Photo IDs")
tag_names: List[str] = Field(..., description="Tag names to add/remove")
linkage_type: int = Field(0, ge=0, le=1, description="Linkage type: 0=single, 1=bulk")
class PhotoTagsResponse(BaseModel):
@@ -47,3 +48,51 @@ class PhotoTagsResponse(BaseModel):
tags_added: int
tags_removed: int
class TagUpdateRequest(BaseModel):
"""Request to update a tag name."""
tag_name: str = Field(..., description="New tag name")
class TagDeleteRequest(BaseModel):
"""Request to delete tags."""
tag_ids: List[int] = Field(..., description="Tag IDs to delete")
class PhotoTagItem(BaseModel):
"""Tag item for a photo."""
tag_id: int
tag_name: str
linkage_type: int # 0=single, 1=bulk
class PhotoTagsListResponse(BaseModel):
"""Response for listing tags on a photo."""
photo_id: int
tags: List[PhotoTagItem]
total: int
class PhotoWithTagsItem(BaseModel):
"""Photo item with tags for tag manager."""
id: int
filename: str
path: str
processed: bool
date_taken: Optional[str] = None
date_added: Optional[str] = None
face_count: int
tags: str # Comma-separated tags string (matching desktop)
class PhotosWithTagsResponse(BaseModel):
"""Response for listing photos with tags."""
items: List[PhotoWithTagsItem]
total: int
+157 -8
View File
@@ -3,10 +3,11 @@
from __future__ import annotations
from typing import List, Optional
from datetime import datetime
from sqlalchemy.orm import Session
from src.web.db.models import Photo, PhotoTagLinkage, Tag
from src.web.db.models import Photo, PhotoTagLinkage, Tag, Face
def list_tags(db: Session) -> List[Tag]:
@@ -33,9 +34,14 @@ def get_or_create_tag(db: Session, tag_name: str) -> Tag:
def add_tags_to_photos(
db: Session, photo_ids: List[int], tag_names: List[str]
db: Session, photo_ids: List[int], tag_names: List[str], linkage_type: int = 0
) -> tuple[int, int]:
"""Add tags to photos.
"""Add tags to photos, matching desktop logic exactly.
Desktop logic:
- linkage_type: 0 = single (manually added to individual photo)
- linkage_type: 1 = bulk (applied to all photos in folder)
- Uses INSERT ... ON CONFLICT DO UPDATE to update linkage_type if exists
Returns:
Tuple of (photos_updated, tags_added)
@@ -43,7 +49,7 @@ def add_tags_to_photos(
photos_updated = 0
tags_added = 0
# Deduplicate tag names (case-insensitive)
# Deduplicate tag names (case-insensitive) - matching desktop deduplicate_tags
seen_tags = set()
unique_tags = []
for tag_name in tag_names:
@@ -55,13 +61,13 @@ def add_tags_to_photos(
if not unique_tags:
return 0, 0
# Get or create tags
# Get or create tags (matching desktop add_tag)
tag_objs = []
for tag_name in unique_tags:
tag = get_or_create_tag(db, tag_name)
tag_objs.append(tag)
# Add tags to photos
# Add tags to photos (matching desktop link_photo_tag with linkage_type)
for photo_id in photo_ids:
photo = db.query(Photo).filter(Photo.id == photo_id).first()
if not photo:
@@ -77,8 +83,19 @@ def add_tags_to_photos(
)
.first()
)
if not existing:
linkage = PhotoTagLinkage(photo_id=photo_id, tag_id=tag.id)
if existing:
# Update linkage_type if different (matching desktop ON CONFLICT DO UPDATE)
if existing.linkage_type != linkage_type:
existing.linkage_type = linkage_type
existing.created_date = datetime.utcnow()
tags_added += 1
else:
# Create new linkage with linkage_type
linkage = PhotoTagLinkage(
photo_id=photo_id,
tag_id=tag.id,
linkage_type=linkage_type,
)
db.add(linkage)
tags_added += 1
@@ -133,3 +150,135 @@ def remove_tags_from_photos(
db.commit()
return photos_updated, tags_removed
def get_photo_tags(db: Session, photo_id: int) -> List[tuple[int, str, int]]:
"""Get all tags for a photo, matching desktop logic exactly.
Returns:
List of (tag_id, tag_name, linkage_type) tuples
"""
linkages = (
db.query(PhotoTagLinkage, Tag)
.join(Tag, PhotoTagLinkage.tag_id == Tag.id)
.filter(PhotoTagLinkage.photo_id == photo_id)
.order_by(Tag.tag_name)
.all()
)
return [
(linkage.tag_id, tag.tag_name, linkage.linkage_type)
for linkage, tag in linkages
]
def update_tag(db: Session, tag_id: int, new_tag_name: str) -> Tag:
"""Update a tag name, matching desktop logic exactly.
Desktop logic:
- Updates tag_name in tags table
- Case-insensitive check for duplicates
"""
tag = db.query(Tag).filter(Tag.id == tag_id).first()
if not tag:
raise ValueError(f"Tag {tag_id} not found")
# Check if new name already exists (case-insensitive)
existing = (
db.query(Tag)
.filter(Tag.tag_name.ilike(new_tag_name.strip()))
.filter(Tag.id != tag_id)
.first()
)
if existing:
raise ValueError(f"Tag name '{new_tag_name}' already exists")
tag.tag_name = new_tag_name.strip()
db.commit()
db.refresh(tag)
return tag
def delete_tags(db: Session, tag_ids: List[int]) -> int:
"""Delete tags and all their linkages, matching desktop logic exactly.
Desktop logic:
- Deletes all phototaglinkage entries for these tags
- Deletes the tags themselves
Returns:
Number of tags deleted
"""
if not tag_ids:
return 0
# Delete all linkages for these tags (matching desktop)
db.query(PhotoTagLinkage).filter(PhotoTagLinkage.tag_id.in_(tag_ids)).delete(
synchronize_session=False
)
# Delete the tags themselves
deleted_count = db.query(Tag).filter(Tag.id.in_(tag_ids)).delete(
synchronize_session=False
)
db.commit()
return deleted_count
def get_photos_with_tags(db: Session) -> List[dict]:
"""Get all photos with tags and face counts, matching desktop query exactly.
Desktop query:
SELECT p.id, p.filename, p.path, p.processed, p.date_taken, p.date_added,
(SELECT COUNT(*) FROM faces f WHERE f.photo_id = p.id) as face_count,
(SELECT GROUP_CONCAT(DISTINCT t.tag_name)
FROM phototaglinkage ptl
JOIN tags t ON t.id = ptl.tag_id
WHERE ptl.photo_id = p.id) as tags
FROM photos p
ORDER BY p.date_taken DESC, p.filename
Returns:
List of dicts with photo info, face_count, and tags (comma-separated string)
"""
from sqlalchemy import func
# Get all photos with face counts and tags
photos = (
db.query(Photo)
.order_by(Photo.date_taken.desc().nullslast(), Photo.filename)
.all()
)
result = []
for photo in photos:
# Get face count
face_count = (
db.query(func.count(Face.id))
.filter(Face.photo_id == photo.id)
.scalar() or 0
)
# Get tags as comma-separated string (matching desktop GROUP_CONCAT)
tags_query = (
db.query(Tag.tag_name)
.join(PhotoTagLinkage, Tag.id == PhotoTagLinkage.tag_id)
.filter(PhotoTagLinkage.photo_id == photo.id)
.order_by(Tag.tag_name)
.all()
)
tags = ", ".join([t[0] for t in tags_query]) if tags_query else ""
result.append({
'id': photo.id,
'filename': photo.filename,
'path': photo.path,
'processed': photo.processed,
'date_taken': photo.date_taken.isoformat() if photo.date_taken else None,
'date_added': photo.date_added.isoformat() if photo.date_added else None,
'face_count': face_count,
'tags': tags,
})
return result