-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathapp.py
More file actions
10617 lines (10100 loc) · 393 KB
/
app.py
File metadata and controls
10617 lines (10100 loc) · 393 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import shutil
import subprocess
from pathlib import Path
import gradio as gr
import pandas as pd
import spaces
from fastapi import FastAPI, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from gradio_image_annotation_redaction import image_annotator
# Gradio will raise if favicon_path points at a missing file. In PyPI installs the
# repo-root `favicon.png` is typically not present, so treat the favicon as optional.
def _resolve_optional_file_path(path_value: str | None) -> Path | None:
if not path_value:
return None
p = Path(path_value)
if p.is_file():
return p
# If a relative path was provided, also try resolving relative to this file.
if not p.is_absolute():
alt = Path(__file__).resolve().parent / p
if alt.is_file():
return alt
# Also try resolving relative to the installed `doc_redaction` package.
try:
import doc_redaction as _doc_redaction_pkg
pkg_dir = Path(_doc_redaction_pkg.__file__).resolve().parent
pkg_rel = pkg_dir / p
if pkg_rel.is_file():
return pkg_rel
# Backwards-compatible: old configs often used "favicon.png" at repo root.
if p.name.lower() == "favicon.png":
pkg_favicon = pkg_dir / "assets" / "favicon.png"
if pkg_favicon.is_file():
return pkg_favicon
except Exception:
pass
return None
def _run_and_capture(cmd: list[str]) -> tuple[int, str]:
try:
p = subprocess.run(cmd, capture_output=True, text=True, check=False)
except FileNotFoundError:
return (127, "")
out = (p.stdout or "") + "\n" + (p.stderr or "")
return (int(p.returncode), out.strip())
def _external_dep_warning_markdown() -> str | None:
"""
Best-effort check that Tesseract + Poppler are discoverable.
We warn (but do not fail) when binaries aren't found, because many workflows
(e.g. tabular-only redaction) can still work without them.
"""
def _find_exe(name: str, folder_hint: str | None) -> str:
"""
Find an executable, respecting PATH and optional folder hints from config.
`folder_hint` may point at either the executable itself, the bin folder,
or a parent folder containing bin/ or Library/bin/.
"""
found = shutil.which(name)
if found:
return found
if not folder_hint:
return name
p = Path(folder_hint)
exe_name = f"{name}.exe" if os.name == "nt" else name
candidates: list[Path] = []
if p.is_file():
candidates.append(p)
else:
candidates.extend(
[
p / exe_name,
p / "bin" / exe_name,
p / "Library" / "bin" / exe_name,
]
)
for c in candidates:
if c.is_file():
return str(c)
return name
# Late import to avoid ordering constraints at module load.
try:
from tools.config import POPPLER_FOLDER, TESSERACT_FOLDER
except Exception:
POPPLER_FOLDER = ""
TESSERACT_FOLDER = ""
tesseract_exe = _find_exe("tesseract", TESSERACT_FOLDER)
pdftoppm_exe = _find_exe("pdftoppm", POPPLER_FOLDER)
t_code, t_out = _run_and_capture([tesseract_exe, "--version"])
p_code, p_out = _run_and_capture([pdftoppm_exe, "-v"])
t_ok = t_code == 0 and bool(t_out.strip())
p_ok = p_code == 0 and bool(p_out.strip())
if t_ok and p_ok:
return None
missing = []
if not t_ok:
missing.append("Tesseract (`tesseract --version` failed)")
if not p_ok:
missing.append("Poppler (`pdftoppm -v` failed)")
missing_text = ", ".join(missing)
return (
"### ⚠️ Missing external dependencies\n\n"
f"This app could not find: **{missing_text}**.\n\n"
"- If you already installed them, ensure they are on your **PATH**, or set "
"`TESSERACT_FOLDER` / `POPPLER_FOLDER` in `config/app_config.env`.\n"
"- To install automatically (recommended), run:\n\n"
"```bash\n"
"python -m doc_redaction.install_deps\n"
"```\n\n"
"See `README.md` for the full setup instructions."
)
from tools.auth import authenticate_user
from tools.aws_functions import (
download_file_from_s3,
export_outputs_to_s3,
upload_log_file_to_s3,
)
from tools.config import (
ACCESS_LOG_DYNAMODB_TABLE_NAME,
ACCESS_LOGS_FOLDER,
ALLOW_LIST_PATH,
ALLOWED_HOSTS,
ALLOWED_ORIGINS,
AWS_ACCESS_KEY,
AWS_LLM_PII_OPTION,
AWS_PII_OPTION,
AWS_REGION,
AWS_SECRET_KEY,
AZURE_OPENAI_API_KEY,
AZURE_OPENAI_INFERENCE_ENDPOINT,
BEDROCK_VLM_TEXT_EXTRACT_OPTION,
CHOSEN_COMPREHEND_ENTITIES,
CHOSEN_LLM_ENTITIES,
CHOSEN_LLM_PII_INFERENCE_METHOD,
CHOSEN_LOCAL_MODEL_INTRO_TEXT,
CHOSEN_REDACT_ENTITIES,
CLOUD_LLM_PII_MODEL_CHOICE,
CLOUD_VLM_MODEL_CHOICE,
COGNITO_AUTH,
CONFIG_FOLDER,
COST_CODE_ACCORDION_OPEN,
COST_CODES_PATH,
CSV_ACCESS_LOG_HEADERS,
CSV_FEEDBACK_LOG_HEADERS,
CSV_USAGE_LOG_HEADERS,
CUSTOM_BOX_COLOUR,
DEFAULT_CONCURRENCY_LIMIT,
DEFAULT_COST_CODE,
DEFAULT_DUPLICATE_DETECTION_THRESHOLD,
DEFAULT_EXCEL_SHEETS,
DEFAULT_FUZZY_SPELLING_MISTAKES_NUM,
DEFAULT_HANDWRITE_SIGNATURE_CHECKBOX,
DEFAULT_INFERENCE_SERVER_PII_MODEL,
DEFAULT_INFERENCE_SERVER_VLM_MODEL,
DEFAULT_LANGUAGE,
DEFAULT_LANGUAGE_FULL_NAME,
DEFAULT_LOCAL_OCR_MODEL,
DEFAULT_MIN_CONSECUTIVE_PAGES,
DEFAULT_MIN_WORD_COUNT,
DEFAULT_PAGE_MAX,
DEFAULT_PAGE_MIN,
DEFAULT_PII_DETECTION_MODEL,
DEFAULT_SEARCH_QUERY,
DEFAULT_TABULAR_ANONYMISATION_STRATEGY,
DEFAULT_TEXT_COLUMNS,
DEFAULT_TEXT_EXTRACTION_MODEL,
DENY_LIST_PATH,
DIRECT_MODE_ANON_STRATEGY,
DIRECT_MODE_CHOSEN_LOCAL_OCR_MODEL,
DIRECT_MODE_COMBINE_PAGES,
DIRECT_MODE_COMPRESS_REDACTED_PDF,
DIRECT_MODE_DEFAULT_USER,
DIRECT_MODE_DUPLICATE_TYPE,
DIRECT_MODE_EXTRACT_FORMS,
DIRECT_MODE_EXTRACT_LAYOUT,
DIRECT_MODE_EXTRACT_SIGNATURES,
DIRECT_MODE_EXTRACT_TABLES,
DIRECT_MODE_FUZZY_MISTAKES,
DIRECT_MODE_GREEDY_MATCH,
DIRECT_MODE_IMAGES_DPI,
DIRECT_MODE_INPUT_FILE,
DIRECT_MODE_JOB_ID,
DIRECT_MODE_LANGUAGE,
DIRECT_MODE_MATCH_FUZZY_WHOLE_PHRASE_BOOL,
DIRECT_MODE_MIN_CONSECUTIVE_PAGES,
DIRECT_MODE_MIN_WORD_COUNT,
DIRECT_MODE_OCR_FIRST_PASS_MAX_WORKERS,
DIRECT_MODE_OCR_METHOD,
DIRECT_MODE_OUTPUT_DIR,
DIRECT_MODE_PAGE_MAX,
DIRECT_MODE_PAGE_MIN,
DIRECT_MODE_PII_DETECTOR,
DIRECT_MODE_PREPROCESS_LOCAL_OCR_IMAGES,
DIRECT_MODE_REMOVE_DUPLICATE_ROWS,
DIRECT_MODE_RETURN_PDF_END_OF_REDACTION,
DIRECT_MODE_SIMILARITY_THRESHOLD,
DIRECT_MODE_SUMMARY_PAGE_GROUP_MAX_WORKERS,
DIRECT_MODE_TASK,
DIRECT_MODE_TEXTRACT_ACTION,
DISPLAY_FILE_NAMES_IN_LOGS,
DO_INITIAL_TABULAR_DATA_CLEAN,
DOCUMENT_REDACTION_BUCKET,
DYNAMODB_ACCESS_LOG_HEADERS,
DYNAMODB_FEEDBACK_LOG_HEADERS,
DYNAMODB_USAGE_LOG_HEADERS,
EFFICIENT_OCR,
EFFICIENT_OCR_MIN_EMBEDDED_IMAGE_PX,
EFFICIENT_OCR_MIN_IMAGE_COVERAGE_FRACTION,
EFFICIENT_OCR_MIN_WORDS,
ENFORCE_COST_CODES,
EXTRACTION_AND_PII_OPTIONS_OPEN_BY_DEFAULT,
FASTAPI_ROOT_PATH,
FAVICON_PATH,
FEEDBACK_LOG_DYNAMODB_TABLE_NAME,
FEEDBACK_LOG_FILE_NAME,
FEEDBACK_LOGS_FOLDER,
FILE_INPUT_HEIGHT,
FILL_SCREEN_WIDTH,
FULL_COMPREHEND_ENTITY_LIST,
FULL_ENTITY_LIST,
FULL_LLM_ENTITY_LIST,
GEMINI_API_KEY,
GET_COST_CODES,
GET_DEFAULT_ALLOW_LIST,
GRADIO_SERVER_NAME,
GRADIO_SERVER_PORT,
GRADIO_TEMP_DIR,
HANDWRITE_SIGNATURE_TEXTBOX_FULL_OPTIONS,
HOST_NAME,
HYBRID_TEXTRACT_BEDROCK_VLM,
INFERENCE_SERVER_API_URL,
INFERENCE_SERVER_PII_OPTION,
INPUT_FOLDER,
INTRO_TEXT,
LANGUAGE_CHOICES,
LLM_MAX_NEW_TOKENS,
LLM_TEMPERATURE,
LOAD_PREVIOUS_TEXTRACT_JOBS_S3,
LOCAL_OCR_MODEL_OPTIONS,
LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION,
LOCAL_PII_OPTION,
LOCAL_TRANSFORMERS_LLM_PII_OPTION,
LOG_FILE_NAME,
MAPPED_LANGUAGE_CHOICES,
MAX_FILE_SIZE,
MAX_OPEN_TEXT_CHARACTERS,
MAX_QUEUE_SIZE,
MPLCONFIGDIR,
NO_REDACTION_PII_OPTION,
OUTPUT_COST_CODES_PATH,
OUTPUT_FOLDER,
OVERWRITE_EXISTING_OCR_RESULTS,
PADDLE_MODEL_PATH,
PII_DETECTION_MODELS,
REMOVE_DUPLICATE_ROWS,
ROOT_PATH,
RUN_ALL_EXAMPLES_THROUGH_AWS,
RUN_AWS_FUNCTIONS,
RUN_DIRECT_MODE,
RUN_FASTAPI,
RUN_MCP_SERVER,
S3_ACCESS_LOGS_FOLDER,
S3_ALLOW_LIST_PATH,
S3_COST_CODES_PATH,
S3_FEEDBACK_LOGS_FOLDER,
S3_OUTPUTS_FOLDER,
S3_USAGE_LOGS_FOLDER,
SAVE_LOGS_TO_CSV,
SAVE_LOGS_TO_DYNAMODB,
SAVE_OUTPUTS_TO_S3,
SAVE_PAGE_OCR_VISUALISATIONS,
SESSION_OUTPUT_FOLDER,
SHOW_ALL_OUTPUTS_IN_OUTPUT_FOLDER,
SHOW_AWS_API_KEYS,
SHOW_AWS_EXAMPLES,
SHOW_AWS_PII_DETECTION_OPTIONS,
SHOW_AWS_TEXT_EXTRACTION_OPTIONS,
SHOW_COSTS,
SHOW_DIFFICULT_OCR_EXAMPLES,
SHOW_EXAMPLES,
SHOW_HYBRID_TEXTRACT_BEDROCK_CHECKBOX,
SHOW_INFERENCE_SERVER_PII_OPTIONS,
SHOW_INFERENCE_SERVER_VLM_MODEL_OPTIONS,
SHOW_LANGUAGE_SELECTION,
SHOW_LOCAL_OCR_MODEL_OPTIONS,
SHOW_OCR_GUI_OPTIONS,
SHOW_PII_IDENTIFICATION_OPTIONS,
SHOW_QUICKSTART,
SHOW_SET_DEFAULT_COST_CODE_BUTTON,
SHOW_SUMMARISATION,
SHOW_TRANSFORMERS_LLM_PII_DETECTION_OPTIONS,
SHOW_WHOLE_DOCUMENT_TEXTRACT_CALL_OPTIONS,
SPACY_MODEL_PATH,
TABULAR_PII_DETECTION_MODELS,
TEXT_EXTRACTION_MODELS,
TEXTRACT_JOBS_LOCAL_LOC,
TEXTRACT_JOBS_S3_INPUT_LOC,
TEXTRACT_JOBS_S3_LOC,
TEXTRACT_TEXT_EXTRACT_OPTION,
TEXTRACT_WHOLE_DOCUMENT_ANALYSIS_BUCKET,
TEXTRACT_WHOLE_DOCUMENT_ANALYSIS_INPUT_SUBFOLDER,
TEXTRACT_WHOLE_DOCUMENT_ANALYSIS_OUTPUT_SUBFOLDER,
USAGE_LOG_DYNAMODB_TABLE_NAME,
USAGE_LOG_FILE_NAME,
USAGE_LOGS_FOLDER,
USE_GREEDY_DUPLICATE_DETECTION,
WHOLE_PAGE_REDACTION_LIST_PATH,
)
from tools.custom_csvlogger import CSVLogger_custom
from tools.data_anonymise import anonymise_files_with_open_text
from tools.file_conversion import (
combine_review_pdf_files,
get_document_file_names,
get_input_file_names,
is_pdf,
prepare_image_or_pdf,
prepare_image_or_pdf_with_efficient_ocr,
)
from tools.file_redaction import choose_and_run_redactor, run_redaction
from tools.find_duplicate_pages import (
apply_whole_page_redactions_from_list,
create_annotation_objects_from_duplicates,
exclude_match,
handle_selection_and_preview,
run_duplicate_analysis,
run_search_with_regex_option,
)
from tools.find_duplicate_tabular import (
clean_tabular_duplicates,
handle_tabular_row_selection,
run_tabular_duplicate_detection,
)
from tools.helper_functions import (
_file_name_from_pdf_path,
all_outputs_file_download_fn,
apply_session_default_cost_code,
auto_set_local_ocr_for_bedrock_vlm,
calculate_aws_costs,
calculate_time_taken,
change_tab_to_review_redactions,
change_tab_to_tabular_or_document_redactions,
check_duplicate_pages_checkbox,
check_for_existing_textract_file,
check_for_relevant_ocr_output_with_words,
custom_regex_load,
enforce_cost_codes,
ensure_folder_exists,
get_connection_params,
lifespan,
load_all_output_files,
load_in_default_allow_list,
load_in_default_cost_codes,
merge_csv_files,
put_columns_in_df,
reset_aws_call_vars,
reset_base_dataframe,
reset_data_vars,
reset_ocr_base_dataframe,
reset_ocr_with_words_base_dataframe,
reset_review_vars,
reset_state_vars,
reveal_feedback_buttons,
save_default_cost_code_for_session,
show_duplicate_info_box_on_click,
show_info_box_on_click,
show_info_box_on_click_ocr_examples,
show_tabular_info_box_on_click,
update_cost_code_dataframe_from_dropdown_select,
update_language_dropdown,
)
from tools.load_spacy_model_custom_recognisers import custom_entities
from tools.quickstart import (
handle_main_pii_method_selection,
handle_main_redaction_method_selection,
handle_main_text_extract_method_selection,
handle_pii_method_selection,
handle_pii_method_selection_tabular,
handle_redaction_method_selection,
handle_step_2_next,
handle_step_3_next,
handle_text_extract_method_selection,
route_walkthrough_files,
update_step_2_on_data_file_upload,
update_step_3_tabular_visibility,
update_step_4_visibility,
)
from tools.redaction_review import (
apply_redactions_to_review_df_and_files,
convert_df_to_xfdf,
convert_xfdf_to_dataframe,
create_annotation_objects_from_filtered_ocr_results_with_words,
decrease_page,
df_select_callback_cost,
df_select_callback_dataframe_row,
df_select_callback_dataframe_row_ocr_with_words,
df_select_callback_ocr,
df_select_callback_textract_api,
exclude_selected_items_from_redaction,
get_all_rows_with_same_text,
get_all_rows_with_same_text_redact,
get_and_merge_current_page_annotations,
increase_bottom_page_count_based_on_top,
increase_page,
page_ocr_review_image,
page_redaction_review_image,
reset_dropdowns,
undo_last_removal,
update_all_entity_df_dropdowns,
update_all_page_annotation_object_based_on_previous_page,
update_annotator_object_and_filter_df,
update_annotator_page_from_review_df,
update_entities_df_page,
update_entities_df_recogniser_entities,
update_entities_df_text,
update_other_annotator_number_from_current,
update_redact_choice_df_from_page_dropdown,
update_selected_review_df_row_colour,
validate_review_file_df,
)
from tools.redaction_types import RedactionContext, RedactionOptions
from tools.summaries import (
_summarisation_upload_to_paths,
_upload_contains_pdf,
concise_summary_format_prompt,
detailed_summary_format_prompt,
summarise_document_wrapper,
)
from tools.textract_batch_call import (
analyse_document_with_textract_api,
check_for_provided_job_id,
check_textract_outputs_exist,
load_in_textract_job_details,
poll_whole_document_textract_analysis_progress_and_download,
replace_existing_pdf_input_for_whole_document_outputs,
)
# Ensure that output folders exist
ensure_folder_exists(CONFIG_FOLDER)
ensure_folder_exists(OUTPUT_FOLDER)
ensure_folder_exists(INPUT_FOLDER)
if GRADIO_TEMP_DIR:
ensure_folder_exists(GRADIO_TEMP_DIR)
if MPLCONFIGDIR:
ensure_folder_exists(MPLCONFIGDIR)
ensure_folder_exists(FEEDBACK_LOGS_FOLDER)
ensure_folder_exists(ACCESS_LOGS_FOLDER)
ensure_folder_exists(USAGE_LOGS_FOLDER)
# Add custom spacy recognisers to the Comprehend list, so that local Spacy model can be used to pick up e.g. titles, streetnames, UK postcodes that are sometimes missed by comprehend
CHOSEN_COMPREHEND_ENTITIES.extend(custom_entities)
FULL_COMPREHEND_ENTITY_LIST.extend(custom_entities)
FULL_LLM_ENTITY_LIST.extend(custom_entities)
###
# Load in FastAPI app
###
# 3. Initialize the App with the lifespan parameter
# Clean the ROOT_PATH for FastAPI
# Ensure it starts with / and has no trailing /
CLEAN_ROOT = f"/{FASTAPI_ROOT_PATH.strip('/')}" if FASTAPI_ROOT_PATH.strip("/") else ""
app = FastAPI(lifespan=lifespan, root_path=CLEAN_ROOT)
# Added to pass lint check, no effect
if 0 == 1:
print(f"spaces.__name__: {spaces.__name__}")
###
# Load in Gradio app components
###
def _resolve_example_data_dir() -> Path | None:
"""
Resolve the example data directory both for repo checkouts and PyPI installs.
- Repo checkout (legacy): ./example_data
- PyPI install (packaged): doc_redaction/example_data (inside site-packages)
"""
# Prefer packaged example data (works in PyPI installs)
try:
import doc_redaction as _doc_redaction_pkg
pkg_dir = Path(_doc_redaction_pkg.__file__).resolve().parent
packaged = pkg_dir / "example_data"
if packaged.is_dir():
return packaged
except Exception:
pass
# Fallback to legacy repo-root path for older checkouts / custom layouts
legacy = Path("example_data").resolve()
if legacy.is_dir():
return legacy
return None
_EXAMPLE_DATA_DIR = _resolve_example_data_dir()
def _example_data_path(rel: str) -> str:
if _EXAMPLE_DATA_DIR is None:
return rel
return str((_EXAMPLE_DATA_DIR / rel).resolve())
# Check which example files exist and create examples only for available files
example_files = [
_example_data_path("example_of_emails_sent_to_a_professor_before_applying.pdf"),
_example_data_path("example_complaint_letter.jpg"),
_example_data_path("graduate-job-example-cover-letter.pdf"),
_example_data_path("Partnership-Agreement-Toolkit_0_0.pdf"),
_example_data_path("partnership_toolkit_redact_custom_deny_list.csv"),
_example_data_path("partnership_toolkit_redact_some_pages.csv"),
]
ocr_example_files = [
_example_data_path("Partnership-Agreement-Toolkit_0_0.pdf"),
_example_data_path("Difficult handwritten note.jpg"),
_example_data_path("Example-cv-university-graduaty-hr-role-with-photo-2.pdf"),
]
# Load some components outside of blocks context that are used for examples
# Components for "Redact all PII" option (conditionally visible)
# Set initial visibility based on default redaction method ("Redact all PII")
initial_show_pii_method = SHOW_PII_IDENTIFICATION_OPTIONS # Default is "Redact all PII"
default_pii_method = DEFAULT_PII_DETECTION_MODEL
initial_show_local_entities = initial_show_pii_method and (
default_pii_method == LOCAL_PII_OPTION
)
initial_show_comprehend_entities = initial_show_pii_method and (
default_pii_method == AWS_PII_OPTION
)
initial_is_llm_method = initial_show_pii_method and (
default_pii_method == LOCAL_TRANSFORMERS_LLM_PII_OPTION
or default_pii_method == INFERENCE_SERVER_PII_OPTION
or default_pii_method == AWS_LLM_PII_OPTION
)
## Walkthrough / quickstart components
walkthrough_file_input = gr.File(
label="Choose a PDF document, image file (PDF, JPG, PNG), tabular data file (Excel, CSV, Parquet), or Word document (DOCX)",
file_count="multiple",
file_types=[
".pdf",
".jpg",
".png",
".json",
".zip",
".xlsx",
".xls",
".csv",
".parquet",
".docx",
],
height=FILE_INPUT_HEIGHT,
)
walkthrough_in_redact_entities = gr.Dropdown(
value=CHOSEN_REDACT_ENTITIES,
choices=FULL_ENTITY_LIST,
multiselect=True,
label="Local PII identification model (click empty space in box for full list)",
visible=initial_show_local_entities,
allow_custom_value=True,
)
walkthrough_in_redact_comprehend_entities = gr.Dropdown(
value=CHOSEN_COMPREHEND_ENTITIES,
choices=FULL_COMPREHEND_ENTITY_LIST,
multiselect=True,
label="AWS Comprehend PII identification model (click empty space in box for full list)",
visible=initial_show_comprehend_entities,
allow_custom_value=True,
)
# Set initial visibility for local OCR and AWS Textract based on default text extraction method
initial_local_ocr_visible = (
DEFAULT_TEXT_EXTRACTION_MODEL == LOCAL_OCR_MODEL_TEXT_EXTRACT_OPTION
)
initial_aws_textract_visible = (
DEFAULT_TEXT_EXTRACTION_MODEL == TEXTRACT_TEXT_EXTRACT_OPTION
)
text_extract_method_radio_message = """Choose text extraction method"""
walkthrough_text_extract_method_radio = gr.Radio(
label=text_extract_method_radio_message,
value=DEFAULT_TEXT_EXTRACTION_MODEL,
choices=TEXT_EXTRACTION_MODELS,
visible=True,
)
# Set initial value for walkthrough local OCR method based on default text extraction method
# If Bedrock VLM is the default, set to "bedrock-vlm", otherwise use DEFAULT_LOCAL_OCR_MODEL
initial_walkthrough_local_ocr_value = DEFAULT_LOCAL_OCR_MODEL
if (
DEFAULT_TEXT_EXTRACTION_MODEL == BEDROCK_VLM_TEXT_EXTRACT_OPTION
and "bedrock-vlm" in LOCAL_OCR_MODEL_OPTIONS
):
initial_walkthrough_local_ocr_value = "bedrock-vlm"
walkthrough_local_ocr_method_radio = gr.Radio(
label=CHOSEN_LOCAL_MODEL_INTRO_TEXT,
value=initial_walkthrough_local_ocr_value,
choices=LOCAL_OCR_MODEL_OPTIONS,
interactive=True,
visible=True,
)
walkthrough_handwrite_signature_checkbox = gr.CheckboxGroup(
label="AWS Textract extraction settings",
choices=HANDWRITE_SIGNATURE_TEXTBOX_FULL_OPTIONS,
value=DEFAULT_HANDWRITE_SIGNATURE_CHECKBOX,
visible=True,
)
walkthrough_pii_identification_method_drop = gr.Radio(
label="""Choose personal information detection model. Note that AWS Comprehend, if shown, has a cost of around £0.0075 ($0.01) per 10,000 characters.""",
value=DEFAULT_PII_DETECTION_MODEL,
choices=PII_DETECTION_MODELS,
visible=initial_show_pii_method,
)
walkthrough_deny_list_state = gr.Dropdown(
allow_custom_value=True,
label="Deny list (always redact these words)",
interactive=True,
multiselect=True,
visible=True,
)
walkthrough_allow_list_state = gr.Dropdown(
allow_custom_value=True,
label="Allow list (never redact these words)",
interactive=True,
multiselect=True,
visible=True,
)
walkthrough_fully_redacted_list_state = gr.Dropdown(
allow_custom_value=True,
label="Fully redacted pages (fully redact these page numbers)",
interactive=True,
multiselect=True,
visible=True,
)
# State variable to sync the checkbox value across both locations
redact_duplicate_pages_state = gr.State(value=False)
# Checkbox for automatically redacting duplicate pages
redact_duplicate_pages_checkbox = gr.Checkbox(
info="Find and redact whole pages that contain duplicate text. See the 'Identify duplicate pages' tab for all settings and duplicate sentence/passage redaction.",
label="Redact duplicate pages",
value=False,
visible=SHOW_PII_IDENTIFICATION_OPTIONS,
elem_id="redact_duplicate_pages_checkbox",
)
if SHOW_AWS_PII_DETECTION_OPTIONS:
aws_comprehend_cost_message = (
". AWS Comprehend has a cost of approximately $0.01 per 10,000 characters."
)
else:
aws_comprehend_cost_message = ""
walkthrough_pii_identification_method_drop_tabular = gr.Radio(
label="Choose PII detection method" + aws_comprehend_cost_message,
value=DEFAULT_PII_DETECTION_MODEL,
choices=TABULAR_PII_DETECTION_MODELS,
visible=False,
)
walkthrough_anon_strategy = gr.Radio(
choices=[
"replace with 'REDACTED'",
"replace with <ENTITY_NAME>",
"redact completely",
"hash",
"mask",
],
label="Select an anonymisation method",
value=DEFAULT_TABULAR_ANONYMISATION_STRATEGY,
visible=False,
)
walkthrough_do_initial_clean = gr.Checkbox(
label="Do initial clean of text (remove URLs, HTML tags, and non-ASCII characters)",
value=DO_INITIAL_TABULAR_DATA_CLEAN,
visible=False,
)
walkthrough_in_redact_llm_entities = gr.Dropdown(
value=CHOSEN_LLM_ENTITIES,
choices=FULL_LLM_ENTITY_LIST,
multiselect=True,
label="LLM PII identification model - subset of entities for LLM detection (click empty space in box for full list)",
visible=True,
allow_custom_value=True,
)
walkthrough_custom_llm_instructions_textbox = gr.Textbox(
label="Custom instructions for LLM-based entity detection",
placeholder="Specify new labels to redact with a description. E.g. 'Redact information related to Mark Wilson with the label MARK_WILSON' or 'redact all company names with the label COMPANY_NAME'.",
value="",
lines=3,
visible=True,
)
## Redaction examples
in_doc_files = gr.File(
label="Choose a PDF document or image file (PDF, JPG, PNG)",
file_count="multiple",
file_types=[".pdf", ".jpg", ".png", ".json", ".zip"],
height=FILE_INPUT_HEIGHT,
)
total_pdf_page_count = gr.Number(
label="Total page count",
value=0,
visible=SHOW_COSTS,
interactive=False,
)
# Override options if OCR GUI is not shown
if not SHOW_OCR_GUI_OPTIONS:
# SHOW_AWS_TEXT_EXTRACTION_OPTIONS = False
SHOW_INFERENCE_SERVER_VLM_MODEL_OPTIONS = False
SHOW_LOCAL_OCR_MODEL_OPTIONS = False
text_extract_method_radio = gr.Radio(
label=text_extract_method_radio_message,
value=DEFAULT_TEXT_EXTRACTION_MODEL,
choices=TEXT_EXTRACTION_MODELS,
visible=SHOW_OCR_GUI_OPTIONS,
)
# Set initial value for local OCR method based on default text extraction method
# If Bedrock VLM is the default, set to "bedrock-vlm", otherwise use DEFAULT_LOCAL_OCR_MODEL
initial_local_ocr_value = DEFAULT_LOCAL_OCR_MODEL
if (
DEFAULT_TEXT_EXTRACTION_MODEL == BEDROCK_VLM_TEXT_EXTRACT_OPTION
and "bedrock-vlm" in LOCAL_OCR_MODEL_OPTIONS
):
initial_local_ocr_value = "bedrock-vlm"
local_ocr_method_radio = gr.Radio(
label=CHOSEN_LOCAL_MODEL_INTRO_TEXT,
value=initial_local_ocr_value,
choices=LOCAL_OCR_MODEL_OPTIONS,
interactive=True,
visible=SHOW_LOCAL_OCR_MODEL_OPTIONS,
)
handwrite_signature_checkbox = gr.CheckboxGroup(
label="AWS Textract extraction settings",
choices=HANDWRITE_SIGNATURE_TEXTBOX_FULL_OPTIONS,
value=DEFAULT_HANDWRITE_SIGNATURE_CHECKBOX,
visible=SHOW_AWS_TEXT_EXTRACTION_OPTIONS,
)
inference_server_vlm_model_textbox = gr.Textbox(
label="Inference Server VLM Model Name",
placeholder="e.g., 'qwen2-vl-7b-instruct' or leave empty to use default",
value=(
DEFAULT_INFERENCE_SERVER_VLM_MODEL if DEFAULT_INFERENCE_SERVER_VLM_MODEL else ""
),
lines=1,
visible=SHOW_INFERENCE_SERVER_VLM_MODEL_OPTIONS,
)
# PII identification components
# Override options if PII identification is not shown
if not SHOW_PII_IDENTIFICATION_OPTIONS:
SHOW_TRANSFORMERS_LLM_PII_DETECTION_OPTIONS = False
redaction_method_radio = gr.Radio(
label="Choose redaction method",
choices=[
"Extract text only",
"Redact all PII",
"Redact selected terms",
],
value="Redact all PII",
interactive=True,
)
pii_identification_method_drop = gr.Radio(
label="""Choose personal information detection model. Note that AWS Comprehend, if shown, has a cost of around £0.0075 ($0.01) per 10,000 characters.""",
value=DEFAULT_PII_DETECTION_MODEL,
choices=PII_DETECTION_MODELS,
visible=SHOW_PII_IDENTIFICATION_OPTIONS,
)
in_redact_entities = gr.Dropdown(
value=CHOSEN_REDACT_ENTITIES,
choices=FULL_ENTITY_LIST,
multiselect=True,
label="Local PII identification model (click empty space in box for full list)",
visible=initial_show_local_entities,
allow_custom_value=True,
)
in_redact_comprehend_entities = gr.Dropdown(
value=CHOSEN_COMPREHEND_ENTITIES,
choices=FULL_COMPREHEND_ENTITY_LIST,
multiselect=True,
label="AWS Comprehend PII identification model (click empty space in box for full list)",
visible=initial_show_comprehend_entities,
allow_custom_value=True,
)
in_redact_llm_entities = gr.Dropdown(
value=CHOSEN_LLM_ENTITIES,
choices=FULL_LLM_ENTITY_LIST,
multiselect=True,
label="LLM PII identification model - subset of entities for LLM detection (click empty space in box for full list)",
visible=initial_is_llm_method,
allow_custom_value=True,
)
custom_llm_instructions_textbox = gr.Textbox(
label="Custom instructions for LLM-based entity detection",
placeholder="Specify new labels to redact with a description. E.g. 'Redact information related to Mark Wilson with the label MARK_WILSON' or 'redact all company names with the label COMPANY_NAME'.",
value="",
lines=3,
visible=True,
)
# Allow / deny / fully redacted lists
in_deny_list_state = gr.Dropdown(
allow_custom_value=True,
label="Deny list (always redact these words)",
interactive=True,
multiselect=True,
visible=SHOW_PII_IDENTIFICATION_OPTIONS,
)
in_allow_list_state = gr.Dropdown(
allow_custom_value=True,
label="Allow list (never redact these words)",
interactive=True,
multiselect=True,
visible=SHOW_PII_IDENTIFICATION_OPTIONS,
)
in_fully_redacted_list_state = gr.Dropdown(
allow_custom_value=True,
label="Fully redact these pages",
interactive=True,
multiselect=True,
visible=SHOW_PII_IDENTIFICATION_OPTIONS,
)
in_deny_list = gr.File(
label="Import custom deny list - csv table with one column of a different word/phrase on each row (case insensitive). Terms in this file will always be redacted.",
file_count="multiple",
height=FILE_INPUT_HEIGHT,
)
in_fully_redacted_list = gr.File(
label="Import fully redacted pages list - csv table with one column of page numbers on each row. Page numbers in this file will be fully redacted.",
file_count="multiple",
height=FILE_INPUT_HEIGHT,
)
max_fuzzy_spelling_mistakes_num = gr.Number(
label="Maximum spelling mistakes for matching deny list terms (slows down PII detection).",
value=DEFAULT_FUZZY_SPELLING_MISTAKES_NUM,
minimum=0,
maximum=9,
precision=0,
)
## Cost codes
cost_code_dataframe = gr.Dataframe(
value=pd.DataFrame(columns=["Cost code", "Description"]),
row_count=(0, "dynamic"),
label="Existing cost codes",
type="pandas",
interactive=True,
show_search="filter",
wrap=True,
max_height=200,
visible=GET_COST_CODES or ENFORCE_COST_CODES,
)
cost_code_choice_drop = gr.Dropdown(
value=DEFAULT_COST_CODE,
label="Choose cost code for analysis",
choices=[DEFAULT_COST_CODE],
allow_custom_value=True,
visible=GET_COST_CODES or ENFORCE_COST_CODES,
)
set_default_cost_code_button = gr.Button(
value="Set default cost code",
visible=(GET_COST_CODES or ENFORCE_COST_CODES)
and SHOW_SET_DEFAULT_COST_CODE_BUTTON,
)
reset_cost_code_dataframe_button = gr.Button(
value="Reset code code table filter",
visible=GET_COST_CODES or ENFORCE_COST_CODES,
)
## Page options
page_min = gr.Number(
value=DEFAULT_PAGE_MIN,
precision=0,
minimum=0,
maximum=9999,
label="Lowest page to redact (set to 0 to redact from the first page)",
)
page_max = gr.Number(
value=DEFAULT_PAGE_MAX,
precision=0,
minimum=0,
maximum=9999,
label="Highest page to redact (set to 0 to redact to the last page)",
)
## Deduplication examples
in_duplicate_pages = gr.File(
label="Upload one or multiple 'ocr_output.csv' files to find duplicate pages and subdocuments",
file_count="multiple",
height=FILE_INPUT_HEIGHT,
file_types=[".csv"],
)
duplicate_threshold_input = gr.Number(
value=DEFAULT_DUPLICATE_DETECTION_THRESHOLD,
label="Similarity threshold",
info="Score (0-1) to consider pages/text lines a match.",
)
min_word_count_input = gr.Number(
value=DEFAULT_MIN_WORD_COUNT,
label="Minimum word count",
info="Pages/text lines with fewer words than this value are ignored.",
)
combine_page_text_for_duplicates_bool = gr.Radio(
label="Duplicate matching mode",
choices=[
("Find duplicates by page", True),
("Find duplicates by text line", False),
],
value=True,
info="By page: compare full-page text. By text line: compare individual lines.",
)
## Tabular examples
in_data_files = gr.File(
label="Choose Excel or csv files",
file_count="multiple",
file_types=[".xlsx", ".xls", ".csv", ".parquet", ".docx"],
height=FILE_INPUT_HEIGHT,
)
in_colnames = gr.Dropdown(
choices=["Choose columns to anonymise"],
multiselect=True,