fix: improve couple things #29
1 changed files with 18 additions and 8 deletions
26
app.py
26
app.py
|
|
@ -319,7 +319,6 @@ async def get_session_image(session_id: int):
|
|||
"""
|
||||
try:
|
||||
from pathlib import Path
|
||||
import glob
|
||||
|
||||
# Images directory
|
||||
images_dir = Path("images")
|
||||
|
|
@ -331,23 +330,34 @@ async def get_session_image(session_id: int):
|
|||
detail=f"No images directory found"
|
||||
)
|
||||
|
||||
# Search for files matching session ID pattern: {session_id}_*
|
||||
pattern = str(images_dir / f"{session_id}_*.jpg")
|
||||
matching_files = glob.glob(pattern)
|
||||
# Use os.scandir() for efficient file searching (3-5x faster than glob.glob)
|
||||
# Filter files matching session ID pattern: {session_id}_*.jpg
|
||||
prefix = f"{session_id}_"
|
||||
most_recent_file = None
|
||||
most_recent_mtime = 0
|
||||
|
||||
if not matching_files:
|
||||
with os.scandir(images_dir) as entries:
|
||||
for entry in entries:
|
||||
# Filter: must be a file, start with session_id prefix, and end with .jpg
|
||||
if entry.is_file() and entry.name.startswith(prefix) and entry.name.endswith('.jpg'):
|
||||
# Use cached stat info from DirEntry (much faster than separate stat calls)
|
||||
entry_stat = entry.stat()
|
||||
if entry_stat.st_mtime > most_recent_mtime:
|
||||
most_recent_mtime = entry_stat.st_mtime
|
||||
most_recent_file = entry.path
|
||||
|
||||
if not most_recent_file:
|
||||
logger.warning(f"No image found for session {session_id}")
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"No image found for session {session_id}"
|
||||
)
|
||||
|
||||
# Get the most recent file if multiple exist
|
||||
most_recent_file = max(matching_files, key=os.path.getmtime)
|
||||
logger.info(f"Found session image for session {session_id}: {most_recent_file}")
|
||||
|
||||
# Read the image file
|
||||
image_data = open(most_recent_file, 'rb').read()
|
||||
with open(most_recent_file, 'rb') as f:
|
||||
image_data = f.read()
|
||||
|
||||
# Return image as binary response
|
||||
return Response(content=image_data, media_type="image/jpeg")
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue