askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
scan_ingest.py · 7.4 KB · 178 lines
| 1 | """action_scan_ingest -- get the paper in, fast, and get out of the way. |
| 2 | |
| 3 | POST {content_base64 | text, filename?, content_type?, source?, |
| 4 | category_hint?, notes?, entity_id?} |
| 5 | |
| 6 | entity_id points the scan at a set of books, and is checked as the record |
| 7 | API checks it (scans.json: relation.requires update), before anything is |
| 8 | stored. |
| 9 | |
| 10 | Ingest is deliberately dumb and deliberately quick. It stores the bytes, |
| 11 | records that a document arrived, and returns -- no OCR, no model call, no |
| 12 | waiting. The reason is behavioural rather than technical: capture has to |
| 13 | happen at the moment the paper exists, standing at a till with a phone, |
| 14 | and anything that makes that moment slower is a receipt that ends up in a |
| 15 | coat pocket instead. Reading it is the processor's problem, later. |
| 16 | |
| 17 | Deduplication is by content hash and lives in the hook, so the second |
| 18 | photo of the same crumpled receipt lands on the scan that already exists |
| 19 | rather than becoming a second expense. That is the normal case, not an |
| 20 | edge case. |
| 21 | |
| 22 | `text` is accepted alongside bytes for documents that arrive as text |
| 23 | already -- a forwarded email receipt, an MCP agent pasting what it read. |
| 24 | Same pipeline, no image, and the free extractor works on it directly. |
| 25 | """ |
| 26 | |
| 27 | import base64 |
| 28 | import hashlib |
| 29 | import os |
| 30 | |
| 31 | import object_access |
| 32 | import object_ids |
| 33 | import object_records |
| 34 | import object_user_files |
| 35 | |
| 36 | ACTOR = "action_scan_ingest" |
| 37 | |
| 38 | MAX_BYTES = 50 * 1024 * 1024 # the predecessor's cap, and a sane one |
| 39 | |
| 40 | SOURCES = ("web", "phone", "email", "mcp", "api") |
| 41 | HINTS = ("receipt", "bill", "invoice", "statement", "document", "photo") |
| 42 | |
| 43 | |
| 44 | def _base_dir(): |
| 45 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 46 | |
| 47 | |
| 48 | def _text(value): |
| 49 | return str(value if value is not None else "").strip() |
| 50 | |
| 51 | |
| 52 | def _owner(request, base): |
| 53 | """Whose scan this is: (owner, refusal). |
| 54 | |
| 55 | Over HTTP the server sets `_identity` (a client cannot), and the scan |
| 56 | is the caller's. An `owner_id` in the body naming somebody else is |
| 57 | refused unless the caller is an admin, the same answer the record API |
| 58 | gives a create that names another owner: it used to win over the |
| 59 | identity, so any signed-in user could file a scan -- and store its |
| 60 | bytes -- under anybody's account. A request with no `_identity` at |
| 61 | all is an in-process call, which names its owner itself. |
| 62 | """ |
| 63 | asked = _text(request.get("owner_id")) |
| 64 | if "_identity" not in request: |
| 65 | return asked, None |
| 66 | identity = request.get("_identity") or {} |
| 67 | caller = _text(identity.get("user_id")) or _text(identity.get("id")) |
| 68 | if not asked or asked == caller: |
| 69 | return caller, None |
| 70 | access = object_access.Access(identity, base_dir=base) |
| 71 | if identity.get("auth_method") == "admin_token" or access.is_admin: |
| 72 | return asked, None |
| 73 | return "", {"status": 403, "code": "forbidden", "field": "owner_id", |
| 74 | "error": ("owner_id names another user. A scan you send in is " |
| 75 | "yours: leave owner_id out (or send your own id). " |
| 76 | "Nothing was stored.")} |
| 77 | |
| 78 | |
| 79 | def POST(request): |
| 80 | base = _base_dir() |
| 81 | owner, refusal = _owner(request, base) |
| 82 | if refusal: |
| 83 | return refusal |
| 84 | if not owner: |
| 85 | return {"status": 401, |
| 86 | "error": "Ingest needs an owner: a scan belongs to somebody."} |
| 87 | |
| 88 | raw = request.get("content_base64") |
| 89 | body = None |
| 90 | if raw: |
| 91 | try: |
| 92 | body = base64.b64decode(_text(raw), validate=True) |
| 93 | except Exception: |
| 94 | return {"status": 400, "error": "content_base64 is not valid base64."} |
| 95 | elif _text(request.get("text")): |
| 96 | body = _text(request.get("text")).encode("utf-8") |
| 97 | |
| 98 | if not body: |
| 99 | return {"status": 400, |
| 100 | "error": "Nothing to ingest: send content_base64 or text."} |
| 101 | if len(body) > MAX_BYTES: |
| 102 | return {"status": 413, |
| 103 | "error": f"Document exceeds the {MAX_BYTES // (1024 * 1024)}MB cap."} |
| 104 | |
| 105 | digest = hashlib.sha256(body).hexdigest() |
| 106 | source = _text(request.get("source")) or "web" |
| 107 | hint = _text(request.get("category_hint")) or "receipt" |
| 108 | if source not in SOURCES: |
| 109 | return {"status": 400, "error": f"source must be one of {', '.join(SOURCES)}"} |
| 110 | if hint not in HINTS: |
| 111 | return {"status": 400, "error": f"category_hint must be one of {', '.join(HINTS)}"} |
| 112 | |
| 113 | # The schema's unique key on content_sha256 (per owner) is the authority |
| 114 | # on duplicates, inside the write lock. This read stays for what that |
| 115 | # refusal cannot do: answer "already received" with the earlier scan's id |
| 116 | # as a success, and keep the bytes of a re-snapped receipt from being |
| 117 | # written a second time before the create is refused. |
| 118 | try: |
| 119 | # access: the caller's own scan: owner_id is the caller's user_id |
| 120 | for row in object_records.read_collection_records("scans", base_dir=base): |
| 121 | if (row.get("content_sha256") == digest |
| 122 | and _text(row.get("owner_id")) == owner): |
| 123 | return {"ok": True, "scan_id": row["id"], "duplicate": True, |
| 124 | "status_of_scan": row.get("status"), |
| 125 | "note": "this document was already received"} |
| 126 | except Exception: |
| 127 | return {"status": 503, |
| 128 | "error": "Scan history unreadable; refusing to ingest against " |
| 129 | "an unknown history rather than risk a duplicate."} |
| 130 | |
| 131 | scan_id = object_ids.new_uuid4() |
| 132 | file_id = f"scan-{scan_id}" |
| 133 | is_text = _text(request.get("text")) and not raw |
| 134 | record = { |
| 135 | "id": scan_id, |
| 136 | "filename": _text(request.get("filename")) or f"{hint}-{scan_id[:8]}", |
| 137 | "content_type": (_text(request.get("content_type")) |
| 138 | or ("text/plain" if is_text else "application/octet-stream")), |
| 139 | "size": str(len(body)), |
| 140 | "content_sha256": digest, |
| 141 | "file_id": file_id, |
| 142 | "source": source, |
| 143 | "category_hint": hint, |
| 144 | "status": "pending", |
| 145 | # Text that arrived as text needs no OCR pass to have text. |
| 146 | "ocr_text": body.decode("utf-8", "replace") if is_text else "", |
| 147 | "notes": _text(request.get("notes")), |
| 148 | "owner_id": owner, |
| 149 | "entity_id": _text(request.get("entity_id")), |
| 150 | } |
| 151 | |
| 152 | # The pointers came from the request, and this write goes below the |
| 153 | # record API, so ask its question here, before any bytes are stored: |
| 154 | # entity_id requires update on the entity (scans.json), and a scan |
| 155 | # pointed at somebody else's books was confirmed into an expense, and |
| 156 | # then a journal, in those books. A missing entity and one the caller |
| 157 | # may not see get the record API's one answer. |
| 158 | refusal = object_access.Access(request.get("_identity"), base_dir=base).relation_refusal( |
| 159 | "scans", record) |
| 160 | if refusal: |
| 161 | status, answer = refusal |
| 162 | return {**answer, "status": status} |
| 163 | |
| 164 | try: |
| 165 | size = object_user_files.save_file(owner, file_id, body, base_dir=base) |
| 166 | except Exception as exc: |
| 167 | return {"status": 500, "error": f"Could not store the document: {str(exc)[:120]}"} |
| 168 | record["size"] = str(size) |
| 169 | |
| 170 | # access: the caller's own scan: owner_id is the caller's user_id; its entity_id passed relation_refusal above |
| 171 | object_records.create_collection_record( |
| 172 | "scans", record, |
| 173 | # file_id is read-only in the schema: only this action names the |
| 174 | # bytes a scan stands for, and the processor reads nothing else. |
| 175 | base_dir=base, actor=ACTOR, preserve_read_only=True) |
| 176 | |
| 177 | return {"ok": True, "scan_id": scan_id, "size": size, "status_of_scan": "pending", |
| 178 | "note": "stored; reading happens on the next intake pass"} |