sticker_cache.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. """Sticker description cache for Telegram.
  2. Stickers are described via the vision tool once and cached by file_unique_id
  3. (``~/.hermes/sticker_cache.json``) so the same image is never re-analyzed.
  4. """
  5. import asyncio
  6. import json
  7. import threading
  8. import time
  9. from pathlib import Path
  10. from typing import Optional
  11. from hermes_cli.config import get_hermes_home
  12. from utils import atomic_json_write
  13. CACHE_PATH = get_hermes_home() / "sticker_cache.json"
  14. _CACHE_PATH_AT_IMPORT = CACHE_PATH
  15. def _resolve_cache_path() -> Path:
  16. """Active profile's cache file at call time: the patched ``CACHE_PATH`` when a test changed
  17. it, else live profile-scoped HERMES_HOME — under the multiplexed gateway one process serves
  18. every profile, so the import-time constant would pin every profile to the launch home."""
  19. return CACHE_PATH if CACHE_PATH != _CACHE_PATH_AT_IMPORT else get_hermes_home() / "sticker_cache.json"
  20. # Kept concise to save tokens.
  21. STICKER_VISION_PROMPT = (
  22. "Describe this sticker in 1-2 sentences. Focus on what it depicts -- "
  23. "character, action, emotion. Be concise and objective."
  24. )
  25. def _load_cache() -> dict:
  26. """Load the sticker cache from disk (utf-8-sig: BOM-tolerant read fix)."""
  27. path = _resolve_cache_path()
  28. if path.exists():
  29. try:
  30. return json.loads(path.read_text(encoding="utf-8-sig"))
  31. except (json.JSONDecodeError, OSError): # OSError covers FileNotFoundError
  32. return {}
  33. return {}
  34. def _save_cache(cache: dict) -> None:
  35. atomic_json_write(_resolve_cache_path(), cache)
  36. # Serializes the read-modify-write in ``cache_sticker_description``. Nothing
  37. # re-acquires it while held (the async wrapper only dispatches the sync form
  38. # to a worker thread), so a plain Lock suffices.
  39. _CACHE_LOCK = threading.Lock()
  40. def get_cached_description(file_unique_id: str) -> Optional[dict]:
  41. """Return ``{description, emoji, set_name, cached_at}`` or None."""
  42. return _load_cache().get(file_unique_id)
  43. def cache_sticker_description(
  44. file_unique_id: str, description: str, emoji: str = "", set_name: str = ""
  45. ) -> None:
  46. """Store a vision-generated description under Telegram's stable sticker id.
  47. Blocking: ``atomic_json_write`` ends in ``os.replace``. Callers on the event
  48. loop must use :func:`cache_sticker_description_async`.
  49. """
  50. entry = {"description": description, "emoji": emoji, "set_name": set_name,
  51. "cached_at": time.time()}
  52. # The lock makes the load/mutate/save triple atomic across worker threads.
  53. with _CACHE_LOCK:
  54. _save_cache({**_load_cache(), file_unique_id: entry})
  55. async def cache_sticker_description_async(
  56. file_unique_id: str, description: str, emoji: str = "", set_name: str = ""
  57. ) -> None:
  58. """Off-loop form of :func:`cache_sticker_description`.
  59. The write ends in ``os.replace``, whose duration is unbounded under
  60. filesystem pressure, and the only caller is Telegram's ``_handle_sticker``
  61. -- an inbound-message coroutine. Paying the rename inline stalls every
  62. adapter and every in-flight turn in the process for its duration.
  63. """
  64. await asyncio.to_thread(
  65. cache_sticker_description, file_unique_id, description, emoji, set_name
  66. )
  67. def build_sticker_injection(description: str, emoji: str = "", set_name: str = "") -> str:
  68. """Warm-style injection text, e.g.
  69. ``[The user sent a sticker 😀 from "MyPack"~ It shows: "A cat waving" (=^.w.^=)]``.
  70. ``set_name`` is only shown together with an emoji."""
  71. context = f" {emoji}" if emoji else ""
  72. if set_name and emoji:
  73. context += f' from "{set_name}"'
  74. return f'[The user sent a sticker{context}~ It shows: "{description}" (=^.w.^=)]'
  75. def build_animated_sticker_injection(emoji: str = "") -> str:
  76. """Injection text for animated/video stickers we can't analyze."""
  77. if emoji:
  78. return (f"[The user sent an animated sticker {emoji}~ "
  79. f"I can't see animated ones yet, but the emoji suggests: {emoji}]")
  80. return "[The user sent an animated sticker~ I can't see animated ones yet]"