|
| 1 | +"""OG Image endpoints for branded social media preview images.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | + |
| 5 | +import httpx |
| 6 | +from fastapi import APIRouter, Depends, HTTPException |
| 7 | +from fastapi.responses import Response |
| 8 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 9 | + |
| 10 | +from api.cache import cache_key, get_cache, set_cache |
| 11 | +from api.dependencies import optional_db |
| 12 | +from core.database import SpecRepository |
| 13 | +from core.images import create_branded_og_image, create_og_collage |
| 14 | + |
| 15 | + |
| 16 | +router = APIRouter(prefix="/og", tags=["og-images"]) |
| 17 | + |
| 18 | +# Cache TTL for generated images (1 hour) |
| 19 | +OG_IMAGE_CACHE_TTL = 3600 |
| 20 | + |
| 21 | + |
| 22 | +async def _fetch_image(url: str) -> bytes: |
| 23 | + """Fetch an image from a URL.""" |
| 24 | + async with httpx.AsyncClient(timeout=30.0) as client: |
| 25 | + response = await client.get(url) |
| 26 | + response.raise_for_status() |
| 27 | + return response.content |
| 28 | + |
| 29 | + |
| 30 | +@router.get("/{spec_id}/{library}.png") |
| 31 | +async def get_branded_impl_image( |
| 32 | + spec_id: str, library: str, db: AsyncSession | None = Depends(optional_db) |
| 33 | +) -> Response: |
| 34 | + """Get a branded OG image for an implementation. |
| 35 | +
|
| 36 | + Returns a 1200x630 PNG with pyplots.ai header and the plot image. |
| 37 | + """ |
| 38 | + # Check cache first |
| 39 | + key = cache_key("og", spec_id, library) |
| 40 | + cached = get_cache(key) |
| 41 | + if cached: |
| 42 | + return Response(content=cached, media_type="image/png", headers={"Cache-Control": "public, max-age=3600"}) |
| 43 | + |
| 44 | + if db is None: |
| 45 | + raise HTTPException(status_code=503, detail="Database not available") |
| 46 | + |
| 47 | + repo = SpecRepository(db) |
| 48 | + spec = await repo.get_by_id(spec_id) |
| 49 | + if not spec: |
| 50 | + raise HTTPException(status_code=404, detail="Spec not found") |
| 51 | + |
| 52 | + # Find the implementation |
| 53 | + impl = next((i for i in spec.impls if i.library_id == library), None) |
| 54 | + if not impl or not impl.preview_url: |
| 55 | + raise HTTPException(status_code=404, detail="Implementation not found") |
| 56 | + |
| 57 | + try: |
| 58 | + # Fetch the original plot image |
| 59 | + image_bytes = await _fetch_image(impl.preview_url) |
| 60 | + |
| 61 | + # Create branded image |
| 62 | + branded_bytes = create_branded_og_image(image_bytes, spec_id=spec_id, library=library) |
| 63 | + |
| 64 | + # Cache the result |
| 65 | + set_cache(key, branded_bytes, ttl=OG_IMAGE_CACHE_TTL) |
| 66 | + |
| 67 | + return Response( |
| 68 | + content=branded_bytes, media_type="image/png", headers={"Cache-Control": "public, max-age=3600"} |
| 69 | + ) |
| 70 | + |
| 71 | + except httpx.HTTPError as e: |
| 72 | + raise HTTPException(status_code=502, detail=f"Failed to fetch image: {e}") from e |
| 73 | + |
| 74 | + |
| 75 | +@router.get("/{spec_id}.png") |
| 76 | +async def get_spec_collage_image(spec_id: str, db: AsyncSession | None = Depends(optional_db)) -> Response: |
| 77 | + """Get a collage OG image for a spec (showing top 6 implementations by quality). |
| 78 | +
|
| 79 | + Returns a 1200x630 PNG with pyplots.ai branding and a 2x3 grid of implementations, |
| 80 | + sorted by quality_score descending. |
| 81 | + """ |
| 82 | + # Check cache first |
| 83 | + key = cache_key("og", spec_id, "collage") |
| 84 | + cached = get_cache(key) |
| 85 | + if cached: |
| 86 | + return Response(content=cached, media_type="image/png", headers={"Cache-Control": "public, max-age=3600"}) |
| 87 | + |
| 88 | + if db is None: |
| 89 | + raise HTTPException(status_code=503, detail="Database not available") |
| 90 | + |
| 91 | + repo = SpecRepository(db) |
| 92 | + spec = await repo.get_by_id(spec_id) |
| 93 | + if not spec: |
| 94 | + raise HTTPException(status_code=404, detail="Spec not found") |
| 95 | + |
| 96 | + # Get implementations with preview images |
| 97 | + impls_with_preview = [i for i in spec.impls if i.preview_url] |
| 98 | + if not impls_with_preview: |
| 99 | + raise HTTPException(status_code=404, detail="No implementations with previews") |
| 100 | + |
| 101 | + # Sort by quality_score (descending) and take top 6 for 2x3 grid |
| 102 | + sorted_impls = sorted( |
| 103 | + impls_with_preview, key=lambda i: i.quality_score if i.quality_score is not None else 0, reverse=True |
| 104 | + ) |
| 105 | + selected_impls = sorted_impls[:6] |
| 106 | + |
| 107 | + try: |
| 108 | + # Fetch all images in parallel for better performance |
| 109 | + images = list(await asyncio.gather(*[_fetch_image(impl.preview_url) for impl in selected_impls])) |
| 110 | + labels = [f"{spec_id} · {impl.library_id}" for impl in selected_impls] |
| 111 | + |
| 112 | + # Create collage |
| 113 | + collage_bytes = create_og_collage(images, labels=labels) |
| 114 | + |
| 115 | + # Cache the result |
| 116 | + set_cache(key, collage_bytes, ttl=OG_IMAGE_CACHE_TTL) |
| 117 | + |
| 118 | + return Response( |
| 119 | + content=collage_bytes, media_type="image/png", headers={"Cache-Control": "public, max-age=3600"} |
| 120 | + ) |
| 121 | + |
| 122 | + except httpx.HTTPError as e: |
| 123 | + raise HTTPException(status_code=502, detail=f"Failed to fetch images: {e}") from e |
0 commit comments