Download encoder.py from sundaycoil/bookmark-manager: direct link, hf CLI and curl.
- Browser
- Download file 1.81 kB
-
https://huggingface.co/sundaycoil/bookmark-manager/resolve/main/encoder.py
- Command line
-
hf download hf://sundaycoil/bookmark-manager/encoder.py
-
curl -L -o encoder.py https://huggingface.co/sundaycoil/bookmark-manager/resolve/main/encoder.py
1.81 kB
| """Bookmark Manager — encoder for collection payloads.""" | |
| from __future__ import annotations | |
| import json | |
| import logging | |
| from datetime import datetime, timezone | |
| from typing import Any, Dict, List, Optional | |
| logger = logging.getLogger(__name__) | |
| class BookmarkEncoder: | |
| """Encoder for Bookmark Manager collection payloads.""" | |
| _DATE_FIELDS = ("saved_at") | |
| def loads(cls, raw: str) -> Dict[str, Any]: | |
| """Deserialise a JSON collection payload.""" | |
| data = json.loads(raw) | |
| return cls._coerce(data) | |
| def dumps(cls, record: Dict[str, Any]) -> str: | |
| """Serialise a collection record to JSON.""" | |
| return json.dumps(record, default=str) | |
| def _coerce(cls, data: Dict[str, Any]) -> Dict[str, Any]: | |
| """Cast known date fields from ISO strings to datetime objects.""" | |
| out: Dict[str, Any] = {} | |
| for k, v in data.items(): | |
| if k in cls._DATE_FIELDS and isinstance(v, str): | |
| try: | |
| out[k] = datetime.fromisoformat(v) | |
| except ValueError: | |
| out[k] = v | |
| else: | |
| out[k] = v | |
| return out | |
| def parse_collections(payload: str) -> List[Dict[str, Any]]: | |
| """Parse a JSON array of Collection payloads.""" | |
| raw = json.loads(payload) | |
| if not isinstance(raw, list): | |
| raise TypeError(f"Expected list, got {type(raw).__name__}") | |
| return [BookmarkEncoder._coerce(item) for item in raw] | |
| def save_collection_to_str( | |
| record: Dict[str, Any], indent: Optional[int] = None | |
| ) -> str: | |
| """Convenience wrapper — serialise a Collection to a JSON string.""" | |
| if indent is None: | |
| return BookmarkEncoder.dumps(record) | |
| return json.dumps(record, indent=indent, default=str) | |