MojoLlama
Archived Mojo/MAX quantizer and serving research repository (read-only history)
Brought by drakestapleton
MojoLlama / process_data.py
| 1 | from typing import Any |
| 2 | |
| 3 | |
| 4 | class InvalidItemTypeError(ValueError): |
| 5 | """Raised when an item has an invalid or missing 'type' field.""" |
| 6 | |
| 7 | |
| 8 | class MissingFieldError(KeyError): |
| 9 | """Raised when a required field is missing from an item.""" |
| 10 | |
| 11 | |
| 12 | def _process_user_item(item: dict[str, Any]) -> dict[str, Any]: |
| 13 | if "id" not in item or "name" not in item: |
| 14 | raise MissingFieldError("User items must have 'id' and 'name' fields") |
| 15 | return {"id": item["id"], "name": item["name"], "role": "user"} |
| 16 | |
| 17 | |
| 18 | def _process_admin_item(item: dict[str, Any]) -> dict[str, Any]: |
| 19 | if "id" not in item or "name" not in item: |
| 20 | raise MissingFieldError("Admin items must have 'id' and 'name' fields") |
| 21 | return { |
| 22 | "id": item["id"], |
| 23 | "name": item["name"], |
| 24 | "role": "admin", |
| 25 | "permissions": ["read", "write", "delete"], |
| 26 | } |
| 27 | |
| 28 | |
| 29 | def _process_guest_item(item: dict[str, Any]) -> dict[str, Any]: |
| 30 | if "id" not in item: |
| 31 | raise MissingFieldError("Guest items must have an 'id' field") |
| 32 | return { |
| 33 | "id": item["id"], |
| 34 | "name": item.get("name", "Guest"), |
| 35 | "role": "guest", |
| 36 | } |
| 37 | |
| 38 | |
| 39 | _ITEM_PROCESSORS: dict[str, Any] = { |
| 40 | "user": _process_user_item, |
| 41 | "admin": _process_admin_item, |
| 42 | "guest": _process_guest_item, |
| 43 | } |
| 44 | |
| 45 | |
| 46 | def process_item(item: dict[str, Any]) -> dict[str, Any]: |
| 47 | item_type = item.get("type") |
| 48 | if item_type not in _ITEM_PROCESSORS: |
| 49 | raise InvalidItemTypeError(f"Unknown or missing item type: {item_type!r}") |
| 50 | return _ITEM_PROCESSORS[item_type](item) |
| 51 | |
| 52 | |
| 53 | def process_data(data: list[dict[str, Any]]) -> list[dict[str, Any]]: |
| 54 | result = [process_item(item) for item in data] |
| 55 | result.sort(key=lambda x: x["id"]) |
| 56 | return result |