doc-redaction 2.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. agent_routes.py +1020 -0
  2. app.py +10418 -0
  3. cli_redact.py +2658 -0
  4. doc_redaction/__init__.py +27 -0
  5. doc_redaction/api.py +41 -0
  6. doc_redaction/cli_api.py +359 -0
  7. doc_redaction/cli_redact.py +26 -0
  8. doc_redaction/data_anonymise.py +9 -0
  9. doc_redaction/file_conversion.py +14 -0
  10. doc_redaction/file_redaction.py +16 -0
  11. doc_redaction/find_duplicate_pages.py +12 -0
  12. doc_redaction/find_duplicate_tabular.py +9 -0
  13. doc_redaction/gradio_app.py +23 -0
  14. doc_redaction/helper_functions.py +9 -0
  15. doc_redaction/install_deps.py +389 -0
  16. doc_redaction/lambda_entrypoint.py +17 -0
  17. doc_redaction/redaction_review.py +21 -0
  18. doc_redaction/summaries.py +9 -0
  19. doc_redaction-2.2.0.dist-info/METADATA +394 -0
  20. doc_redaction-2.2.0.dist-info/RECORD +61 -0
  21. doc_redaction-2.2.0.dist-info/WHEEL +5 -0
  22. doc_redaction-2.2.0.dist-info/entry_points.txt +4 -0
  23. doc_redaction-2.2.0.dist-info/top_level.txt +9 -0
  24. lambda_entrypoint.py +803 -0
  25. load_dynamo_logs.py +278 -0
  26. load_s3_logs.py +187 -0
  27. mcp_doc_redaction/__init__.py +1 -0
  28. mcp_doc_redaction/artifact_bundle.py +88 -0
  29. mcp_doc_redaction/gradio_transport.py +294 -0
  30. mcp_doc_redaction/schemas.py +72 -0
  31. mcp_doc_redaction/server.py +299 -0
  32. tools/__init__.py +11 -0
  33. tools/apply_hf_zero_gpu_readme_frontmatter.py +48 -0
  34. tools/auth.py +88 -0
  35. tools/aws_functions.py +461 -0
  36. tools/aws_textract.py +1271 -0
  37. tools/cli_usage_logger.py +337 -0
  38. tools/config.py +2662 -0
  39. tools/custom_csvlogger.py +335 -0
  40. tools/custom_image_analyser_engine.py +12882 -0
  41. tools/data_anonymise.py +1938 -0
  42. tools/file_conversion.py +3919 -0
  43. tools/file_redaction.py +13087 -0
  44. tools/find_duplicate_pages.py +2190 -0
  45. tools/find_duplicate_tabular.py +742 -0
  46. tools/helper_functions.py +2125 -0
  47. tools/llm_entity_detection.py +1167 -0
  48. tools/llm_entity_detection_prompts.py +102 -0
  49. tools/llm_funcs.py +2119 -0
  50. tools/load_spacy_model_custom_recognisers.py +974 -0
  51. tools/presidio_analyzer_custom.py +142 -0
  52. tools/quickstart.py +934 -0
  53. tools/redaction_review.py +5274 -0
  54. tools/redaction_types.py +137 -0
  55. tools/run_vlm.py +1363 -0
  56. tools/secure_path_utils.py +426 -0
  57. tools/secure_regex_utils.py +297 -0
  58. tools/simplified_api.py +1120 -0
  59. tools/summaries.py +2434 -0
  60. tools/textract_batch_call.py +954 -0
  61. tools/word_segmenter.py +2011 -0
agent_routes.py ADDED
@@ -0,0 +1,1020 @@
1
+ """
2
+ FastAPI routes for programmatic / agent callers.
3
+
4
+ HTTP paths align with Gradio ``api_name`` values in app.py. See GET /agent/operations
5
+ for the full map. Uses cli_redact.main(direct_mode_args=...) where a CLI task exists.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import io
11
+ import os
12
+ import sys
13
+ from pathlib import Path
14
+ from typing import Any, Dict, List, Optional
15
+
16
+ from fastapi import APIRouter, Depends, Header, HTTPException
17
+ from fastapi.responses import JSONResponse
18
+ from pydantic import BaseModel, Field, field_validator
19
+
20
+ from tools.config import (
21
+ AWS_LLM_PII_OPTION,
22
+ AWS_PII_OPTION,
23
+ INFERENCE_SERVER_PII_OPTION,
24
+ INPUT_FOLDER,
25
+ LOCAL_OCR_MODEL_OPTIONS,
26
+ LOCAL_PII_OPTION,
27
+ LOCAL_TRANSFORMERS_LLM_PII_OPTION,
28
+ OUTPUT_FOLDER,
29
+ )
30
+ from tools.secure_path_utils import validate_path_safety
31
+
32
+ router = APIRouter(tags=["Agent"])
33
+
34
+ REPO_ROOT = Path(__file__).resolve().parent
35
+ _MAX_INSTRUCTION_LEN = 16_000
36
+
37
+ # NOTE: Paths from request bodies are untrusted. Avoid Path.resolve() on untrusted
38
+ # input (CodeQL py/path-injection); instead normalize via os.path and enforce
39
+ # containment under trusted roots.
40
+
41
+ # Mirrors app.py api_name values (Gradio).
42
+ GRADIO_API_NAMES: tuple[str, ...] = (
43
+ "redact_document",
44
+ "load_and_prepare_documents_or_data",
45
+ "apply_review_redactions",
46
+ "review_apply",
47
+ "pdf_summarise",
48
+ "tabular_redact",
49
+ "word_level_ocr_text_search",
50
+ "redact_data",
51
+ "find_duplicate_pages",
52
+ "find_duplicate_tabular",
53
+ "summarise_document",
54
+ "combine_review_csvs",
55
+ "combine_review_pdfs",
56
+ "export_review_redaction_overlay",
57
+ "export_review_page_ocr_visualisation",
58
+ )
59
+
60
+
61
+ def _allowed_path_roots() -> list[Path]:
62
+ # Return roots without resolving. These are trusted config values, but avoiding
63
+ # Path.resolve() keeps CodeQL happy and matches our "no resolve on untrusted"
64
+ # approach elsewhere.
65
+ roots = [REPO_ROOT]
66
+ for folder in (INPUT_FOLDER, OUTPUT_FOLDER):
67
+ if folder:
68
+ roots.append(Path(str(folder)))
69
+ return roots
70
+
71
+
72
+ def _sanitize_untrusted_path_input(path_str: str) -> str:
73
+ """Basic raw-input validation before any path normalization."""
74
+ if not isinstance(path_str, str):
75
+ raise HTTPException(status_code=400, detail="Path must be a string.")
76
+ cleaned = path_str.strip()
77
+ if not cleaned:
78
+ raise HTTPException(status_code=400, detail="Path must not be empty.")
79
+ if "\x00" in cleaned:
80
+ raise HTTPException(status_code=400, detail="Path contains invalid null byte.")
81
+ return cleaned
82
+
83
+
84
+ def _normalize_untrusted_path_to_abs(path_str: str) -> str:
85
+ """
86
+ Expand ~, then normalize to an absolute path.
87
+
88
+ Relative paths are interpreted relative to REPO_ROOT (matching prior behaviour).
89
+ """
90
+ safe_input = _sanitize_untrusted_path_input(path_str)
91
+ expanded = os.path.expanduser(safe_input)
92
+ if os.path.isabs(expanded):
93
+ return os.path.normpath(os.path.abspath(expanded))
94
+ return os.path.normpath(os.path.abspath(os.path.join(str(REPO_ROOT), expanded)))
95
+
96
+
97
+ def _must_be_under_allowed_roots(candidate_abs: str, original: str) -> None:
98
+ """Enforce candidate is contained under repo, INPUT_FOLDER, or OUTPUT_FOLDER."""
99
+ candidate_real = os.path.realpath(str(candidate_abs))
100
+ allowed_roots = [
101
+ os.path.realpath(os.path.abspath(str(p))) for p in _allowed_path_roots()
102
+ ]
103
+ for root in allowed_roots:
104
+ try:
105
+ common = os.path.commonpath([candidate_real, root])
106
+ except ValueError:
107
+ # Different drive on Windows or invalid path mix
108
+ continue
109
+ if common == root:
110
+ return
111
+ raise HTTPException(
112
+ status_code=403,
113
+ detail="Path must be under the app repo, INPUT_FOLDER, or OUTPUT_FOLDER",
114
+ )
115
+
116
+
117
+ def _path_must_be_allowed_file(path_str: str) -> str:
118
+ """Resolve path, ensure it is under an allowed root and exists as a file."""
119
+ candidate_abs = _normalize_untrusted_path_to_abs(path_str)
120
+ candidate_real = os.path.realpath(candidate_abs)
121
+
122
+ # Validate both "safe path" patterns and containment under trusted roots.
123
+ _must_be_under_allowed_roots(candidate_real, path_str)
124
+ ok = any(
125
+ validate_path_safety(candidate_real, base_path=str(root))
126
+ for root in _allowed_path_roots()
127
+ )
128
+ if not ok:
129
+ raise HTTPException(status_code=400, detail=f"Unsafe path rejected: {path_str}")
130
+ try:
131
+ candidate_path = Path(candidate_real)
132
+ if not candidate_path.is_file():
133
+ raise HTTPException(
134
+ status_code=400, detail=f"Not a file or missing: {candidate_real}"
135
+ )
136
+ except OSError:
137
+ raise HTTPException(
138
+ status_code=400, detail=f"Not a file or missing: {candidate_real}"
139
+ )
140
+ return candidate_real
141
+
142
+
143
+ def _path_must_be_allowed_directory(path_str: str, *, must_exist: bool = True) -> str:
144
+ """
145
+ Normalize and validate a directory path under allowed roots.
146
+
147
+ By default the directory must already exist; callers can opt out (e.g. output_dir
148
+ that will be created later by the CLI).
149
+ """
150
+ candidate_abs = _normalize_untrusted_path_to_abs(path_str)
151
+ candidate_real = os.path.realpath(candidate_abs)
152
+
153
+ _must_be_under_allowed_roots(candidate_real, path_str)
154
+ ok = any(
155
+ validate_path_safety(candidate_real, base_path=str(root))
156
+ for root in _allowed_path_roots()
157
+ )
158
+ if not ok:
159
+ raise HTTPException(status_code=400, detail=f"Unsafe path rejected: {path_str}")
160
+ if must_exist:
161
+ try:
162
+ if not Path(candidate_real).is_dir():
163
+ raise HTTPException(
164
+ status_code=400, detail=f"Not a directory: {candidate_real}"
165
+ )
166
+ except OSError:
167
+ raise HTTPException(
168
+ status_code=400, detail=f"Not a directory: {candidate_real}"
169
+ )
170
+ return candidate_real
171
+
172
+
173
+ def _optional_agent_api_key(x_agent_api_key: Optional[str] = Header(None)) -> None:
174
+ expected = os.environ.get("AGENT_API_KEY", "").strip()
175
+ if not expected:
176
+ return
177
+ if not x_agent_api_key or x_agent_api_key.strip() != expected:
178
+ raise HTTPException(
179
+ status_code=401,
180
+ detail="Set header X-Agent-API-Key to match AGENT_API_KEY environment variable",
181
+ )
182
+
183
+
184
+ class AgentRedactDocumentRequest(BaseModel):
185
+ """Parity with Gradio api_name ``redact_document``."""
186
+
187
+ input_files: list[str] = Field(
188
+ ...,
189
+ min_length=1,
190
+ description="Paths to input files (PDF, images, or tabular/Word for anonymisation)",
191
+ )
192
+ instruction: Optional[str] = Field(
193
+ None,
194
+ description="Optional instructions for LLM-based PII detection (custom_llm_instructions)",
195
+ )
196
+ output_dir: Optional[str] = None
197
+ input_dir: Optional[str] = None
198
+ ocr_method: Optional[str] = Field(
199
+ None,
200
+ description=(
201
+ "High-level OCR/text mode. Accepted values: 'Local OCR', "
202
+ "'AWS Textract', 'Local text'. To choose a specific local OCR engine "
203
+ "(e.g. paddle/tesseract/vlm), set "
204
+ "overrides.chosen_local_ocr_model."
205
+ ),
206
+ )
207
+ pii_detector: Optional[str] = Field(
208
+ None,
209
+ description=(
210
+ "PII detection method. Recommended configured labels: "
211
+ f"'{LOCAL_PII_OPTION}', '{AWS_PII_OPTION}', '{AWS_LLM_PII_OPTION}', "
212
+ f"'{INFERENCE_SERVER_PII_OPTION}', '{LOCAL_TRANSFORMERS_LLM_PII_OPTION}', "
213
+ "'None'."
214
+ ),
215
+ )
216
+ overrides: Optional[dict[str, Any]] = Field(
217
+ None,
218
+ description=(
219
+ "Optional CLI flag overrides; keys must match argparse destination names. "
220
+ "For local OCR model selection, set 'chosen_local_ocr_model' "
221
+ f"(allowed models depend on deployment; configured options: {LOCAL_OCR_MODEL_OPTIONS})."
222
+ ),
223
+ )
224
+
225
+ model_config = {
226
+ "json_schema_extra": {
227
+ "examples": [
228
+ {
229
+ "input_files": [
230
+ "example_data/example_of_emails_sent_to_a_professor_before_applying.pdf"
231
+ ],
232
+ "instruction": "Do not redact the university name.",
233
+ "ocr_method": "Local OCR",
234
+ "pii_detector": LOCAL_PII_OPTION,
235
+ "overrides": {"chosen_local_ocr_model": "paddle"},
236
+ }
237
+ ]
238
+ }
239
+ }
240
+
241
+ @field_validator("instruction")
242
+ @classmethod
243
+ def _cap_instruction(cls, v: Optional[str]) -> Optional[str]:
244
+ if v is None:
245
+ return v
246
+ if len(v) > _MAX_INSTRUCTION_LEN:
247
+ raise ValueError(f"instruction exceeds {_MAX_INSTRUCTION_LEN} characters")
248
+ return v
249
+
250
+
251
+ class AgentRedactDataRequest(AgentRedactDocumentRequest):
252
+ """Parity with Gradio api_name ``redact_data``; same CLI task as redact_document."""
253
+
254
+
255
+ class AgentTaskResponse(BaseModel):
256
+ status: str
257
+ gradio_api_name: str
258
+ task: str
259
+ output_dir: str
260
+ input_dir: str
261
+ message: str
262
+ log_excerpt: Optional[str] = None
263
+ output_paths: Optional[list[str]] = None
264
+
265
+
266
+ def _merge_redact_direct_mode(body: AgentRedactDocumentRequest) -> dict[str, Any]:
267
+ from cli_redact import get_cli_default_args_dict
268
+
269
+ merged: dict[str, Any] = get_cli_default_args_dict()
270
+ merged["task"] = "redact"
271
+ merged["input_file"] = [_path_must_be_allowed_file(p) for p in body.input_files]
272
+
273
+ if body.instruction is not None:
274
+ merged["custom_llm_instructions"] = body.instruction
275
+ if body.output_dir is not None:
276
+ # Output folders may not exist yet (CLI will create). Still constrain to allowed roots.
277
+ merged["output_dir"] = _path_must_be_allowed_directory(
278
+ body.output_dir, must_exist=False
279
+ )
280
+ if body.input_dir is not None:
281
+ # Input dir should exist if provided.
282
+ merged["input_dir"] = _path_must_be_allowed_directory(
283
+ body.input_dir, must_exist=True
284
+ )
285
+ if body.ocr_method is not None:
286
+ merged["ocr_method"] = body.ocr_method
287
+ if body.pii_detector is not None:
288
+ merged["pii_detector"] = body.pii_detector
289
+
290
+ if body.overrides:
291
+ allowed = set(merged.keys())
292
+ for key, value in body.overrides.items():
293
+ if key not in allowed:
294
+ raise HTTPException(
295
+ status_code=400,
296
+ detail=f"Unknown override key '{key}'. Must be a known CLI argument name.",
297
+ )
298
+ merged[key] = value
299
+
300
+ return merged
301
+
302
+
303
+ def _run_cli_main(direct: dict[str, Any], gradio_api_name: str) -> AgentTaskResponse:
304
+ from cli_redact import main as cli_main
305
+
306
+ buf = io.StringIO()
307
+ old_stdout = sys.stdout
308
+ try:
309
+ sys.stdout = buf
310
+ cli_main(direct_mode_args=direct)
311
+ except Exception as e:
312
+ raise HTTPException(status_code=500, detail=str(e)) from e
313
+ finally:
314
+ sys.stdout = old_stdout
315
+
316
+ log_excerpt = buf.getvalue()
317
+ if len(log_excerpt) > 8000:
318
+ log_excerpt = log_excerpt[-8000:]
319
+
320
+ return AgentTaskResponse(
321
+ status="completed",
322
+ gradio_api_name=gradio_api_name,
323
+ task=str(direct.get("task", "")),
324
+ output_dir=str(direct.get("output_dir", "")),
325
+ input_dir=str(direct.get("input_dir", "")),
326
+ message="cli_redact.main finished; see log_excerpt for console output",
327
+ log_excerpt=log_excerpt or None,
328
+ )
329
+
330
+
331
+ @router.post(
332
+ "/redact_document",
333
+ response_model=AgentTaskResponse,
334
+ summary="redact_document (Gradio api_name)",
335
+ description=(
336
+ "Matches Gradio ``api_name='redact_document'``. "
337
+ "``python cli_redact.py --task redact --input_file ...``. "
338
+ "Optional ``instruction`` maps to ``custom_llm_instructions``. "
339
+ "OCR modes: 'Local OCR' | 'AWS Textract' | 'Local text'. "
340
+ "Specific local OCR engines are set via ``overrides.chosen_local_ocr_model`` "
341
+ f"(for example: {LOCAL_OCR_MODEL_OPTIONS}). "
342
+ "PII methods should use configured labels shown on the request schema."
343
+ ),
344
+ )
345
+ def post_redact_document(
346
+ body: AgentRedactDocumentRequest,
347
+ _: None = Depends(_optional_agent_api_key),
348
+ ) -> AgentTaskResponse:
349
+ direct = _merge_redact_direct_mode(body)
350
+ return _run_cli_main(direct, "redact_document")
351
+
352
+
353
+ @router.post(
354
+ "/redact_data",
355
+ response_model=AgentTaskResponse,
356
+ summary="redact_data (Gradio api_name)",
357
+ description=(
358
+ "Matches Gradio ``api_name='redact_data'``. Same CLI ``redact`` task as "
359
+ "/redact_document; use CSV/XLSX/DOCX paths for tabular/Word flows. "
360
+ "OCR modes: 'Local OCR' | 'AWS Textract' | 'Local text'. "
361
+ "Specific local OCR engines are set via ``overrides.chosen_local_ocr_model`` "
362
+ f"(for example: {LOCAL_OCR_MODEL_OPTIONS}). "
363
+ "PII methods should use configured labels shown on the request schema."
364
+ ),
365
+ )
366
+ def post_redact_data(
367
+ body: AgentRedactDataRequest,
368
+ _: None = Depends(_optional_agent_api_key),
369
+ ) -> AgentTaskResponse:
370
+ direct = _merge_redact_direct_mode(body)
371
+ return _run_cli_main(direct, "redact_data")
372
+
373
+
374
+ @router.post(
375
+ "/tasks/redact",
376
+ response_model=AgentTaskResponse,
377
+ summary="Legacy: same as /redact_document",
378
+ description="Deprecated alias; prefer POST /agent/redact_document.",
379
+ deprecated=True,
380
+ include_in_schema=True,
381
+ )
382
+ def post_tasks_redact_legacy(
383
+ body: AgentRedactDocumentRequest,
384
+ _: None = Depends(_optional_agent_api_key),
385
+ ) -> AgentTaskResponse:
386
+ direct = _merge_redact_direct_mode(body)
387
+ return _run_cli_main(direct, "redact_document")
388
+
389
+
390
+ class AgentFindDuplicatePagesRequest(BaseModel):
391
+ input_files: list[str] = Field(..., min_length=1)
392
+ similarity_threshold: Optional[float] = None
393
+ min_word_count: Optional[int] = None
394
+ min_consecutive_pages: Optional[int] = None
395
+ greedy_match: Optional[bool] = None
396
+ combine_pages: Optional[bool] = None
397
+ overrides: Optional[dict[str, Any]] = None
398
+
399
+
400
+ @router.post(
401
+ "/find_duplicate_pages",
402
+ response_model=AgentTaskResponse,
403
+ summary="find_duplicate_pages (Gradio api_name)",
404
+ description="``cli_redact --task deduplicate --duplicate_type pages``.",
405
+ )
406
+ def post_find_duplicate_pages(
407
+ body: AgentFindDuplicatePagesRequest,
408
+ _: None = Depends(_optional_agent_api_key),
409
+ ) -> AgentTaskResponse:
410
+ from cli_redact import get_cli_default_args_dict
411
+
412
+ merged = get_cli_default_args_dict()
413
+ merged["task"] = "deduplicate"
414
+ merged["duplicate_type"] = "pages"
415
+ merged["input_file"] = [_path_must_be_allowed_file(p) for p in body.input_files]
416
+ if body.similarity_threshold is not None:
417
+ merged["similarity_threshold"] = body.similarity_threshold
418
+ if body.min_word_count is not None:
419
+ merged["min_word_count"] = body.min_word_count
420
+ if body.min_consecutive_pages is not None:
421
+ merged["min_consecutive_pages"] = body.min_consecutive_pages
422
+ if body.greedy_match is not None:
423
+ merged["greedy_match"] = "True" if body.greedy_match else "False"
424
+ if body.combine_pages is not None:
425
+ merged["combine_pages"] = "True" if body.combine_pages else "False"
426
+ if body.overrides:
427
+ allowed = set(merged.keys())
428
+ for k, v in body.overrides.items():
429
+ if k not in allowed:
430
+ raise HTTPException(400, f"Unknown override key: {k}")
431
+ merged[k] = v
432
+ return _run_cli_main(merged, "find_duplicate_pages")
433
+
434
+
435
+ class AgentFindDuplicateTabularRequest(BaseModel):
436
+ input_files: list[str] = Field(..., min_length=1)
437
+ text_columns: Optional[list[str]] = None
438
+ similarity_threshold: Optional[float] = None
439
+ min_word_count: Optional[int] = None
440
+ overrides: Optional[dict[str, Any]] = None
441
+
442
+
443
+ @router.post(
444
+ "/find_duplicate_tabular",
445
+ response_model=AgentTaskResponse,
446
+ summary="find_duplicate_tabular (Gradio api_name)",
447
+ )
448
+ def post_find_duplicate_tabular(
449
+ body: AgentFindDuplicateTabularRequest,
450
+ _: None = Depends(_optional_agent_api_key),
451
+ ) -> AgentTaskResponse:
452
+ from cli_redact import get_cli_default_args_dict
453
+
454
+ merged = get_cli_default_args_dict()
455
+ merged["task"] = "deduplicate"
456
+ merged["duplicate_type"] = "tabular"
457
+ merged["input_file"] = [_path_must_be_allowed_file(p) for p in body.input_files]
458
+ if body.text_columns is not None:
459
+ merged["text_columns"] = body.text_columns
460
+ if body.similarity_threshold is not None:
461
+ merged["similarity_threshold"] = body.similarity_threshold
462
+ if body.min_word_count is not None:
463
+ merged["min_word_count"] = body.min_word_count
464
+ if body.overrides:
465
+ allowed = set(merged.keys())
466
+ for k, v in body.overrides.items():
467
+ if k not in allowed:
468
+ raise HTTPException(400, f"Unknown override key: {k}")
469
+ merged[k] = v
470
+ return _run_cli_main(merged, "find_duplicate_tabular")
471
+
472
+
473
+ class AgentSummariseDocumentRequest(BaseModel):
474
+ input_files: list[str] = Field(..., min_length=1)
475
+ summarisation_inference_method: Optional[str] = None
476
+ summarisation_format: Optional[str] = None
477
+ summarisation_context: Optional[str] = None
478
+ summarisation_additional_instructions: Optional[str] = None
479
+ overrides: Optional[dict[str, Any]] = None
480
+
481
+
482
+ @router.post(
483
+ "/summarise_document",
484
+ response_model=AgentTaskResponse,
485
+ summary="summarise_document (Gradio api_name)",
486
+ )
487
+ def post_summarise_document(
488
+ body: AgentSummariseDocumentRequest,
489
+ _: None = Depends(_optional_agent_api_key),
490
+ ) -> AgentTaskResponse:
491
+ from cli_redact import get_cli_default_args_dict
492
+
493
+ merged = get_cli_default_args_dict()
494
+ merged["task"] = "summarise"
495
+ merged["input_file"] = [_path_must_be_allowed_file(p) for p in body.input_files]
496
+ if body.summarisation_inference_method is not None:
497
+ merged["summarisation_inference_method"] = body.summarisation_inference_method
498
+ if body.summarisation_format is not None:
499
+ merged["summarisation_format"] = body.summarisation_format
500
+ if body.summarisation_context is not None:
501
+ merged["summarisation_context"] = body.summarisation_context
502
+ if body.summarisation_additional_instructions is not None:
503
+ merged["summarisation_additional_instructions"] = (
504
+ body.summarisation_additional_instructions
505
+ )
506
+ if body.overrides:
507
+ allowed = set(merged.keys())
508
+ for k, v in body.overrides.items():
509
+ if k not in allowed:
510
+ raise HTTPException(400, f"Unknown override key: {k}")
511
+ merged[k] = v
512
+ return _run_cli_main(merged, "summarise_document")
513
+
514
+
515
+ class AgentCombineReviewPdfsRequest(BaseModel):
516
+ input_files: list[str] = Field(..., min_length=2)
517
+ output_dir: Optional[str] = None
518
+
519
+
520
+ @router.post(
521
+ "/combine_review_pdfs",
522
+ response_model=AgentTaskResponse,
523
+ summary="combine_review_pdfs (Gradio api_name)",
524
+ )
525
+ def post_combine_review_pdfs(
526
+ body: AgentCombineReviewPdfsRequest,
527
+ _: None = Depends(_optional_agent_api_key),
528
+ ) -> AgentTaskResponse:
529
+ from cli_redact import get_cli_default_args_dict
530
+
531
+ merged = get_cli_default_args_dict()
532
+ merged["task"] = "combine_review_pdfs"
533
+ merged["input_file"] = [_path_must_be_allowed_file(p) for p in body.input_files]
534
+ if body.output_dir is not None:
535
+ merged["output_dir"] = _path_must_be_allowed_directory(body.output_dir)
536
+ return _run_cli_main(merged, "combine_review_pdfs")
537
+
538
+
539
+ class _NamedPath:
540
+ """merge_csv_files expects objects with a .name attribute (Gradio file-like)."""
541
+
542
+ __slots__ = ("name",)
543
+
544
+ def __init__(self, path: str) -> None:
545
+ self.name = path
546
+
547
+
548
+ class AgentCombineReviewCsvsRequest(BaseModel):
549
+ input_files: list[str] = Field(..., min_length=1)
550
+ output_dir: Optional[str] = Field(
551
+ None, description="Defaults to config OUTPUT_FOLDER"
552
+ )
553
+
554
+
555
+ class AgentApplyReviewRedactionsRequest(BaseModel):
556
+ """Headless parity with Gradio ``api_name='apply_review_redactions'`` (prepare + apply)."""
557
+
558
+ pdf_path: str = Field(
559
+ ...,
560
+ description="Path to the source PDF under allowed roots.",
561
+ )
562
+ review_csv_path: str = Field(
563
+ ...,
564
+ description=(
565
+ "Path to the review plan CSV; basename must contain '_review_file' "
566
+ "(e.g. mydoc_review_file.csv)."
567
+ ),
568
+ )
569
+ output_dir: Optional[str] = Field(
570
+ None,
571
+ description="Output directory (created if missing); defaults to OUTPUT_FOLDER.",
572
+ )
573
+ input_dir: Optional[str] = Field(
574
+ None,
575
+ description="Input/working directory for page images; defaults to INPUT_FOLDER.",
576
+ )
577
+ text_extract_method: Optional[str] = Field(
578
+ None,
579
+ description="OCR/text mode passed to prepare (defaults to CLI ocr_method).",
580
+ )
581
+ efficient_ocr: Optional[bool] = Field(
582
+ None,
583
+ description="If set, overrides EFFICIENT_OCR for the prepare step.",
584
+ )
585
+
586
+
587
+ @router.post(
588
+ "/combine_review_csvs",
589
+ response_model=AgentTaskResponse,
590
+ summary="combine_review_csvs (Gradio api_name)",
591
+ description="Uses tools.helper_functions.merge_csv_files (not cli_redact).",
592
+ )
593
+ def post_combine_review_csvs(
594
+ body: AgentCombineReviewCsvsRequest,
595
+ _: None = Depends(_optional_agent_api_key),
596
+ ) -> AgentTaskResponse:
597
+ from tools.helper_functions import merge_csv_files
598
+
599
+ paths = [_NamedPath(_path_must_be_allowed_file(p)) for p in body.input_files]
600
+ out_dir = body.output_dir or OUTPUT_FOLDER
601
+ out_dir_resolved = _path_must_be_allowed_directory(str(out_dir), must_exist=True)
602
+ sep = "/" if not out_dir_resolved.endswith(("/", "\\")) else ""
603
+ out_files = merge_csv_files(paths, output_folder=out_dir_resolved + sep)
604
+ return AgentTaskResponse(
605
+ status="completed",
606
+ gradio_api_name="combine_review_csvs",
607
+ task="combine_review_csvs",
608
+ output_dir=out_dir_resolved,
609
+ input_dir="",
610
+ message="merge_csv_files completed",
611
+ output_paths=out_files,
612
+ )
613
+
614
+
615
+ class AgentExportReviewRedactionOverlayRequest(BaseModel):
616
+ """Agent JSON body for the same overlay render as Gradio ``api_name='page_redaction_review_image'``."""
617
+
618
+ page_image_path: str = Field(
619
+ ...,
620
+ description="Path to page raster (PNG/JPEG) used as underlay; must be under allowed roots.",
621
+ )
622
+ boxes: List[Dict[str, Any]] = Field(
623
+ ...,
624
+ min_length=1,
625
+ description="Annotator-style boxes: label, color, xmin, ymin, xmax, ymax (normalized 0–1).",
626
+ )
627
+ page_number: int = Field(
628
+ 1, ge=1, description="1-based page index for the output filename."
629
+ )
630
+ doc_base_name: str = Field(
631
+ "review",
632
+ description="Basename for output file (e.g. document name without extension).",
633
+ )
634
+ review_df_records: Optional[List[Dict[str, Any]]] = Field(
635
+ None,
636
+ description="Optional rows (include at least 'label') for stable label→line-pattern mapping.",
637
+ )
638
+ label_abbrev_chars: Optional[int] = Field(
639
+ None,
640
+ ge=0,
641
+ le=24,
642
+ description="Draw this many leading characters of each label on the image; omit to use REVIEW_OVERLAY_LABEL_ABBREV_CHARS from config (0 = off).",
643
+ )
644
+
645
+
646
+ class AgentExportReviewPageOcrVisualisationRequest(BaseModel):
647
+ """Agent JSON body for the same OCR visualisation as Gradio ``api_name='page_ocr_review_image'``."""
648
+
649
+ page_image_path: str = Field(
650
+ ...,
651
+ description="Path to page raster (PNG/JPEG) used as underlay; must be under allowed roots.",
652
+ )
653
+ ocr_results: Dict[str, Any] = Field(
654
+ ...,
655
+ description="Word-level OCR results dict (line_key -> {words:[{text, bounding_box, conf, ...}]}).",
656
+ )
657
+ page_number: int = Field(
658
+ 1, ge=1, description="1-based page index (used for naming)."
659
+ )
660
+ doc_base_name: str = Field(
661
+ "review",
662
+ description="Basename for output file (e.g. document name without extension).",
663
+ )
664
+
665
+
666
+ @router.post(
667
+ "/export_review_redaction_overlay",
668
+ response_model=AgentTaskResponse,
669
+ summary="export_review_redaction_overlay (Agent API; Gradio api_name: page_redaction_review_image)",
670
+ description=(
671
+ "Renders hollow redaction outlines and a top-right legend on the page image; "
672
+ "writes ``redaction_overlay/{doc_base_name}_page{n}_redaction_overlay.jpg`` under OUTPUT_FOLDER "
673
+ "(scaled per REVIEW_OVERLAY_MAX_PIXELS, JPEG capped by REVIEW_OVERLAY_MAX_FILE_BYTES). "
674
+ "Uses ``tools.redaction_review.visualise_review_redaction_boxes``."
675
+ ),
676
+ )
677
+ def post_export_review_redaction_overlay(
678
+ body: AgentExportReviewRedactionOverlayRequest,
679
+ _: None = Depends(_optional_agent_api_key),
680
+ ) -> AgentTaskResponse:
681
+ import pandas as pd
682
+
683
+ from tools.redaction_review import visualise_review_redaction_boxes
684
+
685
+ img_path = _path_must_be_allowed_file(body.page_image_path)
686
+ annotator: dict[str, Any] = {"image": img_path, "boxes": body.boxes}
687
+ review_df = (
688
+ pd.DataFrame(body.review_df_records)
689
+ if body.review_df_records
690
+ else pd.DataFrame()
691
+ )
692
+ out_folder_abs = os.path.realpath(
693
+ os.path.abspath(os.path.expanduser(str(OUTPUT_FOLDER)))
694
+ )
695
+ if not validate_path_safety(out_folder_abs):
696
+ raise HTTPException(status_code=400, detail="Unsafe OUTPUT_FOLDER path")
697
+ _must_be_under_allowed_roots(out_folder_abs, str(out_folder_abs))
698
+ try:
699
+ Path(out_folder_abs).mkdir(parents=True, exist_ok=True)
700
+ except OSError:
701
+ raise HTTPException(status_code=500, detail="Could not create OUTPUT_FOLDER")
702
+ out_folder = out_folder_abs
703
+
704
+ path = visualise_review_redaction_boxes(
705
+ annotator,
706
+ review_df=review_df,
707
+ output_folder=out_folder,
708
+ page_number=body.page_number,
709
+ doc_base_name=body.doc_base_name,
710
+ label_abbrev_chars=body.label_abbrev_chars,
711
+ )
712
+ if not path:
713
+ raise HTTPException(
714
+ status_code=500,
715
+ detail=(
716
+ "Could not produce overlay PNG (invalid image/boxes or write failed). "
717
+ "Ensure boxes are valid and the image loads."
718
+ ),
719
+ )
720
+ return AgentTaskResponse(
721
+ status="completed",
722
+ gradio_api_name="export_review_redaction_overlay",
723
+ task="export_review_redaction_overlay",
724
+ output_dir=out_folder,
725
+ input_dir="",
726
+ message="Redaction overlay PNG written",
727
+ output_paths=[path],
728
+ )
729
+
730
+
731
+ @router.post(
732
+ "/export_review_page_ocr_visualisation",
733
+ response_model=AgentTaskResponse,
734
+ summary="export_review_page_ocr_visualisation (Agent API; Gradio api_name: page_ocr_review_image)",
735
+ description=(
736
+ "Renders a per-page OCR visualisation using tools.file_redaction.visualise_ocr_words_bounding_boxes; "
737
+ "writes under OUTPUT_FOLDER/review_ocr_visualisations/."
738
+ ),
739
+ )
740
+ def post_export_review_page_ocr_visualisation(
741
+ body: AgentExportReviewPageOcrVisualisationRequest,
742
+ _: None = Depends(_optional_agent_api_key),
743
+ ) -> AgentTaskResponse:
744
+ from PIL import Image
745
+
746
+ from tools.file_redaction import visualise_ocr_words_bounding_boxes
747
+
748
+ img_path = _path_must_be_allowed_file(body.page_image_path)
749
+
750
+ out_folder_abs = os.path.realpath(
751
+ os.path.abspath(os.path.expanduser(str(OUTPUT_FOLDER)))
752
+ )
753
+ if not validate_path_safety(out_folder_abs):
754
+ raise HTTPException(status_code=400, detail="Unsafe OUTPUT_FOLDER path")
755
+ _must_be_under_allowed_roots(out_folder_abs, str(out_folder_abs))
756
+ try:
757
+ Path(out_folder_abs).mkdir(parents=True, exist_ok=True)
758
+ except OSError:
759
+ raise HTTPException(status_code=500, detail="Could not create OUTPUT_FOLDER")
760
+ out_folder = out_folder_abs
761
+
762
+ safe_base = str(body.doc_base_name or "review")
763
+ image_name = f"{safe_base}_page{int(body.page_number)}.png"
764
+ log_paths: list[str] = []
765
+ try:
766
+ log_paths = visualise_ocr_words_bounding_boxes(
767
+ Image.open(img_path).convert("RGB"),
768
+ body.ocr_results,
769
+ image_name=image_name,
770
+ output_folder=out_folder,
771
+ visualisation_folder="review_ocr_visualisations",
772
+ add_legend=True,
773
+ log_files_output_paths=log_paths,
774
+ )
775
+ except Exception as e:
776
+ raise HTTPException(status_code=500, detail=str(e)) from e
777
+
778
+ if not log_paths:
779
+ raise HTTPException(
780
+ status_code=500,
781
+ detail="Could not produce OCR visualisation (invalid image/ocr_results or write failed).",
782
+ )
783
+ out_path = log_paths[-1]
784
+ return AgentTaskResponse(
785
+ status="completed",
786
+ gradio_api_name="export_review_page_ocr_visualisation",
787
+ task="export_review_page_ocr_visualisation",
788
+ output_dir=out_folder,
789
+ input_dir="",
790
+ message="OCR visualisation written",
791
+ output_paths=[out_path],
792
+ )
793
+
794
+
795
+ def _gradio_only(api_name: str, detail: str) -> JSONResponse:
796
+ return JSONResponse(
797
+ status_code=501,
798
+ content={
799
+ "gradio_api_name": api_name,
800
+ "detail": detail,
801
+ "hint": (
802
+ "This flow is Gradio-session stateful. Call the named route on the "
803
+ "Gradio HTTP API, not /agent."
804
+ ),
805
+ "gradio_http": {
806
+ "discover_schema": "GET /gradio_api/info",
807
+ "start_call": f"POST /gradio_api/call/{api_name}",
808
+ "request_body_shape": '{"data": [<args in schema order>]}',
809
+ "poll": f"GET /gradio_api/call/{api_name}/{{event_id}}",
810
+ },
811
+ "gradio_client_notes": [
812
+ "Pass api_name explicitly; do not rely on inferring the endpoint from "
813
+ "Python function names (large Blocks apps will look ambiguous).",
814
+ "If predict() still cannot resolve the route, open GET /gradio_api/info "
815
+ "and use the numeric fn_index with gradio_client, or call the HTTP "
816
+ "endpoints directly.",
817
+ "The length of data must match the parameter list for this deployment; "
818
+ "copy order and types from /gradio_api/info.",
819
+ ],
820
+ },
821
+ )
822
+
823
+
824
+ @router.post("/load_and_prepare_documents_or_data")
825
+ def post_load_and_prepare_documents_or_data() -> JSONResponse:
826
+ return _gradio_only(
827
+ "load_and_prepare_documents_or_data",
828
+ "Preparation uses Gradio session state and prepare_image_or_pdf_with_efficient_ocr; no single CLI task.",
829
+ )
830
+
831
+
832
+ @router.post(
833
+ "/apply_review_redactions",
834
+ response_model=AgentTaskResponse,
835
+ summary="apply_review_redactions (Gradio api_name)",
836
+ description=(
837
+ "Runs prepare_image_or_pdf_with_efficient_ocr([pdf, review_csv]) then "
838
+ "apply_redactions_to_review_df_and_files — same core pipeline as the Review tab, "
839
+ "without Gradio session state. Requires paths under allowed roots."
840
+ ),
841
+ )
842
+ def post_apply_review_redactions(
843
+ body: AgentApplyReviewRedactionsRequest,
844
+ _: None = Depends(_optional_agent_api_key),
845
+ ) -> AgentTaskResponse:
846
+ from tools.simplified_api import run_apply_review_redactions
847
+
848
+ pdf = _path_must_be_allowed_file(body.pdf_path)
849
+ csv = _path_must_be_allowed_file(body.review_csv_path)
850
+ out_dir: str | None = None
851
+ if body.output_dir is not None:
852
+ out_dir = _path_must_be_allowed_directory(body.output_dir, must_exist=False)
853
+ in_dir: str | None = None
854
+ if body.input_dir is not None:
855
+ in_dir = _path_must_be_allowed_directory(body.input_dir, must_exist=False)
856
+
857
+ try:
858
+ result = run_apply_review_redactions(
859
+ pdf_path=pdf,
860
+ review_csv_path=csv,
861
+ output_dir=out_dir,
862
+ input_dir=in_dir,
863
+ text_extract_method=body.text_extract_method,
864
+ efficient_ocr=body.efficient_ocr,
865
+ )
866
+ except ValueError as e:
867
+ raise HTTPException(status_code=400, detail=str(e)) from e
868
+ except Exception as e:
869
+ raise HTTPException(
870
+ status_code=500,
871
+ detail=f"apply_review_redactions failed: {e}",
872
+ ) from e
873
+
874
+ return AgentTaskResponse(
875
+ status="completed",
876
+ gradio_api_name="apply_review_redactions",
877
+ task="apply_review_redactions",
878
+ output_dir=result["output_dir"],
879
+ input_dir=result["input_dir"],
880
+ message=result["message"],
881
+ output_paths=result.get("output_paths"),
882
+ )
883
+
884
+
885
+ @router.post("/word_level_ocr_text_search")
886
+ def post_word_level_ocr_text_search() -> JSONResponse:
887
+ return _gradio_only(
888
+ "word_level_ocr_text_search",
889
+ "Search uses in-memory OCR dataframes in the UI session.",
890
+ )
891
+
892
+
893
+ @router.get("/operations")
894
+ def list_operations() -> dict[str, Any]:
895
+ return {
896
+ "gradio_api_names": list(GRADIO_API_NAMES),
897
+ "gradio_session_state_endpoints": {
898
+ "description": (
899
+ "These api_name values are exposed on the Gradio HTTP API but return "
900
+ "501 on /agent because they depend on in-memory Gradio state."
901
+ ),
902
+ "discover_schema": "GET /gradio_api/info",
903
+ "call_pattern": 'POST /gradio_api/call/<api_name> with JSON body {"data": [...]}',
904
+ "names": [
905
+ "load_and_prepare_documents_or_data",
906
+ "word_level_ocr_text_search",
907
+ ],
908
+ },
909
+ "routes": [
910
+ {
911
+ "gradio_api_name": "redact_document",
912
+ "method": "POST",
913
+ "path": "/agent/redact_document",
914
+ "implementation": "cli_redact task redact",
915
+ "notes": {
916
+ "ocr_method": [
917
+ "Local OCR",
918
+ "AWS Textract",
919
+ "Local text",
920
+ ],
921
+ "chosen_local_ocr_model_override": LOCAL_OCR_MODEL_OPTIONS,
922
+ "pii_detector_recommended": [
923
+ LOCAL_PII_OPTION,
924
+ AWS_PII_OPTION,
925
+ AWS_LLM_PII_OPTION,
926
+ INFERENCE_SERVER_PII_OPTION,
927
+ LOCAL_TRANSFORMERS_LLM_PII_OPTION,
928
+ "None",
929
+ ],
930
+ },
931
+ },
932
+ {
933
+ "gradio_api_name": "redact_data",
934
+ "method": "POST",
935
+ "path": "/agent/redact_data",
936
+ "implementation": "cli_redact task redact",
937
+ "notes": {
938
+ "ocr_method": [
939
+ "Local OCR",
940
+ "AWS Textract",
941
+ "Local text",
942
+ ],
943
+ "chosen_local_ocr_model_override": LOCAL_OCR_MODEL_OPTIONS,
944
+ "pii_detector_recommended": [
945
+ LOCAL_PII_OPTION,
946
+ AWS_PII_OPTION,
947
+ AWS_LLM_PII_OPTION,
948
+ INFERENCE_SERVER_PII_OPTION,
949
+ LOCAL_TRANSFORMERS_LLM_PII_OPTION,
950
+ "None",
951
+ ],
952
+ },
953
+ },
954
+ {
955
+ "gradio_api_name": "find_duplicate_pages",
956
+ "method": "POST",
957
+ "path": "/agent/find_duplicate_pages",
958
+ "implementation": "cli_redact deduplicate pages",
959
+ },
960
+ {
961
+ "gradio_api_name": "find_duplicate_tabular",
962
+ "method": "POST",
963
+ "path": "/agent/find_duplicate_tabular",
964
+ "implementation": "cli_redact deduplicate tabular",
965
+ },
966
+ {
967
+ "gradio_api_name": "summarise_document",
968
+ "method": "POST",
969
+ "path": "/agent/summarise_document",
970
+ "implementation": "cli_redact task summarise",
971
+ },
972
+ {
973
+ "gradio_api_name": "combine_review_pdfs",
974
+ "method": "POST",
975
+ "path": "/agent/combine_review_pdfs",
976
+ "implementation": "cli_redact combine_review_pdfs",
977
+ },
978
+ {
979
+ "gradio_api_name": "export_review_redaction_overlay",
980
+ "method": "POST",
981
+ "path": "/agent/export_review_redaction_overlay",
982
+ "implementation": "visualise_review_redaction_boxes",
983
+ },
984
+ {
985
+ "gradio_api_name": "export_review_page_ocr_visualisation",
986
+ "method": "POST",
987
+ "path": "/agent/export_review_page_ocr_visualisation",
988
+ "implementation": "visualise_ocr_words_bounding_boxes",
989
+ },
990
+ {
991
+ "gradio_api_name": "combine_review_csvs",
992
+ "method": "POST",
993
+ "path": "/agent/combine_review_csvs",
994
+ "implementation": "helper merge_csv_files",
995
+ },
996
+ {
997
+ "gradio_api_name": "load_and_prepare_documents_or_data",
998
+ "method": "POST",
999
+ "path": "/agent/load_and_prepare_documents_or_data",
1000
+ "implementation": "not_implemented_http",
1001
+ },
1002
+ {
1003
+ "gradio_api_name": "apply_review_redactions",
1004
+ "method": "POST",
1005
+ "path": "/agent/apply_review_redactions",
1006
+ "implementation": "tools.simplified_api.run_apply_review_redactions",
1007
+ },
1008
+ {
1009
+ "gradio_api_name": "word_level_ocr_text_search",
1010
+ "method": "POST",
1011
+ "path": "/agent/word_level_ocr_text_search",
1012
+ "implementation": "not_implemented_http",
1013
+ },
1014
+ ],
1015
+ }
1016
+
1017
+
1018
+ @router.get("/health")
1019
+ def agent_health() -> dict[str, str]:
1020
+ return {"status": "ok", "service": "agent"}