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_processor.py · 10.1 KB · 242 lines
| 1 | """system_scan_processor -- read what arrived, guess, and stop there. |
| 2 | |
| 3 | POST {limit?, engine?, today?} -- the scheduled pass that turns pending |
| 4 | scans into suggestions. It never posts anything; producing a confirmable |
| 5 | draft is the whole of its job (docs/logic-decisions.md #6 -- extraction |
| 6 | is a suggestion, the write that matters is human-confirmed). |
| 7 | |
| 8 | Engine selection is configuration, not code (app_settings |
| 9 | intake.ocr_engine): |
| 10 | |
| 11 | text_rules the default and the FREE path -- regex over whatever text is |
| 12 | already on the scan. No model, no key, no per-page cost, and |
| 13 | it degrades to "found nothing, here is your image" rather |
| 14 | than to wrong numbers. |
| 15 | tesseract local OCR when pytesseract and PIL are installed on the host. |
| 16 | Absent, the pass says so and leaves the scan pending rather |
| 17 | than failing it: a missing system package is an operator's |
| 18 | problem to fix, not a document to give up on. |
| 19 | ai_vision object_ai with the owner's own key. Better guesses, and the |
| 20 | only path with a real per-page cost -- which is why it is |
| 21 | opt-in and why the key is theirs. |
| 22 | |
| 23 | Whatever the engine, the output lands in the same shape |
| 24 | (object_intake.normalize_extraction), so the confirm step cannot tell |
| 25 | which one read the document and does not care. That is what lets the |
| 26 | cheap path be the default without the expensive path being a rewrite. |
| 27 | |
| 28 | Failure posture: attempts are counted and a document that keeps failing |
| 29 | stops being retried and starts being VISIBLE. Churning a paid extractor |
| 30 | forever against a corrupt PDF is how an intake queue silently spends |
| 31 | money. |
| 32 | """ |
| 33 | |
| 34 | import json |
| 35 | import os |
| 36 | from datetime import date |
| 37 | |
| 38 | import object_access |
| 39 | import object_corrections |
| 40 | import object_intake |
| 41 | import object_records |
| 42 | import object_user_files |
| 43 | |
| 44 | ACTOR = "system_scan_processor" |
| 45 | |
| 46 | DEFAULT_LIMIT = 25 |
| 47 | MAX_ATTEMPTS = 3 |
| 48 | |
| 49 | |
| 50 | def _base_dir(): |
| 51 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 52 | |
| 53 | |
| 54 | def _setting(base, key, default=""): |
| 55 | try: |
| 56 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 57 | if row.get("key") == key and str(row.get("value") or "").strip(): |
| 58 | return row["value"].strip() |
| 59 | except Exception: |
| 60 | pass |
| 61 | return default |
| 62 | |
| 63 | |
| 64 | def _int(value, default=0): |
| 65 | try: |
| 66 | return int(str(value or "").strip() or default) |
| 67 | except (TypeError, ValueError): |
| 68 | return default |
| 69 | |
| 70 | |
| 71 | def _text(value): |
| 72 | return str(value if value is not None else "").strip() |
| 73 | |
| 74 | |
| 75 | NOT_ITS_DOCUMENT = ("this scan does not point at the document intake stored " |
| 76 | "for it, so it was not read") |
| 77 | |
| 78 | |
| 79 | def _stored_document(base, scan): |
| 80 | """The bytes intake stored for THIS scan, under its owner, or None. |
| 81 | |
| 82 | The processor runs as the system and reads storage directly, so it is |
| 83 | the only gate between a scan row and a file's bytes. It reads exactly |
| 84 | one file: `scan-{id}` under the scan's owner, which is the name |
| 85 | action_scan_ingest gives the bytes it stores and the only name it |
| 86 | gives. file_id is read-only in the schema, but a row written below |
| 87 | the record API (an import, a restore, a hand edit) could still name |
| 88 | another of the owner's files, or a path that happens to exist, and |
| 89 | the text read would land on a row its writer can see. Anything else |
| 90 | is refused without being opened. Files uploaded through /api/files |
| 91 | are never named scan-*, so their policy is never in question here. |
| 92 | """ |
| 93 | scan_id = _text(scan.get("id")) |
| 94 | owner = _text(scan.get("owner_id")) |
| 95 | if not (scan_id and owner) or _text(scan.get("file_id")) != f"scan-{scan_id}": |
| 96 | return None |
| 97 | return object_user_files.read_file(owner, f"scan-{scan_id}", base_dir=base) |
| 98 | |
| 99 | |
| 100 | def _read_text(base, scan, engine): |
| 101 | """Whatever text we can get, and how we got it. |
| 102 | |
| 103 | Returns (text, engine_used, error, recoverable). `recoverable` is |
| 104 | carried explicitly rather than sniffed out of the error message |
| 105 | later, because the two failures need opposite treatment and telling |
| 106 | them apart by substring is the kind of thing that silently stops |
| 107 | working when somebody rewords a message: |
| 108 | |
| 109 | recoverable -- the HOST is not set up (a package missing, an engine |
| 110 | not built in). The document is fine; leave it pending so fixing |
| 111 | the host drains the backlog. |
| 112 | not recoverable -- THIS document could not be read. Count the |
| 113 | attempt against it, so a corrupt file surfaces instead of |
| 114 | churning an extractor forever. |
| 115 | |
| 116 | Text already on the scan wins outright: a forwarded email receipt |
| 117 | needs no OCR, and re-reading an image we already read is pure cost. |
| 118 | """ |
| 119 | existing = _text(scan.get("ocr_text")) |
| 120 | if existing: |
| 121 | return existing, _text(scan.get("ocr_engine")) or "supplied", "", False |
| 122 | |
| 123 | if engine == "tesseract": |
| 124 | try: |
| 125 | import pytesseract # noqa: F401 |
| 126 | from PIL import Image # noqa: F401 |
| 127 | except ImportError: |
| 128 | return "", "", ("tesseract engine selected but pytesseract/PIL are " |
| 129 | "not installed on this host"), True |
| 130 | try: |
| 131 | import io |
| 132 | |
| 133 | content = _stored_document(base, scan) |
| 134 | if content is None: |
| 135 | return "", "", NOT_ITS_DOCUMENT, False |
| 136 | image = Image.open(io.BytesIO(content)) |
| 137 | return pytesseract.image_to_string(image), "tesseract", "", False |
| 138 | except Exception as exc: |
| 139 | return "", "", f"tesseract failed: {str(exc)[:120]}", False |
| 140 | |
| 141 | if engine == "ai_vision": |
| 142 | try: |
| 143 | import object_ai |
| 144 | except ImportError: |
| 145 | return "", "", "ai_vision engine selected but object_ai is unavailable", True |
| 146 | reader = getattr(object_ai, "read_document", None) |
| 147 | if reader is None: |
| 148 | return "", "", ("ai_vision engine selected but object_ai has no " |
| 149 | "document reader on this build"), True |
| 150 | try: |
| 151 | content = _stored_document(base, scan) |
| 152 | except Exception as exc: |
| 153 | return "", "", f"could not read the stored document: {str(exc)[:120]}", False |
| 154 | if content is None: |
| 155 | return "", "", NOT_ITS_DOCUMENT, False |
| 156 | try: |
| 157 | return (_text(reader(content, kind=_text(scan.get("category_hint")))), |
| 158 | "ai_vision", "", False) |
| 159 | except Exception as exc: |
| 160 | return "", "", f"ai_vision failed: {str(exc)[:120]}", False |
| 161 | |
| 162 | # text_rules and anything unrecognised: we read what is there, which |
| 163 | # for an image with no OCR engine is nothing -- and nothing is an |
| 164 | # honest answer that still leaves a confirmable draft. |
| 165 | return "", "text_rules", "", False |
| 166 | |
| 167 | |
| 168 | def POST(request): |
| 169 | base = _base_dir() |
| 170 | # The action is the grant: a pass spends the owner's AI budget and |
| 171 | # touches every pending scan, everybody's, so over HTTP it asks for |
| 172 | # itself that the caller is staff (an admin, or a role the installed |
| 173 | # execute rules name for this object; app-intake names none) instead |
| 174 | # of leaning on a rule that is only asked with enforcement on. With |
| 175 | # enforcement off any signed-in user could start one. The scheduler |
| 176 | # and other in-process callers send no _identity and run as the system. |
| 177 | if "_identity" in request: |
| 178 | access = object_access.Access(request.get("_identity"), base_dir=base) |
| 179 | staff = object_corrections.staff_refusal(access, "system_scan_processor", |
| 180 | doing="start a scan reading pass") |
| 181 | if staff: |
| 182 | return staff |
| 183 | limit = _int(request.get("limit"), DEFAULT_LIMIT) or DEFAULT_LIMIT |
| 184 | engine = (_text(request.get("engine")) |
| 185 | or _setting(base, "intake.ocr_engine", "text_rules")) |
| 186 | |
| 187 | try: |
| 188 | scans = object_records.read_collection_records("scans", base_dir=base) |
| 189 | except Exception: |
| 190 | return {"ok": True, "skipped": "intake not installed (scans absent)"} |
| 191 | |
| 192 | pending = [row for row in scans |
| 193 | if _text(row.get("status")) in ("pending", "processing") |
| 194 | and _int(row.get("attempts")) < MAX_ATTEMPTS] |
| 195 | pending.sort(key=lambda row: _text(row.get("created_at"))) |
| 196 | |
| 197 | read = extracted = failed = 0 |
| 198 | results = [] |
| 199 | for scan in pending[:limit]: |
| 200 | attempts = _int(scan.get("attempts")) + 1 |
| 201 | text, engine_used, error, recoverable = _read_text(base, scan, engine) |
| 202 | if error: |
| 203 | # A host misconfiguration leaves the document PENDING (fix the |
| 204 | # host, run again); a genuine read failure counts against it. |
| 205 | object_records.update_collection_record( |
| 206 | "scans", scan["id"], |
| 207 | {"status": "pending" if recoverable else "error", |
| 208 | "attempts": str(attempts), "error": error}, |
| 209 | base_dir=base, actor=ACTOR) |
| 210 | failed += 1 |
| 211 | results.append({"scan": scan["id"], "error": error}) |
| 212 | continue |
| 213 | |
| 214 | suggestion = object_intake.guess_from_text( |
| 215 | text, kind_hint=_text(scan.get("category_hint"))) |
| 216 | if engine_used and engine_used not in ("text_rules", "supplied"): |
| 217 | suggestion["engine"] = engine_used |
| 218 | object_records.update_collection_record( |
| 219 | "scans", scan["id"], |
| 220 | { |
| 221 | "status": "extracted", |
| 222 | "ocr_text": text, |
| 223 | "ocr_engine": engine_used or "text_rules", |
| 224 | "extracted": json.dumps(suggestion), |
| 225 | "confidence": str(suggestion["confidence"]), |
| 226 | "attempts": str(attempts), |
| 227 | "error": "", |
| 228 | }, |
| 229 | base_dir=base, actor=ACTOR) |
| 230 | read += 1 if text else 0 |
| 231 | extracted += 1 |
| 232 | results.append({"scan": scan["id"], "engine": engine_used, |
| 233 | "total_cents": suggestion["total_cents"], |
| 234 | "confidence": suggestion["confidence"]}) |
| 235 | |
| 236 | stuck = [row["id"] for row in scans |
| 237 | if _int(row.get("attempts")) >= MAX_ATTEMPTS |
| 238 | and _text(row.get("status")) == "error"] |
| 239 | return {"ok": True, "today": _text(request.get("today")) or date.today().isoformat(), |
| 240 | "engine": engine, "considered": len(pending), "extracted": extracted, |
| 241 | "text_read": read, "failed": failed, |
| 242 | "needing_a_human": stuck, "results": results} |