-
Notifications
You must be signed in to change notification settings - Fork 583
Implement Memories feature end-to-end (time & location based highlights) #773
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
amansingh-001
wants to merge
1
commit into
AOSSIE-Org:main
from
amansingh-001:feature/memories-end-to-end
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,171 @@ | ||
| """ | ||
| Memories API routes for retrieving auto-generated photo memories. | ||
| """ | ||
|
|
||
| from fastapi import APIRouter, HTTPException, status, Query | ||
| from typing import List, Optional | ||
| from pydantic import BaseModel | ||
| from app.utils.memories import generate_memories | ||
| from app.schemas.images import ErrorResponse | ||
| from app.logging.setup_logging import get_logger | ||
|
|
||
| logger = get_logger(__name__) | ||
| router = APIRouter() | ||
|
|
||
|
|
||
| # Response Models | ||
| class RepresentativeMedia(BaseModel): | ||
| """Representative media thumbnail for a memory.""" | ||
| id: str | ||
| thumbnailPath: str | ||
|
|
||
|
|
||
| class DateRange(BaseModel): | ||
| """Date range for a memory.""" | ||
| start: str | ||
| end: str | ||
|
|
||
|
|
||
| class Memory(BaseModel): | ||
| """A memory object containing clustered photos.""" | ||
| id: str | ||
| title: str | ||
| type: str # "on_this_day", "trip", "date_cluster", etc. | ||
| date_range: DateRange | ||
| location: Optional[str] = None | ||
| media_count: int | ||
| representative_media: List[RepresentativeMedia] | ||
| media_ids: List[str] | ||
|
|
||
|
|
||
| class GetMemoriesResponse(BaseModel): | ||
| """Response model for GET /memories endpoint.""" | ||
| success: bool | ||
| message: str | ||
| data: List[Memory] | ||
|
|
||
|
|
||
| @router.get( | ||
| "/", | ||
| response_model=GetMemoriesResponse, | ||
| responses={500: {"model": ErrorResponse}}, | ||
| ) | ||
| def get_memories( | ||
| limit: Optional[int] = Query(None, description="Maximum number of memories to return", ge=1, le=100) | ||
| ): | ||
| """ | ||
| Get all auto-generated memories. | ||
|
|
||
| Memories are automatically generated by clustering photos based on: | ||
| - Date similarity (same day, month, year, or "on this day" from past years) | ||
| - Geographic proximity (nearby locations) | ||
|
|
||
| Returns memories sorted by date (most recent first). | ||
| """ | ||
| try: | ||
| memories = generate_memories() | ||
|
|
||
| # Apply limit if specified | ||
| if limit is not None: | ||
| memories = memories[:limit] | ||
|
|
||
| # Convert to response models | ||
| memory_models = [ | ||
| Memory( | ||
| id=mem["id"], | ||
| title=mem["title"], | ||
| type=mem["type"], | ||
| date_range=DateRange( | ||
| start=mem["date_range"]["start"], | ||
| end=mem["date_range"]["end"], | ||
| ), | ||
| location=mem.get("location"), | ||
| media_count=mem["media_count"], | ||
| representative_media=[ | ||
| RepresentativeMedia( | ||
| id=media["id"], | ||
| thumbnailPath=media["thumbnailPath"], | ||
| ) | ||
| for media in mem["representative_media"] | ||
| ], | ||
| media_ids=mem["media_ids"], | ||
| ) | ||
| for mem in memories | ||
| ] | ||
|
|
||
| return GetMemoriesResponse( | ||
| success=True, | ||
| message=f"Successfully retrieved {len(memory_models)} memories", | ||
| data=memory_models, | ||
| ) | ||
|
|
||
| except Exception as e: | ||
| logger.error(f"Error retrieving memories: {e}", exc_info=True) | ||
| raise HTTPException( | ||
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | ||
| detail=ErrorResponse( | ||
| success=False, | ||
| error="Internal server error", | ||
| message=f"Unable to retrieve memories: {str(e)}", | ||
| ).model_dump(), | ||
| ) | ||
|
|
||
|
|
||
| @router.get( | ||
| "/{memory_id}", | ||
| response_model=Memory, | ||
| responses={404: {"model": ErrorResponse}, 500: {"model": ErrorResponse}}, | ||
| ) | ||
| def get_memory_by_id(memory_id: str): | ||
| """ | ||
| Get a specific memory by ID. | ||
| """ | ||
| try: | ||
| memories = generate_memories() | ||
|
|
||
| # Find memory by ID | ||
| memory = next((m for m in memories if m["id"] == memory_id), None) | ||
|
|
||
| if not memory: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_404_NOT_FOUND, | ||
| detail=ErrorResponse( | ||
| success=False, | ||
| error="Not Found", | ||
| message=f"Memory with ID '{memory_id}' not found", | ||
| ).model_dump(), | ||
| ) | ||
|
|
||
| return Memory( | ||
| id=memory["id"], | ||
| title=memory["title"], | ||
| type=memory["type"], | ||
| date_range=DateRange( | ||
| start=memory["date_range"]["start"], | ||
| end=memory["date_range"]["end"], | ||
| ), | ||
| location=memory.get("location"), | ||
| media_count=memory["media_count"], | ||
| representative_media=[ | ||
| RepresentativeMedia( | ||
| id=media["id"], | ||
| thumbnailPath=media["thumbnailPath"], | ||
| ) | ||
| for media in memory["representative_media"] | ||
| ], | ||
| media_ids=memory["media_ids"], | ||
| ) | ||
|
|
||
| except HTTPException: | ||
| raise | ||
| except Exception as e: | ||
| logger.error(f"Error retrieving memory {memory_id}: {e}", exc_info=True) | ||
| raise HTTPException( | ||
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | ||
| detail=ErrorResponse( | ||
| success=False, | ||
| error="Internal server error", | ||
| message=f"Unable to retrieve memory: {str(e)}", | ||
| ).model_dump(), | ||
| ) | ||
|
|
||
|
Comment on lines
+114
to
+171
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same error-shape + info-leak problem on 404/500 for @@
- if not memory:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=ErrorResponse(
- success=False,
- error="Not Found",
- message=f"Memory with ID '{memory_id}' not found",
- ).model_dump(),
- )
+ if not memory:
+ err = ErrorResponse(
+ success=False,
+ error="Not Found",
+ message=f"Memory with ID '{memory_id}' not found",
+ )
+ return JSONResponse(
+ status_code=status.HTTP_404_NOT_FOUND,
+ content=err.model_dump(),
+ )
@@
- except HTTPException:
- raise
except Exception as e:
logger.error(f"Error retrieving memory {memory_id}: {e}", exc_info=True)
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail=ErrorResponse(
- success=False,
- error="Internal server error",
- message=f"Unable to retrieve memory: {str(e)}",
- ).model_dump(),
- )
+ err = ErrorResponse(
+ success=False,
+ error="Internal server error",
+ message="Unable to retrieve memory",
+ )
+ return JSONResponse(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ content=err.model_dump(),
+ )🤖 Prompt for AI Agents |
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Error responses won’t match
ErrorResponseschema (wrapped underdetail) + leak internals.HTTPException(detail=ErrorResponse(...).model_dump())yields{"detail": {...}}, not anErrorResponsebody, andmessageechoesstr(e)to clients.🤖 Prompt for AI Agents