Add image service: Wikipedia photos + emoji fallback for vocabulary

image_service.py: Fetches thumbnail from Wikipedia REST API (free,
no account). Falls back to emoji for abstract words (40+ mapped).

Auto-enrichment: When a learning unit is created, images are
automatically fetched for all words that don't have one yet.

Manual endpoint: POST /api/vocabulary/enrich-images fills images
for existing words without images.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Benjamin Admin
2026-04-27 23:36:48 +02:00
parent 91d6918e2c
commit f6caa3091f
2 changed files with 142 additions and 0 deletions

View File

@@ -270,6 +270,13 @@ async def api_create_unit_from_words(payload: CreateUnitFromWordsPayload):
},
}, f, ensure_ascii=False, indent=2)
# Auto-enrich words with images (Wikipedia + emoji fallback)
try:
from services.image_service import enrich_words_with_images
await enrich_words_with_images(payload.word_ids)
except Exception as e:
logger.warning(f"Image enrichment failed (non-critical): {e}")
logger.info(f"Created vocab unit {lu.id} with {len(words)} words")
return {
@@ -347,6 +354,26 @@ async def api_bulk_import(payload: BulkImportPayload):
# ---------------------------------------------------------------------------
@router.post("/enrich-images")
async def api_enrich_images(word_ids: List[str] = None):
"""Fetch and store images for vocabulary words (Wikipedia + emoji fallback)."""
from services.image_service import enrich_words_with_images
from vocabulary.db import get_pool
import uuid as _uuid
if not word_ids:
pool = await get_pool()
async with pool.acquire() as conn:
rows = await conn.fetch("SELECT id FROM vocabulary_words WHERE image_url = '' OR image_url IS NULL")
word_ids = [str(r["id"]) for r in rows]
if not word_ids:
return {"enriched": 0, "message": "All words already have images"}
count = await enrich_words_with_images(word_ids)
return {"enriched": count, "total": len(word_ids)}
class TranslateRequest(BaseModel):
word_ids: List[str]
target_language: str