seanpedrickcase commited on
Commit
0412597
·
0 Parent(s):

Sync: Minor updates to pi agent implementation

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .coveragerc +56 -0
  2. .dockerignore +52 -0
  3. .gitattributes +9 -0
  4. .github/scripts/setup_test_data.py +320 -0
  5. .github/workflow_README.md +183 -0
  6. .github/workflows/archive_workflows/multi-os-test.yml +115 -0
  7. .github/workflows/ci.yml +269 -0
  8. .github/workflows/simple-test.yml +74 -0
  9. .github/workflows/sync-pi-agent-space.yml +63 -0
  10. .github/workflows/sync_to_hf.yml +54 -0
  11. .github/workflows/sync_to_hf_zero_gpu.yml +59 -0
  12. .gitignore +60 -0
  13. AGENTS.md +113 -0
  14. Dockerfile +232 -0
  15. Dockerfile.pi +40 -0
  16. MANIFEST.in +4 -0
  17. README.md +346 -0
  18. README_PYPI.md +330 -0
  19. agent-redact-space/pi-agent/.dockerignore +10 -0
  20. agent-redact-space/pi-agent/.gitattributes +2 -0
  21. agent-redact-space/pi-agent/Dockerfile +66 -0
  22. agent-redact-space/pi-agent/README.md +45 -0
  23. agent-redact-space/pi-agent/sync-manifest.txt +8 -0
  24. agent-redact-space/pi-agent/sync_to_space.sh +42 -0
  25. agent_routes.py +1167 -0
  26. app.py +0 -0
  27. cdk/__init__.py +0 -0
  28. cdk/app.py +119 -0
  29. cdk/cdk.json.example +7 -0
  30. cdk/cdk_appregistry.py +69 -0
  31. cdk/cdk_config.py +393 -0
  32. cdk/cdk_functions.py +1679 -0
  33. cdk/cdk_stack.py +2010 -0
  34. cdk/check_resources.py +400 -0
  35. cdk/lambda_load_dynamo_logs.py +321 -0
  36. cdk/post_cdk_build_quickstart.py +40 -0
  37. cdk/requirements.txt +6 -0
  38. cli_redact.py +0 -0
  39. config/pi_agent.env.example +33 -0
  40. doc_redaction/__init__.py +27 -0
  41. doc_redaction/api.py +43 -0
  42. doc_redaction/assets/favicon.png +3 -0
  43. doc_redaction/cli_api.py +405 -0
  44. doc_redaction/cli_redact.py +26 -0
  45. doc_redaction/data_anonymise.py +9 -0
  46. doc_redaction/example_data/Bold minimalist professional cover letter.docx +3 -0
  47. doc_redaction/example_data/Difficult handwritten note.jpg +3 -0
  48. doc_redaction/example_data/Example-cv-university-graduaty-hr-role-with-photo-2.pdf +3 -0
  49. doc_redaction/example_data/Lambeth_2030-Our_Future_Our_Lambeth.pdf.csv +0 -0
  50. doc_redaction/example_data/Partnership-Agreement-Toolkit_0_0.pdf +3 -0
.coveragerc ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [run]
2
+ source = .
3
+ omit =
4
+ */tests/*
5
+ */test/*
6
+ */__pycache__/*
7
+ */venv/*
8
+ */env/*
9
+ */build/*
10
+ */dist/*
11
+ */cdk/*
12
+ */docs/*
13
+ */example_data/*
14
+ */examples/*
15
+ */feedback/*
16
+ */logs/*
17
+ */old_code/*
18
+ */output/*
19
+ */tmp/*
20
+ */usage/*
21
+ */tld/*
22
+ */tesseract/*
23
+ */poppler/*
24
+ config*.py
25
+ setup.py
26
+ lambda_entrypoint.py
27
+ entrypoint.sh
28
+ cli_redact.py
29
+ load_dynamo_logs.py
30
+ load_s3_logs.py
31
+ *.spec
32
+ Dockerfile
33
+ *.qmd
34
+ *.md
35
+ *.txt
36
+ *.yml
37
+ *.yaml
38
+ *.json
39
+ *.csv
40
+ *.env
41
+ *.bat
42
+ *.ps1
43
+ *.sh
44
+
45
+ [report]
46
+ exclude_lines =
47
+ pragma: no cover
48
+ def __repr__
49
+ if self.debug:
50
+ if settings.DEBUG
51
+ raise AssertionError
52
+ raise NotImplementedError
53
+ if 0:
54
+ if __name__ == .__main__.:
55
+ class .*\bProtocol\):
56
+ @(abc\.)?abstractmethod
.dockerignore ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.url
2
+ *.ipynb
3
+ *.pyc
4
+ *.qmd
5
+ _quarto.yml
6
+ quarto_site/*
7
+ src/*
8
+ redaction_deps/*
9
+ .venv/*
10
+ examples/*
11
+ processing/*
12
+ tools/__pycache__/*
13
+ old_code/*
14
+ tesseract/*
15
+ poppler/*
16
+ build/*
17
+ dist/*
18
+ docs/*
19
+ .pi/*
20
+ build_deps/*
21
+ user_guide/*
22
+ _extensions/*
23
+ workspace/*
24
+ doc_redaction.egg-info/*
25
+ .venv_pypi_test/*
26
+ cdk/config/*
27
+ tld/*
28
+ cdk/config/*
29
+ cdk/cdk.out/*
30
+ cdk/archive/*
31
+ cdk.json
32
+ cdk.context.json
33
+ .quarto/*
34
+ logs/
35
+ output/
36
+ input/
37
+ feedback/
38
+ config/
39
+ usage/
40
+ test/config/*
41
+ test/feedback/*
42
+ test/input/*
43
+ test/logs/*
44
+ test/output/*
45
+ test/tmp/*
46
+ test/usage/*
47
+ .ruff_cache/*
48
+ model_cache/*
49
+ sanitized_file/*
50
+ src/doc_redaction.egg-info/*
51
+ docker_compose/*
52
+ skills/example_prompts/*
.gitattributes ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ *.pdf filter=lfs diff=lfs merge=lfs -text
2
+ *.sh text eol=lf
3
+ *.jpg filter=lfs diff=lfs merge=lfs -text
4
+ *.xls filter=lfs diff=lfs merge=lfs -text
5
+ *.xlsx filter=lfs diff=lfs merge=lfs -text
6
+ *.docx filter=lfs diff=lfs merge=lfs -text
7
+ *.doc filter=lfs diff=lfs merge=lfs -text
8
+ *.png filter=lfs diff=lfs merge=lfs -text
9
+ *.ico filter=lfs diff=lfs merge=lfs -text
.github/scripts/setup_test_data.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Setup script for GitHub Actions test data.
4
+ Creates dummy test files when example data is not available.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+
10
+ import pandas as pd
11
+
12
+
13
+ def create_directories():
14
+ """Create necessary directories."""
15
+ dirs = ["doc_redaction/example_data", "doc_redaction/example_data/example_outputs"]
16
+
17
+ for dir_path in dirs:
18
+ os.makedirs(dir_path, exist_ok=True)
19
+ print(f"Created directory: {dir_path}")
20
+
21
+
22
+ def create_dummy_pdf():
23
+ """Create dummy PDFs for testing."""
24
+
25
+ # Install reportlab if not available
26
+ try:
27
+ from reportlab.lib.pagesizes import letter
28
+ from reportlab.pdfgen import canvas
29
+ except ImportError:
30
+ import subprocess
31
+
32
+ subprocess.check_call(["pip", "install", "reportlab"])
33
+ from reportlab.lib.pagesizes import letter
34
+ from reportlab.pdfgen import canvas
35
+
36
+ try:
37
+ # Create the main test PDF
38
+ pdf_path = "doc_redaction/example_data/example_of_emails_sent_to_a_professor_before_applying.pdf"
39
+ print(f"Creating PDF: {pdf_path}")
40
+ print(f"Directory exists: {os.path.exists('doc_redaction/example_data')}")
41
+
42
+ c = canvas.Canvas(pdf_path, pagesize=letter)
43
+ c.drawString(100, 750, "This is a test document for redaction testing.")
44
+ c.drawString(100, 700, "Email: test@example.com")
45
+ c.drawString(100, 650, "Phone: 123-456-7890")
46
+ c.drawString(100, 600, "Name: John Doe")
47
+ c.drawString(100, 550, "Address: 123 Test Street, Test City, TC 12345")
48
+ c.showPage()
49
+
50
+ # Add second page
51
+ c.drawString(100, 750, "Second page content")
52
+ c.drawString(100, 700, "More test data: jane.doe@example.com")
53
+ c.drawString(100, 650, "Another phone: 987-654-3210")
54
+ c.save()
55
+
56
+ print(f"Created dummy PDF: {pdf_path}")
57
+
58
+ # Create Partnership Agreement Toolkit PDF
59
+ partnership_pdf_path = (
60
+ "doc_redaction/example_data/Partnership-Agreement-Toolkit_0_0.pdf"
61
+ )
62
+ print(f"Creating PDF: {partnership_pdf_path}")
63
+ c = canvas.Canvas(partnership_pdf_path, pagesize=letter)
64
+ c.drawString(100, 750, "Partnership Agreement Toolkit")
65
+ c.drawString(100, 700, "This is a test partnership agreement document.")
66
+ c.drawString(100, 650, "Contact: partnership@example.com")
67
+ c.drawString(100, 600, "Phone: (555) 123-4567")
68
+ c.drawString(100, 550, "Address: 123 Partnership Street, City, State 12345")
69
+ c.showPage()
70
+
71
+ # Add second page
72
+ c.drawString(100, 750, "Page 2 - Partnership Details")
73
+ c.drawString(100, 700, "More partnership information here.")
74
+ c.drawString(100, 650, "Contact: info@partnership.org")
75
+ c.showPage()
76
+
77
+ # Add third page
78
+ c.drawString(100, 750, "Page 3 - Terms and Conditions")
79
+ c.drawString(100, 700, "Terms and conditions content.")
80
+ c.drawString(100, 650, "Legal contact: legal@partnership.org")
81
+ c.save()
82
+
83
+ print(f"Created dummy PDF: {partnership_pdf_path}")
84
+
85
+ # Create Graduate Job Cover Letter PDF
86
+ cover_letter_pdf_path = (
87
+ "doc_redaction/example_data/graduate-job-example-cover-letter.pdf"
88
+ )
89
+ print(f"Creating PDF: {cover_letter_pdf_path}")
90
+ c = canvas.Canvas(cover_letter_pdf_path, pagesize=letter)
91
+ c.drawString(100, 750, "Cover Letter Example")
92
+ c.drawString(100, 700, "Dear Hiring Manager,")
93
+ c.drawString(100, 650, "I am writing to apply for the position.")
94
+ c.drawString(100, 600, "Contact: applicant@example.com")
95
+ c.drawString(100, 550, "Phone: (555) 987-6543")
96
+ c.drawString(100, 500, "Address: 456 Job Street, Employment City, EC 54321")
97
+ c.drawString(100, 450, "Sincerely,")
98
+ c.drawString(100, 400, "John Applicant")
99
+ c.save()
100
+
101
+ print(f"Created dummy PDF: {cover_letter_pdf_path}")
102
+
103
+ except ImportError:
104
+ print("ReportLab not available, skipping PDF creation")
105
+ # Create simple text files instead
106
+ with open(
107
+ "doc_redaction/example_data/example_of_emails_sent_to_a_professor_before_applying.pdf",
108
+ "w",
109
+ ) as f:
110
+ f.write("This is a dummy PDF file for testing")
111
+
112
+ with open(
113
+ "doc_redaction/example_data/Partnership-Agreement-Toolkit_0_0.pdf",
114
+ "w",
115
+ ) as f:
116
+ f.write("This is a dummy Partnership Agreement PDF file for testing")
117
+
118
+ with open(
119
+ "doc_redaction/example_data/graduate-job-example-cover-letter.pdf",
120
+ "w",
121
+ ) as f:
122
+ f.write("This is a dummy cover letter PDF file for testing")
123
+
124
+ print("Created dummy text files instead of PDFs")
125
+
126
+
127
+ def create_dummy_csv():
128
+ """Create dummy CSV files for testing."""
129
+ # Main CSV
130
+ csv_data = {
131
+ "Case Note": [
132
+ "Client visited for consultation regarding housing issues",
133
+ "Follow-up appointment scheduled for next week",
134
+ "Documentation submitted for review",
135
+ ],
136
+ "Client": ["John Smith", "Jane Doe", "Bob Johnson"],
137
+ "Date": ["2024-01-15", "2024-01-16", "2024-01-17"],
138
+ }
139
+ df = pd.DataFrame(csv_data)
140
+ df.to_csv("doc_redaction/example_data/combined_case_notes.csv", index=False)
141
+ print("Created dummy CSV: doc_redaction/example_data/combined_case_notes.csv")
142
+
143
+ # Lambeth CSV
144
+ lambeth_data = {
145
+ "text": [
146
+ "Lambeth 2030 vision document content",
147
+ "Our Future Our Lambeth strategic plan",
148
+ "Community engagement and development",
149
+ ],
150
+ "page": [1, 2, 3],
151
+ }
152
+ df_lambeth = pd.DataFrame(lambeth_data)
153
+ df_lambeth.to_csv(
154
+ "doc_redaction/example_data/Lambeth_2030-Our_Future_Our_Lambeth.pdf.csv",
155
+ index=False,
156
+ )
157
+ print(
158
+ "Created dummy CSV: doc_redaction/example_data/Lambeth_2030-Our_Future_Our_Lambeth.pdf.csv"
159
+ )
160
+
161
+
162
+ def create_dummy_word_doc():
163
+ """Create dummy Word document."""
164
+ try:
165
+ from docx import Document
166
+
167
+ doc = Document()
168
+ doc.add_heading("Test Document for Redaction", 0)
169
+ doc.add_paragraph("This is a test document for redaction testing.")
170
+ doc.add_paragraph("Contact Information:")
171
+ doc.add_paragraph("Email: test@example.com")
172
+ doc.add_paragraph("Phone: 123-456-7890")
173
+ doc.add_paragraph("Name: John Doe")
174
+ doc.add_paragraph("Address: 123 Test Street, Test City, TC 12345")
175
+
176
+ doc.save(
177
+ "doc_redaction/example_data/Bold minimalist professional cover letter.docx"
178
+ )
179
+ print("Created dummy Word document")
180
+
181
+ except ImportError:
182
+ print("python-docx not available, skipping Word document creation")
183
+
184
+
185
+ def create_allow_deny_lists():
186
+ """Create dummy allow/deny lists."""
187
+ # Allow lists
188
+ allow_data = {"word": ["test", "example", "document"]}
189
+ pd.DataFrame(allow_data).to_csv(
190
+ "doc_redaction/example_data/test_allow_list_graduate.csv", index=False
191
+ )
192
+ pd.DataFrame(allow_data).to_csv(
193
+ "doc_redaction/example_data/test_allow_list_partnership.csv", index=False
194
+ )
195
+ print("Created allow lists")
196
+
197
+ # Deny lists
198
+ deny_data = {"word": ["sensitive", "confidential", "private"]}
199
+ pd.DataFrame(deny_data).to_csv(
200
+ "doc_redaction/example_data/partnership_toolkit_redact_custom_deny_list.csv",
201
+ index=False,
202
+ )
203
+ pd.DataFrame(deny_data).to_csv(
204
+ "doc_redaction/example_data/Partnership-Agreement-Toolkit_test_deny_list_para_single_spell.csv",
205
+ index=False,
206
+ )
207
+ print("Created deny lists")
208
+
209
+ # Whole page redaction list
210
+ page_data = {"page": [1, 2]}
211
+ pd.DataFrame(page_data).to_csv(
212
+ "doc_redaction/example_data/partnership_toolkit_redact_some_pages.csv",
213
+ index=False,
214
+ )
215
+ print("Created whole page redaction list")
216
+
217
+
218
+ def create_ocr_output():
219
+ """Create dummy OCR output CSV."""
220
+ ocr_data = {
221
+ "page": [1, 2, 3],
222
+ "text": [
223
+ "This is page 1 content with some text",
224
+ "This is page 2 content with different text",
225
+ "This is page 3 content with more text",
226
+ ],
227
+ "left": [0.1, 0.3, 0.5],
228
+ "top": [0.95, 0.92, 0.88],
229
+ "width": [0.05, 0.02, 0.02],
230
+ "height": [0.01, 0.02, 0.02],
231
+ "line": [1, 2, 3],
232
+ }
233
+ df = pd.DataFrame(ocr_data)
234
+ df.to_csv(
235
+ "doc_redaction/example_data/example_outputs/doubled_output_joined.pdf_ocr_output.csv",
236
+ index=False,
237
+ )
238
+ print("Created dummy OCR output CSV")
239
+
240
+
241
+ def create_dummy_image():
242
+ """Create dummy image for testing."""
243
+ try:
244
+ from PIL import Image, ImageDraw, ImageFont
245
+
246
+ img = Image.new("RGB", (800, 600), color="white")
247
+ draw = ImageDraw.Draw(img)
248
+
249
+ # Try to use a system font
250
+ try:
251
+ font = ImageFont.truetype(
252
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 20
253
+ )
254
+ except Exception as e:
255
+ print(f"Error loading DejaVuSans font: {e}")
256
+ try:
257
+ font = ImageFont.truetype("/System/Library/Fonts/Arial.ttf", 20)
258
+ except Exception as e:
259
+ print(f"Error loading Arial font: {e}")
260
+ font = ImageFont.load_default()
261
+
262
+ # Add text to image
263
+ draw.text((50, 50), "Test Document for Redaction", fill="black", font=font)
264
+ draw.text((50, 100), "Email: test@example.com", fill="black", font=font)
265
+ draw.text((50, 150), "Phone: 123-456-7890", fill="black", font=font)
266
+ draw.text((50, 200), "Name: John Doe", fill="black", font=font)
267
+ draw.text((50, 250), "Address: 123 Test Street", fill="black", font=font)
268
+
269
+ img.save("doc_redaction/example_data/example_complaint_letter.jpg")
270
+ print("Created dummy image")
271
+
272
+ except ImportError:
273
+ print("PIL not available, skipping image creation")
274
+
275
+
276
+ def main():
277
+ """Main setup function."""
278
+ print("Setting up test data for GitHub Actions...")
279
+ print(f"Current working directory: {os.getcwd()}")
280
+ print(f"Python version: {sys.version}")
281
+
282
+ create_directories()
283
+ create_dummy_pdf()
284
+ create_dummy_csv()
285
+ create_dummy_word_doc()
286
+ create_allow_deny_lists()
287
+ create_ocr_output()
288
+ create_dummy_image()
289
+
290
+ print("\nTest data setup complete!")
291
+ print("Created files:")
292
+ for root, dirs, files in os.walk("doc_redaction/example_data"):
293
+ for file in files:
294
+ file_path = os.path.join(root, file)
295
+ print(f" {file_path}")
296
+ # Verify the file exists and has content
297
+ if os.path.exists(file_path):
298
+ file_size = os.path.getsize(file_path)
299
+ print(f" Size: {file_size} bytes")
300
+ else:
301
+ print(" WARNING: File does not exist!")
302
+
303
+ # Verify critical files exist
304
+ critical_files = [
305
+ "doc_redaction/example_data/Partnership-Agreement-Toolkit_0_0.pdf",
306
+ "doc_redaction/example_data/graduate-job-example-cover-letter.pdf",
307
+ "doc_redaction/example_data/example_of_emails_sent_to_a_professor_before_applying.pdf",
308
+ ]
309
+
310
+ print("\nVerifying critical test files:")
311
+ for file_path in critical_files:
312
+ if os.path.exists(file_path):
313
+ file_size = os.path.getsize(file_path)
314
+ print(f"✅ {file_path} exists ({file_size} bytes)")
315
+ else:
316
+ print(f"❌ {file_path} MISSING!")
317
+
318
+
319
+ if __name__ == "__main__":
320
+ main()
.github/workflow_README.md ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GitHub Actions CI/CD Setup
2
+
3
+ This directory contains GitHub Actions workflows for automated testing of the CLI redaction application.
4
+
5
+ ## Workflows Overview
6
+
7
+ ### 1. **Simple Test Run** (`.github/workflows/simple-test.yml`)
8
+ - **Purpose**: Basic test execution
9
+ - **Triggers**: Push to main/dev, Pull requests
10
+ - **OS**: Ubuntu Latest
11
+ - **Python**: 3.11
12
+ - **Features**:
13
+ - Installs system dependencies
14
+ - Sets up test data
15
+ - Runs CLI tests
16
+ - Runs pytest
17
+
18
+ ### 2. **Comprehensive CI/CD** (`.github/workflows/ci.yml`)
19
+ - **Purpose**: Full CI/CD pipeline
20
+ - **Features**:
21
+ - Linting (Ruff, Black)
22
+ - Unit tests (Python 3.10, 3.11, 3.12)
23
+ - Integration tests
24
+ - Security scanning (Safety, Bandit)
25
+ - Coverage reporting
26
+ - Package building (on main branch)
27
+
28
+ ### 3. **Multi-OS Testing** (`.github/workflows/multi-os-test.yml`)
29
+ - **Purpose**: Cross-platform testing
30
+ - **OS**: Ubuntu, macOS (Windows not included currently but may be reintroduced)
31
+ - **Python**: 3.10, 3.11, 3.12
32
+ - **Features**: Tests compatibility across different operating systems
33
+
34
+ ### 4. **Basic Test Suite** (`.github/workflows/test.yml`)
35
+ - **Purpose**: Original test workflow
36
+ - **Features**:
37
+ - Multiple Python versions
38
+ - System dependency installation
39
+ - Test data creation
40
+ - Coverage reporting
41
+
42
+ ## Setup Scripts
43
+
44
+ ### Test Data Setup (`.github/scripts/setup_test_data.py`)
45
+ Creates dummy test files when example data is not available:
46
+ - PDF documents
47
+ - CSV files
48
+ - Word documents
49
+ - Images
50
+ - Allow/deny lists
51
+ - OCR output files
52
+
53
+ ## Usage
54
+
55
+ ### Running Tests Locally
56
+
57
+ ```bash
58
+ # Install dependencies
59
+ pip install -r requirements.txt
60
+ pip install pytest pytest-cov
61
+
62
+ # Setup test data
63
+ python .github/scripts/setup_test_data.py
64
+
65
+ # Run tests
66
+ cd test
67
+ python cli_epilog_suite.py
68
+ ```
69
+
70
+ ### GitHub Actions Triggers
71
+
72
+ 1. **Push to main/dev**: Runs all tests
73
+ 2. **Pull Request**: Runs tests and linting
74
+ 3. **Daily Schedule**: Runs tests at 2 AM UTC
75
+ 4. **Manual Trigger**: Can be triggered manually from GitHub
76
+
77
+ ## Configuration
78
+
79
+ ### Environment Variables
80
+ - `PYTHON_VERSION`: Default Python version (3.11)
81
+ - `PYTHONPATH`: Set automatically for test discovery
82
+
83
+ ### Caching
84
+ - Pip dependencies are cached for faster builds
85
+ - Cache key based on requirements.txt hash
86
+
87
+ ### Artifacts
88
+ - Test results (JUnit XML)
89
+ - Coverage reports (HTML, XML)
90
+ - Security reports
91
+ - Build artifacts (on main branch)
92
+
93
+ ## Test Data
94
+
95
+ The workflows automatically create test data when example files are missing:
96
+
97
+ ### Required Files Created:
98
+ - `example_data/example_of_emails_sent_to_a_professor_before_applying.pdf`
99
+ - `example_data/combined_case_notes.csv`
100
+ - `example_data/Bold minimalist professional cover letter.docx`
101
+ - `example_data/example_complaint_letter.jpg`
102
+ - `example_data/test_allow_list_*.csv`
103
+ - `example_data/partnership_toolkit_redact_*.csv`
104
+ - `example_data/example_outputs/doubled_output_joined.pdf_ocr_output.csv`
105
+
106
+ ### Dependencies Installed:
107
+ - **System**: tesseract-ocr, poppler-utils, OpenGL libraries
108
+ - **Python**: All requirements.txt packages + pytest, reportlab, pillow
109
+
110
+ ## Workflow Status
111
+
112
+ ### Success Criteria:
113
+ - ✅ All tests pass
114
+ - ✅ No linting errors
115
+ - ✅ Security checks pass
116
+ - ✅ Coverage meets threshold (if configured)
117
+
118
+ ### Failure Handling:
119
+ - Tests are designed to skip gracefully if files are missing
120
+ - AWS tests are expected to fail without credentials
121
+ - System dependency failures are handled with fallbacks
122
+
123
+ ## Customization
124
+
125
+ ### Adding New Tests:
126
+ 1. Add test methods to `test/cli_epilog_suite.py` or pytest files under `test/test_*.py`
127
+ 2. Update test data in `setup_test_data.py` if needed
128
+ 3. Tests will automatically run in all workflows
129
+
130
+ ### Modifying Workflows:
131
+ 1. Edit the appropriate `.yml` file
132
+ 2. Test locally first
133
+ 3. Push to trigger the workflow
134
+
135
+ ### Environment-Specific Settings:
136
+ - **Ubuntu**: Full system dependencies
137
+ - **Windows**: Python packages only
138
+ - **macOS**: Homebrew dependencies
139
+
140
+ ## Troubleshooting
141
+
142
+ ### Common Issues:
143
+
144
+ 1. **Missing Dependencies**:
145
+ - Check system dependency installation
146
+ - Verify Python package versions
147
+
148
+ 2. **Test Failures**:
149
+ - Check test data creation
150
+ - Verify file paths
151
+ - Review test output logs
152
+
153
+ 3. **AWS Test Failures**:
154
+ - Expected without credentials
155
+ - Tests are designed to handle this gracefully
156
+
157
+ 4. **System Dependency Issues**:
158
+ - Different OS have different requirements
159
+ - Check the specific OS section in workflows
160
+
161
+ ### Debug Mode:
162
+ Add `--verbose` or `-v` flags to pytest commands for more detailed output.
163
+
164
+ ## Security
165
+
166
+ - Dependencies are scanned with Safety
167
+ - Code is scanned with Bandit
168
+ - No secrets are exposed in logs
169
+ - Test data is temporary and cleaned up
170
+
171
+ ## Performance
172
+
173
+ - Tests run in parallel where possible
174
+ - Dependencies are cached
175
+ - Only necessary system packages are installed
176
+ - Test data is created efficiently
177
+
178
+ ## Monitoring
179
+
180
+ - Workflow status is visible in GitHub Actions tab
181
+ - Coverage reports are uploaded to Codecov
182
+ - Test results are available as artifacts
183
+ - Security reports are generated and stored
.github/workflows/archive_workflows/multi-os-test.yml ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Multi-OS Test
2
+
3
+ on:
4
+ push:
5
+ branches: [ main ]
6
+ pull_request:
7
+ branches: [ main ]
8
+
9
+ permissions:
10
+ contents: read
11
+ actions: read
12
+
13
+ jobs:
14
+ test:
15
+ runs-on: ${{ matrix.os }}
16
+ env:
17
+ SHOW_VLM_MODEL_OPTIONS: "False"
18
+ strategy:
19
+ matrix:
20
+ os: [ubuntu-latest, macos-latest] # windows-latest, not included as tesseract cannot be installed silently
21
+ python-version: ["3.11", "3.12", "3.13"]
22
+ exclude:
23
+ # Exclude some combinations to reduce CI time
24
+ #- os: windows-latest
25
+ # python-version: ["3.12", "3.13"]
26
+ - os: macos-latest
27
+ python-version: ["3.12", "3.13"]
28
+
29
+ steps:
30
+ - uses: actions/checkout@v6
31
+
32
+ - name: Set up Python ${{ matrix.python-version }}
33
+ uses: actions/setup-python@v6
34
+ with:
35
+ python-version: ${{ matrix.python-version }}
36
+
37
+ - name: Install system dependencies (Ubuntu)
38
+ if: matrix.os == 'ubuntu-latest'
39
+ run: |
40
+ sudo apt-get update
41
+ sudo apt-get install -y \
42
+ tesseract-ocr \
43
+ tesseract-ocr-eng \
44
+ poppler-utils \
45
+ libgl1-mesa-dri \
46
+ libglib2.0-0 \
47
+ libsm6 \
48
+ libxext6 \
49
+ libxrender-dev \
50
+ libgomp1
51
+
52
+ - name: Install system dependencies (macOS)
53
+ if: matrix.os == 'macos-latest'
54
+ run: |
55
+ brew install tesseract poppler
56
+
57
+ - name: Install system dependencies (Windows)
58
+ if: matrix.os == 'windows-latest'
59
+ run: |
60
+ # Create tools directory
61
+ if (!(Test-Path "C:\tools")) {
62
+ mkdir C:\tools
63
+ }
64
+
65
+ # Download and install Tesseract
66
+ $tesseractUrl = "https://github.com/tesseract-ocr/tesseract/releases/download/5.5.0/tesseract-ocr-w64-setup-5.5.0.20241111.exe"
67
+ $tesseractInstaller = "C:\tools\tesseract-installer.exe"
68
+ Invoke-WebRequest -Uri $tesseractUrl -OutFile $tesseractInstaller
69
+
70
+ # Install Tesseract silently
71
+ Start-Process -FilePath $tesseractInstaller -ArgumentList "/S", "/D=C:\tools\tesseract" -Wait
72
+
73
+ # Download and extract Poppler
74
+ $popplerUrl = "https://github.com/oschwartz10612/poppler-windows/releases/download/v25.07.0-0/Release-25.07.0-0.zip"
75
+ $popplerZip = "C:\tools\poppler.zip"
76
+ Invoke-WebRequest -Uri $popplerUrl -OutFile $popplerZip
77
+
78
+ # Extract Poppler
79
+ Expand-Archive -Path $popplerZip -DestinationPath C:\tools\poppler -Force
80
+
81
+ # Add to PATH
82
+ echo "C:\tools\tesseract" >> $env:GITHUB_PATH
83
+ echo "C:\tools\poppler\poppler-25.07.0\Library\bin" >> $env:GITHUB_PATH
84
+
85
+ # Set environment variables for your application
86
+ echo "TESSERACT_FOLDER=C:\tools\tesseract" >> $env:GITHUB_ENV
87
+ echo "POPPLER_FOLDER=C:\tools\poppler\poppler-25.07.0\Library\bin" >> $env:GITHUB_ENV
88
+ echo "TESSERACT_DATA_FOLDER=C:\tools\tesseract\tessdata" >> $env:GITHUB_ENV
89
+
90
+ # Verify installation using full paths (since PATH won't be updated in current session)
91
+ & "C:\tools\tesseract\tesseract.exe" --version
92
+ & "C:\tools\poppler\poppler-25.07.0\Library\bin\pdftoppm.exe" -v
93
+
94
+ - name: Install Python dependencies
95
+ run: |
96
+ python -m pip install --upgrade pip
97
+ pip install -r requirements.txt
98
+ pip install pytest pytest-cov reportlab pillow
99
+
100
+ - name: Download spaCy model
101
+ run: |
102
+ python -m spacy download en_core_web_lg
103
+
104
+ - name: Setup test data
105
+ run: |
106
+ python .github/scripts/setup_test_data.py
107
+
108
+ - name: Run CLI tests
109
+ run: |
110
+ cd test
111
+ python cli_epilog_suite.py
112
+
113
+ - name: Run tests with pytest
114
+ run: |
115
+ pytest test/ -v --tb=short
.github/workflows/ci.yml ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CI/CD Pipeline
2
+
3
+ on:
4
+ push:
5
+ branches: [ main ]
6
+ pull_request:
7
+ branches: [ main ]
8
+ workflow_dispatch:
9
+ #schedule:
10
+ # Run tests daily at 2 AM UTC
11
+ # - cron: '0 2 * * *'
12
+
13
+ permissions:
14
+ contents: read
15
+ actions: read
16
+ pull-requests: write
17
+ issues: write
18
+
19
+ env:
20
+ PYTHON_VERSION: "3.11"
21
+
22
+ jobs:
23
+ lint:
24
+ runs-on: ubuntu-latest
25
+ steps:
26
+ - uses: actions/checkout@v6
27
+
28
+ - name: Set up Python
29
+ uses: actions/setup-python@v6
30
+ with:
31
+ python-version: ${{ env.PYTHON_VERSION }}
32
+
33
+ - name: Install dependencies
34
+ run: |
35
+ python -m pip install --upgrade pip
36
+ pip install ruff black
37
+
38
+ - name: Run Ruff linter
39
+ run: ruff check .
40
+
41
+ - name: Run Black formatter check
42
+ run: black --check .
43
+
44
+ test-unit:
45
+ runs-on: ubuntu-latest
46
+ env:
47
+ # Avoid optional VLM/torch import path in tools.run_vlm (not installed in lightweight CI deps)
48
+ SHOW_VLM_MODEL_OPTIONS: "False"
49
+ strategy:
50
+ matrix:
51
+ python-version: [3.11, 3.12, 3.13]
52
+
53
+ steps:
54
+ - uses: actions/checkout@v6
55
+
56
+ - name: Set up Python ${{ matrix.python-version }}
57
+ uses: actions/setup-python@v6
58
+ with:
59
+ python-version: ${{ matrix.python-version }}
60
+
61
+ - name: Cache pip dependencies
62
+ uses: actions/cache@v5
63
+ with:
64
+ path: ~/.cache/pip
65
+ key: ${{ runner.os }}-pip-${{ hashFiles('requirements_lightweight.txt') }}
66
+ restore-keys: |
67
+ ${{ runner.os }}-pip-
68
+
69
+ - name: Install system dependencies
70
+ run: |
71
+ sudo apt-get update
72
+ sudo apt-get install -y \
73
+ tesseract-ocr \
74
+ tesseract-ocr-eng \
75
+ poppler-utils \
76
+ libgl1-mesa-dri \
77
+ libglib2.0-0 \
78
+ libsm6 \
79
+ libxext6 \
80
+ libxrender-dev \
81
+ libgomp1
82
+
83
+ - name: Install Python dependencies
84
+ run: |
85
+ python -m pip install --upgrade pip
86
+ pip install -r requirements_lightweight.txt
87
+ pip install pytest pytest-cov pytest-html pytest-xdist reportlab pillow
88
+
89
+ - name: Download spaCy model
90
+ run: |
91
+ python -m spacy download en_core_web_lg
92
+
93
+ - name: Setup test data
94
+ run: |
95
+ python .github/scripts/setup_test_data.py
96
+ echo "Setup script completed. Checking results:"
97
+ ls -la doc_redaction/example_data/ || echo "doc_redaction/example_data directory not found"
98
+
99
+ - name: Verify test data files
100
+ run: |
101
+ echo "Checking if critical test files exist:"
102
+ ls -la doc_redaction/example_data/
103
+ echo "Checking for specific PDF files:"
104
+ ls -la doc_redaction/example_data/*.pdf || echo "No PDF files found"
105
+ echo "Checking file sizes:"
106
+ find doc_redaction/example_data -name "*.pdf" -exec ls -lh {} \;
107
+
108
+ - name: Clean up problematic config files
109
+ run: |
110
+ rm -f config*.py || true
111
+
112
+ - name: Run CLI tests
113
+ run: |
114
+ cd test
115
+ python cli_epilog_suite.py
116
+
117
+ - name: Run tests with pytest (JUnit and coverage)
118
+ run: |
119
+ pytest test/ -v --tb=short \
120
+ --junitxml=test-results.xml \
121
+ --cov=. --cov-config=.coveragerc \
122
+ --cov-report=xml --cov-report=html --cov-report=term
123
+
124
+ #- name: Upload coverage to Codecov - not necessary
125
+ # uses: codecov/codecov-action@v3
126
+ # if: matrix.python-version == '3.11'
127
+ # with:
128
+ # file: ./coverage.xml
129
+ # flags: unittests
130
+ # name: codecov-umbrella
131
+ # fail_ci_if_error: false
132
+
133
+ - name: Upload test results
134
+ uses: actions/upload-artifact@v6
135
+ if: always()
136
+ with:
137
+ name: test-results-python-${{ matrix.python-version }}
138
+ path: |
139
+ test-results.xml
140
+ htmlcov/
141
+ coverage.xml
142
+
143
+ test-integration:
144
+ runs-on: ubuntu-latest
145
+ needs: [lint, test-unit]
146
+ env:
147
+ SHOW_VLM_MODEL_OPTIONS: "False"
148
+
149
+ steps:
150
+ - uses: actions/checkout@v6
151
+
152
+ - name: Set up Python
153
+ uses: actions/setup-python@v6
154
+ with:
155
+ python-version: ${{ env.PYTHON_VERSION }}
156
+
157
+ - name: Install dependencies
158
+ run: |
159
+ python -m pip install --upgrade pip
160
+ pip install -r requirements_lightweight.txt
161
+ pip install pytest pytest-cov reportlab pillow
162
+
163
+ - name: Install system dependencies
164
+ run: |
165
+ sudo apt-get update
166
+ sudo apt-get install -y \
167
+ tesseract-ocr \
168
+ tesseract-ocr-eng \
169
+ poppler-utils \
170
+ libgl1-mesa-dri \
171
+ libglib2.0-0 \
172
+ libsm6 \
173
+ libxext6 \
174
+ libxrender-dev \
175
+ libgomp1
176
+
177
+ - name: Download spaCy model
178
+ run: |
179
+ python -m spacy download en_core_web_lg
180
+
181
+ - name: Setup test data
182
+ run: |
183
+ python .github/scripts/setup_test_data.py
184
+ echo "Setup script completed. Checking results:"
185
+ ls -la doc_redaction/example_data/ || echo "doc_redaction/example_data directory not found"
186
+
187
+ - name: Verify test data files
188
+ run: |
189
+ echo "Checking if critical test files exist:"
190
+ ls -la doc_redaction/example_data/
191
+ echo "Checking for specific PDF files:"
192
+ ls -la doc_redaction/example_data/*.pdf || echo "No PDF files found"
193
+ echo "Checking file sizes:"
194
+ find doc_redaction/example_data -name "*.pdf" -exec ls -lh {} \;
195
+
196
+ - name: Run integration tests
197
+ run: |
198
+ cd test
199
+ python demo_single_test.py
200
+
201
+ - name: Test CLI help
202
+ run: |
203
+ python cli_redact.py --help
204
+
205
+ - name: Test CLI version
206
+ run: |
207
+ python -c "import sys; print(f'Python {sys.version}')"
208
+
209
+ security:
210
+ runs-on: ubuntu-latest
211
+ steps:
212
+ - uses: actions/checkout@v6
213
+
214
+ - name: Set up Python
215
+ uses: actions/setup-python@v6
216
+ with:
217
+ python-version: ${{ env.PYTHON_VERSION }}
218
+
219
+ - name: Install dependencies
220
+ run: |
221
+ python -m pip install --upgrade pip
222
+ pip install safety bandit
223
+
224
+ #- name: Run safety scan - removed as now requires login
225
+ # run: |
226
+ # safety scan -r requirements.txt
227
+
228
+ - name: Run bandit security check
229
+ run: |
230
+ bandit -r . -f json -o bandit-report.json || true
231
+
232
+ - name: Upload security report
233
+ uses: actions/upload-artifact@v6
234
+ if: always()
235
+ with:
236
+ name: security-report
237
+ path: bandit-report.json
238
+
239
+ build:
240
+ runs-on: ubuntu-latest
241
+ needs: [lint, test-unit]
242
+ if: github.event_name == 'push' && github.ref == 'refs/heads/main'
243
+
244
+ steps:
245
+ - uses: actions/checkout@v6
246
+
247
+ - name: Set up Python
248
+ uses: actions/setup-python@v6
249
+ with:
250
+ python-version: ${{ env.PYTHON_VERSION }}
251
+
252
+ - name: Install build dependencies
253
+ run: |
254
+ python -m pip install --upgrade pip
255
+ pip install build twine
256
+
257
+ - name: Build package
258
+ run: |
259
+ python -m build
260
+
261
+ - name: Check package
262
+ run: |
263
+ twine check dist/*
264
+
265
+ - name: Upload build artifacts
266
+ uses: actions/upload-artifact@v6
267
+ with:
268
+ name: dist
269
+ path: dist/
.github/workflows/simple-test.yml ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Simple Test Run
2
+
3
+ on:
4
+ push:
5
+ branches: [ dev ]
6
+ pull_request:
7
+ branches: [ dev ]
8
+ workflow_dispatch:
9
+
10
+ permissions:
11
+ contents: read
12
+ actions: read
13
+
14
+ jobs:
15
+ test:
16
+ runs-on: ubuntu-latest
17
+ env:
18
+ SHOW_VLM_MODEL_OPTIONS: "False"
19
+
20
+ steps:
21
+ - uses: actions/checkout@v6
22
+
23
+ - name: Set up Python 3.12
24
+ uses: actions/setup-python@v6
25
+ with:
26
+ python-version: "3.12"
27
+
28
+ - name: Install system dependencies
29
+ run: |
30
+ sudo apt-get update
31
+ sudo apt-get install -y \
32
+ tesseract-ocr \
33
+ tesseract-ocr-eng \
34
+ poppler-utils \
35
+ libgl1-mesa-dri \
36
+ libglib2.0-0 \
37
+ libsm6 \
38
+ libxext6 \
39
+ libxrender-dev \
40
+ libgomp1
41
+
42
+ - name: Install Python dependencies
43
+ run: |
44
+ python -m pip install --upgrade pip
45
+ pip install -r requirements_lightweight.txt
46
+ pip install pytest pytest-cov reportlab pillow
47
+
48
+ - name: Download spaCy model
49
+ run: |
50
+ python -m spacy download en_core_web_lg
51
+
52
+ - name: Setup test data
53
+ run: |
54
+ python .github/scripts/setup_test_data.py
55
+ echo "Setup script completed. Checking results:"
56
+ ls -la doc_redaction/example_data/ || echo "doc_redaction/example_data directory not found"
57
+
58
+ - name: Verify test data files
59
+ run: |
60
+ echo "Checking if critical test files exist:"
61
+ ls -la doc_redaction/example_data/
62
+ echo "Checking for specific PDF files:"
63
+ ls -la doc_redaction/example_data/*.pdf || echo "No PDF files found"
64
+ echo "Checking file sizes:"
65
+ find doc_redaction/example_data -name "*.pdf" -exec ls -lh {} \;
66
+
67
+ - name: Run CLI tests
68
+ run: |
69
+ cd test
70
+ python cli_epilog_suite.py
71
+
72
+ - name: Run tests with pytest
73
+ run: |
74
+ pytest test/ -v --tb=short
.github/workflows/sync-pi-agent-space.yml ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync Pi agent to Hugging Face Space
2
+
3
+ on:
4
+ push:
5
+ branches: [dev]
6
+ paths:
7
+ - "docker/pi/**"
8
+ - "skills/**"
9
+ - "agent-redact-space/pi-agent/**"
10
+ - "doc_redaction/example_data/**"
11
+ - "requirements_pi_agent.txt"
12
+ - "AGENTS.md"
13
+ - ".github/workflows/sync-pi-agent-space.yml"
14
+ workflow_dispatch:
15
+
16
+ permissions:
17
+ contents: read
18
+
19
+ jobs:
20
+ sync-pi-agent-space:
21
+ runs-on: ubuntu-latest
22
+ steps:
23
+ - uses: actions/checkout@v6
24
+ with:
25
+ fetch-depth: 1
26
+ lfs: true
27
+
28
+ - name: Install Git LFS
29
+ run: git lfs install
30
+
31
+ - name: Materialize example PDFs (Git LFS)
32
+ run: |
33
+ git lfs pull --include="doc_redaction/example_data/*.pdf"
34
+ for f in \
35
+ doc_redaction/example_data/example_of_emails_sent_to_a_professor_before_applying.pdf \
36
+ doc_redaction/example_data/graduate-job-example-cover-letter.pdf; do
37
+ if head -1 "$f" | grep -q "^version https://git-lfs.github.com/spec/v1"; then
38
+ echo "Example PDF is still an LFS pointer (not materialized): $f" >&2
39
+ exit 1
40
+ fi
41
+ done
42
+
43
+ - name: Flatten Pi agent Space tree
44
+ run: |
45
+ chmod +x agent-redact-space/pi-agent/sync_to_space.sh
46
+ agent-redact-space/pi-agent/sync_to_space.sh /tmp/pi-agent-space
47
+
48
+ - name: Push to Hugging Face Space
49
+ run: |
50
+ COMMIT_MSG=$(git log -1 --pretty=%B)
51
+ echo "Syncing Pi agent Space: seanpedrickcase/agentic_document_redaction"
52
+ cd /tmp/pi-agent-space
53
+ git init -b main
54
+ git config user.name "$HF_USERNAME"
55
+ git config user.email "$HF_EMAIL"
56
+ git add .
57
+ git commit -m "Sync Pi agent Space: $COMMIT_MSG"
58
+ git remote add hf "https://${HF_USERNAME}:${HF_TOKEN}@huggingface.co/spaces/${HF_USERNAME}/agentic_document_redaction"
59
+ git push --force hf main
60
+ env:
61
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
62
+ HF_USERNAME: ${{ secrets.HF_USERNAME }}
63
+ HF_EMAIL: ${{ secrets.HF_EMAIL }}
.github/workflows/sync_to_hf.yml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync to Hugging Face hub
2
+ on:
3
+ push:
4
+ branches: [dev]
5
+ workflow_dispatch:
6
+
7
+ permissions:
8
+ contents: read
9
+
10
+ jobs:
11
+ sync-to-hub:
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - uses: actions/checkout@v6
15
+ with:
16
+ fetch-depth: 1 # Only get the latest state
17
+ lfs: true # Download actual LFS files so they can be pushed
18
+
19
+ - name: Install Git LFS
20
+ run: git lfs install
21
+
22
+ - name: Recreate repo history (single-commit force push)
23
+ run: |
24
+ # 1. Capture the message BEFORE we delete the .git folder
25
+ COMMIT_MSG=$(git log -1 --pretty=%B)
26
+ echo "Syncing commit message: $COMMIT_MSG"
27
+
28
+ # 2. DELETE the .git folder.
29
+ # This turns the repo into a standard folder of files.
30
+ rm -rf .git
31
+
32
+ # 3. Re-initialize a brand new git repo
33
+ git init -b main
34
+ git config --global user.name "$HF_USERNAME"
35
+ git config --global user.email "$HF_EMAIL"
36
+
37
+ # 4. Re-install LFS (needs to be done after git init)
38
+ git lfs install
39
+
40
+ # 5. Add the remote
41
+ git remote add hf https://$HF_USERNAME:$HF_TOKEN@huggingface.co/spaces/$HF_USERNAME/$HF_REPO_ID
42
+
43
+ # 6. Add all files
44
+ # Since this is a fresh init, Git sees EVERY file as "New"
45
+ git add .
46
+
47
+ # 7. Commit and Force Push
48
+ git commit -m "Sync: $COMMIT_MSG"
49
+ git push --force hf main
50
+ env:
51
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
52
+ HF_USERNAME: ${{ secrets.HF_USERNAME }}
53
+ HF_EMAIL: ${{ secrets.HF_EMAIL }}
54
+ HF_REPO_ID: ${{ secrets.HF_REPO_ID }}
.github/workflows/sync_to_hf_zero_gpu.yml ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync to Hugging Face hub Zero GPU
2
+ on:
3
+ push:
4
+ branches: [dev]
5
+ workflow_dispatch:
6
+
7
+ permissions:
8
+ contents: read
9
+
10
+ jobs:
11
+ sync-to-hub-zero-gpu:
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - uses: actions/checkout@v6
15
+ with:
16
+ fetch-depth: 1 # Only get the latest state
17
+ lfs: true # Download actual LFS files so they can be pushed
18
+
19
+ - name: Install Git LFS
20
+ run: git lfs install
21
+
22
+ # HF Spaces read Space config from README.md front matter. The repo README
23
+ # targets GitHub (e.g. docker); patch only this CI checkout before HF push.
24
+ - name: Apply HF Zero GPU Space README front matter
25
+ run: python3 tools/apply_hf_zero_gpu_readme_frontmatter.py
26
+
27
+ - name: Recreate repo history (single-commit force push)
28
+ run: |
29
+ # 1. Capture the message BEFORE we delete the .git folder
30
+ COMMIT_MSG=$(git log -1 --pretty=%B)
31
+ echo "Syncing commit message: $COMMIT_MSG"
32
+
33
+ # 2. DELETE the .git folder.
34
+ # This turns the repo into a standard folder of files.
35
+ rm -rf .git
36
+
37
+ # 3. Re-initialize a brand new git repo
38
+ git init -b main
39
+ git config --global user.name "$HF_USERNAME"
40
+ git config --global user.email "$HF_EMAIL"
41
+
42
+ # 4. Re-install LFS (needs to be done after git init)
43
+ git lfs install
44
+
45
+ # 5. Add the remote
46
+ git remote add hf https://$HF_USERNAME:$HF_TOKEN@huggingface.co/spaces/$HF_USERNAME/$HF_REPO_ID_ZERO_GPU
47
+
48
+ # 6. Add all files
49
+ # Since this is a fresh init, Git sees EVERY file as "New"
50
+ git add .
51
+
52
+ # 7. Commit and Force Push
53
+ git commit -m "Sync: $COMMIT_MSG"
54
+ git push --force hf main
55
+ env:
56
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
57
+ HF_USERNAME: ${{ secrets.HF_USERNAME }}
58
+ HF_EMAIL: ${{ secrets.HF_EMAIL }}
59
+ HF_REPO_ID_ZERO_GPU: ${{ secrets.HF_REPO_ID_ZERO_GPU }}
.gitignore ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.url
2
+ *.ipynb
3
+ *.pyc
4
+ *.qmd
5
+ _quarto.yml
6
+ quarto_site/*
7
+ src/*
8
+ redaction_deps/*
9
+ .venv/*
10
+ examples/*
11
+ processing/*
12
+ input/*
13
+ output/*
14
+ tools/__pycache__/*
15
+ old_code/*
16
+ tesseract/*
17
+ poppler/*
18
+ build/*
19
+ dist/*
20
+ build_deps/*
21
+ logs/*
22
+ usage/*
23
+ feedback/*
24
+ config/*
25
+ !config/pi_agent.env.example
26
+ workspace/*
27
+ user_guide/*
28
+ _extensions/*
29
+ doc_redaction.egg-info/*
30
+ .venv_pypi_test/*
31
+ cdk/config/*
32
+ cdk/cdk.out/*
33
+ cdk/archive/*
34
+ tld/*
35
+ tmp/*
36
+ docs/*
37
+ .pi/*
38
+ cdk.out/*
39
+ cdk.json
40
+ cdk.context.json
41
+ precheck.context.json
42
+ .quarto/*
43
+ /.quarto/
44
+ /_site/
45
+ test/config/*
46
+ test/feedback/*
47
+ test/input/*
48
+ test/logs/*
49
+ test/output/*
50
+ test/tmp/*
51
+ test/usage/*
52
+ .ruff_cache/*
53
+ model_cache/*
54
+ sanitized_file/*
55
+ src/doc_redaction.egg-info/*
56
+ docker_compose/*
57
+ **/*.quarto_ipynb
58
+ skills/example_prompts/*
59
+ .pi/sessions/
60
+ docker/pi/agent/sessions/
AGENTS.md ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AGENTS.md
2
+
3
+ Context for AI coding agents working on **doc_redaction** (PII redaction for PDFs, images, Word, and tabular files). Human-oriented docs: [README.md](README.md). User guide: [doc_redaction user guide](https://seanpedrick-case.github.io/doc_redaction/src/user_guide.html).
4
+
5
+ ## Project overview
6
+
7
+ - **Stack**: Python 3.10+, Gradio UI ([app.py](app.py)), optional FastAPI when `RUN_FASTAPI` is enabled, AWS/LLM integrations via [tools/config.py](tools/config.py) and env files under `config/`.
8
+ - **License**: AGPL-3.0-only (see [pyproject.toml](pyproject.toml)). Respect license terms when adding dependencies.
9
+ - **Accuracy**: Outputs are not guaranteed complete; downstream use should assume **human review** of redacted material.
10
+
11
+ ## Cursor skills: redaction workflow (optional)
12
+
13
+ For agents operating the deployed app (Gradio Client, review CSV, `/review_apply`), these repo-local playbooks are a suggested ladder:
14
+
15
+ 0. **[`skills/doc-redaction-task-prompt/TASK_PROMPT_TEMPLATE.md`](skills/doc-redaction-task-prompt/TASK_PROMPT_TEMPLATE.md)** — copy-paste user task prompt (Pass 1 default, Pass 2 gated); **user redaction requirements go at the end of the prompt**.
16
+ 1. **[`skills/doc-redaction-app/SKILL.md`](skills/doc-redaction-app/SKILL.md)** — first-pass redaction (`/doc_redact` / `/redact_document`) and downloading artifacts.
17
+ 2. **[`skills/doc-redact-page-review/SKILL.md`](skills/doc-redact-page-review/SKILL.md)** — after outputs exist: **parallel per-page** child agents, merge into one full-document `*_review_file.csv`, **single** `/review_apply` from the parent.
18
+ 3. **[`skills/doc-redaction-modifications/SKILL.md`](skills/doc-redaction-modifications/SKILL.md)** — CSV mechanics, `preview_redaction_boxes`, `/review_apply` patterns, verification, VLM and PyMuPDF fallbacks (single-thread edits and the **technical** reference for page-review children).
19
+
20
+ ## Setup
21
+
22
+ 1. **System**: Install **Tesseract** and **Poppler** (required for OCR/PDF). See [README.md](README.md) (Windows/Linux sections).
23
+ 2. **Python**: Create a venv, then install the project (e.g. `pip install -e ".[dev]"` or follow README).
24
+ 3. **Configuration**: Copy or edit environment/config as described in README / `config/` (e.g. `app_config.env`). Do not commit secrets.
25
+
26
+ ## Run locally
27
+
28
+ - Gradio/FastAPI entrypoint is [app.py](app.py). With FastAPI enabled, typical pattern is `uvicorn app:app --host 0.0.0.0 --port 7860` (exact host/port from your config).
29
+ - OpenAPI docs: `/docs` when the FastAPI app is mounted.
30
+
31
+ ## Tests
32
+
33
+ - Run from repo root: `pytest` (optional: `pytest test/`).
34
+ - Fix failures related to your changes before opening a PR.
35
+
36
+ ## Line order (local OCR and simple text extraction)
37
+
38
+ Multi-column layouts use shared logic in [`tools/ocr_reading_order.py`](tools/ocr_reading_order.py). Controlled by **`LOCAL_OCR_READING_ORDER`** (`column` default, `legacy` for previous top-left behaviour).
39
+
40
+ ### Local OCR (Paddle/Tesseract)
41
+
42
+ Word boxes are merged into line-level CSV rows in [`combine_ocr_results`](tools/custom_image_analyser_engine.py).
43
+
44
+ - **`column`**: detect text columns, assign line numbers down each column left-to-right; full-width lines (headers) first. Stops cross-column merging that produced wide erroneous lines on multi-column PDFs. **Auto-fallback**: the page is treated as single-column unless a *consecutive cluster* of gutter rows (y-gap between adjacent rows ≤ `OCR_COLUMN_MAX_CONSECUTIVE_GUTTER_GAP`, default `0.06` of page height) has ≥ `OCR_COLUMN_MIN_GUTTER_ROWS` (default `3`) rows **and** the cluster's topmost row is above the footer zone (`OCR_COLUMN_FOOTER_ZONE_FRACTION`, default `0.75`). This prevents isolated header bands (logo | title, 1 gutter row), signature-only blocks at the page bottom (cluster starts at y ≥ 0.75), or the combination of both, from forcing column mode on the single-column body text between them.
45
+ - **`PADDLE_PRESERVE_LINE_BOXES=True`** or **`CONVERT_LINE_TO_WORD_LEVEL=False`** with Paddle: keep Paddle line boxes (skip word split + regrouping); line numbers still use column reading order.
46
+
47
+ ### Simple text extraction (PyMuPDF)
48
+
49
+ [`redact_text_pdf`](tools/file_redaction.py) → [`process_page_to_structured_ocr_pymupdf`](tools/file_redaction.py) calls [`reorder_structured_text_lines`](tools/ocr_reading_order.py) after collecting lines, using **`page.mediabox`** width/height for full-span header detection.
50
+
51
+ `reorder_structured_text_lines` now mirrors `build_line_groups` (local OCR route):
52
+
53
+ 1. **Column-aware sort** (`sort_reading_order` / `assign_layout_boxes` / `detect_column_split_xpoints`) — or legacy top-left for single-column pages.
54
+ 2. **Y-band grouping** (`group_into_lines`) — merges any same-row PyMuPDF lines that were emitted as separate objects (e.g. mixed-font spans) and splits horizontally-disparate boxes via `_finalize_line`. *Column mode only.*
55
+ 3. **Secondary sub-column pass** (`_reorder_lines_column_major`) — ensures correct column-major order when sub-columns sit within a single macro-column. *Column mode only.*
56
+ 4. When a group contains more than one box, constituent boxes are **merged** into a single `OCRResult` (union bbox, joined text, concatenated chars/words).
57
+
58
+ In single-column / legacy mode only step 1 is applied; PyMuPDF lines are pre-formed so no merging is needed.
59
+
60
+ ### Tunables (both routes)
61
+
62
+ `OCR_FULL_SPAN_WIDTH_RATIO`, `OCR_COLUMN_GAP_MIN_FRACTION`, `OCR_COLUMN_GUTTER_MIN_FRACTION`, `OCR_COLUMN_SUBGUTTER_MIN_FRACTION` (default `0.015` — fine-grained gutter scan in `assign_layout_boxes`; lower = detects narrower sub-column boundaries), `OCR_COLUMN_MIN_GUTTER_ROWS`, `OCR_COLUMN_MAX_BOX_HEIGHT_RATIO`, `OCR_COLUMN_MAX_CONSECUTIVE_GUTTER_GAP`, `OCR_COLUMN_FOOTER_ZONE_FRACTION`, `OCR_LINE_SPLIT_GAP_FRACTION` (default 0.025 — horizontal gap fraction that forces a line split; must be below the narrowest column gutter, ~0.030 for two-page spreads; also used as the gap threshold for the secondary sub-column sort in `build_line_groups`), `OCR_LINE_Y_THRESHOLD_FRACTION` (default 0.013 — row-alignment tolerance as a fraction of page height; reduced from 0.015 to correctly separate tightly-set 10 pt body text whose row spacing is ~0.014), `OCR_LINE_Y_THRESHOLD_MIN_PX`.
63
+
64
+ **Sub-column ordering** (`build_line_groups`): after the primary word-level column sort, a second pass (`_reorder_lines_column_major`) clusters the produced line groups by their leftmost x-position using `OCR_LINE_SPLIT_GAP_FRACTION` as the gap threshold. This ensures that adjacent narrow sub-columns whose word-level centre gap is below `column_gap_threshold` (e.g. two columns on a spread where each page is already one macro-column) are still output in left-to-right column-major order rather than interleaved by y-position.
65
+
66
+ **Fine-grained gutter-based column assignment** (`assign_layout_boxes`): before falling back to centre-gap clustering, `detect_column_split_xpoints` scans the page for structural gutters at the finer `OCR_COLUMN_SUBGUTTER_MIN_FRACTION` threshold (default 0.015). Each qualifying gutter cluster produces a `(split_x, y_min)` pair — the split point is only applied to boxes whose `top ≥ y_min`, preventing a narrow sub-column gutter (visible only in the lower two-column section) from mis-splitting a full-width introductory paragraph that sits above it. This correctly separates narrow adjacent columns (e.g. 1.9 % gutter on a two-page spread) without fragmenting full-width headings or paragraphs.
67
+
68
+ Changing line order affects PII page text, duplicate-page detection, and review CSV line indices on multi-column documents; re-review after upgrading.
69
+
70
+ ## Agentic / programmatic access (two surfaces)
71
+
72
+ ### 1. FastAPI Agent API (recommended for LLM agents: small JSON bodies)
73
+
74
+ When `RUN_FASTAPI` is true, routes are mounted under **`/agent`** ([agent_routes.py](agent_routes.py)).
75
+
76
+ - **Catalog**: `GET /agent/operations` — maps each Gradio `api_name` to an HTTP path and notes whether the route is implemented via CLI or returns HTTP 501 for Gradio-only flows.
77
+ - **Implemented POST routes** (CLI- or [tools/simplified_api.py](tools/simplified_api.py)-backed where noted):
78
+ `redact_document`, `redact_data`, `find_duplicate_pages`, `find_duplicate_tabular`, `summarise_document`, `combine_review_pdfs`, `combine_review_csvs`, `export_review_redaction_overlay`, `export_review_page_ocr_visualisation`, `apply_review_redactions`, **`verify_redaction_coverage`** (Pass 1 QA: `must_redact` / `must_not_redact` regex lists, optional `redacted_pdf_path`, optional `auto_prune_suspicious` + `pruned_output_path`; returns `pass_strict`, `pass_with_cleanup`, `pages_flagged_for_vlm`, `pages_needing_csv_cleanup`), **`word_level_ocr_text_search`** (headless word OCR search with optional review-box overlap flags).
79
+
80
+ **Optional post-redaction Pass 1 QA (main app / CLI):** When `POST_REDACT_PASS1_QA=True` in [`tools/config.py`](tools/config.py) (or `config/app_config.env`), initial redaction emits `*_coverage_report.json` beside the review CSV and optionally `*_review_file_pruned.csv` (sibling, when `POST_REDACT_PASS1_AUTO_PRUNE=True`). Uses deny/allow lists and/or `POST_REDACT_PASS1_MUST_REDACT_PATH` / `POST_REDACT_PASS1_MUST_NOT_REDACT_PATH`. CLI overrides: `--post-redact-pass1-qa`, `--post-redact-pass1-auto-prune`. This is pre-review-apply sanity QA only — agent Pass 1 (policy edits + `/review_apply`) remains separate.
81
+ Note: on Gradio ([app.py](app.py)), the Review-tab visual exports use `api_name` **`page_redaction_review_image`** and **`page_ocr_review_image`**; the **`/agent`** routes above keep the explicit `export_review_*` names for the same operations.
82
+ - **Gradio-only stubs** (501 + JSON hint): `load_and_prepare_documents_or_data`.
83
+ - **Auth**: If `AGENT_API_KEY` is set in the environment, send header `X-Agent-API-Key` with that value.
84
+ - **Paths**: Inputs must resolve to files under the repo root, `INPUT_FOLDER`, or `OUTPUT_FOLDER` (see router validation).
85
+
86
+ Implementation uses **`cli_redact.main(direct_mode_args=...)`** where a CLI task exists (same behaviour as [cli_redact.py](cli_redact.py)); `apply_review_redactions` calls [tools/simplified_api.py](tools/simplified_api.py) instead.
87
+
88
+ ### 2. Gradio Client API (e.g. Hugging Face Spaces)
89
+
90
+ For remote Spaces or any Gradio deployment exposing the HTTP API:
91
+
92
+ - **Schema**: `GET https://<host>/gradio_api/info`
93
+ - **Call**: `POST https://<host>/gradio_api/call/{api_name}` with body `{"data":[...]}` (argument order matches the named endpoint’s component list).
94
+ - **Poll**: `GET https://<host>/gradio_api/call/{api_name}/{event_id}`
95
+ - **Hugging Face**: `Authorization: Bearer $HF_TOKEN`
96
+
97
+ Named `api_name` values in this app include: `redact_document`, `load_and_prepare_documents_or_data`, `apply_review_redactions`, **`doc_redact`** (simple `gr.api`: one PDF/image + optional OCR/PII knobs; returns `(output_paths, message)`; `api_name='/doc_redact'`; parameters include `document_file`, `redact_entities`, `output_dir`, `ocr_method`, `pii_method`, `allow_list`, `deny_list`, `page_min`, `page_max`, **`handwrite_signature_checkbox`** — AWS Textract extraction options such as `Extract handwriting` / `Extract signatures`), **`review_apply`** (simple `gr.api`: PDF + `*_review_file.csv`; returns `(output_paths, message)`; `api_name='/review_apply'`), **`preview_boxes`** (simple `gr.api`: PDF + `*_review_file.csv`; renders proposed boxes onto the original PDF and returns `(zip_path, message)` — use to verify coordinates *before* calling `review_apply`, no redaction applied; `api_name='/preview_boxes'`), **`pdf_summarise`** (simple `gr.api`: PDF + optional summarisation/OCR knobs; returns `(output_paths, status_message, summary_text)`; `api_name='/pdf_summarise'`), **`tabular_redact`** (simple `gr.api`: one tabular file (CSV/XLSX/Parquet/DOCX) + optional knobs; returns `(output_paths, message)`; `api_name='/tabular_redact'`), **`page_redaction_review_image`** (short review overlay export; `api_name='/page_redaction_review_image'`), **`page_ocr_review_image`** (short OCR visualisation export; `api_name='/page_ocr_review_image'`), `word_level_ocr_text_search`, `redact_data`, `find_duplicate_pages`, `find_duplicate_tabular`, `summarise_document`, `combine_review_csvs`, `combine_review_pdfs`. The matching **`POST /agent`** names for those two visual exports are `export_review_redaction_overlay` and `export_review_page_ocr_visualisation` (§1). Many endpoints require **many positional arguments** (full Gradio state); prefer the short `gr.api` routes above or **`POST /agent/apply_review_redactions`** where applicable instead of building the full `data` array from `/gradio_api/info`.
98
+
99
+ ## CLI parity
100
+
101
+ For scripting and tests, `python cli_redact.py` with flags is authoritative; programmatic merges use `get_cli_default_args_dict()` in [cli_redact.py](cli_redact.py).
102
+
103
+ ## Security and data handling
104
+
105
+ - Do not commit API keys, tokens, or customer data.
106
+ - Treat paths as untrusted outside validated roots (see [tools/secure_path_utils.py](tools/secure_path_utils.py)).
107
+ - Optional `instruction` / LLM fields must not be passed into shell or unconstrained config keys.
108
+
109
+ ## Conventions for PRs
110
+
111
+ - Keep changes focused; avoid drive-by refactors.
112
+ - Match existing naming and patterns in [app.py](app.py) and [tools/](tools/).
113
+ - Update tests when behaviour changes; run `pytest` before merge.
Dockerfile ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stage 1: Build dependencies and download models
2
+ FROM public.ecr.aws/docker/library/python:3.12.13-slim-trixie AS builder
3
+
4
+ # Install system dependencies
5
+ RUN apt-get update \
6
+ && apt-get upgrade -y \
7
+ && apt-get install -y --no-install-recommends \
8
+ g++ \
9
+ make \
10
+ cmake \
11
+ unzip \
12
+ libcurl4-openssl-dev \
13
+ git \
14
+ && pip install --upgrade pip \
15
+ && apt-get clean \
16
+ && rm -rf /var/lib/apt/lists/*
17
+
18
+ WORKDIR /src
19
+
20
+ COPY requirements_lightweight.txt .
21
+
22
+ RUN pip install --verbose --no-cache-dir --target=/install -r requirements_lightweight.txt && rm requirements_lightweight.txt
23
+
24
+ ARG INSTALL_GRADIO_MCP=False
25
+ ENV INSTALL_GRADIO_MCP=${INSTALL_GRADIO_MCP}
26
+
27
+ RUN if [ "$INSTALL_GRADIO_MCP" = "True" ]; then \
28
+ pip install --verbose --no-cache-dir --force-reinstall --target=/install "gradio[mcp]<=6.10.0"; \
29
+ fi
30
+
31
+ # Optionally install PaddleOCR if the INSTALL_PADDLEOCR environment variable is set to True. Note that GPU-enabled PaddleOCR is unlikely to work in the same environment as a GPU-enabled version of PyTorch, so it is recommended to install PaddleOCR as a CPU-only version if you want to use GPU-enabled PyTorch.
32
+
33
+ ARG INSTALL_PADDLEOCR=False
34
+ ENV INSTALL_PADDLEOCR=${INSTALL_PADDLEOCR}
35
+
36
+ ARG PADDLE_GPU_ENABLED=False
37
+ ENV PADDLE_GPU_ENABLED=${PADDLE_GPU_ENABLED}
38
+
39
+ RUN if [ "$INSTALL_PADDLEOCR" = "True" ] && [ "$PADDLE_GPU_ENABLED" = "False" ]; then \
40
+ pip install --verbose --no-cache-dir --target=/install "protobuf<=7.34.0" && \
41
+ pip install --verbose --no-cache-dir --target=/install "paddlepaddle<=3.2.1" && \
42
+ pip install --verbose --no-cache-dir --target=/install "paddleocr<=3.3.0"; \
43
+ elif [ "$INSTALL_PADDLEOCR" = "True" ] && [ "$PADDLE_GPU_ENABLED" = "True" ]; then \
44
+ pip install --verbose --no-cache-dir --target=/install "protobuf<=7.34.0" && \
45
+ pip install --verbose --no-cache-dir --target=/install "paddlepaddle-gpu<=3.2.1" --index-url https://www.paddlepaddle.org.cn/packages/stable/cu129/ && \
46
+ pip install --verbose --no-cache-dir --target=/install "paddleocr<=3.3.0"; \
47
+ fi
48
+
49
+ ARG INSTALL_VLM=False
50
+ ENV INSTALL_VLM=${INSTALL_VLM}
51
+
52
+ ARG TORCH_GPU_ENABLED=False
53
+ ENV TORCH_GPU_ENABLED=${TORCH_GPU_ENABLED}
54
+
55
+ # Optionally install VLM/LLM packages if the INSTALL_VLM environment variable is set to True.
56
+ RUN if [ "$INSTALL_VLM" = "True" ] && [ "$TORCH_GPU_ENABLED" = "False" ]; then \
57
+ pip install --verbose --no-cache-dir --target=/install \
58
+ "torch==2.9.1+cpu" \
59
+ "torchvision==0.24.1+cpu" \
60
+ "transformers<=5.5.4" \
61
+ "accelerate<=1.13.0" \
62
+ "bitsandbytes<=0.49.2" \
63
+ "sentencepiece<=0.2.1" \
64
+ --extra-index-url https://download.pytorch.org/whl/cpu; \
65
+ elif [ "$INSTALL_VLM" = "True" ] && [ "$TORCH_GPU_ENABLED" = "True" ]; then \
66
+ pip install --verbose --no-cache-dir --target=/install "torch<=2.8.0" --index-url https://download.pytorch.org/whl/cu129 && \
67
+ pip install --verbose --no-cache-dir --target=/install "torchvision<=0.23.0" --index-url https://download.pytorch.org/whl/cu129 && \
68
+ pip install --verbose --no-cache-dir --target=/install \
69
+ "transformers<=5.5.4" \
70
+ "accelerate<=1.13.0" \
71
+ "bitsandbytes<=0.49.2" \
72
+ "sentencepiece<=0.2.1" && \
73
+ pip install --verbose --no-cache-dir --target=/install "optimum<=2.1.0" && \
74
+ pip install --verbose --no-cache-dir --target=/install https://github.com/Dao-AILab/flash-attention/releases/download/v2.8.3/flash_attn-2.8.3+cu12torch2.8cxx11abiTRUE-cp312-cp312-linux_x86_64.whl && \
75
+ pip install --verbose --no-cache-dir --target=/install https://github.com/ModelCloud/GPTQModel/releases/download/v5.8.0/gptqmodel-5.8.0+cu128torch2.8-cp312-cp312-linux_x86_64.whl; \
76
+ fi
77
+
78
+ # ===================================================================
79
+ # Stage 2: A common base for both Lambda and Gradio
80
+ # ===================================================================
81
+ FROM public.ecr.aws/docker/library/python:3.12.13-slim-trixie AS base
82
+
83
+ # MUST re-declare ARGs in every stage where they are used in RUN commands
84
+ ARG TORCH_GPU_ENABLED=False
85
+ ARG PADDLE_GPU_ENABLED=False
86
+
87
+ ENV TORCH_GPU_ENABLED=${TORCH_GPU_ENABLED}
88
+ ENV PADDLE_GPU_ENABLED=${PADDLE_GPU_ENABLED}
89
+
90
+ RUN apt-get update && apt-get install -y --no-install-recommends \
91
+ tesseract-ocr \
92
+ poppler-utils \
93
+ libgl1 \
94
+ libglib2.0-0 && \
95
+ if [ "$TORCH_GPU_ENABLED" = "True" ] || [ "$PADDLE_GPU_ENABLED" = "True" ]; then \
96
+ apt-get install -y --no-install-recommends libgomp1; \
97
+ fi && \
98
+ apt-get clean && rm -rf /var/lib/apt/lists/*
99
+
100
+ ENV APP_HOME=/home/user
101
+
102
+ # Set env variables for Gradio & other apps
103
+ ENV GRADIO_TEMP_DIR=/tmp/gradio_tmp/ \
104
+ MPLCONFIGDIR=/tmp/matplotlib_cache/ \
105
+ GRADIO_OUTPUT_FOLDER=$APP_HOME/app/output/ \
106
+ GRADIO_INPUT_FOLDER=$APP_HOME/app/input/ \
107
+ FEEDBACK_LOGS_FOLDER=$APP_HOME/app/feedback/ \
108
+ ACCESS_LOGS_FOLDER=$APP_HOME/app/logs/ \
109
+ USAGE_LOGS_FOLDER=$APP_HOME/app/usage/ \
110
+ CONFIG_FOLDER=$APP_HOME/app/config/ \
111
+ XDG_CACHE_HOME=/tmp/xdg_cache/user_1000 \
112
+ TESSERACT_DATA_FOLDER=/usr/share/tessdata \
113
+ GRADIO_SERVER_NAME=0.0.0.0 \
114
+ GRADIO_SERVER_PORT=7860 \
115
+ PATH=$APP_HOME/.local/bin:$PATH \
116
+ PYTHONPATH=$APP_HOME/app \
117
+ PYTHONUNBUFFERED=1 \
118
+ PYTHONDONTWRITEBYTECODE=1 \
119
+ GRADIO_ALLOW_FLAGGING=never \
120
+ GRADIO_NUM_PORTS=1 \
121
+ GRADIO_ANALYTICS_ENABLED=False
122
+
123
+ # Copy Python packages from the builder stage
124
+ COPY --from=builder /install /usr/local/lib/python3.12/site-packages/
125
+ COPY --from=builder /install/bin /usr/local/bin/
126
+
127
+ # Reinstall protobuf into the final site-packages. Builder uses multiple `pip install --target=/install`
128
+ # passes; that can break the `google` namespace so `google.protobuf` is missing and Paddle fails at import.
129
+ RUN pip install --no-cache-dir "protobuf<=7.34.0"
130
+
131
+ # English pipeline is not a normal PyPI dependency; bundle it in the image so runtime works offline.
132
+ # Placed before COPY app code so application changes do not invalidate this layer.
133
+ RUN python -m spacy download en_core_web_lg
134
+
135
+ # Copy your application code and entrypoint
136
+ COPY . ${APP_HOME}/app
137
+ COPY entrypoint.sh ${APP_HOME}/app/entrypoint.sh
138
+ # Fix line endings and set execute permissions
139
+ RUN sed -i 's/\r$//' ${APP_HOME}/app/entrypoint.sh \
140
+ && chmod +x ${APP_HOME}/app/entrypoint.sh
141
+
142
+ WORKDIR ${APP_HOME}/app
143
+
144
+ # ===================================================================
145
+ # FINAL Stage 3: The Lambda Image (runs as root for simplicity)
146
+ # ===================================================================
147
+ FROM base AS lambda
148
+ # Set runtime ENV for Lambda mode
149
+ ENV APP_MODE=lambda
150
+ ENTRYPOINT ["/home/user/app/entrypoint.sh"]
151
+ CMD ["lambda_entrypoint.lambda_handler"]
152
+
153
+ # ===================================================================
154
+ # FINAL Stage 4: The Gradio Image (runs as a secure, non-root user)
155
+ # ===================================================================
156
+ FROM base AS gradio
157
+ # Set runtime ENV for Gradio mode
158
+ ENV APP_MODE=gradio
159
+
160
+ # Create non-root user
161
+ RUN useradd -m -u 1000 user
162
+
163
+ # Create the base application directory and set its ownership
164
+ RUN mkdir -p ${APP_HOME}/app && chown user:user ${APP_HOME}/app
165
+
166
+ # Create required sub-folders within the app directory and set their permissions
167
+ # This ensures these specific directories are owned by 'user'
168
+ RUN mkdir -p \
169
+ ${APP_HOME}/app/output \
170
+ ${APP_HOME}/app/input \
171
+ ${APP_HOME}/app/logs \
172
+ ${APP_HOME}/app/usage \
173
+ ${APP_HOME}/app/feedback \
174
+ ${APP_HOME}/app/config \
175
+ && chown user:user \
176
+ ${APP_HOME}/app/output \
177
+ ${APP_HOME}/app/input \
178
+ ${APP_HOME}/app/logs \
179
+ ${APP_HOME}/app/usage \
180
+ ${APP_HOME}/app/feedback \
181
+ ${APP_HOME}/app/config \
182
+ && chmod 755 \
183
+ ${APP_HOME}/app/output \
184
+ ${APP_HOME}/app/input \
185
+ ${APP_HOME}/app/logs \
186
+ ${APP_HOME}/app/usage \
187
+ ${APP_HOME}/app/feedback \
188
+ ${APP_HOME}/app/config
189
+
190
+ # Now handle the /tmp and /var/tmp directories and their subdirectories, paddle, spacy, tessdata
191
+ RUN mkdir -p /tmp/gradio_tmp /tmp/tld /tmp/matplotlib_cache /tmp /var/tmp ${XDG_CACHE_HOME} \
192
+ && chown user:user /tmp /var/tmp /tmp/gradio_tmp /tmp/tld /tmp/matplotlib_cache ${XDG_CACHE_HOME} \
193
+ && chmod 1777 /tmp /var/tmp /tmp/gradio_tmp /tmp/tld /tmp/matplotlib_cache \
194
+ && chmod 700 ${XDG_CACHE_HOME} \
195
+ && mkdir -p ${APP_HOME}/.paddlex \
196
+ && chown user:user ${APP_HOME}/.paddlex \
197
+ && chmod 755 ${APP_HOME}/.paddlex \
198
+ && mkdir -p ${APP_HOME}/.local/share/spacy/data \
199
+ && chown user:user ${APP_HOME}/.local/share/spacy/data \
200
+ && chmod 755 ${APP_HOME}/.local/share/spacy/data \
201
+ && mkdir -p /usr/share/tessdata \
202
+ && chown user:user /usr/share/tessdata \
203
+ && chmod 755 /usr/share/tessdata
204
+
205
+ # Fix apply user ownership to all files in the home directory
206
+ RUN chown -R user:user /home/user
207
+
208
+ # Set permissions for Python executable
209
+ RUN chmod 755 /usr/local/bin/python
210
+
211
+ # Declare volumes (NOTE: runtime mounts will override permissions — handle with care)
212
+ VOLUME ["/tmp/matplotlib_cache"]
213
+ VOLUME ["/tmp/gradio_tmp"]
214
+ VOLUME ["/tmp/tld"]
215
+ VOLUME ["/home/user/app/output"]
216
+ VOLUME ["/home/user/app/input"]
217
+ VOLUME ["/home/user/app/logs"]
218
+ VOLUME ["/home/user/app/usage"]
219
+ VOLUME ["/home/user/app/feedback"]
220
+ VOLUME ["/home/user/app/config"]
221
+ VOLUME ["/home/user/.paddlex"]
222
+ VOLUME ["/home/user/.local/share/spacy/data"]
223
+ VOLUME ["/usr/share/tessdata"]
224
+ VOLUME ["/tmp"]
225
+ VOLUME ["/var/tmp"]
226
+
227
+ USER user
228
+
229
+ EXPOSE $GRADIO_SERVER_PORT
230
+
231
+ ENTRYPOINT ["/home/user/app/entrypoint.sh"]
232
+ CMD ["python", "app.py"]
Dockerfile.pi ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+
3
+ FROM node:22-bookworm-slim
4
+
5
+ ENV NODE_ENV=production
6
+ ENV DEBIAN_FRONTEND=noninteractive
7
+ ENV NPM_CONFIG_LOGLEVEL=warn
8
+ ENV PYTHONUNBUFFERED=1
9
+ ENV PYTHONDONTWRITEBYTECODE=1
10
+ ENV PYTHONPATH=/workspace/doc_redaction
11
+
12
+ RUN apt-get update && apt-get install -y --no-install-recommends \
13
+ bash \
14
+ git \
15
+ curl \
16
+ ca-certificates \
17
+ procps \
18
+ python3 \
19
+ python3-pip \
20
+ python3-venv \
21
+ && rm -rf /var/lib/apt/lists/*
22
+
23
+ RUN npm install -g --ignore-scripts @earendil-works/pi-coding-agent
24
+
25
+ COPY requirements_pi_agent.txt /tmp/requirements_pi_agent.txt
26
+ RUN pip3 install --no-cache-dir --break-system-packages \
27
+ -r /tmp/requirements_pi_agent.txt \
28
+ && rm /tmp/requirements_pi_agent.txt
29
+
30
+ RUN mkdir -p /home/node/.pi/agent/sessions /workspace/doc_redaction \
31
+ && chown -R node:node /home/node/.pi /workspace
32
+
33
+ WORKDIR /workspace/doc_redaction
34
+
35
+ USER node
36
+
37
+ RUN pi --version
38
+
39
+ ENTRYPOINT ["pi"]
40
+ CMD []
MANIFEST.in ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ recursive-include doc_redaction/assets *.png
2
+ recursive-include doc_redaction/example_data *
3
+ recursive-include intros *.txt
4
+
README.md ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Document redaction
3
+ emoji: 📝
4
+ colorFrom: blue
5
+ colorTo: yellow
6
+ sdk: docker
7
+ app_file: app.py
8
+ pinned: true
9
+ license: agpl-3.0
10
+ short_description: OCR / redact PDF documents and tabular data
11
+ ---
12
+ # Document redaction (doc_redaction)
13
+
14
+ <a href="https://pypi.org/project/doc-redaction/" target="_blank"><img alt="PyPI - Version" src="https://img.shields.io/pypi/v/doc-redaction"></a>
15
+
16
+ Redact personally identifiable information (PII) from documents (PDF, PNG, JPG), Word files (DOCX), or tabular data (XLSX/CSV/Parquet). Please see the [User Guide](https://seanpedrick-case.github.io/doc_redaction/src/user_guide.html) for a full walkthrough of all the features in the app.
17
+
18
+ ---
19
+
20
+ ## 🚀 Quick Start - Installation and first run
21
+
22
+ Follow these instructions to get the document redaction application running on your local machine.
23
+
24
+ ### 1. Package installation
25
+
26
+ #### Option 1 - Recommended: Install from source repo
27
+
28
+ Clone the repository and install in editable mode:
29
+
30
+ ```bash
31
+ git clone https://github.com/seanpedrick-case/doc_redaction.git
32
+ cd doc_redaction
33
+ pip install -e .
34
+ ```
35
+
36
+ ##### Install extras (Paddle or Transformers/Torch VLM)
37
+
38
+ To install with PaddleOCR:
39
+
40
+ ```bash
41
+ pip install -e ".[paddle]"
42
+ ```
43
+
44
+ Note that the versions of both PaddleOCR and Torch installed by default are the CPU-only versions. If you want to install the equivalent GPU versions, you will need to run the following commands:
45
+ ```bash
46
+ pip install paddlepaddle-gpu==3.2.1 --index-url https://www.paddlepaddle.org.cn/packages/stable/cu129/
47
+ ```
48
+
49
+ If you want to run VLMs / LLMs with the transformers package:
50
+
51
+ ```bash
52
+ pip install -e ".[vlm]"
53
+ ```
54
+
55
+
56
+ **Note:** It is difficult to get paddlepaddle gpu working in an environment alongside torch. You may well need to reinstall the cpu version to ensure compatibility, and run paddlepaddle-gpu in a separate environment without torch installed. If you get errors related to .dll files following paddle gpu install, you may need to install the latest c++ redistributables. For Windows, you can find them [here](https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170)
57
+
58
+ ```bash
59
+ pip install torch==2.8.0 --index-url https://download.pytorch.org/whl/cu129
60
+ pip install torchvision --index-url https://download.pytorch.org/whl/cu129
61
+ ```
62
+
63
+ #### Option 2 - Install from PyPI
64
+
65
+ Create a virtual environment (recommended) and install **doc_redaction**.
66
+
67
+ ```bash
68
+ python -m venv venv
69
+ # Windows:
70
+ .\venv\Scripts\activate
71
+ # macOS/Linux:
72
+ source venv/bin/activate
73
+ ```
74
+
75
+ The package is published on PyPI as **`doc-redaction`** (import name **`doc_redaction`**):
76
+
77
+ ```bash
78
+ pip install doc_redaction
79
+ ```
80
+
81
+ Optional extras (same as in `pyproject.toml`). For installing paddleOCR:
82
+
83
+ ```bash
84
+ pip install "doc_redaction[paddle]"
85
+ ```
86
+
87
+ For running VLMs / LLMs with the transformers package:
88
+
89
+ ```bash
90
+ pip install "doc_redaction[vlm]"
91
+ ```
92
+
93
+ For programmatic use (CLI-first API matching Gradio `api_name` routes), see **[Python Package usage (Python)](https://seanpedrick-case.github.io/doc_redaction/src/python_package_usage.html)**. The console script **`cli_redact`** is available after install.
94
+
95
+ **Web UI from a PyPI install:** You *can* start the Gradio UI after `pip install doc_redaction` by running (note that the prerequisites tesseract and poppler will need to be correctly installed following step 2 below):
96
+
97
+ ```bash
98
+ python -m app
99
+ ```
100
+
101
+ **Important: your working directory matters.** When you run `python -m app`, the app treats your *current folder* as the “app folder”:
102
+
103
+ - It will look for configuration at `config/app_config.env` *relative to the folder you run it from* (and `python -m doc_redaction.install_deps` will also write `config/app_config.env` there).
104
+ - It may create new folders in that location (for example `config/`, `output/`, `input/`, `logs/`, `usage/`, `feedback/`, and temporary/cache folders depending on your settings).
105
+ - The UI example files and bundled assets are packaged with the PyPI install (they live inside the installed `doc_redaction` package). If you run from a “random” directory after a PyPI install, the app can still locate its packaged examples; your working directory mainly affects where `config/`, `input/`, `output/`, logs, and temp folders are created.
106
+
107
+ In practice, the **smoothest UI experience** (examples, bundled assets, docs links, predictable relative paths) is still usually via a **repository checkout** or **Docker**, but PyPI install is sufficient to launch the UI as long as you run it from a suitable working folder and have the system dependencies available (or run `python -m doc_redaction.install_deps` first).
108
+
109
+ #### Option 3 - Docker installation
110
+
111
+ The doc_redaction Redaction app can be installed by using the [Dockerfile](https://github.com/seanpedrick-case/doc_redaction/blob/main/Dockerfile) or Docker compose files ([llama.cpp](https://github.com/ggml-org/llama.cpp), [vLLM](https://docs.vllm.ai/en/stable/)) provided in the repo.
112
+
113
+ ##### With Llama.cpp / vLLM inference server
114
+
115
+ The project now has Docker and Docker compose files available to pair running the Redaction app with local inference servers powered by [llama.cpp](https://github.com/ggml-org/llama.cpp), or [vLLM](https://docs.vllm.ai/en/stable/). Llama.cpp is more flexible than vLLM for low VRAM systems, as Llama.cpp will offload to cpu/system RAM automatically rather than failing as vLLM tends to do.
116
+
117
+ For Llama.cpp, you can use the [docker-compose_llama.yml](https://github.com/seanpedrick-case/doc_redaction/blob/main/docker-compose_llama.yml) file, and for vLLM, you can use the [docker-compose_vllm.yml](https://github.com/seanpedrick-case/doc_redaction/blob/main/docker-compose_vllm.yml) file. To run, Docker / Docker Desktop should be installed, and then you can run the commands suggested in the top of the files to run the servers.
118
+
119
+ You will need ~40 GB of disk space to run everything depending on the model chosen from the compose file. For the vLLM server, you will need 24 GB VRAM. For the Llama.cpp server, 24 GB VRAM is needed to run at full speed, but the n-gpu-layers and n-cpu-moe parameters in the Docker compose file can be adjusted to fit into your system. I would suggest that 8 GB VRAM is needed as a bare minimum for decent inference speed. See the [Unsloth guide](https://unsloth.ai/docs/models/qwen3.5) for more details on working with GGUF files for Qwen 3.5.
120
+
121
+ ##### Without Llama.cpp / vLLM inference server
122
+
123
+ If you want a working Docker installation without GPU support, you can install from the [Dockerfile](https://github.com/seanpedrick-case/doc_redaction/blob/main/Dockerfile) in the repo. A working example of this, with the CPU version of PaddleOCR, can be found on [Hugging Face](https://huggingface.co/spaces/seanpedrickcase/document_redaction). You can adjust the INSTALL_PADDLEOCR, PADDLE_GPU_ENABLED, INSTALL_VLM, and TORCH_GPU_ENABLED config variables to adjust for PaddleOCR and Transformers packages for local VLM support. Note that GPU-enabled PaddleOCR, and GPU-enabled Transformers/Torch often don't work well together, which is one reason why a Llama.cpp/vLLM inference server Docker installation option is provided below.
124
+
125
+ ### 2. Install prerequisites: Tesseract and Poppler
126
+
127
+ This application relies on two external tools for OCR (Tesseract) and PDF processing (Poppler). Please install them on your system before proceeding. To run the Document Redaction app successfully, these tools need to be installed and either 1. added to PATH, or 2. be in a folder that is directly referenced in the config/app_config.env file with the variables TESSERACT_FOLDER and POPPLER_FOLDER (defined [here](https://github.com/seanpedrick-case/doc_redaction/blob/main/tools/config.py) if you want to see the code). The instructions below will guide you through diffferent ways to install these dependencies.
128
+
129
+ ---
130
+
131
+ #### Automated dependency setup (recommended)
132
+
133
+ If you **don’t have admin rights** (or you just want the simplest setup), you can have the project download and configure **Tesseract** and **Poppler** into a local `redaction_deps/` folder inside the doc_redaction folder.
134
+
135
+ You need the installer script available first, which means either:
136
+
137
+ - **Repository checkout**: `git clone ...` and run the command from the repo root (recommended for the web UI), or
138
+ - **PyPI install**: `pip install doc_redaction` and run from a writable folder where you want `redaction_deps/` and `config/app_config.env` to be created/updated.
139
+
140
+ From the repository root (or your chosen working folder) after creating/activating your venv and installing Python requirements:
141
+
142
+ ```bash
143
+ python -m doc_redaction.install_deps
144
+ ```
145
+
146
+ This writes `TESSERACT_FOLDER` / `POPPLER_FOLDER` into `config/app_config.env` so the app can find the binaries without you editing your system PATH.
147
+
148
+ To just check whether your machine can already see the tools:
149
+
150
+ ```bash
151
+ python -m doc_redaction.install_deps --verify-only
152
+ ```
153
+
154
+ #### **On Windows**
155
+
156
+ If you don’t use the automated setup above, you can install the dependencies manually by downloading installers and adding the programs to your system's PATH.
157
+
158
+ 1. **Install Tesseract OCR:**
159
+ * Download the installer from the official Tesseract at [UB Mannheim page](https://github.com/UB-Mannheim/tesseract/wiki) (e.g., `tesseract-ocr-w64-setup-v5.X.X...exe`).
160
+ * Run the installer.
161
+ * **IMPORTANT:** During installation, ensure you select the option to "Add Tesseract to system PATH for all users" or a similar option. This is crucial for the application to find the Tesseract executable.
162
+
163
+
164
+ 2. **Install Poppler:**
165
+ * Download the latest Poppler binary for Windows. A common source is the [Poppler for Windows](https://github.com/oschwartz10612/poppler-windows) GitHub releases page. Download the `.zip` file (e.g., `poppler-25.07.0-win.zip`).
166
+ * Extract the contents of the zip file to a permanent location on your computer, for example, `C:\Program Files\poppler\`.
167
+ * You must add the `bin` folder from your Poppler installation to your system's PATH environment variable.
168
+ * Search for "Edit the system environment variables" in the Windows Start Menu and open it.
169
+ * Click the "Environment Variables..." button.
170
+ * In the "System variables" section, find and select the `Path` variable, then click "Edit...".
171
+ * Click "New" and add the full path to the `bin` directory inside your Poppler folder (e.g., `C:\Program Files\poppler\poppler-24.02.0\bin`).
172
+ * Click OK on all windows to save the changes.
173
+
174
+ To verify, open a new Command Prompt and run `tesseract --version` and `pdftoppm -v`. If they both return version information, you have successfully installed the prerequisites.
175
+ ---
176
+
177
+ #### **On Linux (Debian/Ubuntu)**
178
+
179
+ Open your terminal and run the following command to install Tesseract and Poppler:
180
+
181
+ ```bash
182
+ sudo apt-get update && sudo apt-get install -y tesseract-ocr poppler-utils
183
+ ```
184
+
185
+ #### **On Linux (Fedora/CentOS/RHEL)**
186
+
187
+ Open your terminal and use the `dnf` or `yum` package manager:
188
+
189
+ ```bash
190
+ sudo dnf install -y tesseract poppler-utils
191
+ ```
192
+ ---
193
+
194
+ ### 3. Run the Application
195
+
196
+ With all dependencies installed, you can now start the Gradio application GUI. For a guide on how to use this, please go [here](https://seanpedrick-case.github.io/doc_redaction/src/user_guide.html).
197
+
198
+ ```bash
199
+ python app.py
200
+ ```
201
+
202
+ After running the command, the application will start, and you will see a local URL in your terminal (usually `http://127.0.0.1:7860`).
203
+
204
+ Open this URL in your web browser to use the document redaction tool
205
+
206
+ #### Command line interface
207
+
208
+ For example CLI commands, please refer to [this guide](https://seanpedrick-case.github.io/doc_redaction/src/user_guide.html#command-line-interface-cli) or the examples in [cli_redact.py](https://github.com/seanpedrick-case/doc_redaction/blob/main/cli_redact.py#L321)
209
+
210
+ If you installed from **PyPI**, use the installed console script:
211
+
212
+ ```bash
213
+ cli_redact --help
214
+ ```
215
+
216
+ From a **repository checkout**, you can also run:
217
+
218
+ ```bash
219
+ python cli_redact.py --help
220
+ ```
221
+
222
+ #### Python package commands
223
+
224
+ For Python examples in using the Python package, please see [Python Package usage (Python)](https://seanpedrick-case.github.io/doc_redaction/src/python_package_usage.html).
225
+
226
+ ---
227
+
228
+
229
+ ### 4. ⚙️ Configuration (Optional)
230
+
231
+ You can customise the application's behavior by creating a configuration file. This allows you to change settings without modifying the source code, such as enabling AWS features, changing logging behavior, or pointing to local Tesseract/Poppler installations. A full overview of all the potential settings you can modify in the app_config.env file can be seen in tools/config.py, with explanation on the documentation website for [the github repo](https://seanpedrick-case.github.io/doc_redaction/)
232
+
233
+ To get started:
234
+ 1. Locate the `example_config.env` file in the root of the project.
235
+ 2. Create a new file named `app_config.env` inside the `config/` directory (i.e., `config/app_config.env`).
236
+ 3. Copy the contents from `example_config.env` into your new `config/app_config.env` file.
237
+ 4. Modify the values in `config/app_config.env` to suit your needs. The application will automatically load these settings on startup.
238
+
239
+ If you do not create this file, the application will run with default settings.
240
+
241
+ #### Configuration Breakdown
242
+
243
+ Here is an overview of the most important settings, separated by whether they are for local use or require AWS.
244
+
245
+ ---
246
+
247
+ #### **Local & General Settings (No AWS Required)**
248
+
249
+ These settings are useful for all users, regardless of whether you are using AWS.
250
+
251
+ * `TESSERACT_FOLDER` / `POPPLER_FOLDER`
252
+ * Use these if you installed Tesseract or Poppler to a custom location on **Windows** and did not add them to the system PATH.
253
+ * Provide the path to the respective installation folders (for Poppler, point to the `bin` sub-directory).
254
+ * **Examples:** `POPPLER_FOLDER=C:/Program Files/poppler-24.02.0/bin/` `TESSERACT_FOLDER=tesseract/`
255
+
256
+ * `TESSERACT_DATA_FOLDER`
257
+ * If Tesseract runs but you see an error like `Error opening data file ./eng.traineddata` or `Tesseract couldn't load any languages`, this is usually because it can't find the `tessdata/` language files.
258
+ * Set this to the folder that contains `eng.traineddata` (typically a `tessdata` directory).
259
+ * **Examples (Windows):** `TESSERACT_DATA_FOLDER=C:/Program Files/Tesseract-OCR/tessdata`
260
+
261
+ * `SHOW_LANGUAGE_SELECTION=True`
262
+ * Set to `True` to display a language selection dropdown in the UI for OCR processing.
263
+
264
+ * `DEFAULT_LOCAL_OCR_MODEL=tesseract`"
265
+ * Choose the backend for local OCR. Options are `tesseract`, `paddle`, or `hybrid`. "Tesseract" is the default, and is recommended. "hybrid-paddle" is a combination of the two - first pass through the redactions will be done with Tesseract, and then a second pass will be done with PaddleOCR on words with low confidence. "paddle" will only return whole line text extraction, and so will only work for OCR, not redaction.
266
+
267
+ * `SESSION_OUTPUT_FOLDER=False`
268
+ * If `True`, redacted files will be saved in unique subfolders within the `output/` directory for each session.
269
+
270
+ * `DISPLAY_FILE_NAMES_IN_LOGS=False`
271
+ * For privacy, file names are not recorded in usage logs by default. Set to `True` to include them.
272
+
273
+ ---
274
+
275
+ #### **AWS-Specific Settings**
276
+
277
+ These settings are only relevant if you intend to use AWS services like Textract for OCR and Comprehend for PII detection.
278
+
279
+ * `RUN_AWS_FUNCTIONS=True`
280
+ * **This is the master switch.** You must set this to `True` to enable any AWS functionality. If it is `False`, all other AWS settings will be ignored.
281
+
282
+ * **UI Options:**
283
+ * `SHOW_AWS_TEXT_EXTRACTION_OPTIONS=True`: Adds "AWS Textract" as an option in the text extraction dropdown.
284
+ * `SHOW_AWS_PII_DETECTION_OPTIONS=True`: Adds "AWS Comprehend" as an option in the PII detection dropdown.
285
+
286
+ * **Core AWS Configuration:**
287
+ * `AWS_REGION=example-region`: Set your AWS region (e.g., `us-east-1`).
288
+ * `DOCUMENT_REDACTION_BUCKET=example-bucket`: The name of the S3 bucket the application will use for temporary file storage and processing.
289
+
290
+ * **AWS Logging:**
291
+ * `SAVE_LOGS_TO_DYNAMODB=True`: If enabled, usage and feedback logs will be saved to DynamoDB tables.
292
+ * `ACCESS_LOG_DYNAMODB_TABLE_NAME`, `USAGE_LOG_DYNAMODB_TABLE_NAME`, etc.: Specify the names of your DynamoDB tables for logging.
293
+
294
+ * **Advanced AWS Textract Features:**
295
+ * `SHOW_WHOLE_DOCUMENT_TEXTRACT_CALL_OPTIONS=True`: Enables UI components for large-scale, asynchronous document processing via Textract.
296
+ * `TEXTRACT_WHOLE_DOCUMENT_ANALYSIS_BUCKET=example-bucket-output`: A separate S3 bucket for the final output of asynchronous Textract jobs.
297
+ * `LOAD_PREVIOUS_TEXTRACT_JOBS_S3=True`: If enabled, the app will try to load the status of previously submitted asynchronous jobs from S3.
298
+
299
+ * **Cost Tracking (for internal accounting):**
300
+ * `SHOW_COSTS=True`: Displays an estimated cost for AWS operations. Can be enabled even if AWS functions are off.
301
+ * `GET_COST_CODES=True`: Enables a dropdown for users to select a cost code before running a job.
302
+ * `COST_CODES_PATH=config/cost_codes.csv`: The local path to a CSV file containing your cost codes.
303
+ * `ENFORCE_COST_CODES=True`: Makes selecting a cost code mandatory before starting a redaction.
304
+
305
+ Now you have the app installed, please refer to the [User Guide](https://seanpedrick-case.github.io/doc_redaction/src/user_guide.html) for more information on how to use it for basic and advanced redaction.
306
+
307
+ ## For agents (API quickstart)
308
+
309
+ If you are an LLM/agent interacting with this app over HTTP (e.g. Hugging Face Spaces), **do not guess inputs** from the UI. Use the Gradio schema as the source of truth:
310
+
311
+ - **Discover schema**: `GET /gradio_api/info`
312
+ - **Upload files**: `POST /gradio_api/upload` (multipart field `files`) → returns server-internal paths like `/tmp/gradio_tmp/...`
313
+ - **Call**: `POST /gradio_api/call/{api_name}` with body `{"data":[...]}` (argument order must match `/gradio_api/info`)
314
+ - **Poll**: `GET /gradio_api/call/{api_name}/{event_id}` until complete
315
+ - **Download outputs**: `GET /gradio_api/file={path}` (note: some deployments return 403 without session cookies)
316
+
317
+ ### Choose the correct route (prefer short `gr.api` endpoints)
318
+
319
+ Fetch `/gradio_api/info` and then prefer the simplest route that exists:
320
+
321
+ - **Apply edited review CSV to a PDF**: `/review_apply`
322
+ - **Redact a PDF/image document**: `/doc_redact` — optional `handwrite_signature_checkbox` for AWS Textract (e.g. `Extract handwriting`, `Extract signatures`)
323
+ - **Summarise a PDF**: `/pdf_summarise`
324
+ - **Redact tabular files (CSV/XLSX/Parquet/DOCX)**: `/tabular_redact`
325
+
326
+ If those endpoints are not present in your deployment, fall back to the long UI-chained routes (`/apply_review_redactions`, `/redact_data`, etc.) and build `data[]` strictly from `/gradio_api/info`.
327
+
328
+ ### Common gotchas
329
+
330
+ - **Arity errors** (`needed: N, got: M`) mean you called a session-heavy UI handler with the wrong `data[]`. Prefer the short endpoints above.
331
+ - **`handle_file()` gotcha** (for `gradio_client` users): do **not** wrap server-internal upload paths (e.g. `/tmp/gradio_tmp/...`) with `handle_file()`. Pass them as plain strings.
332
+ - **Container-only outputs**: outputs may be written to container paths (e.g. `/home/user/app/output/`). Plan to download via `file=...` or use a mounted output directory in Docker.
333
+
334
+ ### Optional: MCP server
335
+
336
+ If you want external agents to call this app reliably without re-implementing Gradio upload/call/poll/download details, consider an **MCP server** that wraps the main tasks (`redact_document`, `apply_review_redactions`, `redact_tabular`, `summarise_document`) behind a small tool interface. See the [relevant documentation](https://github.com/seanpedrick-case/doc_redaction/blob/main/mcp_doc_redaction/README.md).
337
+
338
+ **Use as a library:** After installing from [PyPI](https://pypi.org/project/doc-redaction/) (`pip install doc_redaction`), you can call the same workflows as the Gradio `api_name` routes from Python. See the documentation: [Python Package usage (Python)](https://seanpedrick-case.github.io/doc_redaction/src/python_package_usage.html).
339
+
340
+ To extract text from documents, the 'Local' options are PikePDF for PDFs with selectable text, and OCR with Tesseract. Use AWS Textract to extract more complex elements e.g. handwriting, signatures, or unclear text. PaddleOCR and VLM support is also provided (see the installation instructions below).
341
+
342
+ For PII identification, 'Local' (based on spaCy) gives good results if you are looking for common names or terms, or a custom list of terms to redact (see Redaction settings). AWS Comprehend gives better results at a small cost.
343
+
344
+ Additional options on the 'Redaction settings' include, the type of information to redact (e.g. people, places), custom terms to include/ exclude from redaction, fuzzy matching, language settings, and whole page redaction. After redaction is complete, you can view and modify suggested redactions on the 'Review redactions' tab to quickly create a final redacted document.
345
+
346
+ NOTE: The app is not 100% accurate, and it will miss some personal information. It is essential that all outputs are reviewed **by a human** before using the final outputs.
README_PYPI.md ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Document redaction (doc_redaction)
2
+
3
+ <a href="https://pypi.org/project/doc-redaction/" target="_blank"><img alt="PyPI - Version" src="https://img.shields.io/pypi/v/doc-redaction"></a>
4
+
5
+ Redact personally identifiable information (PII) from documents (PDF, PNG, JPG), Word files (DOCX), or tabular data (XLSX/CSV/Parquet). Please see the [User Guide](https://seanpedrick-case.github.io/doc_redaction/src/user_guide.html) for a full walkthrough of all the features in the app.
6
+
7
+ ---
8
+
9
+ ## 🚀 Quick Start - Installation and first run
10
+
11
+ Follow these instructions to get the document redaction application running on your local machine.
12
+
13
+ ### 1. Package installation
14
+
15
+ #### Option 1 - Recommended: Install from source repo
16
+
17
+ Clone the repository and install in editable mode:
18
+
19
+ ```bash
20
+ git clone https://github.com/seanpedrick-case/doc_redaction.git
21
+ cd doc_redaction
22
+ pip install -e .
23
+ ```
24
+
25
+ ##### Install extras (Paddle or Transformers/Torch VLM)
26
+
27
+ To install with PaddleOCR:
28
+
29
+ ```bash
30
+ pip install -e ".[paddle]"
31
+ ```
32
+
33
+ Note that the versions of both PaddleOCR and Torch installed by default are the CPU-only versions. If you want to install the equivalent GPU versions, you will need to run the following commands:
34
+ ```bash
35
+ pip install paddlepaddle-gpu==3.2.1 --index-url https://www.paddlepaddle.org.cn/packages/stable/cu129/
36
+ ```
37
+
38
+ If you want to run VLMs / LLMs with the transformers package:
39
+
40
+ ```bash
41
+ pip install -e ".[vlm]"
42
+ ```
43
+
44
+
45
+ **Note:** It is difficult to get paddlepaddle gpu working in an environment alongside torch. You may well need to reinstall the cpu version to ensure compatibility, and run paddlepaddle-gpu in a separate environment without torch installed. If you get errors related to .dll files following paddle gpu install, you may need to install the latest c++ redistributables. For Windows, you can find them [here](https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170)
46
+
47
+ ```bash
48
+ pip install torch==2.8.0 --index-url https://download.pytorch.org/whl/cu129
49
+ pip install torchvision --index-url https://download.pytorch.org/whl/cu129
50
+ ```
51
+
52
+ #### Option 2 - Install from PyPI
53
+
54
+ Create a virtual environment (recommended) and install **doc_redaction**.
55
+
56
+ ```bash
57
+ python -m venv venv
58
+ # Windows:
59
+ .\venv\Scripts\activate
60
+ # macOS/Linux:
61
+ source venv/bin/activate
62
+ ```
63
+
64
+ The package is published on PyPI as **`doc-redaction`** (import name **`doc_redaction`**):
65
+
66
+ ```bash
67
+ pip install doc_redaction
68
+ ```
69
+
70
+ Optional extras (same as in `pyproject.toml`). For installing paddleOCR:
71
+
72
+ ```bash
73
+ pip install "doc_redaction[paddle]"
74
+ ```
75
+
76
+ For running VLMs / LLMs with the transformers package:
77
+
78
+ ```bash
79
+ pip install "doc_redaction[vlm]"
80
+ ```
81
+
82
+ For programmatic use (CLI-first API matching Gradio `api_name` routes), see **[Python Package usage (Python)](https://seanpedrick-case.github.io/doc_redaction/src/python_package_usage.html)**. The console script **`cli_redact`** is available after install.
83
+
84
+ **Web UI from a PyPI install:** You *can* start the Gradio UI after `pip install doc_redaction` by running (note that the prerequisites tesseract and poppler will need to be correctly installed following step 2 below):
85
+
86
+ ```bash
87
+ python -m app
88
+ ```
89
+
90
+ **Important: your working directory matters.** When you run `python -m app`, the app treats your *current folder* as the “app folder”:
91
+
92
+ - It will look for configuration at `config/app_config.env` *relative to the folder you run it from* (and `python -m doc_redaction.install_deps` will also write `config/app_config.env` there).
93
+ - It may create new folders in that location (for example `config/`, `output/`, `input/`, `logs/`, `usage/`, `feedback/`, and temporary/cache folders depending on your settings).
94
+ - The UI example files and bundled assets are packaged with the PyPI install (they live inside the installed `doc_redaction` package). If you run from a “random” directory after a PyPI install, the app can still locate its packaged examples; your working directory mainly affects where `config/`, `input/`, `output/`, logs, and temp folders are created.
95
+
96
+ In practice, the **smoothest UI experience** (examples, bundled assets, docs links, predictable relative paths) is still usually via a **repository checkout** or **Docker**, but PyPI install is sufficient to launch the UI as long as you run it from a suitable working folder and have the system dependencies available (or run `python -m doc_redaction.install_deps` first).
97
+
98
+ #### Option 3 - Docker installation
99
+
100
+ The doc_redaction Redaction app can be installed by using the [Dockerfile](https://github.com/seanpedrick-case/doc_redaction/blob/main/Dockerfile) or Docker compose files ([llama.cpp](https://github.com/ggml-org/llama.cpp), [vLLM](https://docs.vllm.ai/en/stable/)) provided in the repo.
101
+
102
+ ##### With Llama.cpp / vLLM inference server
103
+
104
+ The project now has Docker and Docker compose files available to pair running the Redaction app with local inference servers powered by [llama.cpp](https://github.com/ggml-org/llama.cpp), or [vLLM](https://docs.vllm.ai/en/stable/). Llama.cpp is more flexible than vLLM for low VRAM systems, as Llama.cpp will offload to cpu/system RAM automatically rather than failing as vLLM tends to do.
105
+
106
+ For Llama.cpp, you can use the [docker-compose_llama.yml](https://github.com/seanpedrick-case/doc_redaction/blob/main/docker-compose_llama.yml) file, and for vLLM, you can use the [docker-compose_vllm.yml](https://github.com/seanpedrick-case/doc_redaction/blob/main/docker-compose_vllm.yml) file. To run, Docker / Docker Desktop should be installed, and then you can run the commands suggested in the top of the files to run the servers.
107
+
108
+ You will need ~40 GB of disk space to run everything depending on the model chosen from the compose file. For the vLLM server, you will need 24 GB VRAM. For the Llama.cpp server, 24 GB VRAM is needed to run at full speed, but the n-gpu-layers and n-cpu-moe parameters in the Docker compose file can be adjusted to fit into your system. I would suggest that 8 GB VRAM is needed as a bare minimum for decent inference speed. See the [Unsloth guide](https://unsloth.ai/docs/models/qwen3.5) for more details on working with GGUF files for Qwen 3.5.
109
+
110
+ ##### Without Llama.cpp / vLLM inference server
111
+
112
+ If you want a working Docker installation without GPU support, you can install from the [Dockerfile](https://github.com/seanpedrick-case/doc_redaction/blob/main/Dockerfile) in the repo. A working example of this, with the CPU version of PaddleOCR, can be found on [Hugging Face](https://huggingface.co/spaces/seanpedrickcase/document_redaction). You can adjust the INSTALL_PADDLEOCR, PADDLE_GPU_ENABLED, INSTALL_VLM, and TORCH_GPU_ENABLED config variables to adjust for PaddleOCR and Transformers packages for local VLM support. Note that GPU-enabled PaddleOCR, and GPU-enabled Transformers/Torch often don't work well together, which is one reason why a Llama.cpp/vLLM inference server Docker installation option is provided below.
113
+
114
+ ### 2. Install prerequisites: Tesseract and Poppler
115
+
116
+ This application relies on two external tools for OCR (Tesseract) and PDF processing (Poppler). Please install them on your system before proceeding.
117
+
118
+ ---
119
+
120
+ #### Automated dependency setup (recommended)
121
+
122
+ If you **don’t have admin rights** (or you just want the simplest setup), you can have the project download and configure **Tesseract** and **Poppler** into a local `redaction_deps/` folder inside the doc_redaction folder.
123
+
124
+ You need the installer script available first, which means either:
125
+
126
+ - **Repository checkout**: `git clone ...` and run the command from the repo root (recommended for the web UI), or
127
+ - **PyPI install**: `pip install doc_redaction` and run from a writable folder where you want `redaction_deps/` and `config/app_config.env` to be created/updated.
128
+
129
+ From the repository root (or your chosen working folder) after creating/activating your venv and installing Python requirements:
130
+
131
+ ```bash
132
+ python -m doc_redaction.install_deps
133
+ ```
134
+
135
+ This writes `TESSERACT_FOLDER` / `POPPLER_FOLDER` into `config/app_config.env` so the app can find the binaries without you editing your system PATH.
136
+
137
+ To just check whether your machine can already see the tools:
138
+
139
+ ```bash
140
+ python -m doc_redaction.install_deps --verify-only
141
+ ```
142
+
143
+ #### **On Windows**
144
+
145
+ If you don’t use the automated setup above, you can install the dependencies manually by downloading installers and adding the programs to your system's PATH.
146
+
147
+ 1. **Install Tesseract OCR:**
148
+ * Download the installer from the official Tesseract at [UB Mannheim page](https://github.com/UB-Mannheim/tesseract/wiki) (e.g., `tesseract-ocr-w64-setup-v5.X.X...exe`).
149
+ * Run the installer.
150
+ * **IMPORTANT:** During installation, ensure you select the option to "Add Tesseract to system PATH for all users" or a similar option. This is crucial for the application to find the Tesseract executable.
151
+
152
+
153
+ 2. **Install Poppler:**
154
+ * Download the latest Poppler binary for Windows. A common source is the [Poppler for Windows](https://github.com/oschwartz10612/poppler-windows) GitHub releases page. Download the `.zip` file (e.g., `poppler-25.07.0-win.zip`).
155
+ * Extract the contents of the zip file to a permanent location on your computer, for example, `C:\Program Files\poppler\`.
156
+ * You must add the `bin` folder from your Poppler installation to your system's PATH environment variable.
157
+ * Search for "Edit the system environment variables" in the Windows Start Menu and open it.
158
+ * Click the "Environment Variables..." button.
159
+ * In the "System variables" section, find and select the `Path` variable, then click "Edit...".
160
+ * Click "New" and add the full path to the `bin` directory inside your Poppler folder (e.g., `C:\Program Files\poppler\poppler-24.02.0\bin`).
161
+ * Click OK on all windows to save the changes.
162
+
163
+ To verify, open a new Command Prompt and run `tesseract --version` and `pdftoppm -v`. If they both return version information, you have successfully installed the prerequisites.
164
+ ---
165
+
166
+ #### **On Linux (Debian/Ubuntu)**
167
+
168
+ Open your terminal and run the following command to install Tesseract and Poppler:
169
+
170
+ ```bash
171
+ sudo apt-get update && sudo apt-get install -y tesseract-ocr poppler-utils
172
+ ```
173
+
174
+ #### **On Linux (Fedora/CentOS/RHEL)**
175
+
176
+ Open your terminal and use the `dnf` or `yum` package manager:
177
+
178
+ ```bash
179
+ sudo dnf install -y tesseract poppler-utils
180
+ ```
181
+ ---
182
+
183
+ ### 3. Run the Application
184
+
185
+ With all dependencies installed, you can now start the Gradio application GUI. For a guide on how to use this, please go [here](https://seanpedrick-case.github.io/doc_redaction/src/user_guide.html).
186
+
187
+ ```bash
188
+ python app.py
189
+ ```
190
+
191
+ After running the command, the application will start, and you will see a local URL in your terminal (usually `http://127.0.0.1:7860`).
192
+
193
+ Open this URL in your web browser to use the document redaction tool
194
+
195
+ #### Command line interface
196
+
197
+ For example CLI commands, please refer to [this guide](https://seanpedrick-case.github.io/doc_redaction/src/user_guide.html#command-line-interface-cli) or the examples in [cli_redact.py](https://github.com/seanpedrick-case/doc_redaction/blob/main/cli_redact.py#L321)
198
+
199
+ If you installed from **PyPI**, use the installed console script:
200
+
201
+ ```bash
202
+ cli_redact --help
203
+ ```
204
+
205
+ From a **repository checkout**, you can also run:
206
+
207
+ ```bash
208
+ python cli_redact.py --help
209
+ ```
210
+
211
+ #### Python package commands
212
+
213
+ For Python examples in using the Python package, please see [Python Package usage (Python)](https://seanpedrick-case.github.io/doc_redaction/src/python_package_usage.html).
214
+
215
+ ---
216
+
217
+
218
+ ### 4. ⚙️ Configuration (Optional)
219
+
220
+ You can customise the application's behavior by creating a configuration file. This allows you to change settings without modifying the source code, such as enabling AWS features, changing logging behavior, or pointing to local Tesseract/Poppler installations. A full overview of all the potential settings you can modify in the app_config.env file can be seen in tools/config.py, with explanation on the documentation website for [the github repo](https://seanpedrick-case.github.io/doc_redaction/)
221
+
222
+ To get started:
223
+ 1. Locate the `example_config.env` file in the root of the project.
224
+ 2. Create a new file named `app_config.env` inside the `config/` directory (i.e., `config/app_config.env`).
225
+ 3. Copy the contents from `example_config.env` into your new `config/app_config.env` file.
226
+ 4. Modify the values in `config/app_config.env` to suit your needs. The application will automatically load these settings on startup.
227
+
228
+ If you do not create this file, the application will run with default settings.
229
+
230
+ #### Configuration Breakdown
231
+
232
+ Here is an overview of the most important settings, separated by whether they are for local use or require AWS.
233
+
234
+ ---
235
+
236
+ #### **Local & General Settings (No AWS Required)**
237
+
238
+ These settings are useful for all users, regardless of whether you are using AWS.
239
+
240
+ * `TESSERACT_FOLDER` / `POPPLER_FOLDER`
241
+ * Use these if you installed Tesseract or Poppler to a custom location on **Windows** and did not add them to the system PATH.
242
+ * Provide the path to the respective installation folders (for Poppler, point to the `bin` sub-directory).
243
+ * **Examples:** `POPPLER_FOLDER=C:/Program Files/poppler-24.02.0/bin/` `TESSERACT_FOLDER=tesseract/`
244
+
245
+ * `SHOW_LANGUAGE_SELECTION=True`
246
+ * Set to `True` to display a language selection dropdown in the UI for OCR processing.
247
+
248
+ * `DEFAULT_LOCAL_OCR_MODEL=tesseract`"
249
+ * Choose the backend for local OCR. Options are `tesseract`, `paddle`, or `hybrid`. "Tesseract" is the default, and is recommended. "hybrid-paddle" is a combination of the two - first pass through the redactions will be done with Tesseract, and then a second pass will be done with PaddleOCR on words with low confidence. "paddle" will only return whole line text extraction, and so will only work for OCR, not redaction.
250
+
251
+ * `SESSION_OUTPUT_FOLDER=False`
252
+ * If `True`, redacted files will be saved in unique subfolders within the `output/` directory for each session.
253
+
254
+ * `DISPLAY_FILE_NAMES_IN_LOGS=False`
255
+ * For privacy, file names are not recorded in usage logs by default. Set to `True` to include them.
256
+
257
+ ---
258
+
259
+ #### **AWS-Specific Settings**
260
+
261
+ These settings are only relevant if you intend to use AWS services like Textract for OCR and Comprehend for PII detection.
262
+
263
+ * `RUN_AWS_FUNCTIONS=True`
264
+ * **This is the master switch.** You must set this to `True` to enable any AWS functionality. If it is `False`, all other AWS settings will be ignored.
265
+
266
+ * **UI Options:**
267
+ * `SHOW_AWS_TEXT_EXTRACTION_OPTIONS=True`: Adds "AWS Textract" as an option in the text extraction dropdown.
268
+ * `SHOW_AWS_PII_DETECTION_OPTIONS=True`: Adds "AWS Comprehend" as an option in the PII detection dropdown.
269
+
270
+ * **Core AWS Configuration:**
271
+ * `AWS_REGION=example-region`: Set your AWS region (e.g., `us-east-1`).
272
+ * `DOCUMENT_REDACTION_BUCKET=example-bucket`: The name of the S3 bucket the application will use for temporary file storage and processing.
273
+
274
+ * **AWS Logging:**
275
+ * `SAVE_LOGS_TO_DYNAMODB=True`: If enabled, usage and feedback logs will be saved to DynamoDB tables.
276
+ * `ACCESS_LOG_DYNAMODB_TABLE_NAME`, `USAGE_LOG_DYNAMODB_TABLE_NAME`, etc.: Specify the names of your DynamoDB tables for logging.
277
+
278
+ * **Advanced AWS Textract Features:**
279
+ * `SHOW_WHOLE_DOCUMENT_TEXTRACT_CALL_OPTIONS=True`: Enables UI components for large-scale, asynchronous document processing via Textract.
280
+ * `TEXTRACT_WHOLE_DOCUMENT_ANALYSIS_BUCKET=example-bucket-output`: A separate S3 bucket for the final output of asynchronous Textract jobs.
281
+ * `LOAD_PREVIOUS_TEXTRACT_JOBS_S3=True`: If enabled, the app will try to load the status of previously submitted asynchronous jobs from S3.
282
+
283
+ * **Cost Tracking (for internal accounting):**
284
+ * `SHOW_COSTS=True`: Displays an estimated cost for AWS operations. Can be enabled even if AWS functions are off.
285
+ * `GET_COST_CODES=True`: Enables a dropdown for users to select a cost code before running a job.
286
+ * `COST_CODES_PATH=config/cost_codes.csv`: The local path to a CSV file containing your cost codes.
287
+ * `ENFORCE_COST_CODES=True`: Makes selecting a cost code mandatory before starting a redaction.
288
+
289
+ Now you have the app installed, please refer to the [User Guide](https://seanpedrick-case.github.io/doc_redaction/src/user_guide.html) for more information on how to use it for basic and advanced redaction.
290
+
291
+ ## For agents (API quickstart)
292
+
293
+ If you are an LLM/agent interacting with this app over HTTP (e.g. Hugging Face Spaces), **do not guess inputs** from the UI. Use the Gradio schema as the source of truth:
294
+
295
+ - **Discover schema**: `GET /gradio_api/info`
296
+ - **Upload files**: `POST /gradio_api/upload` (multipart field `files`) → returns server-internal paths like `/tmp/gradio_tmp/...`
297
+ - **Call**: `POST /gradio_api/call/{api_name}` with body `{"data":[...]}` (argument order must match `/gradio_api/info`)
298
+ - **Poll**: `GET /gradio_api/call/{api_name}/{event_id}` until complete
299
+ - **Download outputs**: `GET /gradio_api/file={path}` (note: some deployments return 403 without session cookies)
300
+
301
+ ### Choose the correct route (prefer short `gr.api` endpoints)
302
+
303
+ Fetch `/gradio_api/info` and then prefer the simplest route that exists:
304
+
305
+ - **Apply edited review CSV to a PDF**: `/review_apply`
306
+ - **Redact a PDF/image document**: `/doc_redact` — optional `handwrite_signature_checkbox` for AWS Textract (e.g. `Extract handwriting`, `Extract signatures`)
307
+ - **Summarise a PDF**: `/pdf_summarise`
308
+ - **Redact tabular files (CSV/XLSX/Parquet/DOCX)**: `/tabular_redact`
309
+
310
+ If those endpoints are not present in your deployment, fall back to the long UI-chained routes (`/apply_review_redactions`, `/redact_data`, etc.) and build `data[]` strictly from `/gradio_api/info`.
311
+
312
+ ### Common gotchas
313
+
314
+ - **Arity errors** (`needed: N, got: M`) mean you called a session-heavy UI handler with the wrong `data[]`. Prefer the short endpoints above.
315
+ - **`handle_file()` gotcha** (for `gradio_client` users): do **not** wrap server-internal upload paths (e.g. `/tmp/gradio_tmp/...`) with `handle_file()`. Pass them as plain strings.
316
+ - **Container-only outputs**: outputs may be written to container paths (e.g. `/home/user/app/output/`). Plan to download via `file=...` or use a mounted output directory in Docker.
317
+
318
+ ### Optional: MCP server
319
+
320
+ If you want external agents to call this app reliably without re-implementing Gradio upload/call/poll/download details, consider an **MCP server** that wraps the main tasks (`redact_document`, `apply_review_redactions`, `redact_tabular`, `summarise_document`) behind a small tool interface. See the [relevant documentation](https://github.com/seanpedrick-case/doc_redaction/blob/main/mcp_doc_redaction/README.md).
321
+
322
+ **Use as a library:** After installing from [PyPI](https://pypi.org/project/doc-redaction/) (`pip install doc_redaction`), you can call the same workflows as the Gradio `api_name` routes from Python. See the documentation: [Python Package usage (Python)](https://seanpedrick-case.github.io/doc_redaction/src/python_package_usage.html).
323
+
324
+ To extract text from documents, the 'Local' options are PikePDF for PDFs with selectable text, and OCR with Tesseract. Use AWS Textract to extract more complex elements e.g. handwriting, signatures, or unclear text. PaddleOCR and VLM support is also provided (see the installation instructions below).
325
+
326
+ For PII identification, 'Local' (based on spaCy) gives good results if you are looking for common names or terms, or a custom list of terms to redact (see Redaction settings). AWS Comprehend gives better results at a small cost.
327
+
328
+ Additional options on the 'Redaction settings' include, the type of information to redact (e.g. people, places), custom terms to include/ exclude from redaction, fuzzy matching, language settings, and whole page redaction. After redaction is complete, you can view and modify suggested redactions on the 'Review redactions' tab to quickly create a final redacted document.
329
+
330
+ NOTE: The app is not 100% accurate, and it will miss some personal information. It is essential that all outputs are reviewed **by a human** before using the final outputs.
agent-redact-space/pi-agent/.dockerignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ .git
2
+ .github
3
+ **/__pycache__
4
+ **/*.pyc
5
+ **/.pytest_cache
6
+ **/node_modules
7
+ workspace
8
+ output
9
+ input
10
+ config/pi_agent.env
agent-redact-space/pi-agent/.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Example PDFs must be plain files in the Space repo (not Git LFS pointers).
2
+ *.pdf -filter -diff -merge
agent-redact-space/pi-agent/Dockerfile ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+ # Pi agent Gradio UI for Hugging Face Docker Space (remote doc_redaction backend).
3
+ # Build from monorepo root: docker build -f agent-redact-space/pi-agent/Dockerfile .
4
+
5
+ FROM node:22-bookworm-slim
6
+
7
+ ENV NODE_ENV=production
8
+ ENV DEBIAN_FRONTEND=noninteractive
9
+ ENV NPM_CONFIG_LOGLEVEL=warn
10
+ ENV PYTHONUNBUFFERED=1
11
+ ENV PYTHONDONTWRITEBYTECODE=1
12
+ ENV PYTHONPATH=/workspace/doc_redaction/docker/pi
13
+ ENV PI_DEPLOYMENT_PROFILE=hf-space
14
+ ENV PI_DEFAULT_PROVIDER=google-gemini
15
+ ENV PI_DEFAULT_MODEL=gemini-flash-lite-latest
16
+ ENV DOC_REDACTION_GRADIO_URL=https://seanpedrickcase-document-redaction.hf.space
17
+ ENV GRADIO_SERVER_NAME=0.0.0.0
18
+ ENV GRADIO_SERVER_PORT=7860
19
+ ENV PI_WORKSPACE_DIR=/home/user/app/workspace
20
+ ENV PI_WORKDIR=/workspace/doc_redaction
21
+ ENV PI_UPLOAD_ROOT=/tmp/gradio
22
+ ENV PI_OFFLINE=1
23
+ ENV PI_SKIP_VERSION_CHECK=1
24
+ ENV PI_GRADIO_SHOW_EXAMPLES=true
25
+ ENV HOME=/home/node
26
+
27
+ RUN apt-get update && apt-get install -y --no-install-recommends \
28
+ bash \
29
+ git \
30
+ curl \
31
+ ca-certificates \
32
+ procps \
33
+ python3 \
34
+ python3-pip \
35
+ python3-venv \
36
+ && rm -rf /var/lib/apt/lists/*
37
+
38
+ RUN npm install -g --ignore-scripts @earendil-works/pi-coding-agent
39
+
40
+ COPY requirements_pi_agent.txt /tmp/requirements_pi_agent.txt
41
+ RUN pip3 install --no-cache-dir --break-system-packages \
42
+ -r /tmp/requirements_pi_agent.txt \
43
+ && rm /tmp/requirements_pi_agent.txt
44
+
45
+ WORKDIR /workspace/doc_redaction
46
+
47
+ COPY docker/pi docker/pi
48
+ COPY skills skills
49
+ COPY AGENTS.md AGENTS.md
50
+ COPY doc_redaction/example_data doc_redaction/example_data
51
+
52
+ RUN test -f doc_redaction/example_data/example_of_emails_sent_to_a_professor_before_applying.pdf \
53
+ && test -f doc_redaction/example_data/graduate-job-example-cover-letter.pdf \
54
+ && ! head -1 doc_redaction/example_data/example_of_emails_sent_to_a_professor_before_applying.pdf \
55
+ | grep -q "^version https://git-lfs.github.com/spec/v1"
56
+
57
+ RUN mkdir -p /home/node/.pi/agent/sessions /home/user/app/workspace /tmp/gradio \
58
+ && chown -R node:node /home/node/.pi /home/user/app /tmp/gradio /workspace
59
+
60
+ USER node
61
+
62
+ RUN pi --version
63
+
64
+ EXPOSE 7860
65
+
66
+ CMD ["bash", "-c", "python3 docker/pi/pi_agent_config.py && exec python3 docker/pi/gradio_app.py"]
agent-redact-space/pi-agent/README.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Agentic Document Redaction
3
+ emoji: 🤖
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ license: agpl-3.0
10
+ ---
11
+
12
+ # Pi agent — agentic document redaction
13
+
14
+ Orchestrate document redaction with **[Pi](https://github.com/earendil-works/pi)** and **Google Gemini**. Heavy redaction runs on a separate **private [doc_redaction](https://huggingface.co/spaces/seanpedrickcase/document_redaction)** Hugging Face Space (simple text extraction + Local PII).
15
+
16
+ ## Before you start
17
+
18
+ 1. **Gemini API key** — paste in **Agent backend** → **Apply backend** (session-only; not stored on disk).
19
+ 2. **HF token** — Space admin should set `HF_TOKEN` under **Settings → Secrets** so this Space can call the private redaction backend. Users may optionally override per session in the UI.
20
+
21
+ ## Limitations
22
+
23
+ - **No face or signature VLM** — text-layer PII only via Local spaCy/Presidio on the remote Space.
24
+ - **No Pass 2 VLM** on this deployment.
25
+ - **Ephemeral storage** — download deliverables from **Workspace output files** before the Space restarts.
26
+ - **Human review** — outputs are not guaranteed complete; review redacted PDFs before release.
27
+
28
+ ## Defaults
29
+
30
+ | Setting | Value |
31
+ |---------|--------|
32
+ | Pi LLM | Gemini (`gemini-flash-latest` default) |
33
+ | Redaction backend | `https://seanpedrickcase-document-redaction.hf.space` |
34
+ | Text extraction | `Local model - selectable text` |
35
+ | PII detection | `Local` |
36
+
37
+ ## Examples
38
+
39
+ Two sample PDFs load in **Redaction task** → **Try an example** (same demos as the main doc_redaction app). Examples are **on by default**; set Space variable `PI_GRADIO_SHOW_EXAMPLES=false` to hide them. (`SHOW_PI_EXAMPLES` is also accepted.)
40
+
41
+ If examples do not appear, the UI shows a short status message (usually missing PDFs in the image — rebuild after a successful sync with LFS materialization).
42
+
43
+ ## Development
44
+
45
+ This Space is synced from the [doc_redaction monorepo](https://github.com/seanpedrick-case/doc_redaction) on pushes to **`dev`** (see `.github/workflows/sync-pi-agent-space.yml`). Space: [seanpedrickcase/agentic_document_redaction](https://huggingface.co/spaces/seanpedrickcase/agentic_document_redaction).
agent-redact-space/pi-agent/sync-manifest.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Paths copied from the monorepo root into the flattened Pi agent HF Space repo.
2
+ requirements_pi_agent.txt
3
+ docker/pi
4
+ skills
5
+ AGENTS.md
6
+ config/pi_agent.env.example
7
+ doc_redaction/example_data/example_of_emails_sent_to_a_professor_before_applying.pdf
8
+ doc_redaction/example_data/graduate-job-example-cover-letter.pdf
agent-redact-space/pi-agent/sync_to_space.sh ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Flatten monorepo paths into a temp directory for the Pi agent HF Space repo.
3
+ # Usage (from repo root):
4
+ # agent-redact-space/pi-agent/sync_to_space.sh /path/to/output-dir
5
+ set -euo pipefail
6
+
7
+ ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
8
+ OUT="${1:?Output directory required}"
9
+ MANIFEST="$(dirname "$0")/sync-manifest.txt"
10
+
11
+ _is_lfs_pointer() {
12
+ [[ -f "$1" ]] && head -1 "$1" 2>/dev/null | grep -q "^version https://git-lfs.github.com/spec/v1"
13
+ }
14
+
15
+ rm -rf "$OUT"
16
+ mkdir -p "$OUT"
17
+
18
+ cp "$(dirname "$0")/Dockerfile" "$OUT/Dockerfile"
19
+ cp "$(dirname "$0")/README.md" "$OUT/README.md"
20
+ cp "$(dirname "$0")/.dockerignore" "$OUT/.dockerignore"
21
+ cp "$(dirname "$0")/.gitattributes" "$OUT/.gitattributes"
22
+
23
+ while IFS= read -r line || [[ -n "$line" ]]; do
24
+ line="${line%%#*}"
25
+ line="$(echo "$line" | xargs)"
26
+ [[ -z "$line" ]] && continue
27
+ src="$ROOT/$line"
28
+ if [[ ! -e "$src" ]]; then
29
+ echo "Missing: $src" >&2
30
+ exit 1
31
+ fi
32
+ dest="$OUT/$line"
33
+ mkdir -p "$(dirname "$dest")"
34
+ cp -a "$src" "$dest"
35
+ if [[ "$line" == *.pdf ]] && _is_lfs_pointer "$dest"; then
36
+ echo "Copied file is a Git LFS pointer, not a PDF: $line" >&2
37
+ echo "Run 'git lfs pull' in the monorepo before syncing." >&2
38
+ exit 1
39
+ fi
40
+ done < "$MANIFEST"
41
+
42
+ echo "Flattened Pi agent Space tree: $OUT"
agent_routes.py ADDED
@@ -0,0 +1,1167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "verify_redaction_coverage",
59
+ )
60
+
61
+
62
+ def _allowed_path_roots() -> list[Path]:
63
+ # Return roots without resolving. These are trusted config values, but avoiding
64
+ # Path.resolve() keeps CodeQL happy and matches our "no resolve on untrusted"
65
+ # approach elsewhere.
66
+ roots = [REPO_ROOT]
67
+ for folder in (INPUT_FOLDER, OUTPUT_FOLDER):
68
+ if folder:
69
+ roots.append(Path(str(folder)))
70
+ return roots
71
+
72
+
73
+ def _sanitize_untrusted_path_input(path_str: str) -> str:
74
+ """Basic raw-input validation before any path normalization."""
75
+ if not isinstance(path_str, str):
76
+ raise HTTPException(status_code=400, detail="Path must be a string.")
77
+ cleaned = path_str.strip()
78
+ if not cleaned:
79
+ raise HTTPException(status_code=400, detail="Path must not be empty.")
80
+ if "\x00" in cleaned:
81
+ raise HTTPException(status_code=400, detail="Path contains invalid null byte.")
82
+ return cleaned
83
+
84
+
85
+ def _normalize_untrusted_path_to_abs(path_str: str) -> str:
86
+ """
87
+ Expand ~, then normalize to an absolute path.
88
+
89
+ Relative paths are interpreted relative to REPO_ROOT (matching prior behaviour).
90
+ """
91
+ safe_input = _sanitize_untrusted_path_input(path_str)
92
+ expanded = os.path.expanduser(safe_input)
93
+ if os.path.isabs(expanded):
94
+ return os.path.normpath(os.path.abspath(expanded))
95
+ return os.path.normpath(os.path.abspath(os.path.join(str(REPO_ROOT), expanded)))
96
+
97
+
98
+ def _must_be_under_allowed_roots(candidate_abs: str, original: str) -> None:
99
+ """Enforce candidate is contained under repo, INPUT_FOLDER, or OUTPUT_FOLDER."""
100
+ candidate_real = os.path.realpath(str(candidate_abs))
101
+ allowed_roots = [
102
+ os.path.realpath(os.path.abspath(str(p))) for p in _allowed_path_roots()
103
+ ]
104
+ for root in allowed_roots:
105
+ try:
106
+ common = os.path.commonpath([candidate_real, root])
107
+ except ValueError:
108
+ # Different drive on Windows or invalid path mix
109
+ continue
110
+ if common == root:
111
+ return
112
+ raise HTTPException(
113
+ status_code=403,
114
+ detail="Path must be under the app repo, INPUT_FOLDER, or OUTPUT_FOLDER",
115
+ )
116
+
117
+
118
+ def _path_must_be_allowed_file(path_str: str) -> str:
119
+ """Resolve path, ensure it is under an allowed root and exists as a file."""
120
+ candidate_abs = _normalize_untrusted_path_to_abs(path_str)
121
+ candidate_real = os.path.realpath(candidate_abs)
122
+
123
+ # Validate both "safe path" patterns and containment under trusted roots.
124
+ _must_be_under_allowed_roots(candidate_real, path_str)
125
+ ok = any(
126
+ validate_path_safety(candidate_real, base_path=str(root))
127
+ for root in _allowed_path_roots()
128
+ )
129
+ if not ok:
130
+ raise HTTPException(status_code=400, detail=f"Unsafe path rejected: {path_str}")
131
+ try:
132
+ candidate_path = Path(candidate_real)
133
+ if not candidate_path.is_file():
134
+ raise HTTPException(
135
+ status_code=400, detail=f"Not a file or missing: {candidate_real}"
136
+ )
137
+ except OSError:
138
+ raise HTTPException(
139
+ status_code=400, detail=f"Not a file or missing: {candidate_real}"
140
+ )
141
+ return candidate_real
142
+
143
+
144
+ def _path_must_be_allowed_directory(path_str: str, *, must_exist: bool = True) -> str:
145
+ """
146
+ Normalize and validate a directory path under allowed roots.
147
+
148
+ By default the directory must already exist; callers can opt out (e.g. output_dir
149
+ that will be created later by the CLI).
150
+ """
151
+ candidate_abs = _normalize_untrusted_path_to_abs(path_str)
152
+ candidate_real = os.path.realpath(candidate_abs)
153
+
154
+ _must_be_under_allowed_roots(candidate_real, path_str)
155
+ ok = any(
156
+ validate_path_safety(candidate_real, base_path=str(root))
157
+ for root in _allowed_path_roots()
158
+ )
159
+ if not ok:
160
+ raise HTTPException(status_code=400, detail=f"Unsafe path rejected: {path_str}")
161
+ if must_exist:
162
+ try:
163
+ if not Path(candidate_real).is_dir():
164
+ raise HTTPException(
165
+ status_code=400, detail=f"Not a directory: {candidate_real}"
166
+ )
167
+ except OSError:
168
+ raise HTTPException(
169
+ status_code=400, detail=f"Not a directory: {candidate_real}"
170
+ )
171
+ return candidate_real
172
+
173
+
174
+ def _optional_agent_api_key(x_agent_api_key: Optional[str] = Header(None)) -> None:
175
+ expected = os.environ.get("AGENT_API_KEY", "").strip()
176
+ if not expected:
177
+ return
178
+ if not x_agent_api_key or x_agent_api_key.strip() != expected:
179
+ raise HTTPException(
180
+ status_code=401,
181
+ detail="Set header X-Agent-API-Key to match AGENT_API_KEY environment variable",
182
+ )
183
+
184
+
185
+ class AgentRedactDocumentRequest(BaseModel):
186
+ """Parity with Gradio api_name ``redact_document``."""
187
+
188
+ input_files: list[str] = Field(
189
+ ...,
190
+ min_length=1,
191
+ description="Paths to input files (PDF, images, or tabular/Word for anonymisation)",
192
+ )
193
+ instruction: Optional[str] = Field(
194
+ None,
195
+ description="Optional instructions for LLM-based PII detection (custom_llm_instructions)",
196
+ )
197
+ output_dir: Optional[str] = None
198
+ input_dir: Optional[str] = None
199
+ ocr_method: Optional[str] = Field(
200
+ None,
201
+ description=(
202
+ "High-level OCR/text mode. Accepted values: 'Local OCR', "
203
+ "'AWS Textract', 'Local text'. To choose a specific local OCR engine "
204
+ "(e.g. paddle/tesseract/vlm), set "
205
+ "overrides.chosen_local_ocr_model."
206
+ ),
207
+ )
208
+ pii_detector: Optional[str] = Field(
209
+ None,
210
+ description=(
211
+ "PII detection method. Recommended configured labels: "
212
+ f"'{LOCAL_PII_OPTION}', '{AWS_PII_OPTION}', '{AWS_LLM_PII_OPTION}', "
213
+ f"'{INFERENCE_SERVER_PII_OPTION}', '{LOCAL_TRANSFORMERS_LLM_PII_OPTION}', "
214
+ "'None'."
215
+ ),
216
+ )
217
+ overrides: Optional[dict[str, Any]] = Field(
218
+ None,
219
+ description=(
220
+ "Optional CLI flag overrides; keys must match argparse destination names. "
221
+ "For local OCR model selection, set 'chosen_local_ocr_model' "
222
+ f"(allowed models depend on deployment; configured options: {LOCAL_OCR_MODEL_OPTIONS})."
223
+ ),
224
+ )
225
+
226
+ model_config = {
227
+ "json_schema_extra": {
228
+ "examples": [
229
+ {
230
+ "input_files": [
231
+ "example_data/example_of_emails_sent_to_a_professor_before_applying.pdf"
232
+ ],
233
+ "instruction": "Do not redact the university name.",
234
+ "ocr_method": "Local OCR",
235
+ "pii_detector": LOCAL_PII_OPTION,
236
+ "overrides": {"chosen_local_ocr_model": "paddle"},
237
+ }
238
+ ]
239
+ }
240
+ }
241
+
242
+ @field_validator("instruction")
243
+ @classmethod
244
+ def _cap_instruction(cls, v: Optional[str]) -> Optional[str]:
245
+ if v is None:
246
+ return v
247
+ if len(v) > _MAX_INSTRUCTION_LEN:
248
+ raise ValueError(f"instruction exceeds {_MAX_INSTRUCTION_LEN} characters")
249
+ return v
250
+
251
+
252
+ class AgentRedactDataRequest(AgentRedactDocumentRequest):
253
+ """Parity with Gradio api_name ``redact_data``; same CLI task as redact_document."""
254
+
255
+
256
+ class AgentTaskResponse(BaseModel):
257
+ status: str
258
+ gradio_api_name: str
259
+ task: str
260
+ output_dir: str
261
+ input_dir: str
262
+ message: str
263
+ log_excerpt: Optional[str] = None
264
+ output_paths: Optional[list[str]] = None
265
+
266
+
267
+ class AgentVerifyRedactionRequest(BaseModel):
268
+ review_csv_path: str = Field(..., description="Path to *_review_file.csv")
269
+ ocr_words_csv_path: str = Field(
270
+ ..., description="Path to *_ocr_results_with_words_*.csv from the same run"
271
+ )
272
+ must_redact: Optional[List[str]] = Field(
273
+ None,
274
+ description="Regex patterns for terms that must be covered by review boxes.",
275
+ )
276
+ must_not_redact: Optional[List[str]] = Field(
277
+ None,
278
+ description="Regex patterns for terms that must not appear in review rows.",
279
+ )
280
+ redacted_pdf_path: Optional[str] = Field(
281
+ None, description="Optional applied *_redacted.pdf for text-layer leak checks."
282
+ )
283
+ total_pages: Optional[int] = Field(None, ge=1)
284
+ min_word_length: int = Field(3, ge=1, le=32)
285
+ sample_pixels: bool = Field(
286
+ False,
287
+ description="Sample pixel darkness at box centres on redacted PDF (requires redacted_pdf_path).",
288
+ )
289
+ auto_prune_suspicious: bool = Field(
290
+ False,
291
+ description="Remove prunable suspicious short/OCR-fragment rows and write pruned CSV.",
292
+ )
293
+ pruned_output_path: Optional[str] = Field(
294
+ None,
295
+ description="Output path for pruned CSV when auto_prune_suspicious is true.",
296
+ )
297
+
298
+
299
+ class AgentVerifyRedactionResponse(BaseModel):
300
+ status: str
301
+ gradio_api_name: str = "verify_redaction_coverage"
302
+ coverage_pass: bool
303
+ coverage_pass_strict: bool
304
+ coverage_pass_with_cleanup: bool
305
+ pruned_csv_path: Optional[str] = None
306
+ prune_log: Optional[Dict[str, Any]] = None
307
+ report: Dict[str, Any]
308
+
309
+
310
+ class AgentWordLevelOcrSearchRequest(BaseModel):
311
+ ocr_words_csv_path: str = Field(
312
+ ..., description="Path to *_ocr_results_with_words_*.csv"
313
+ )
314
+ search_text: str = Field(..., min_length=3, max_length=500)
315
+ similarity_threshold: float = Field(1.0, ge=0.0, le=1.0)
316
+ use_regex: bool = False
317
+ review_csv_path: Optional[str] = Field(
318
+ None,
319
+ description="Optional *_review_file.csv to flag whether each hit is covered by a box.",
320
+ )
321
+
322
+
323
+ class AgentWordLevelOcrSearchResponse(BaseModel):
324
+ status: str
325
+ gradio_api_name: str = "word_level_ocr_text_search"
326
+ result: Dict[str, Any]
327
+
328
+
329
+ def _merge_redact_direct_mode(body: AgentRedactDocumentRequest) -> dict[str, Any]:
330
+ from cli_redact import get_cli_default_args_dict
331
+
332
+ merged: dict[str, Any] = get_cli_default_args_dict()
333
+ merged["task"] = "redact"
334
+ merged["input_file"] = [_path_must_be_allowed_file(p) for p in body.input_files]
335
+
336
+ if body.instruction is not None:
337
+ merged["custom_llm_instructions"] = body.instruction
338
+ if body.output_dir is not None:
339
+ # Output folders may not exist yet (CLI will create). Still constrain to allowed roots.
340
+ merged["output_dir"] = _path_must_be_allowed_directory(
341
+ body.output_dir, must_exist=False
342
+ )
343
+ if body.input_dir is not None:
344
+ # Input dir should exist if provided.
345
+ merged["input_dir"] = _path_must_be_allowed_directory(
346
+ body.input_dir, must_exist=True
347
+ )
348
+ if body.ocr_method is not None:
349
+ merged["ocr_method"] = body.ocr_method
350
+ if body.pii_detector is not None:
351
+ merged["pii_detector"] = body.pii_detector
352
+
353
+ if body.overrides:
354
+ allowed = set(merged.keys())
355
+ for key, value in body.overrides.items():
356
+ if key not in allowed:
357
+ raise HTTPException(
358
+ status_code=400,
359
+ detail=f"Unknown override key '{key}'. Must be a known CLI argument name.",
360
+ )
361
+ merged[key] = value
362
+
363
+ return merged
364
+
365
+
366
+ def _run_cli_main(direct: dict[str, Any], gradio_api_name: str) -> AgentTaskResponse:
367
+ from cli_redact import main as cli_main
368
+
369
+ buf = io.StringIO()
370
+ old_stdout = sys.stdout
371
+ try:
372
+ sys.stdout = buf
373
+ cli_main(direct_mode_args=direct)
374
+ except Exception as e:
375
+ raise HTTPException(status_code=500, detail=str(e)) from e
376
+ finally:
377
+ sys.stdout = old_stdout
378
+
379
+ log_excerpt = buf.getvalue()
380
+ if len(log_excerpt) > 8000:
381
+ log_excerpt = log_excerpt[-8000:]
382
+
383
+ return AgentTaskResponse(
384
+ status="completed",
385
+ gradio_api_name=gradio_api_name,
386
+ task=str(direct.get("task", "")),
387
+ output_dir=str(direct.get("output_dir", "")),
388
+ input_dir=str(direct.get("input_dir", "")),
389
+ message="cli_redact.main finished; see log_excerpt for console output",
390
+ log_excerpt=log_excerpt or None,
391
+ )
392
+
393
+
394
+ @router.post(
395
+ "/redact_document",
396
+ response_model=AgentTaskResponse,
397
+ summary="redact_document (Gradio api_name)",
398
+ description=(
399
+ "Matches Gradio ``api_name='redact_document'``. "
400
+ "``python cli_redact.py --task redact --input_file ...``. "
401
+ "Optional ``instruction`` maps to ``custom_llm_instructions``. "
402
+ "OCR modes: 'Local OCR' | 'AWS Textract' | 'Local text'. "
403
+ "Specific local OCR engines are set via ``overrides.chosen_local_ocr_model`` "
404
+ f"(for example: {LOCAL_OCR_MODEL_OPTIONS}). "
405
+ "PII methods should use configured labels shown on the request schema."
406
+ ),
407
+ )
408
+ def post_redact_document(
409
+ body: AgentRedactDocumentRequest,
410
+ _: None = Depends(_optional_agent_api_key),
411
+ ) -> AgentTaskResponse:
412
+ direct = _merge_redact_direct_mode(body)
413
+ return _run_cli_main(direct, "redact_document")
414
+
415
+
416
+ @router.post(
417
+ "/redact_data",
418
+ response_model=AgentTaskResponse,
419
+ summary="redact_data (Gradio api_name)",
420
+ description=(
421
+ "Matches Gradio ``api_name='redact_data'``. Same CLI ``redact`` task as "
422
+ "/redact_document; use CSV/XLSX/DOCX paths for tabular/Word flows. "
423
+ "OCR modes: 'Local OCR' | 'AWS Textract' | 'Local text'. "
424
+ "Specific local OCR engines are set via ``overrides.chosen_local_ocr_model`` "
425
+ f"(for example: {LOCAL_OCR_MODEL_OPTIONS}). "
426
+ "PII methods should use configured labels shown on the request schema."
427
+ ),
428
+ )
429
+ def post_redact_data(
430
+ body: AgentRedactDataRequest,
431
+ _: None = Depends(_optional_agent_api_key),
432
+ ) -> AgentTaskResponse:
433
+ direct = _merge_redact_direct_mode(body)
434
+ return _run_cli_main(direct, "redact_data")
435
+
436
+
437
+ @router.post(
438
+ "/tasks/redact",
439
+ response_model=AgentTaskResponse,
440
+ summary="Legacy: same as /redact_document",
441
+ description="Deprecated alias; prefer POST /agent/redact_document.",
442
+ deprecated=True,
443
+ include_in_schema=True,
444
+ )
445
+ def post_tasks_redact_legacy(
446
+ body: AgentRedactDocumentRequest,
447
+ _: None = Depends(_optional_agent_api_key),
448
+ ) -> AgentTaskResponse:
449
+ direct = _merge_redact_direct_mode(body)
450
+ return _run_cli_main(direct, "redact_document")
451
+
452
+
453
+ class AgentFindDuplicatePagesRequest(BaseModel):
454
+ input_files: list[str] = Field(..., min_length=1)
455
+ similarity_threshold: Optional[float] = None
456
+ min_word_count: Optional[int] = None
457
+ min_consecutive_pages: Optional[int] = None
458
+ greedy_match: Optional[bool] = None
459
+ combine_pages: Optional[bool] = None
460
+ overrides: Optional[dict[str, Any]] = None
461
+
462
+
463
+ @router.post(
464
+ "/find_duplicate_pages",
465
+ response_model=AgentTaskResponse,
466
+ summary="find_duplicate_pages (Gradio api_name)",
467
+ description="``cli_redact --task deduplicate --duplicate_type pages``.",
468
+ )
469
+ def post_find_duplicate_pages(
470
+ body: AgentFindDuplicatePagesRequest,
471
+ _: None = Depends(_optional_agent_api_key),
472
+ ) -> AgentTaskResponse:
473
+ from cli_redact import get_cli_default_args_dict
474
+
475
+ merged = get_cli_default_args_dict()
476
+ merged["task"] = "deduplicate"
477
+ merged["duplicate_type"] = "pages"
478
+ merged["input_file"] = [_path_must_be_allowed_file(p) for p in body.input_files]
479
+ if body.similarity_threshold is not None:
480
+ merged["similarity_threshold"] = body.similarity_threshold
481
+ if body.min_word_count is not None:
482
+ merged["min_word_count"] = body.min_word_count
483
+ if body.min_consecutive_pages is not None:
484
+ merged["min_consecutive_pages"] = body.min_consecutive_pages
485
+ if body.greedy_match is not None:
486
+ merged["greedy_match"] = "True" if body.greedy_match else "False"
487
+ if body.combine_pages is not None:
488
+ merged["combine_pages"] = "True" if body.combine_pages else "False"
489
+ if body.overrides:
490
+ allowed = set(merged.keys())
491
+ for k, v in body.overrides.items():
492
+ if k not in allowed:
493
+ raise HTTPException(400, f"Unknown override key: {k}")
494
+ merged[k] = v
495
+ return _run_cli_main(merged, "find_duplicate_pages")
496
+
497
+
498
+ class AgentFindDuplicateTabularRequest(BaseModel):
499
+ input_files: list[str] = Field(..., min_length=1)
500
+ text_columns: Optional[list[str]] = None
501
+ similarity_threshold: Optional[float] = None
502
+ min_word_count: Optional[int] = None
503
+ overrides: Optional[dict[str, Any]] = None
504
+
505
+
506
+ @router.post(
507
+ "/find_duplicate_tabular",
508
+ response_model=AgentTaskResponse,
509
+ summary="find_duplicate_tabular (Gradio api_name)",
510
+ )
511
+ def post_find_duplicate_tabular(
512
+ body: AgentFindDuplicateTabularRequest,
513
+ _: None = Depends(_optional_agent_api_key),
514
+ ) -> AgentTaskResponse:
515
+ from cli_redact import get_cli_default_args_dict
516
+
517
+ merged = get_cli_default_args_dict()
518
+ merged["task"] = "deduplicate"
519
+ merged["duplicate_type"] = "tabular"
520
+ merged["input_file"] = [_path_must_be_allowed_file(p) for p in body.input_files]
521
+ if body.text_columns is not None:
522
+ merged["text_columns"] = body.text_columns
523
+ if body.similarity_threshold is not None:
524
+ merged["similarity_threshold"] = body.similarity_threshold
525
+ if body.min_word_count is not None:
526
+ merged["min_word_count"] = body.min_word_count
527
+ if body.overrides:
528
+ allowed = set(merged.keys())
529
+ for k, v in body.overrides.items():
530
+ if k not in allowed:
531
+ raise HTTPException(400, f"Unknown override key: {k}")
532
+ merged[k] = v
533
+ return _run_cli_main(merged, "find_duplicate_tabular")
534
+
535
+
536
+ class AgentSummariseDocumentRequest(BaseModel):
537
+ input_files: list[str] = Field(..., min_length=1)
538
+ summarisation_inference_method: Optional[str] = None
539
+ summarisation_format: Optional[str] = None
540
+ summarisation_context: Optional[str] = None
541
+ summarisation_additional_instructions: Optional[str] = None
542
+ overrides: Optional[dict[str, Any]] = None
543
+
544
+
545
+ @router.post(
546
+ "/summarise_document",
547
+ response_model=AgentTaskResponse,
548
+ summary="summarise_document (Gradio api_name)",
549
+ )
550
+ def post_summarise_document(
551
+ body: AgentSummariseDocumentRequest,
552
+ _: None = Depends(_optional_agent_api_key),
553
+ ) -> AgentTaskResponse:
554
+ from cli_redact import get_cli_default_args_dict
555
+
556
+ merged = get_cli_default_args_dict()
557
+ merged["task"] = "summarise"
558
+ merged["input_file"] = [_path_must_be_allowed_file(p) for p in body.input_files]
559
+ if body.summarisation_inference_method is not None:
560
+ merged["summarisation_inference_method"] = body.summarisation_inference_method
561
+ if body.summarisation_format is not None:
562
+ merged["summarisation_format"] = body.summarisation_format
563
+ if body.summarisation_context is not None:
564
+ merged["summarisation_context"] = body.summarisation_context
565
+ if body.summarisation_additional_instructions is not None:
566
+ merged["summarisation_additional_instructions"] = (
567
+ body.summarisation_additional_instructions
568
+ )
569
+ if body.overrides:
570
+ allowed = set(merged.keys())
571
+ for k, v in body.overrides.items():
572
+ if k not in allowed:
573
+ raise HTTPException(400, f"Unknown override key: {k}")
574
+ merged[k] = v
575
+ return _run_cli_main(merged, "summarise_document")
576
+
577
+
578
+ class AgentCombineReviewPdfsRequest(BaseModel):
579
+ input_files: list[str] = Field(..., min_length=2)
580
+ output_dir: Optional[str] = None
581
+
582
+
583
+ @router.post(
584
+ "/combine_review_pdfs",
585
+ response_model=AgentTaskResponse,
586
+ summary="combine_review_pdfs (Gradio api_name)",
587
+ )
588
+ def post_combine_review_pdfs(
589
+ body: AgentCombineReviewPdfsRequest,
590
+ _: None = Depends(_optional_agent_api_key),
591
+ ) -> AgentTaskResponse:
592
+ from cli_redact import get_cli_default_args_dict
593
+
594
+ merged = get_cli_default_args_dict()
595
+ merged["task"] = "combine_review_pdfs"
596
+ merged["input_file"] = [_path_must_be_allowed_file(p) for p in body.input_files]
597
+ if body.output_dir is not None:
598
+ merged["output_dir"] = _path_must_be_allowed_directory(body.output_dir)
599
+ return _run_cli_main(merged, "combine_review_pdfs")
600
+
601
+
602
+ class _NamedPath:
603
+ """merge_csv_files expects objects with a .name attribute (Gradio file-like)."""
604
+
605
+ __slots__ = ("name",)
606
+
607
+ def __init__(self, path: str) -> None:
608
+ self.name = path
609
+
610
+
611
+ class AgentCombineReviewCsvsRequest(BaseModel):
612
+ input_files: list[str] = Field(..., min_length=1)
613
+ output_dir: Optional[str] = Field(
614
+ None, description="Defaults to config OUTPUT_FOLDER"
615
+ )
616
+
617
+
618
+ class AgentApplyReviewRedactionsRequest(BaseModel):
619
+ """Headless parity with Gradio ``api_name='apply_review_redactions'`` (prepare + apply)."""
620
+
621
+ pdf_path: str = Field(
622
+ ...,
623
+ description="Path to the source PDF under allowed roots.",
624
+ )
625
+ review_csv_path: str = Field(
626
+ ...,
627
+ description=(
628
+ "Path to the review plan CSV; basename must contain '_review_file' "
629
+ "(e.g. mydoc_review_file.csv)."
630
+ ),
631
+ )
632
+ output_dir: Optional[str] = Field(
633
+ None,
634
+ description="Output directory (created if missing); defaults to OUTPUT_FOLDER.",
635
+ )
636
+ input_dir: Optional[str] = Field(
637
+ None,
638
+ description="Input/working directory for page images; defaults to INPUT_FOLDER.",
639
+ )
640
+ text_extract_method: Optional[str] = Field(
641
+ None,
642
+ description="OCR/text mode passed to prepare (defaults to CLI ocr_method).",
643
+ )
644
+ efficient_ocr: Optional[bool] = Field(
645
+ None,
646
+ description="If set, overrides EFFICIENT_OCR for the prepare step.",
647
+ )
648
+
649
+
650
+ @router.post(
651
+ "/combine_review_csvs",
652
+ response_model=AgentTaskResponse,
653
+ summary="combine_review_csvs (Gradio api_name)",
654
+ description="Uses tools.helper_functions.merge_csv_files (not cli_redact).",
655
+ )
656
+ def post_combine_review_csvs(
657
+ body: AgentCombineReviewCsvsRequest,
658
+ _: None = Depends(_optional_agent_api_key),
659
+ ) -> AgentTaskResponse:
660
+ from tools.helper_functions import merge_csv_files
661
+
662
+ paths = [_NamedPath(_path_must_be_allowed_file(p)) for p in body.input_files]
663
+ out_dir = body.output_dir or OUTPUT_FOLDER
664
+ out_dir_resolved = _path_must_be_allowed_directory(str(out_dir), must_exist=True)
665
+ sep = "/" if not out_dir_resolved.endswith(("/", "\\")) else ""
666
+ out_files = merge_csv_files(paths, output_folder=out_dir_resolved + sep)
667
+ return AgentTaskResponse(
668
+ status="completed",
669
+ gradio_api_name="combine_review_csvs",
670
+ task="combine_review_csvs",
671
+ output_dir=out_dir_resolved,
672
+ input_dir="",
673
+ message="merge_csv_files completed",
674
+ output_paths=out_files,
675
+ )
676
+
677
+
678
+ class AgentExportReviewRedactionOverlayRequest(BaseModel):
679
+ """Agent JSON body for the same overlay render as Gradio ``api_name='page_redaction_review_image'``."""
680
+
681
+ page_image_path: str = Field(
682
+ ...,
683
+ description="Path to page raster (PNG/JPEG) used as underlay; must be under allowed roots.",
684
+ )
685
+ boxes: List[Dict[str, Any]] = Field(
686
+ ...,
687
+ min_length=1,
688
+ description="Annotator-style boxes: label, color, xmin, ymin, xmax, ymax (normalized 0–1).",
689
+ )
690
+ page_number: int = Field(
691
+ 1, ge=1, description="1-based page index for the output filename."
692
+ )
693
+ doc_base_name: str = Field(
694
+ "review",
695
+ description="Basename for output file (e.g. document name without extension).",
696
+ )
697
+ review_df_records: Optional[List[Dict[str, Any]]] = Field(
698
+ None,
699
+ description="Optional rows (include at least 'label') for stable label→line-pattern mapping.",
700
+ )
701
+ label_abbrev_chars: Optional[int] = Field(
702
+ None,
703
+ ge=0,
704
+ le=24,
705
+ description="Draw this many leading characters of each label on the image; omit to use REVIEW_OVERLAY_LABEL_ABBREV_CHARS from config (0 = off).",
706
+ )
707
+
708
+
709
+ class AgentExportReviewPageOcrVisualisationRequest(BaseModel):
710
+ """Agent JSON body for the same OCR visualisation as Gradio ``api_name='page_ocr_review_image'``."""
711
+
712
+ page_image_path: str = Field(
713
+ ...,
714
+ description="Path to page raster (PNG/JPEG) used as underlay; must be under allowed roots.",
715
+ )
716
+ ocr_results: Dict[str, Any] = Field(
717
+ ...,
718
+ description="Word-level OCR results dict (line_key -> {words:[{text, bounding_box, conf, ...}]}).",
719
+ )
720
+ page_number: int = Field(
721
+ 1, ge=1, description="1-based page index (used for naming)."
722
+ )
723
+ doc_base_name: str = Field(
724
+ "review",
725
+ description="Basename for output file (e.g. document name without extension).",
726
+ )
727
+
728
+
729
+ @router.post(
730
+ "/export_review_redaction_overlay",
731
+ response_model=AgentTaskResponse,
732
+ summary="export_review_redaction_overlay (Agent API; Gradio api_name: page_redaction_review_image)",
733
+ description=(
734
+ "Renders hollow redaction outlines and a top-right legend on the page image; "
735
+ "writes ``redaction_overlay/{doc_base_name}_page{n}_redaction_overlay.jpg`` under OUTPUT_FOLDER "
736
+ "(scaled per REVIEW_OVERLAY_MAX_PIXELS, JPEG capped by REVIEW_OVERLAY_MAX_FILE_BYTES). "
737
+ "Uses ``tools.redaction_review.visualise_review_redaction_boxes``."
738
+ ),
739
+ )
740
+ def post_export_review_redaction_overlay(
741
+ body: AgentExportReviewRedactionOverlayRequest,
742
+ _: None = Depends(_optional_agent_api_key),
743
+ ) -> AgentTaskResponse:
744
+ import pandas as pd
745
+
746
+ from tools.redaction_review import visualise_review_redaction_boxes
747
+
748
+ img_path = _path_must_be_allowed_file(body.page_image_path)
749
+ annotator: dict[str, Any] = {"image": img_path, "boxes": body.boxes}
750
+ review_df = (
751
+ pd.DataFrame(body.review_df_records)
752
+ if body.review_df_records
753
+ else pd.DataFrame()
754
+ )
755
+ out_folder_abs = os.path.realpath(
756
+ os.path.abspath(os.path.expanduser(str(OUTPUT_FOLDER)))
757
+ )
758
+ if not validate_path_safety(out_folder_abs):
759
+ raise HTTPException(status_code=400, detail="Unsafe OUTPUT_FOLDER path")
760
+ _must_be_under_allowed_roots(out_folder_abs, str(out_folder_abs))
761
+ try:
762
+ Path(out_folder_abs).mkdir(parents=True, exist_ok=True)
763
+ except OSError:
764
+ raise HTTPException(status_code=500, detail="Could not create OUTPUT_FOLDER")
765
+ out_folder = out_folder_abs
766
+
767
+ path = visualise_review_redaction_boxes(
768
+ annotator,
769
+ review_df=review_df,
770
+ output_folder=out_folder,
771
+ page_number=body.page_number,
772
+ doc_base_name=body.doc_base_name,
773
+ label_abbrev_chars=body.label_abbrev_chars,
774
+ )
775
+ if not path:
776
+ raise HTTPException(
777
+ status_code=500,
778
+ detail=(
779
+ "Could not produce overlay PNG (invalid image/boxes or write failed). "
780
+ "Ensure boxes are valid and the image loads."
781
+ ),
782
+ )
783
+ return AgentTaskResponse(
784
+ status="completed",
785
+ gradio_api_name="export_review_redaction_overlay",
786
+ task="export_review_redaction_overlay",
787
+ output_dir=out_folder,
788
+ input_dir="",
789
+ message="Redaction overlay PNG written",
790
+ output_paths=[path],
791
+ )
792
+
793
+
794
+ @router.post(
795
+ "/export_review_page_ocr_visualisation",
796
+ response_model=AgentTaskResponse,
797
+ summary="export_review_page_ocr_visualisation (Agent API; Gradio api_name: page_ocr_review_image)",
798
+ description=(
799
+ "Renders a per-page OCR visualisation using tools.file_redaction.visualise_ocr_words_bounding_boxes; "
800
+ "writes under OUTPUT_FOLDER/review_ocr_visualisations/."
801
+ ),
802
+ )
803
+ def post_export_review_page_ocr_visualisation(
804
+ body: AgentExportReviewPageOcrVisualisationRequest,
805
+ _: None = Depends(_optional_agent_api_key),
806
+ ) -> AgentTaskResponse:
807
+ from PIL import Image
808
+
809
+ from tools.file_redaction import visualise_ocr_words_bounding_boxes
810
+
811
+ img_path = _path_must_be_allowed_file(body.page_image_path)
812
+
813
+ out_folder_abs = os.path.realpath(
814
+ os.path.abspath(os.path.expanduser(str(OUTPUT_FOLDER)))
815
+ )
816
+ if not validate_path_safety(out_folder_abs):
817
+ raise HTTPException(status_code=400, detail="Unsafe OUTPUT_FOLDER path")
818
+ _must_be_under_allowed_roots(out_folder_abs, str(out_folder_abs))
819
+ try:
820
+ Path(out_folder_abs).mkdir(parents=True, exist_ok=True)
821
+ except OSError:
822
+ raise HTTPException(status_code=500, detail="Could not create OUTPUT_FOLDER")
823
+ out_folder = out_folder_abs
824
+
825
+ safe_base = str(body.doc_base_name or "review")
826
+ image_name = f"{safe_base}_page{int(body.page_number)}.png"
827
+ log_paths: list[str] = []
828
+ try:
829
+ log_paths = visualise_ocr_words_bounding_boxes(
830
+ Image.open(img_path).convert("RGB"),
831
+ body.ocr_results,
832
+ image_name=image_name,
833
+ output_folder=out_folder,
834
+ visualisation_folder="review_ocr_visualisations",
835
+ add_legend=True,
836
+ log_files_output_paths=log_paths,
837
+ )
838
+ except Exception as e:
839
+ raise HTTPException(status_code=500, detail=str(e)) from e
840
+
841
+ if not log_paths:
842
+ raise HTTPException(
843
+ status_code=500,
844
+ detail="Could not produce OCR visualisation (invalid image/ocr_results or write failed).",
845
+ )
846
+ out_path = log_paths[-1]
847
+ return AgentTaskResponse(
848
+ status="completed",
849
+ gradio_api_name="export_review_page_ocr_visualisation",
850
+ task="export_review_page_ocr_visualisation",
851
+ output_dir=out_folder,
852
+ input_dir="",
853
+ message="OCR visualisation written",
854
+ output_paths=[out_path],
855
+ )
856
+
857
+
858
+ def _gradio_only(api_name: str, detail: str) -> JSONResponse:
859
+ return JSONResponse(
860
+ status_code=501,
861
+ content={
862
+ "gradio_api_name": api_name,
863
+ "detail": detail,
864
+ "hint": (
865
+ "This flow is Gradio-session stateful. Call the named route on the "
866
+ "Gradio HTTP API, not /agent."
867
+ ),
868
+ "gradio_http": {
869
+ "discover_schema": "GET /gradio_api/info",
870
+ "start_call": f"POST /gradio_api/call/{api_name}",
871
+ "request_body_shape": '{"data": [<args in schema order>]}',
872
+ "poll": f"GET /gradio_api/call/{api_name}/{{event_id}}",
873
+ },
874
+ "gradio_client_notes": [
875
+ "Pass api_name explicitly; do not rely on inferring the endpoint from "
876
+ "Python function names (large Blocks apps will look ambiguous).",
877
+ "If predict() still cannot resolve the route, open GET /gradio_api/info "
878
+ "and use the numeric fn_index with gradio_client, or call the HTTP "
879
+ "endpoints directly.",
880
+ "The length of data must match the parameter list for this deployment; "
881
+ "copy order and types from /gradio_api/info.",
882
+ ],
883
+ },
884
+ )
885
+
886
+
887
+ @router.post("/load_and_prepare_documents_or_data")
888
+ def post_load_and_prepare_documents_or_data() -> JSONResponse:
889
+ return _gradio_only(
890
+ "load_and_prepare_documents_or_data",
891
+ "Preparation uses Gradio session state and prepare_image_or_pdf_with_efficient_ocr; no single CLI task.",
892
+ )
893
+
894
+
895
+ @router.post(
896
+ "/apply_review_redactions",
897
+ response_model=AgentTaskResponse,
898
+ summary="apply_review_redactions (Gradio api_name)",
899
+ description=(
900
+ "Runs prepare_image_or_pdf_with_efficient_ocr([pdf, review_csv]) then "
901
+ "apply_redactions_to_review_df_and_files — same core pipeline as the Review tab, "
902
+ "without Gradio session state. Requires paths under allowed roots."
903
+ ),
904
+ )
905
+ def post_apply_review_redactions(
906
+ body: AgentApplyReviewRedactionsRequest,
907
+ _: None = Depends(_optional_agent_api_key),
908
+ ) -> AgentTaskResponse:
909
+ from tools.simplified_api import run_apply_review_redactions
910
+
911
+ pdf = _path_must_be_allowed_file(body.pdf_path)
912
+ csv = _path_must_be_allowed_file(body.review_csv_path)
913
+ out_dir: str | None = None
914
+ if body.output_dir is not None:
915
+ out_dir = _path_must_be_allowed_directory(body.output_dir, must_exist=False)
916
+ in_dir: str | None = None
917
+ if body.input_dir is not None:
918
+ in_dir = _path_must_be_allowed_directory(body.input_dir, must_exist=False)
919
+
920
+ try:
921
+ result = run_apply_review_redactions(
922
+ pdf_path=pdf,
923
+ review_csv_path=csv,
924
+ output_dir=out_dir,
925
+ input_dir=in_dir,
926
+ text_extract_method=body.text_extract_method,
927
+ efficient_ocr=body.efficient_ocr,
928
+ )
929
+ except ValueError as e:
930
+ raise HTTPException(status_code=400, detail=str(e)) from e
931
+ except Exception as e:
932
+ raise HTTPException(
933
+ status_code=500,
934
+ detail=f"apply_review_redactions failed: {e}",
935
+ ) from e
936
+
937
+ return AgentTaskResponse(
938
+ status="completed",
939
+ gradio_api_name="apply_review_redactions",
940
+ task="apply_review_redactions",
941
+ output_dir=result["output_dir"],
942
+ input_dir=result["input_dir"],
943
+ message=result["message"],
944
+ output_paths=result.get("output_paths"),
945
+ )
946
+
947
+
948
+ @router.post(
949
+ "/verify_redaction_coverage",
950
+ response_model=AgentVerifyRedactionResponse,
951
+ summary="verify_redaction_coverage (Pass 1 programmatic QA)",
952
+ )
953
+ def post_verify_redaction_coverage(
954
+ body: AgentVerifyRedactionRequest,
955
+ _: None = Depends(_optional_agent_api_key),
956
+ ) -> AgentVerifyRedactionResponse:
957
+ from tools.simplified_api import run_verify_redaction_coverage
958
+
959
+ review = _path_must_be_allowed_file(body.review_csv_path)
960
+ ocr_words = _path_must_be_allowed_file(body.ocr_words_csv_path)
961
+ redacted = None
962
+ if body.redacted_pdf_path:
963
+ redacted = _path_must_be_allowed_file(body.redacted_pdf_path)
964
+ try:
965
+ report, pruned_csv_path, prune_log = run_verify_redaction_coverage(
966
+ review_csv_path=review,
967
+ ocr_words_csv_path=ocr_words,
968
+ must_redact=body.must_redact,
969
+ must_not_redact=body.must_not_redact,
970
+ redacted_pdf_path=redacted,
971
+ total_pages=body.total_pages,
972
+ min_word_length=body.min_word_length,
973
+ sample_pixels=body.sample_pixels,
974
+ auto_prune_suspicious=body.auto_prune_suspicious,
975
+ pruned_output_path=body.pruned_output_path,
976
+ )
977
+ except ValueError as e:
978
+ raise HTTPException(status_code=400, detail=str(e)) from e
979
+ except Exception as e:
980
+ raise HTTPException(
981
+ status_code=500, detail=f"verify_redaction_coverage failed: {e}"
982
+ ) from e
983
+ return AgentVerifyRedactionResponse(
984
+ status="completed",
985
+ coverage_pass=bool(report.get("pass_strict", report.get("pass"))),
986
+ coverage_pass_strict=bool(report.get("pass_strict", report.get("pass"))),
987
+ coverage_pass_with_cleanup=bool(report.get("pass_with_cleanup")),
988
+ pruned_csv_path=pruned_csv_path,
989
+ prune_log=prune_log,
990
+ report=report,
991
+ )
992
+
993
+
994
+ @router.post(
995
+ "/word_level_ocr_text_search",
996
+ response_model=AgentWordLevelOcrSearchResponse,
997
+ summary="word_level_ocr_text_search (headless OCR CSV search)",
998
+ )
999
+ def post_word_level_ocr_text_search(
1000
+ body: AgentWordLevelOcrSearchRequest,
1001
+ _: None = Depends(_optional_agent_api_key),
1002
+ ) -> AgentWordLevelOcrSearchResponse:
1003
+ from tools.simplified_api import run_word_level_ocr_text_search_api
1004
+
1005
+ ocr_words = _path_must_be_allowed_file(body.ocr_words_csv_path)
1006
+ review = None
1007
+ if body.review_csv_path:
1008
+ review = _path_must_be_allowed_file(body.review_csv_path)
1009
+ try:
1010
+ result = run_word_level_ocr_text_search_api(
1011
+ ocr_words_csv_path=ocr_words,
1012
+ search_text=body.search_text,
1013
+ similarity_threshold=body.similarity_threshold,
1014
+ use_regex=body.use_regex,
1015
+ review_csv_path=review,
1016
+ )
1017
+ except ValueError as e:
1018
+ raise HTTPException(status_code=400, detail=str(e)) from e
1019
+ except Exception as e:
1020
+ raise HTTPException(
1021
+ status_code=500, detail=f"word_level_ocr_text_search failed: {e}"
1022
+ ) from e
1023
+ return AgentWordLevelOcrSearchResponse(status="completed", result=result)
1024
+
1025
+
1026
+ @router.get("/operations")
1027
+ def list_operations() -> dict[str, Any]:
1028
+ return {
1029
+ "gradio_api_names": list(GRADIO_API_NAMES),
1030
+ "gradio_session_state_endpoints": {
1031
+ "description": (
1032
+ "These api_name values are exposed on the Gradio HTTP API but return "
1033
+ "501 on /agent because they depend on in-memory Gradio state."
1034
+ ),
1035
+ "discover_schema": "GET /gradio_api/info",
1036
+ "call_pattern": 'POST /gradio_api/call/<api_name> with JSON body {"data": [...]}',
1037
+ "names": [
1038
+ "load_and_prepare_documents_or_data",
1039
+ ],
1040
+ },
1041
+ "routes": [
1042
+ {
1043
+ "gradio_api_name": "redact_document",
1044
+ "method": "POST",
1045
+ "path": "/agent/redact_document",
1046
+ "implementation": "cli_redact task redact",
1047
+ "notes": {
1048
+ "ocr_method": [
1049
+ "Local OCR",
1050
+ "AWS Textract",
1051
+ "Local text",
1052
+ ],
1053
+ "chosen_local_ocr_model_override": LOCAL_OCR_MODEL_OPTIONS,
1054
+ "pii_detector_recommended": [
1055
+ LOCAL_PII_OPTION,
1056
+ AWS_PII_OPTION,
1057
+ AWS_LLM_PII_OPTION,
1058
+ INFERENCE_SERVER_PII_OPTION,
1059
+ LOCAL_TRANSFORMERS_LLM_PII_OPTION,
1060
+ "None",
1061
+ ],
1062
+ },
1063
+ },
1064
+ {
1065
+ "gradio_api_name": "redact_data",
1066
+ "method": "POST",
1067
+ "path": "/agent/redact_data",
1068
+ "implementation": "cli_redact task redact",
1069
+ "notes": {
1070
+ "ocr_method": [
1071
+ "Local OCR",
1072
+ "AWS Textract",
1073
+ "Local text",
1074
+ ],
1075
+ "chosen_local_ocr_model_override": LOCAL_OCR_MODEL_OPTIONS,
1076
+ "pii_detector_recommended": [
1077
+ LOCAL_PII_OPTION,
1078
+ AWS_PII_OPTION,
1079
+ AWS_LLM_PII_OPTION,
1080
+ INFERENCE_SERVER_PII_OPTION,
1081
+ LOCAL_TRANSFORMERS_LLM_PII_OPTION,
1082
+ "None",
1083
+ ],
1084
+ },
1085
+ },
1086
+ {
1087
+ "gradio_api_name": "find_duplicate_pages",
1088
+ "method": "POST",
1089
+ "path": "/agent/find_duplicate_pages",
1090
+ "implementation": "cli_redact deduplicate pages",
1091
+ },
1092
+ {
1093
+ "gradio_api_name": "find_duplicate_tabular",
1094
+ "method": "POST",
1095
+ "path": "/agent/find_duplicate_tabular",
1096
+ "implementation": "cli_redact deduplicate tabular",
1097
+ },
1098
+ {
1099
+ "gradio_api_name": "summarise_document",
1100
+ "method": "POST",
1101
+ "path": "/agent/summarise_document",
1102
+ "implementation": "cli_redact task summarise",
1103
+ },
1104
+ {
1105
+ "gradio_api_name": "combine_review_pdfs",
1106
+ "method": "POST",
1107
+ "path": "/agent/combine_review_pdfs",
1108
+ "implementation": "cli_redact combine_review_pdfs",
1109
+ },
1110
+ {
1111
+ "gradio_api_name": "export_review_redaction_overlay",
1112
+ "method": "POST",
1113
+ "path": "/agent/export_review_redaction_overlay",
1114
+ "implementation": "visualise_review_redaction_boxes",
1115
+ },
1116
+ {
1117
+ "gradio_api_name": "export_review_page_ocr_visualisation",
1118
+ "method": "POST",
1119
+ "path": "/agent/export_review_page_ocr_visualisation",
1120
+ "implementation": "visualise_ocr_words_bounding_boxes",
1121
+ },
1122
+ {
1123
+ "gradio_api_name": "combine_review_csvs",
1124
+ "method": "POST",
1125
+ "path": "/agent/combine_review_csvs",
1126
+ "implementation": "helper merge_csv_files",
1127
+ },
1128
+ {
1129
+ "gradio_api_name": "load_and_prepare_documents_or_data",
1130
+ "method": "POST",
1131
+ "path": "/agent/load_and_prepare_documents_or_data",
1132
+ "implementation": "not_implemented_http",
1133
+ },
1134
+ {
1135
+ "gradio_api_name": "apply_review_redactions",
1136
+ "method": "POST",
1137
+ "path": "/agent/apply_review_redactions",
1138
+ "implementation": "tools.simplified_api.run_apply_review_redactions",
1139
+ },
1140
+ {
1141
+ "gradio_api_name": "verify_redaction_coverage",
1142
+ "method": "POST",
1143
+ "path": "/agent/verify_redaction_coverage",
1144
+ "implementation": "tools.verify_redaction_coverage.verify_redaction_coverage",
1145
+ "notes": {
1146
+ "purpose": "Pass 1 programmatic QA — pass_strict (policy), pass_with_cleanup (+ suspicious rows), optional prune and text/pixel checks.",
1147
+ "must_redact": "list of regex strings",
1148
+ "must_not_redact": "list of regex strings",
1149
+ "auto_prune_suspicious": "remove short OCR-fragment rows before reporting",
1150
+ "pages_flagged_for_vlm": "policy/visual failures only",
1151
+ "pages_needing_csv_cleanup": "suspicious rows — prune, not VLM",
1152
+ "leak_likely_causes": "per-page hints when text_layer_leaks (coord_not_normalized, missing_page_boxes, etc.) — not a broken /review_apply",
1153
+ },
1154
+ },
1155
+ {
1156
+ "gradio_api_name": "word_level_ocr_text_search",
1157
+ "method": "POST",
1158
+ "path": "/agent/word_level_ocr_text_search",
1159
+ "implementation": "tools.verify_redaction_coverage.run_word_level_ocr_text_search",
1160
+ },
1161
+ ],
1162
+ }
1163
+
1164
+
1165
+ @router.get("/health")
1166
+ def agent_health() -> dict[str, str]:
1167
+ return {"status": "ok", "service": "agent"}
app.py ADDED
The diff for this file is too large to render. See raw diff
 
cdk/__init__.py ADDED
File without changes
cdk/app.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from aws_cdk import App, Environment
4
+ from cdk_appregistry import register_doc_redaction_application
5
+ from cdk_config import (
6
+ ALB_NAME,
7
+ APPREGISTRY_APPLICATION_NAME,
8
+ APPREGISTRY_ATTRIBUTE_GROUP_NAME,
9
+ APPREGISTRY_DESCRIPTION,
10
+ APPREGISTRY_REPOSITORY_URL,
11
+ APPREGISTRY_STACK_NAME,
12
+ AWS_ACCOUNT_ID,
13
+ AWS_REGION,
14
+ CDK_CONTEXT_FILE,
15
+ CDK_PREFIX,
16
+ ENABLE_APPREGISTRY,
17
+ RUN_USEAST_STACK,
18
+ USE_CLOUDFRONT,
19
+ )
20
+ from cdk_functions import (
21
+ create_basic_config_env,
22
+ load_context_from_file,
23
+ log_aws_credential_context,
24
+ purge_cdk_lookup_context,
25
+ )
26
+ from cdk_stack import CdkStack, CdkStackCloudfront # , CdkStackMain
27
+ from check_resources import CONTEXT_FILE, check_and_set_context
28
+
29
+ # Initialize the CDK app
30
+ app = App()
31
+
32
+ log_aws_credential_context(
33
+ expected_account_id=AWS_ACCOUNT_ID,
34
+ expected_region=AWS_REGION,
35
+ )
36
+
37
+ # Drop stale CDK lookup cache entries (require bootstrap lookup role in target account).
38
+ purge_cdk_lookup_context(CDK_CONTEXT_FILE)
39
+
40
+ # --- Pre-check context (boto3) — written to precheck.context.json, NOT cdk.context.json ---
41
+ print(f"Pre-check context file: {CONTEXT_FILE}")
42
+ print(f"CDK lookup cache file: {CDK_CONTEXT_FILE}")
43
+ if os.path.basename(CONTEXT_FILE.replace("\\", "/")) == os.path.basename(
44
+ CDK_CONTEXT_FILE.replace("\\", "/")
45
+ ):
46
+ raise RuntimeError(
47
+ f"CONTEXT_FILE and CDK_CONTEXT_FILE must differ (got '{CONTEXT_FILE}' for both). "
48
+ "Set CONTEXT_FILE=precheck.context.json in config/cdk_config.env."
49
+ )
50
+
51
+ print("Running pre-check script to generate application context...")
52
+ try:
53
+ check_and_set_context()
54
+ if not os.path.exists(CONTEXT_FILE):
55
+ raise RuntimeError(
56
+ f"check_and_set_context() finished, but {CONTEXT_FILE} was not created."
57
+ )
58
+ print(f"Context generated successfully at {CONTEXT_FILE}.")
59
+ except Exception as e:
60
+ raise RuntimeError(f"Failed to generate context via check_and_set_context(): {e}")
61
+
62
+ # Pre-check must not repopulate CDK lookup keys; purge again if paths were ever shared.
63
+ purge_cdk_lookup_context(CDK_CONTEXT_FILE)
64
+
65
+ if os.path.exists(CONTEXT_FILE):
66
+ load_context_from_file(app, CONTEXT_FILE)
67
+ else:
68
+ raise RuntimeError(f"Could not find {CONTEXT_FILE}.")
69
+
70
+ create_basic_config_env("config")
71
+
72
+ aws_env_regional = Environment(account=AWS_ACCOUNT_ID, region=AWS_REGION)
73
+
74
+ regional_stack = CdkStack(
75
+ app, "RedactionStack", env=aws_env_regional, cross_region_references=True
76
+ )
77
+ regional_stack.termination_protection = True
78
+
79
+ if ENABLE_APPREGISTRY == "True":
80
+ # Use pre-check context only — not regional_stack.params (avoids AppRegistry
81
+ # -> RedactionStack dependency cycle during synth).
82
+ _alb_dns_context = app.node.try_get_context(f"dns:{ALB_NAME}")
83
+ _alb_dns_name = (
84
+ _alb_dns_context.strip()
85
+ if isinstance(_alb_dns_context, str) and _alb_dns_context.strip()
86
+ else None
87
+ )
88
+ appregistry_stack = register_doc_redaction_application(
89
+ app,
90
+ aws_account_id=AWS_ACCOUNT_ID,
91
+ aws_region=AWS_REGION,
92
+ application_name=APPREGISTRY_APPLICATION_NAME,
93
+ application_description=APPREGISTRY_DESCRIPTION,
94
+ appregistry_stack_name=APPREGISTRY_STACK_NAME,
95
+ attribute_group_name=APPREGISTRY_ATTRIBUTE_GROUP_NAME,
96
+ repository_url=APPREGISTRY_REPOSITORY_URL,
97
+ cdk_prefix=CDK_PREFIX,
98
+ use_cloudfront=USE_CLOUDFRONT,
99
+ alb_dns_name=_alb_dns_name,
100
+ )
101
+ appregistry_stack.termination_protection = True
102
+
103
+ if USE_CLOUDFRONT == "True" and RUN_USEAST_STACK == "True":
104
+ aws_env_us_east_1 = Environment(account=AWS_ACCOUNT_ID, region="us-east-1")
105
+
106
+ cloudfront_stack = CdkStackCloudfront(
107
+ app,
108
+ "RedactionStackCloudfront",
109
+ env=aws_env_us_east_1,
110
+ alb_arn=regional_stack.params["alb_arn_output"],
111
+ alb_sec_group_id=regional_stack.params["alb_security_group_id"],
112
+ alb_dns_name=regional_stack.params["alb_dns_name"],
113
+ cross_region_references=True,
114
+ )
115
+
116
+ # CDK CLI invokes this script and expects a cloud assembly in cdk.out.
117
+ # Without app.synth(), Python defines constructs but never writes manifest.json
118
+ # (ENOENT on deploy). See: https://github.com/aws/aws-cdk/issues/11023
119
+ app.synth()
cdk/cdk.json.example ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "app": "python app.py",
3
+ "output": "cdk.out",
4
+ "context": {
5
+ "@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": false
6
+ }
7
+ }
cdk/cdk_appregistry.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AWS Console myApplications (Service Catalog AppRegistry) integration."""
2
+
3
+ from aws_cdk import App, Environment
4
+ from aws_cdk.aws_servicecatalogappregistry_alpha import (
5
+ ApplicationAssociator,
6
+ TargetApplication,
7
+ )
8
+
9
+
10
+ def register_doc_redaction_application(
11
+ app: App,
12
+ *,
13
+ aws_account_id: str,
14
+ aws_region: str,
15
+ application_name: str,
16
+ application_description: str,
17
+ appregistry_stack_name: str,
18
+ attribute_group_name: str,
19
+ repository_url: str,
20
+ cdk_prefix: str,
21
+ use_cloudfront: str,
22
+ alb_dns_name: str | None = None,
23
+ ) -> ApplicationAssociator:
24
+ """
25
+ Register regional CDK stacks with AWS Console myApplications.
26
+
27
+ Only stacks in ``aws_region`` are associated (phase 1). Cross-region stacks
28
+ such as RedactionStackCloudfront (us-east-1) are not included.
29
+
30
+ ``alb_dns_name`` must be a plain string (e.g. from pre-check context). Do not
31
+ pass a CloudFormation token from RedactionStack or synth will fail with a
32
+ dependency cycle against the associator stack.
33
+ """
34
+ associator = ApplicationAssociator(
35
+ app,
36
+ "DocRedactionAppRegistry",
37
+ applications=[
38
+ TargetApplication.create_application_stack(
39
+ application_name=application_name,
40
+ application_description=application_description,
41
+ stack_name=appregistry_stack_name,
42
+ env=Environment(account=aws_account_id, region=aws_region),
43
+ )
44
+ ],
45
+ )
46
+
47
+ attributes = {
48
+ "repository": repository_url,
49
+ "cdkPrefix": cdk_prefix,
50
+ "awsRegion": aws_region,
51
+ "useCloudFront": use_cloudfront,
52
+ "cloudFrontInAppRegistry": "false",
53
+ "cloudFrontNote": (
54
+ "CloudFront/WAF (RedactionStackCloudfront) is in us-east-1 and is "
55
+ "not linked to this myApplications entry in phase 1. View it in "
56
+ "CloudFormation (us-east-1) or the CloudFront console."
57
+ ),
58
+ }
59
+ if alb_dns_name:
60
+ attributes["albDnsName"] = alb_dns_name
61
+
62
+ associator.app_registry_application.add_attribute_group(
63
+ "DocRedactionAttributeGroup",
64
+ attribute_group_name=attribute_group_name,
65
+ description="doc_redaction deployment metadata",
66
+ attributes=attributes,
67
+ )
68
+
69
+ return associator
cdk/cdk_config.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tempfile
3
+
4
+ from dotenv import load_dotenv
5
+
6
+ # Set or retrieve configuration variables for CDK redaction deployment
7
+
8
+
9
+ def convert_string_to_boolean(value: str) -> bool:
10
+ """Convert string to boolean, handling various formats."""
11
+ if isinstance(value, bool):
12
+ return value
13
+ elif value in ["True", "1", "true", "TRUE"]:
14
+ return True
15
+ elif value in ["False", "0", "false", "FALSE"]:
16
+ return False
17
+ else:
18
+ raise ValueError(f"Invalid boolean value: {value}")
19
+
20
+
21
+ def get_or_create_env_var(var_name: str, default_value: str, print_val: bool = False):
22
+ """
23
+ Get an environmental variable, and set it to a default value if it doesn't exist
24
+ """
25
+ # Get the environment variable if it exists
26
+ value = os.environ.get(var_name)
27
+
28
+ # If it doesn't exist, set the environment variable to the default value
29
+ if value is None:
30
+ os.environ[var_name] = default_value
31
+ value = default_value
32
+
33
+ if print_val is True:
34
+ print(f"The value of {var_name} is {value}")
35
+
36
+ return value
37
+
38
+
39
+ def ensure_folder_exists(output_folder: str):
40
+ """Checks if the specified folder exists, creates it if not."""
41
+
42
+ if not os.path.exists(output_folder):
43
+ # Create the folder if it doesn't exist
44
+ os.makedirs(output_folder, exist_ok=True)
45
+ print(f"Created the {output_folder} folder.")
46
+ else:
47
+ print(f"The {output_folder} folder already exists.")
48
+
49
+
50
+ def add_folder_to_path(folder_path: str):
51
+ """
52
+ Check if a folder exists on your system. If so, get the absolute path and then add it to the system Path variable if it doesn't already exist. Function is only relevant for locally-created executable files based on this app (when using pyinstaller it creates a _internal folder that contains tesseract and poppler. These need to be added to the system path to enable the app to run)
53
+ """
54
+
55
+ if os.path.exists(folder_path) and os.path.isdir(folder_path):
56
+ print(folder_path, "folder exists.")
57
+
58
+ # Resolve relative path to absolute path
59
+ absolute_path = os.path.abspath(folder_path)
60
+
61
+ current_path = os.environ["PATH"]
62
+ if absolute_path not in current_path.split(os.pathsep):
63
+ full_path_extension = absolute_path + os.pathsep + current_path
64
+ os.environ["PATH"] = full_path_extension
65
+ # print(f"Updated PATH with: ", full_path_extension)
66
+ else:
67
+ print(f"Directory {folder_path} already exists in PATH.")
68
+ else:
69
+ print(f"Folder not found at {folder_path} - not added to PATH")
70
+
71
+
72
+ ###
73
+ # LOAD CONFIG FROM ENV FILE
74
+ ###
75
+ CONFIG_FOLDER = get_or_create_env_var("CONFIG_FOLDER", "config/")
76
+
77
+ ensure_folder_exists(CONFIG_FOLDER)
78
+
79
+ # If you have an aws_config env file in the config folder, you can load in app variables this way, e.g. 'config/cdk_config.env'
80
+ CDK_CONFIG_PATH = get_or_create_env_var(
81
+ "CDK_CONFIG_PATH", "config/cdk_config.env"
82
+ ) # e.g. config/cdk_config.env
83
+
84
+ if CDK_CONFIG_PATH:
85
+ if os.path.exists(CDK_CONFIG_PATH):
86
+ print(f"Loading CDK variables from config file {CDK_CONFIG_PATH}")
87
+ load_dotenv(CDK_CONFIG_PATH)
88
+ else:
89
+ print("CDK config file not found at location:", CDK_CONFIG_PATH)
90
+
91
+ ###
92
+ # AWS OPTIONS
93
+ ###
94
+ AWS_REGION = get_or_create_env_var("AWS_REGION", "")
95
+ AWS_ACCOUNT_ID = get_or_create_env_var("AWS_ACCOUNT_ID", "")
96
+
97
+ ###
98
+ # CDK OPTIONS
99
+ ###
100
+ CDK_PREFIX = get_or_create_env_var("CDK_PREFIX", "")
101
+
102
+ # AWS Console myApplications (Service Catalog AppRegistry)
103
+ ENABLE_APPREGISTRY = get_or_create_env_var("ENABLE_APPREGISTRY", "True")
104
+ APPREGISTRY_APPLICATION_NAME = get_or_create_env_var(
105
+ "APPREGISTRY_APPLICATION_NAME", f"{CDK_PREFIX}doc-redaction"
106
+ )
107
+ APPREGISTRY_DESCRIPTION = get_or_create_env_var(
108
+ "APPREGISTRY_DESCRIPTION",
109
+ "PII document redaction app (ALB, ECS Fargate, Cognito, S3)",
110
+ )
111
+ APPREGISTRY_STACK_NAME = get_or_create_env_var(
112
+ "APPREGISTRY_STACK_NAME", f"{CDK_PREFIX}AppRegistryStack"
113
+ )
114
+ APPREGISTRY_ATTRIBUTE_GROUP_NAME = get_or_create_env_var(
115
+ "APPREGISTRY_ATTRIBUTE_GROUP_NAME",
116
+ f"{APPREGISTRY_APPLICATION_NAME}-metadata",
117
+ )
118
+ APPREGISTRY_REPOSITORY_URL = get_or_create_env_var(
119
+ "APPREGISTRY_REPOSITORY_URL",
120
+ "https://github.com/seanpedrick-case/doc_redaction",
121
+ )
122
+
123
+ _precheck_context_file = get_or_create_env_var("CONTEXT_FILE", "precheck.context.json")
124
+ # Never write boto3 pre-check output into CDK's lookup cache file (causes stale
125
+ # vpc-provider / load-balancer entries and wrong-account lookup validation errors).
126
+ if os.path.basename(_precheck_context_file.replace("\\", "/")) == "cdk.context.json":
127
+ print(
128
+ "WARNING: CONTEXT_FILE must not be 'cdk.context.json' (that file is CDK's "
129
+ "lookup cache). Using 'precheck.context.json' instead. Update "
130
+ "config/cdk_config.env and remove CONTEXT_FILE=cdk.context.json if set."
131
+ )
132
+ _precheck_context_file = "precheck.context.json"
133
+ CONTEXT_FILE = _precheck_context_file
134
+ CDK_CONTEXT_FILE = get_or_create_env_var("CDK_CONTEXT_FILE", "cdk.context.json")
135
+ CDK_FOLDER = get_or_create_env_var(
136
+ "CDK_FOLDER", ""
137
+ ) # FULL_PATH_TO_CDK_FOLDER_HERE (with forward slash)
138
+ RUN_USEAST_STACK = get_or_create_env_var("RUN_USEAST_STACK", "False")
139
+
140
+ ### VPC and connections
141
+ VPC_NAME = get_or_create_env_var("VPC_NAME", "")
142
+ NEW_VPC_DEFAULT_NAME = get_or_create_env_var("NEW_VPC_DEFAULT_NAME", f"{CDK_PREFIX}vpc")
143
+ NEW_VPC_CIDR = get_or_create_env_var("NEW_VPC_CIDR", "") # "10.0.0.0/24"
144
+
145
+
146
+ EXISTING_IGW_ID = get_or_create_env_var("EXISTING_IGW_ID", "")
147
+ SINGLE_NAT_GATEWAY_ID = get_or_create_env_var("SINGLE_NAT_GATEWAY_ID", "")
148
+
149
+ ### SUBNETS / ROUTE TABLES / NAT GATEWAY
150
+ PUBLIC_SUBNETS_TO_USE = get_or_create_env_var(
151
+ "PUBLIC_SUBNETS_TO_USE", ""
152
+ ) # e.g. ['PublicSubnet1', 'PublicSubnet2']
153
+ PUBLIC_SUBNET_CIDR_BLOCKS = get_or_create_env_var(
154
+ "PUBLIC_SUBNET_CIDR_BLOCKS", ""
155
+ ) # e.g. ["10.0.1.0/24", "10.0.2.0/24"]
156
+ PUBLIC_SUBNET_AVAILABILITY_ZONES = get_or_create_env_var(
157
+ "PUBLIC_SUBNET_AVAILABILITY_ZONES", ""
158
+ ) # e.g. ["eu-east-1b", "eu-east1b"]
159
+
160
+ PRIVATE_SUBNETS_TO_USE = get_or_create_env_var(
161
+ "PRIVATE_SUBNETS_TO_USE", ""
162
+ ) # e.g. ['PrivateSubnet1', 'PrivateSubnet2']
163
+ PRIVATE_SUBNET_CIDR_BLOCKS = get_or_create_env_var(
164
+ "PRIVATE_SUBNET_CIDR_BLOCKS", ""
165
+ ) # e.g. ["10.0.1.0/24", "10.0.2.0/24"]
166
+ PRIVATE_SUBNET_AVAILABILITY_ZONES = get_or_create_env_var(
167
+ "PRIVATE_SUBNET_AVAILABILITY_ZONES", ""
168
+ ) # e.g. ["eu-east-1b", "eu-east1b"]
169
+
170
+ ROUTE_TABLE_BASE_NAME = get_or_create_env_var(
171
+ "ROUTE_TABLE_BASE_NAME", f"{CDK_PREFIX}PrivateRouteTable"
172
+ )
173
+ NAT_GATEWAY_EIP_NAME = get_or_create_env_var(
174
+ "NAT_GATEWAY_EIP_NAME", f"{CDK_PREFIX}NatGatewayEip"
175
+ )
176
+ NAT_GATEWAY_NAME = get_or_create_env_var("NAT_GATEWAY_NAME", f"{CDK_PREFIX}NatGateway")
177
+
178
+ # IAM roles
179
+ AWS_MANAGED_TASK_ROLES_LIST = get_or_create_env_var(
180
+ "AWS_MANAGED_TASK_ROLES_LIST",
181
+ '["AmazonCognitoReadOnly", "service-role/AmazonECSTaskExecutionRolePolicy", "AmazonS3FullAccess", "AmazonTextractFullAccess", "ComprehendReadOnly", "AmazonDynamoDBFullAccess", "service-role/AWSAppSyncPushToCloudWatchLogs", "AmazonBedrockFullAccess"]',
182
+ )
183
+ POLICY_FILE_LOCATIONS = get_or_create_env_var(
184
+ "POLICY_FILE_LOCATIONS", ""
185
+ ) # e.g. '["config/sts_permissions.json"]'
186
+ POLICY_FILE_ARNS = get_or_create_env_var("POLICY_FILE_ARNS", "")
187
+
188
+ # GITHUB REPO
189
+ GITHUB_REPO_USERNAME = get_or_create_env_var("GITHUB_REPO_USERNAME", "seanpedrick-case")
190
+ GITHUB_REPO_NAME = get_or_create_env_var("GITHUB_REPO_NAME", "doc_redaction")
191
+ GITHUB_REPO_BRANCH = get_or_create_env_var("GITHUB_REPO_BRANCH", "main")
192
+
193
+ ### CODEBUILD
194
+ CODEBUILD_ROLE_NAME = get_or_create_env_var(
195
+ "CODEBUILD_ROLE_NAME", f"{CDK_PREFIX}CodeBuildRole"
196
+ )
197
+ CODEBUILD_PROJECT_NAME = get_or_create_env_var(
198
+ "CODEBUILD_PROJECT_NAME", f"{CDK_PREFIX}CodeBuildProject"
199
+ )
200
+
201
+ ### ECR
202
+ ECR_REPO_NAME = get_or_create_env_var(
203
+ "ECR_REPO_NAME", "doc-redaction"
204
+ ) # Beware - cannot have underscores and must be lower case
205
+ ECR_CDK_REPO_NAME = get_or_create_env_var(
206
+ "ECR_CDK_REPO_NAME", f"{CDK_PREFIX}{ECR_REPO_NAME}".lower()
207
+ )
208
+
209
+ ### S3
210
+ S3_LOG_CONFIG_BUCKET_NAME = get_or_create_env_var(
211
+ "S3_LOG_CONFIG_BUCKET_NAME", f"{CDK_PREFIX}s3-logs".lower()
212
+ ) # S3 bucket names need to be lower case
213
+ S3_OUTPUT_BUCKET_NAME = get_or_create_env_var(
214
+ "S3_OUTPUT_BUCKET_NAME", f"{CDK_PREFIX}s3-output".lower()
215
+ )
216
+
217
+ ### KMS KEYS FOR S3 AND SECRETS MANAGER
218
+ USE_CUSTOM_KMS_KEY = get_or_create_env_var("USE_CUSTOM_KMS_KEY", "1")
219
+ CUSTOM_KMS_KEY_NAME = get_or_create_env_var(
220
+ "CUSTOM_KMS_KEY_NAME", f"alias/{CDK_PREFIX}kms-key".lower()
221
+ )
222
+
223
+ ### ECS
224
+ FARGATE_TASK_DEFINITION_NAME = get_or_create_env_var(
225
+ "FARGATE_TASK_DEFINITION_NAME", f"{CDK_PREFIX}FargateTaskDefinition"
226
+ )
227
+ TASK_DEFINITION_FILE_LOCATION = get_or_create_env_var(
228
+ "TASK_DEFINITION_FILE_LOCATION", CDK_FOLDER + CONFIG_FOLDER + "task_definition.json"
229
+ )
230
+
231
+ CLUSTER_NAME = get_or_create_env_var("CLUSTER_NAME", f"{CDK_PREFIX}Cluster")
232
+ ECS_SERVICE_NAME = get_or_create_env_var("ECS_SERVICE_NAME", f"{CDK_PREFIX}ECSService")
233
+ ECS_TASK_ROLE_NAME = get_or_create_env_var(
234
+ "ECS_TASK_ROLE_NAME", f"{CDK_PREFIX}TaskRole"
235
+ )
236
+ ECS_TASK_EXECUTION_ROLE_NAME = get_or_create_env_var(
237
+ "ECS_TASK_EXECUTION_ROLE_NAME", f"{CDK_PREFIX}ExecutionRole"
238
+ )
239
+ ECS_SECURITY_GROUP_NAME = get_or_create_env_var(
240
+ "ECS_SECURITY_GROUP_NAME", f"{CDK_PREFIX}SecurityGroupECS"
241
+ )
242
+ ECS_LOG_GROUP_NAME = get_or_create_env_var(
243
+ "ECS_LOG_GROUP_NAME", f"/ecs/{ECS_SERVICE_NAME}-logs".lower()
244
+ )
245
+
246
+ ECS_TASK_CPU_SIZE = get_or_create_env_var("ECS_TASK_CPU_SIZE", "1024")
247
+ ECS_TASK_MEMORY_SIZE = get_or_create_env_var("ECS_TASK_MEMORY_SIZE", "4096")
248
+ ECS_USE_FARGATE_SPOT = get_or_create_env_var("USE_FARGATE_SPOT", "False")
249
+ ECS_READ_ONLY_FILE_SYSTEM = get_or_create_env_var("ECS_READ_ONLY_FILE_SYSTEM", "True")
250
+
251
+ ### Cognito
252
+ COGNITO_USER_POOL_NAME = get_or_create_env_var(
253
+ "COGNITO_USER_POOL_NAME", f"{CDK_PREFIX}UserPool"
254
+ )
255
+ COGNITO_USER_POOL_CLIENT_NAME = get_or_create_env_var(
256
+ "COGNITO_USER_POOL_CLIENT_NAME", f"{CDK_PREFIX}UserPoolClient"
257
+ )
258
+ COGNITO_USER_POOL_CLIENT_SECRET_NAME = get_or_create_env_var(
259
+ "COGNITO_USER_POOL_CLIENT_SECRET_NAME", f"{CDK_PREFIX}ParamCognitoSecret"
260
+ )
261
+ COGNITO_USER_POOL_DOMAIN_PREFIX = get_or_create_env_var(
262
+ "COGNITO_USER_POOL_DOMAIN_PREFIX", "redaction-app-domain"
263
+ ) # Should change this to something unique or you'll probably hit an error
264
+
265
+ COGNITO_REFRESH_TOKEN_VALIDITY = int(
266
+ get_or_create_env_var("COGNITO_REFRESH_TOKEN_VALIDITY", "480")
267
+ ) # Minutes
268
+ COGNITO_ID_TOKEN_VALIDITY = int(
269
+ get_or_create_env_var("COGNITO_ID_TOKEN_VALIDITY", "60")
270
+ ) # Minutes
271
+ COGNITO_ACCESS_TOKEN_VALIDITY = int(
272
+ get_or_create_env_var("COGNITO_ACCESS_TOKEN_VALIDITY", "60")
273
+ ) # Minutes
274
+
275
+ # Application load balancer
276
+ ALB_NAME = get_or_create_env_var(
277
+ "ALB_NAME", f"{CDK_PREFIX}Alb"[-32:]
278
+ ) # Application load balancer name can be max 32 characters, so taking the last 32 characters of the suggested name
279
+ ALB_NAME_SECURITY_GROUP_NAME = get_or_create_env_var(
280
+ "ALB_SECURITY_GROUP_NAME", f"{CDK_PREFIX}SecurityGroupALB"
281
+ )
282
+ ALB_TARGET_GROUP_NAME = get_or_create_env_var(
283
+ "ALB_TARGET_GROUP_NAME", f"{CDK_PREFIX}-tg"[-32:]
284
+ ) # Max 32 characters
285
+ EXISTING_LOAD_BALANCER_ARN = get_or_create_env_var("EXISTING_LOAD_BALANCER_ARN", "")
286
+ EXISTING_LOAD_BALANCER_DNS = get_or_create_env_var(
287
+ "EXISTING_LOAD_BALANCER_DNS", "placeholder_load_balancer_dns.net"
288
+ )
289
+
290
+ ## CLOUDFRONT
291
+ USE_CLOUDFRONT = get_or_create_env_var("USE_CLOUDFRONT", "True")
292
+ CLOUDFRONT_PREFIX_LIST_ID = get_or_create_env_var(
293
+ "CLOUDFRONT_PREFIX_LIST_ID", "pl-93a247fa"
294
+ )
295
+ CLOUDFRONT_GEO_RESTRICTION = get_or_create_env_var(
296
+ "CLOUDFRONT_GEO_RESTRICTION", ""
297
+ ) # A country that Cloudfront restricts access to. See here: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/georestrictions.html
298
+ CLOUDFRONT_DISTRIBUTION_NAME = get_or_create_env_var(
299
+ "CLOUDFRONT_DISTRIBUTION_NAME", f"{CDK_PREFIX}CfDist"
300
+ )
301
+ CLOUDFRONT_DOMAIN = get_or_create_env_var(
302
+ "CLOUDFRONT_DOMAIN", "cloudfront_placeholder.net"
303
+ )
304
+
305
+
306
+ # Certificate for Application load balancer (optional, for HTTPS and logins through the ALB)
307
+ ACM_SSL_CERTIFICATE_ARN = get_or_create_env_var("ACM_SSL_CERTIFICATE_ARN", "")
308
+ SSL_CERTIFICATE_DOMAIN = get_or_create_env_var(
309
+ "SSL_CERTIFICATE_DOMAIN", ""
310
+ ) # e.g. example.com or www.example.com
311
+
312
+ # This should be the CloudFront domain, the domain linked to your ACM certificate, or the DNS of your application load balancer in console afterwards
313
+ if USE_CLOUDFRONT == "True":
314
+ COGNITO_REDIRECTION_URL = get_or_create_env_var(
315
+ "COGNITO_REDIRECTION_URL", "https://" + CLOUDFRONT_DOMAIN
316
+ )
317
+ elif SSL_CERTIFICATE_DOMAIN:
318
+ COGNITO_REDIRECTION_URL = get_or_create_env_var(
319
+ "COGNITO_REDIRECTION_URL", "https://" + SSL_CERTIFICATE_DOMAIN
320
+ )
321
+ else:
322
+ COGNITO_REDIRECTION_URL = get_or_create_env_var(
323
+ "COGNITO_REDIRECTION_URL", "https://" + EXISTING_LOAD_BALANCER_DNS
324
+ )
325
+
326
+ # Custom headers e.g. if routing traffic through Cloudfront
327
+ CUSTOM_HEADER = get_or_create_env_var(
328
+ "CUSTOM_HEADER", ""
329
+ ) # Retrieving or setting CUSTOM_HEADER
330
+ CUSTOM_HEADER_VALUE = get_or_create_env_var(
331
+ "CUSTOM_HEADER_VALUE", ""
332
+ ) # Retrieving or setting CUSTOM_HEADER_VALUE
333
+
334
+ # Firewall on top of load balancer
335
+ LOAD_BALANCER_WEB_ACL_NAME = get_or_create_env_var(
336
+ "LOAD_BALANCER_WEB_ACL_NAME", f"{CDK_PREFIX}alb-web-acl"
337
+ )
338
+
339
+ # Firewall on top of CloudFront
340
+ WEB_ACL_NAME = get_or_create_env_var("WEB_ACL_NAME", f"{CDK_PREFIX}cloudfront-web-acl")
341
+
342
+ ###
343
+ # File I/O options
344
+ ###
345
+
346
+ OUTPUT_FOLDER = get_or_create_env_var("GRADIO_OUTPUT_FOLDER", "output/") # 'output/'
347
+ INPUT_FOLDER = get_or_create_env_var("GRADIO_INPUT_FOLDER", "input/") # 'input/'
348
+
349
+ # Allow for files to be saved in a temporary folder for increased security in some instances
350
+ if OUTPUT_FOLDER == "TEMP" or INPUT_FOLDER == "TEMP":
351
+ # Create a temporary directory
352
+ with tempfile.TemporaryDirectory() as temp_dir:
353
+ print(f"Temporary directory created at: {temp_dir}")
354
+
355
+ if OUTPUT_FOLDER == "TEMP":
356
+ OUTPUT_FOLDER = temp_dir + "/"
357
+ if INPUT_FOLDER == "TEMP":
358
+ INPUT_FOLDER = temp_dir + "/"
359
+
360
+ ###
361
+ # LOGGING OPTIONS
362
+ ###
363
+
364
+ SAVE_LOGS_TO_CSV = get_or_create_env_var("SAVE_LOGS_TO_CSV", "True")
365
+
366
+ ### DYNAMODB logs. Whether to save to DynamoDB, and the headers of the table
367
+ SAVE_LOGS_TO_DYNAMODB = get_or_create_env_var("SAVE_LOGS_TO_DYNAMODB", "True")
368
+ ACCESS_LOG_DYNAMODB_TABLE_NAME = get_or_create_env_var(
369
+ "ACCESS_LOG_DYNAMODB_TABLE_NAME", f"{CDK_PREFIX}dynamodb-access-logs".lower()
370
+ )
371
+ FEEDBACK_LOG_DYNAMODB_TABLE_NAME = get_or_create_env_var(
372
+ "FEEDBACK_LOG_DYNAMODB_TABLE_NAME", f"{CDK_PREFIX}dynamodb-feedback-logs".lower()
373
+ )
374
+ USAGE_LOG_DYNAMODB_TABLE_NAME = get_or_create_env_var(
375
+ "USAGE_LOG_DYNAMODB_TABLE_NAME", f"{CDK_PREFIX}dynamodb-usage-logs".lower()
376
+ )
377
+
378
+ ###
379
+ # REDACTION OPTIONS
380
+ ###
381
+
382
+ # Get some environment variables and Launch the Gradio app
383
+ COGNITO_AUTH = get_or_create_env_var("COGNITO_AUTH", "0")
384
+
385
+ GRADIO_SERVER_PORT = int(get_or_create_env_var("GRADIO_SERVER_PORT", "7860"))
386
+
387
+ ###
388
+ # WHOLE DOCUMENT API OPTIONS
389
+ ###
390
+
391
+ DAYS_TO_DISPLAY_WHOLE_DOCUMENT_JOBS = get_or_create_env_var(
392
+ "DAYS_TO_DISPLAY_WHOLE_DOCUMENT_JOBS", "7"
393
+ ) # How many days into the past should whole document Textract jobs be displayed? After that, the data is not deleted from the Textract jobs csv, but it is just filtered out. Included to align with S3 buckets where the file outputs will be automatically deleted after X days.
cdk/cdk_functions.py ADDED
@@ -0,0 +1,1679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ipaddress
2
+ import json
3
+ import os
4
+ from typing import Any, Dict, List, Optional, Tuple
5
+
6
+ import boto3
7
+ import pandas as pd
8
+ from aws_cdk import App, CfnOutput, CfnTag, Tags
9
+ from aws_cdk import aws_cognito as cognito
10
+ from aws_cdk import aws_ec2 as ec2
11
+ from aws_cdk import aws_elasticloadbalancingv2 as elb
12
+ from aws_cdk import aws_elasticloadbalancingv2_actions as elb_act
13
+ from aws_cdk import aws_iam as iam
14
+ from aws_cdk import aws_s3 as s3
15
+ from aws_cdk import aws_wafv2 as wafv2
16
+ from botocore.exceptions import ClientError, NoCredentialsError
17
+ from cdk_config import (
18
+ ACCESS_LOG_DYNAMODB_TABLE_NAME,
19
+ AWS_REGION,
20
+ FEEDBACK_LOG_DYNAMODB_TABLE_NAME,
21
+ NAT_GATEWAY_EIP_NAME,
22
+ POLICY_FILE_LOCATIONS,
23
+ PRIVATE_SUBNET_AVAILABILITY_ZONES,
24
+ PRIVATE_SUBNET_CIDR_BLOCKS,
25
+ PRIVATE_SUBNETS_TO_USE,
26
+ PUBLIC_SUBNET_AVAILABILITY_ZONES,
27
+ PUBLIC_SUBNET_CIDR_BLOCKS,
28
+ PUBLIC_SUBNETS_TO_USE,
29
+ S3_LOG_CONFIG_BUCKET_NAME,
30
+ S3_OUTPUT_BUCKET_NAME,
31
+ USAGE_LOG_DYNAMODB_TABLE_NAME,
32
+ )
33
+ from constructs import Construct
34
+ from dotenv import set_key
35
+
36
+ # CDK CLI stores lookup-provider results under these key prefixes in cdk.context.json.
37
+ _CDK_LOOKUP_CONTEXT_PREFIXES = (
38
+ "vpc-provider:",
39
+ "load-balancer:",
40
+ "availability-zones:",
41
+ "hosted-zone:",
42
+ "security-group:",
43
+ "key-provider:",
44
+ "ami:",
45
+ )
46
+
47
+
48
+ def purge_cdk_lookup_context(file_path: str) -> int:
49
+ """Remove stale CDK lookup cache entries that require the bootstrap lookup role."""
50
+ if not os.path.exists(file_path):
51
+ return 0
52
+ with open(file_path, "r", encoding="utf-8") as f:
53
+ context_data = json.load(f)
54
+ cleaned = {
55
+ key: value
56
+ for key, value in context_data.items()
57
+ if not key.startswith(_CDK_LOOKUP_CONTEXT_PREFIXES)
58
+ }
59
+ removed = len(context_data) - len(cleaned)
60
+ if removed:
61
+ with open(file_path, "w", encoding="utf-8") as f:
62
+ json.dump(cleaned, f, indent=2)
63
+ print(f"Removed {removed} stale CDK lookup context key(s) from {file_path}.")
64
+ return removed
65
+
66
+
67
+ def log_aws_credential_context(
68
+ expected_account_id: Optional[str] = None,
69
+ expected_region: Optional[str] = None,
70
+ ) -> Dict[str, Any]:
71
+ """
72
+ Print the active AWS identity and non-secret credential hints for CDK debugging.
73
+
74
+ Helps distinguish SSO/assumed-role sessions from long-lived access keys in
75
+ ~/.aws/credentials or environment variables.
76
+ """
77
+ profile = os.environ.get("AWS_PROFILE") or "(not set — using default profile chain)"
78
+ default_region = (
79
+ os.environ.get("AWS_REGION")
80
+ or os.environ.get("AWS_DEFAULT_REGION")
81
+ or "(not set in environment)"
82
+ )
83
+ env_access_key_set = bool(os.environ.get("AWS_ACCESS_KEY_ID"))
84
+ env_secret_key_set = bool(os.environ.get("AWS_SECRET_ACCESS_KEY"))
85
+ env_session_token_set = bool(os.environ.get("AWS_SESSION_TOKEN"))
86
+
87
+ print("\n--- AWS credential context (CDK / boto3) ---")
88
+ print(f"AWS_PROFILE: {profile}")
89
+ print(f"AWS_REGION / AWS_DEFAULT_REGION (env): {default_region}")
90
+ print(
91
+ "Environment credential variables: "
92
+ f"AWS_ACCESS_KEY_ID={'set' if env_access_key_set else 'not set'}, "
93
+ f"AWS_SECRET_ACCESS_KEY={'set' if env_secret_key_set else 'not set'}, "
94
+ f"AWS_SESSION_TOKEN={'set' if env_session_token_set else 'not set'}"
95
+ )
96
+ if expected_account_id:
97
+ print(f"Configured CDK target account (AWS_ACCOUNT_ID): {expected_account_id}")
98
+ if expected_region:
99
+ print(f"Configured CDK target region (AWS_REGION): {expected_region}")
100
+
101
+ session = boto3.Session()
102
+ active_profile = session.profile_name or "(default)"
103
+ print(f"boto3 session profile: {active_profile}")
104
+ print(f"boto3 session region: {session.region_name or '(not set)'}")
105
+
106
+ credentials = session.get_credentials()
107
+ credential_summary: Dict[str, Any] = {
108
+ "profile": profile,
109
+ "session_profile": active_profile,
110
+ }
111
+
112
+ if credentials is None:
113
+ print("WARNING: No AWS credentials found in the default provider chain.")
114
+ print("--- End AWS credential context ---\n")
115
+ credential_summary["error"] = "no_credentials"
116
+ return credential_summary
117
+
118
+ frozen = credentials.get_frozen_credentials()
119
+ access_key = frozen.access_key or ""
120
+ access_key_prefix = (access_key[:4] + "...") if len(access_key) >= 4 else "(none)"
121
+ credential_summary["access_key_prefix"] = access_key_prefix
122
+
123
+ if env_access_key_set:
124
+ credential_source = "environment variables (highest precedence)"
125
+ elif access_key.startswith("AKIA"):
126
+ credential_source = "long-lived access key (likely ~/.aws/credentials [default] or named profile)"
127
+ elif access_key.startswith("ASIA"):
128
+ credential_source = "temporary credentials (SSO, assumed role, or STS session)"
129
+ else:
130
+ credential_source = (
131
+ "resolved credentials (source could not be classified from key prefix)"
132
+ )
133
+
134
+ print(f"Inferred credential type: {credential_source}")
135
+ credential_summary["inferred_credential_type"] = credential_source
136
+
137
+ if env_access_key_set and profile != "(not set — using default profile chain)":
138
+ print(
139
+ "NOTE: AWS_ACCESS_KEY_ID is set in the environment, so it overrides "
140
+ f"profile '{profile}' and SSO."
141
+ )
142
+
143
+ try:
144
+ sts = session.client("sts", region_name=session.region_name or expected_region)
145
+ identity = sts.get_caller_identity()
146
+ except (ClientError, NoCredentialsError) as exc:
147
+ print(f"WARNING: sts:GetCallerIdentity failed: {exc}")
148
+ print("--- End AWS credential context ---\n")
149
+ credential_summary["error"] = str(exc)
150
+ return credential_summary
151
+
152
+ account = identity.get("Account", "")
153
+ arn = identity.get("Arn", "")
154
+ user_id = identity.get("UserId", "")
155
+
156
+ print(f"Caller account: {account}")
157
+ print(f"Caller ARN: {arn}")
158
+ print(f"Caller UserId: {user_id}")
159
+
160
+ if ":assumed-role/" in arn:
161
+ principal_kind = "assumed IAM role (typical for SSO or role chaining)"
162
+ elif ":user/" in arn:
163
+ principal_kind = "IAM user (typical for static access keys in credentials file)"
164
+ elif ":federated-user/" in arn:
165
+ principal_kind = "federated user"
166
+ else:
167
+ principal_kind = "other IAM principal"
168
+
169
+ print(f"Principal kind: {principal_kind}")
170
+ credential_summary.update(
171
+ {
172
+ "account": account,
173
+ "arn": arn,
174
+ "user_id": user_id,
175
+ "principal_kind": principal_kind,
176
+ }
177
+ )
178
+
179
+ if expected_account_id and account and account != str(expected_account_id):
180
+ print(
181
+ "WARNING: Caller account does not match configured AWS_ACCOUNT_ID. "
182
+ "CDK will target the configured account but act as this identity — "
183
+ "deployments and lookups may fail. Set AWS_PROFILE to your SSO profile "
184
+ "and unset AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY if needed."
185
+ )
186
+ credential_summary["account_mismatch"] = True
187
+ elif expected_account_id and account == str(expected_account_id):
188
+ print("Caller account matches configured AWS_ACCOUNT_ID.")
189
+
190
+ if profile == "(not set — using default profile chain)":
191
+ print(
192
+ "TIP: Set AWS_PROFILE to your SSO profile name so Python and the CDK CLI "
193
+ "(Node) use the same session. Example: "
194
+ '$env:AWS_PROFILE = "YourSsoProfileName"'
195
+ )
196
+
197
+ print("--- End AWS credential context ---\n")
198
+ return credential_summary
199
+
200
+
201
+ # --- Function to load context from file ---
202
+ def load_context_from_file(app: App, file_path: str):
203
+ if os.path.exists(file_path):
204
+ with open(file_path, "r", encoding="utf-8") as f:
205
+ context_data = json.load(f)
206
+ for key, value in context_data.items():
207
+ app.node.set_context(key, value)
208
+ print(f"Loaded context from {file_path}")
209
+ else:
210
+ print(f"Context file not found: {file_path}")
211
+
212
+
213
+ # --- Helper to parse environment variables into lists ---
214
+ def _get_env_list(env_var_name: str) -> List[str]:
215
+ """Parses a comma-separated environment variable into a list of strings."""
216
+ value = env_var_name[1:-1].strip().replace('"', "").replace("'", "")
217
+ if not value:
218
+ return []
219
+ # Split by comma and filter out any empty strings that might result from extra commas
220
+ return [s.strip() for s in value.split(",") if s.strip()]
221
+
222
+
223
+ # 1. Try to load CIDR/AZs from environment variables
224
+ if PUBLIC_SUBNETS_TO_USE:
225
+ PUBLIC_SUBNETS_TO_USE = _get_env_list(PUBLIC_SUBNETS_TO_USE)
226
+ if PRIVATE_SUBNETS_TO_USE:
227
+ PRIVATE_SUBNETS_TO_USE = _get_env_list(PRIVATE_SUBNETS_TO_USE)
228
+
229
+ if PUBLIC_SUBNET_CIDR_BLOCKS:
230
+ PUBLIC_SUBNET_CIDR_BLOCKS = _get_env_list("PUBLIC_SUBNET_CIDR_BLOCKS")
231
+ if PUBLIC_SUBNET_AVAILABILITY_ZONES:
232
+ PUBLIC_SUBNET_AVAILABILITY_ZONES = _get_env_list("PUBLIC_SUBNET_AVAILABILITY_ZONES")
233
+ if PRIVATE_SUBNET_CIDR_BLOCKS:
234
+ PRIVATE_SUBNET_CIDR_BLOCKS = _get_env_list("PRIVATE_SUBNET_CIDR_BLOCKS")
235
+ if PRIVATE_SUBNET_AVAILABILITY_ZONES:
236
+ PRIVATE_SUBNET_AVAILABILITY_ZONES = _get_env_list(
237
+ "PRIVATE_SUBNET_AVAILABILITY_ZONES"
238
+ )
239
+
240
+ if POLICY_FILE_LOCATIONS:
241
+ POLICY_FILE_LOCATIONS = _get_env_list(POLICY_FILE_LOCATIONS)
242
+
243
+
244
+ def check_for_existing_role(role_name: str):
245
+ try:
246
+ iam = boto3.client("iam")
247
+ # iam.get_role(RoleName=role_name)
248
+
249
+ response = iam.get_role(RoleName=role_name)
250
+ role = response["Role"]["Arn"]
251
+
252
+ print("Response Role:", role)
253
+
254
+ return True, role, ""
255
+ except iam.exceptions.NoSuchEntityException:
256
+ return False, "", ""
257
+ except Exception as e:
258
+ raise Exception("Getting information on IAM role failed due to:", e)
259
+
260
+
261
+ from typing import List
262
+
263
+ # Assume POLICY_FILE_LOCATIONS is defined globally or passed as a default
264
+ # For example:
265
+ # POLICY_FILE_LOCATIONS = ["./policies/my_read_policy.json", "./policies/my_write_policy.json"]
266
+
267
+
268
+ def add_statement_to_policy(role: iam.IRole, policy_document: Dict[str, Any]):
269
+ """
270
+ Adds individual policy statements from a parsed policy document to a CDK Role.
271
+
272
+ Args:
273
+ role: The CDK Role construct to attach policies to.
274
+ policy_document: A Python dictionary representing an IAM policy document.
275
+ """
276
+ # Ensure the loaded JSON is a valid policy document structure
277
+ if "Statement" not in policy_document or not isinstance(
278
+ policy_document["Statement"], list
279
+ ):
280
+ print("Warning: Policy document does not contain a 'Statement' list. Skipping.")
281
+ return # Do not return role, just log and exit
282
+
283
+ for statement_dict in policy_document["Statement"]:
284
+ try:
285
+ # Create a CDK PolicyStatement from the dictionary
286
+ cdk_policy_statement = iam.PolicyStatement.from_json(statement_dict)
287
+
288
+ # Add the policy statement to the role
289
+ role.add_to_policy(cdk_policy_statement)
290
+ print(f" - Added statement: {statement_dict.get('Sid', 'No Sid')}")
291
+ except Exception as e:
292
+ print(
293
+ f"Warning: Could not process policy statement: {statement_dict}. Error: {e}"
294
+ )
295
+
296
+
297
+ def add_s3_enforce_ssl_policy(bucket: s3.IBucket) -> None:
298
+ """Deny non-TLS S3 requests (Security Hub S3.5). Compatible with all CDK versions."""
299
+ bucket.add_to_resource_policy(
300
+ iam.PolicyStatement(
301
+ effect=iam.Effect.DENY,
302
+ principals=[iam.AnyPrincipal()],
303
+ actions=["s3:*"],
304
+ resources=[bucket.bucket_arn, f"{bucket.bucket_arn}/*"],
305
+ conditions={"Bool": {"aws:SecureTransport": "false"}},
306
+ )
307
+ )
308
+
309
+
310
+ def add_custom_policies(
311
+ scope: Construct, # Not strictly used here, but good practice if you expand to ManagedPolicies
312
+ role: iam.IRole,
313
+ policy_file_locations: Optional[List[str]] = None,
314
+ custom_policy_text: Optional[str] = None,
315
+ ) -> iam.IRole:
316
+ """
317
+ Loads custom policies from JSON files or a string and attaches them to a CDK Role.
318
+
319
+ Args:
320
+ scope: The scope in which to define constructs (if needed, e.g., for iam.ManagedPolicy).
321
+ role: The CDK Role construct to attach policies to.
322
+ policy_file_locations: List of file paths to JSON policy documents.
323
+ custom_policy_text: A JSON string representing a policy document.
324
+
325
+ Returns:
326
+ The modified CDK Role construct.
327
+ """
328
+ if policy_file_locations is None:
329
+ policy_file_locations = []
330
+
331
+ current_source = "unknown source" # For error messages
332
+
333
+ try:
334
+ if policy_file_locations:
335
+ print(f"Attempting to add policies from files to role {role.node.id}...")
336
+ for path in policy_file_locations:
337
+ current_source = f"file: {path}"
338
+ try:
339
+ with open(path, "r") as f:
340
+ policy_document = json.load(f)
341
+ print(f"Processing policy from {current_source}...")
342
+ add_statement_to_policy(role, policy_document)
343
+ except FileNotFoundError:
344
+ print(f"Warning: Policy file not found at {path}. Skipping.")
345
+ except json.JSONDecodeError as e:
346
+ print(
347
+ f"Warning: Invalid JSON in policy file {path}: {e}. Skipping."
348
+ )
349
+ except Exception as e:
350
+ print(
351
+ f"An unexpected error occurred processing policy from {path}: {e}. Skipping."
352
+ )
353
+
354
+ if custom_policy_text:
355
+ current_source = "custom policy text string"
356
+ print(
357
+ f"Attempting to add policy from custom text to role {role.node.id}..."
358
+ )
359
+ try:
360
+ # *** FIX: Parse the JSON string into a Python dictionary ***
361
+ policy_document = json.loads(custom_policy_text)
362
+ print(f"Processing policy from {current_source}...")
363
+ add_statement_to_policy(role, policy_document)
364
+ except json.JSONDecodeError as e:
365
+ print(f"Warning: Invalid JSON in custom_policy_text: {e}. Skipping.")
366
+ except Exception as e:
367
+ print(
368
+ f"An unexpected error occurred processing policy from custom_policy_text: {e}. Skipping."
369
+ )
370
+
371
+ # You might want a final success message, but individual processing messages are also good.
372
+ print(f"Finished processing custom policies for role {role.node.id}.")
373
+
374
+ except Exception as e:
375
+ print(
376
+ f"An unhandled error occurred during policy addition for {current_source}: {e}"
377
+ )
378
+
379
+ return role
380
+
381
+
382
+ # Import the S3 Bucket class if you intend to return a CDK object later
383
+ # from aws_cdk import aws_s3 as s3
384
+
385
+
386
+ def check_s3_bucket_exists(
387
+ bucket_name: str,
388
+ ): # Return type hint depends on what you return
389
+ """
390
+ Checks if an S3 bucket with the given name exists and is accessible.
391
+
392
+ Args:
393
+ bucket_name: The name of the S3 bucket to check.
394
+
395
+ Returns:
396
+ A tuple: (bool indicating existence, optional S3 Bucket object or None)
397
+ Note: Returning a Boto3 S3 Bucket object from here is NOT ideal
398
+ for direct use in CDK. You'll likely only need the boolean result
399
+ or the bucket name for CDK lookups/creations.
400
+ For this example, let's return the boolean and the name.
401
+ """
402
+ s3_client = boto3.client("s3")
403
+ try:
404
+ # Use head_bucket to check for existence and access
405
+ s3_client.head_bucket(Bucket=bucket_name)
406
+ print(f"Bucket '{bucket_name}' exists and is accessible.")
407
+ return True, bucket_name # Return True and the bucket name
408
+
409
+ except ClientError as e:
410
+ # If a ClientError occurs, check the error code.
411
+ # '404' means the bucket does not exist.
412
+ # '403' means the bucket exists but you don't have permission.
413
+ error_code = e.response["Error"]["Code"]
414
+ if error_code == "404":
415
+ print(f"Bucket '{bucket_name}' does not exist.")
416
+ return False, None
417
+ elif error_code == "403":
418
+ # The bucket exists, but you can't access it.
419
+ # Depending on your requirements, this might be treated as "exists"
420
+ # or "not accessible for our purpose". For checking existence,
421
+ # we'll say it exists here, but note the permission issue.
422
+ # NOTE - when I tested this, it was returning 403 even for buckets that don't exist. So I will return False instead
423
+ print(
424
+ f"Bucket '{bucket_name}' returned 403, which indicates it may exist but is not accessible due to permissions, or that it doesn't exist. Returning False for existence just in case."
425
+ )
426
+ return False, bucket_name # It exists, even if not accessible
427
+ else:
428
+ # For other errors, it's better to raise the exception
429
+ # to indicate something unexpected happened.
430
+ print(
431
+ f"An unexpected AWS ClientError occurred checking bucket '{bucket_name}': {e}"
432
+ )
433
+ # Decide how to handle other errors - raising might be safer
434
+ raise # Re-raise the original exception
435
+ except Exception as e:
436
+ print(
437
+ f"An unexpected non-ClientError occurred checking bucket '{bucket_name}': {e}"
438
+ )
439
+ # Decide how to handle other errors
440
+ raise # Re-raise the original exception
441
+
442
+
443
+ # Example usage in your check_resources.py:
444
+ # exists, bucket_name_if_exists = check_s3_bucket_exists(log_bucket_name)
445
+ # context_data[f"exists:{log_bucket_name}"] = exists
446
+ # # You don't necessarily need to store the name in context if using from_bucket_name
447
+
448
+
449
+ # Delete an S3 bucket
450
+ def delete_s3_bucket(bucket_name: str):
451
+ s3 = boto3.client("s3")
452
+
453
+ try:
454
+ # List and delete all objects
455
+ response = s3.list_object_versions(Bucket=bucket_name)
456
+ versions = response.get("Versions", []) + response.get("DeleteMarkers", [])
457
+ for version in versions:
458
+ s3.delete_object(
459
+ Bucket=bucket_name, Key=version["Key"], VersionId=version["VersionId"]
460
+ )
461
+
462
+ # Delete the bucket
463
+ s3.delete_bucket(Bucket=bucket_name)
464
+ return {"Status": "SUCCESS"}
465
+ except Exception as e:
466
+ return {"Status": "FAILED", "Reason": str(e)}
467
+
468
+
469
+ # Function to get subnet ID from subnet name
470
+ def get_subnet_id(vpc: str, ec2_client: str, subnet_name: str):
471
+ response = ec2_client.describe_subnets(
472
+ Filters=[{"Name": "vpc-id", "Values": [vpc.vpc_id]}]
473
+ )
474
+
475
+ for subnet in response["Subnets"]:
476
+ if subnet["Tags"] and any(
477
+ tag["Key"] == "Name" and tag["Value"] == subnet_name
478
+ for tag in subnet["Tags"]
479
+ ):
480
+ return subnet["SubnetId"]
481
+
482
+ return None
483
+
484
+
485
+ def check_ecr_repo_exists(repo_name: str) -> tuple[bool, dict]:
486
+ """
487
+ Checks if an ECR repository with the given name exists.
488
+
489
+ Args:
490
+ repo_name: The name of the ECR repository to check.
491
+
492
+ Returns:
493
+ True if the repository exists, False otherwise.
494
+ """
495
+ ecr_client = boto3.client("ecr")
496
+ try:
497
+ print("ecr repo_name to check:", repo_name)
498
+ response = ecr_client.describe_repositories(repositoryNames=[repo_name])
499
+ # If describe_repositories succeeds and returns a list of repositories,
500
+ # and the list is not empty, the repository exists.
501
+ return len(response["repositories"]) > 0, response["repositories"][0]
502
+ except ClientError as e:
503
+ # Check for the specific error code indicating the repository doesn't exist
504
+ if e.response["Error"]["Code"] == "RepositoryNotFoundException":
505
+ return False, {}
506
+ else:
507
+ # Re-raise other exceptions to handle unexpected errors
508
+ raise
509
+ except Exception as e:
510
+ print(f"An unexpected error occurred: {e}")
511
+ return False, {}
512
+
513
+
514
+ def check_codebuild_project_exists(
515
+ project_name: str,
516
+ ): # Adjust return type hint as needed
517
+ """
518
+ Checks if a CodeBuild project with the given name exists.
519
+
520
+ Args:
521
+ project_name: The name of the CodeBuild project to check.
522
+
523
+ Returns:
524
+ A tuple:
525
+ - The first element is True if the project exists, False otherwise.
526
+ - The second element is the project object (dictionary) if found,
527
+ None otherwise.
528
+ """
529
+ codebuild_client = boto3.client("codebuild")
530
+ try:
531
+ # Use batch_get_projects with a list containing the single project name
532
+ response = codebuild_client.batch_get_projects(names=[project_name])
533
+
534
+ # The response for batch_get_projects includes 'projects' (found)
535
+ # and 'projectsNotFound' (not found).
536
+ if response["projects"]:
537
+ # If the project is found in the 'projects' list
538
+ print(f"CodeBuild project '{project_name}' found.")
539
+ project = response["projects"][0]
540
+ return (
541
+ True,
542
+ project["arn"],
543
+ project.get("serviceRole"),
544
+ )
545
+ elif (
546
+ response["projectsNotFound"]
547
+ and project_name in response["projectsNotFound"]
548
+ ):
549
+ # If the project name is explicitly in the 'projectsNotFound' list
550
+ print(f"CodeBuild project '{project_name}' not found.")
551
+ return False, None, None
552
+ else:
553
+ # This case is less expected for a single name lookup,
554
+ # but could happen if there's an internal issue or the response
555
+ # structure is slightly different than expected for an error.
556
+ # It's safer to assume it wasn't found if not in 'projects'.
557
+ print(
558
+ f"CodeBuild project '{project_name}' not found (not in 'projects' list)."
559
+ )
560
+ return False, None, None
561
+
562
+ except ClientError as e:
563
+ # Catch specific ClientErrors. batch_get_projects might not throw
564
+ # 'InvalidInputException' for a non-existent project name if the
565
+ # name format is valid. It typically just lists it in projectsNotFound.
566
+ # However, other ClientErrors are possible (e.g., permissions).
567
+ print(
568
+ f"An AWS ClientError occurred checking CodeBuild project '{project_name}': {e}"
569
+ )
570
+ # Decide how to handle other ClientErrors - raising might be safer
571
+ raise # Re-raise the original exception
572
+ except Exception as e:
573
+ print(
574
+ f"An unexpected non-ClientError occurred checking CodeBuild project '{project_name}': {e}"
575
+ )
576
+ # Decide how to handle other errors
577
+ raise # Re-raise the original exception
578
+
579
+
580
+ def get_vpc_id_by_name(vpc_name: str) -> Optional[str]:
581
+ """
582
+ Finds a VPC ID by its 'Name' tag.
583
+ """
584
+ ec2_client = boto3.client("ec2")
585
+ try:
586
+ response = ec2_client.describe_vpcs(
587
+ Filters=[{"Name": "tag:Name", "Values": [vpc_name]}]
588
+ )
589
+ if response and response["Vpcs"]:
590
+ vpc_id = response["Vpcs"][0]["VpcId"]
591
+ print(f"VPC '{vpc_name}' found with ID: {vpc_id}")
592
+
593
+ # In get_vpc_id_by_name, after finding VPC ID:
594
+
595
+ # Look for NAT Gateways in this VPC
596
+ ec2_client = boto3.client("ec2")
597
+ nat_gateways = []
598
+ try:
599
+ response = ec2_client.describe_nat_gateways(
600
+ Filters=[
601
+ {"Name": "vpc-id", "Values": [vpc_id]},
602
+ # Optional: Add a tag filter if you consistently tag your NATs
603
+ # {'Name': 'tag:Name', 'Values': [f"{prefix}-nat-gateway"]}
604
+ ]
605
+ )
606
+ nat_gateways = response.get("NatGateways", [])
607
+ except Exception as e:
608
+ print(
609
+ f"Warning: Could not describe NAT Gateways in VPC '{vpc_id}': {e}"
610
+ )
611
+ # Decide how to handle this error - proceed or raise?
612
+
613
+ # Decide how to identify the specific NAT Gateway you want to check for.
614
+
615
+ return vpc_id, nat_gateways
616
+ else:
617
+ print(f"VPC '{vpc_name}' not found.")
618
+ return None
619
+ except Exception as e:
620
+ print(f"An unexpected error occurred finding VPC '{vpc_name}': {e}")
621
+ raise
622
+
623
+
624
+ # --- Helper to fetch all existing subnets in a VPC once ---
625
+ def _get_existing_subnets_in_vpc(vpc_id: str) -> Dict[str, Any]:
626
+ """
627
+ Fetches all subnets in a given VPC.
628
+ Returns a dictionary with 'by_name' (map of name to subnet data),
629
+ 'by_id' (map of id to subnet data), and 'cidr_networks' (list of ipaddress.IPv4Network).
630
+ """
631
+ ec2_client = boto3.client("ec2")
632
+ existing_subnets_data = {
633
+ "by_name": {}, # {subnet_name: {'id': 'subnet-id', 'cidr': 'x.x.x.x/x'}}
634
+ "by_id": {}, # {subnet_id: {'name': 'subnet-name', 'cidr': 'x.x.x.x/x/x'}}
635
+ "cidr_networks": [], # List of ipaddress.IPv4Network objects
636
+ }
637
+ try:
638
+ subnet_to_route_table: Dict[str, str] = {}
639
+ rt_response = ec2_client.describe_route_tables(
640
+ Filters=[{"Name": "vpc-id", "Values": [vpc_id]}]
641
+ )
642
+ for route_table in rt_response.get("RouteTables", []):
643
+ route_table_id = route_table["RouteTableId"]
644
+ for association in route_table.get("Associations", []):
645
+ associated_subnet_id = association.get("SubnetId")
646
+ if associated_subnet_id:
647
+ subnet_to_route_table[associated_subnet_id] = route_table_id
648
+
649
+ response = ec2_client.describe_subnets(
650
+ Filters=[{"Name": "vpc-id", "Values": [vpc_id]}]
651
+ )
652
+ for s in response.get("Subnets", []):
653
+ subnet_id = s["SubnetId"]
654
+ cidr_block = s.get("CidrBlock")
655
+ # Extract 'Name' tag, which is crucial for lookup by name
656
+ name_tag = next(
657
+ (tag["Value"] for tag in s.get("Tags", []) if tag["Key"] == "Name"),
658
+ None,
659
+ )
660
+
661
+ subnet_info = {
662
+ "id": subnet_id,
663
+ "cidr": cidr_block,
664
+ "name": name_tag,
665
+ "az": s.get("AvailabilityZone"),
666
+ "route_table_id": subnet_to_route_table.get(subnet_id),
667
+ }
668
+
669
+ if name_tag:
670
+ existing_subnets_data["by_name"][name_tag] = subnet_info
671
+ existing_subnets_data["by_id"][subnet_id] = subnet_info
672
+
673
+ if cidr_block:
674
+ try:
675
+ existing_subnets_data["cidr_networks"].append(
676
+ ipaddress.ip_network(cidr_block, strict=False)
677
+ )
678
+ except ValueError:
679
+ print(
680
+ f"Warning: Existing subnet {subnet_id} has an invalid CIDR: {cidr_block}. Skipping for overlap check."
681
+ )
682
+
683
+ print(
684
+ f"Fetched {len(response.get('Subnets', []))} existing subnets from VPC '{vpc_id}'."
685
+ )
686
+ except Exception as e:
687
+ print(
688
+ f"Error describing existing subnets in VPC '{vpc_id}': {e}. Cannot perform full validation."
689
+ )
690
+ raise # Re-raise if this essential step fails
691
+
692
+ return existing_subnets_data
693
+
694
+
695
+ # --- Modified validate_subnet_creation_parameters to take pre-fetched data ---
696
+ def validate_subnet_creation_parameters(
697
+ vpc_id: str,
698
+ proposed_subnets_data: List[
699
+ Dict[str, str]
700
+ ], # e.g., [{'name': 'my-public-subnet', 'cidr': '10.0.0.0/24', 'az': 'us-east-1a'}]
701
+ existing_aws_subnets_data: Dict[
702
+ str, Any
703
+ ], # Pre-fetched data from _get_existing_subnets_in_vpc
704
+ ) -> None:
705
+ """
706
+ Validates proposed subnet names and CIDR blocks against existing AWS subnets
707
+ in the specified VPC and against each other.
708
+ This function uses pre-fetched AWS subnet data.
709
+
710
+ Args:
711
+ vpc_id: The ID of the VPC (for logging/error messages).
712
+ proposed_subnets_data: A list of dictionaries, where each dict represents
713
+ a proposed subnet with 'name', 'cidr', and 'az'.
714
+ existing_aws_subnets_data: Dictionary containing existing AWS subnet data
715
+ (e.g., from _get_existing_subnets_in_vpc).
716
+
717
+ Raises:
718
+ ValueError: If any proposed subnet name or CIDR block
719
+ conflicts with existing AWS resources or other proposed resources.
720
+ """
721
+ if not proposed_subnets_data:
722
+ print("No proposed subnet data provided for validation. Skipping.")
723
+ return
724
+
725
+ print(
726
+ f"--- Starting pre-synth validation for VPC '{vpc_id}' with proposed subnets ---"
727
+ )
728
+
729
+ print("Existing subnet data:", pd.DataFrame(existing_aws_subnets_data["by_name"]))
730
+
731
+ existing_aws_subnet_names = set(existing_aws_subnets_data["by_name"].keys())
732
+ existing_aws_cidr_networks = existing_aws_subnets_data["cidr_networks"]
733
+
734
+ # Sets to track names and list to track networks for internal batch consistency
735
+ proposed_names_seen: set[str] = set()
736
+ proposed_cidr_networks_seen: List[ipaddress.IPv4Network] = []
737
+
738
+ for i, proposed_subnet in enumerate(proposed_subnets_data):
739
+ subnet_name = proposed_subnet.get("name")
740
+ cidr_block_str = proposed_subnet.get("cidr")
741
+ availability_zone = proposed_subnet.get("az")
742
+
743
+ if not all([subnet_name, cidr_block_str, availability_zone]):
744
+ raise ValueError(
745
+ f"Proposed subnet at index {i} is incomplete. Requires 'name', 'cidr', and 'az'."
746
+ )
747
+
748
+ # 1. Check for duplicate names within the proposed batch
749
+ if subnet_name in proposed_names_seen:
750
+ raise ValueError(
751
+ f"Proposed subnet name '{subnet_name}' is duplicated within the input list."
752
+ )
753
+ proposed_names_seen.add(subnet_name)
754
+
755
+ # 2. Check for duplicate names against existing AWS subnets
756
+ if subnet_name in existing_aws_subnet_names:
757
+ print(
758
+ f"Proposed subnet name '{subnet_name}' already exists in VPC '{vpc_id}'."
759
+ )
760
+
761
+ # Parse proposed CIDR
762
+ try:
763
+ proposed_net = ipaddress.ip_network(cidr_block_str, strict=False)
764
+ except ValueError as e:
765
+ raise ValueError(
766
+ f"Invalid CIDR format '{cidr_block_str}' for proposed subnet '{subnet_name}': {e}"
767
+ )
768
+
769
+ # 3. Check for overlapping CIDRs within the proposed batch
770
+ for existing_proposed_net in proposed_cidr_networks_seen:
771
+ if proposed_net.overlaps(existing_proposed_net):
772
+ raise ValueError(
773
+ f"Proposed CIDR '{cidr_block_str}' for subnet '{subnet_name}' "
774
+ f"overlaps with another proposed CIDR '{str(existing_proposed_net)}' "
775
+ f"within the same batch."
776
+ )
777
+
778
+ # 4. Check for overlapping CIDRs against existing AWS subnets
779
+ for existing_aws_net in existing_aws_cidr_networks:
780
+ if proposed_net.overlaps(existing_aws_net):
781
+ raise ValueError(
782
+ f"Proposed CIDR '{cidr_block_str}' for subnet '{subnet_name}' "
783
+ f"overlaps with an existing AWS subnet CIDR '{str(existing_aws_net)}' "
784
+ f"in VPC '{vpc_id}'."
785
+ )
786
+
787
+ # If all checks pass for this subnet, add its network to the list for subsequent checks
788
+ proposed_cidr_networks_seen.append(proposed_net)
789
+ print(
790
+ f"Validation successful for proposed subnet '{subnet_name}' with CIDR '{cidr_block_str}'."
791
+ )
792
+
793
+ print(
794
+ f"--- All proposed subnets passed pre-synth validation checks for VPC '{vpc_id}'. ---"
795
+ )
796
+
797
+
798
+ # --- Modified check_subnet_exists_by_name (Uses pre-fetched data) ---
799
+ def check_subnet_exists_by_name(
800
+ subnet_name: str, existing_aws_subnets_data: Dict[str, Any]
801
+ ) -> Tuple[bool, Optional[str]]:
802
+ """
803
+ Checks if a subnet with the given name exists within the pre-fetched data.
804
+
805
+ Args:
806
+ subnet_name: The 'Name' tag value of the subnet to check.
807
+ existing_aws_subnets_data: Dictionary containing existing AWS subnet data
808
+ (e.g., from _get_existing_subnets_in_vpc).
809
+
810
+ Returns:
811
+ A tuple:
812
+ - The first element is True if the subnet exists, False otherwise.
813
+ - The second element is the Subnet ID if found, None otherwise.
814
+ """
815
+ subnet_info = existing_aws_subnets_data["by_name"].get(subnet_name)
816
+ if subnet_info:
817
+ print(f"Subnet '{subnet_name}' found with ID: {subnet_info['id']}")
818
+ return True, subnet_info["id"]
819
+ else:
820
+ print(f"Subnet '{subnet_name}' not found.")
821
+ return False, None
822
+
823
+
824
+ def create_nat_gateway(
825
+ scope: Construct,
826
+ public_subnet_for_nat: ec2.ISubnet, # Expects a proper ISubnet
827
+ nat_gateway_name: str,
828
+ nat_gateway_id_context_key: str,
829
+ ) -> str:
830
+ """
831
+ Creates a single NAT Gateway in the specified public subnet.
832
+ It does not handle lookup from context; the calling stack should do that.
833
+ Returns the CloudFormation Ref of the NAT Gateway ID.
834
+ """
835
+ print(
836
+ f"Defining a new NAT Gateway '{nat_gateway_name}' in subnet '{public_subnet_for_nat.subnet_id}'."
837
+ )
838
+
839
+ # Create an Elastic IP for the NAT Gateway
840
+ eip = ec2.CfnEIP(
841
+ scope,
842
+ NAT_GATEWAY_EIP_NAME,
843
+ tags=[CfnTag(key="Name", value=NAT_GATEWAY_EIP_NAME)],
844
+ )
845
+
846
+ # Create the NAT Gateway
847
+ nat_gateway_logical_id = nat_gateway_name.replace("-", "") + "NatGateway"
848
+ nat_gateway = ec2.CfnNatGateway(
849
+ scope,
850
+ nat_gateway_logical_id,
851
+ subnet_id=public_subnet_for_nat.subnet_id, # Associate with the public subnet
852
+ allocation_id=eip.attr_allocation_id, # Associate with the EIP
853
+ tags=[CfnTag(key="Name", value=nat_gateway_name)],
854
+ )
855
+ # The NAT GW depends on the EIP. The dependency on the subnet is implicit via subnet_id.
856
+ nat_gateway.add_dependency(eip)
857
+
858
+ # *** CRUCIAL: Use CfnOutput to export the ID after deployment ***
859
+ # This is how you will get the ID to put into cdk.context.json
860
+ CfnOutput(
861
+ scope,
862
+ "SingleNatGatewayIdOutput",
863
+ value=nat_gateway.ref,
864
+ description=f"Physical ID of the Single NAT Gateway. Add this to cdk.context.json under the key '{nat_gateway_id_context_key}'.",
865
+ export_name=f"{scope.stack_name}-NatGatewayId", # Make export name unique
866
+ )
867
+
868
+ print(
869
+ f"CDK: Defined new NAT Gateway '{nat_gateway.ref}'. Its physical ID will be available in the stack outputs after deployment."
870
+ )
871
+ # Return the tokenised reference for use within this synthesis
872
+ return nat_gateway.ref
873
+
874
+
875
+ def create_subnets(
876
+ scope: Construct,
877
+ vpc: ec2.IVpc,
878
+ prefix: str,
879
+ subnet_names: List[str],
880
+ cidr_blocks: List[str],
881
+ availability_zones: List[str],
882
+ is_public: bool,
883
+ internet_gateway_id: Optional[str] = None,
884
+ single_nat_gateway_id: Optional[str] = None,
885
+ ) -> Tuple[List[ec2.CfnSubnet], List[ec2.CfnRouteTable]]:
886
+ """
887
+ Creates subnets using L2 constructs but returns the underlying L1 Cfn objects
888
+ for backward compatibility.
889
+ """
890
+ # --- Validations remain the same ---
891
+ if not (len(subnet_names) == len(cidr_blocks) == len(availability_zones) > 0):
892
+ raise ValueError(
893
+ "Subnet names, CIDR blocks, and Availability Zones lists must be non-empty and match in length."
894
+ )
895
+ if is_public and not internet_gateway_id:
896
+ raise ValueError("internet_gateway_id must be provided for public subnets.")
897
+ if not is_public and not single_nat_gateway_id:
898
+ raise ValueError(
899
+ "single_nat_gateway_id must be provided for private subnets when using a single NAT Gateway."
900
+ )
901
+
902
+ # --- We will populate these lists with the L1 objects to return ---
903
+ created_subnets: List[ec2.CfnSubnet] = []
904
+ created_route_tables: List[ec2.CfnRouteTable] = []
905
+
906
+ subnet_type_tag = "public" if is_public else "private"
907
+
908
+ for i, subnet_name in enumerate(subnet_names):
909
+ logical_id = f"{prefix}{subnet_type_tag.capitalize()}Subnet{i+1}"
910
+
911
+ # 1. Create the L2 Subnet (this is the easy part)
912
+ subnet = ec2.Subnet(
913
+ scope,
914
+ logical_id,
915
+ vpc_id=vpc.vpc_id,
916
+ cidr_block=cidr_blocks[i],
917
+ availability_zone=availability_zones[i],
918
+ map_public_ip_on_launch=is_public,
919
+ )
920
+ Tags.of(subnet).add("Name", subnet_name)
921
+ Tags.of(subnet).add("Type", subnet_type_tag)
922
+
923
+ if is_public:
924
+ # The subnet's route_table is automatically created by the L2 Subnet construct
925
+ try:
926
+ subnet.add_route(
927
+ "DefaultInternetRoute", # A logical ID for the CfnRoute resource
928
+ router_id=internet_gateway_id,
929
+ router_type=ec2.RouterType.GATEWAY,
930
+ # destination_cidr_block="0.0.0.0/0" is the default for this method
931
+ )
932
+ except Exception as e:
933
+ print("Could not create IGW route for public subnet due to:", e)
934
+ print(f"CDK: Defined public L2 subnet '{subnet_name}' and added IGW route.")
935
+ else:
936
+ try:
937
+ # Using .add_route() for private subnets as well for consistency
938
+ subnet.add_route(
939
+ "DefaultNatRoute", # A logical ID for the CfnRoute resource
940
+ router_id=single_nat_gateway_id,
941
+ router_type=ec2.RouterType.NAT_GATEWAY,
942
+ )
943
+ except Exception as e:
944
+ print("Could not create NAT gateway route for public subnet due to:", e)
945
+ print(
946
+ f"CDK: Defined private L2 subnet '{subnet_name}' and added NAT GW route."
947
+ )
948
+
949
+ route_table = subnet.route_table
950
+
951
+ created_subnets.append(subnet)
952
+ created_route_tables.append(route_table)
953
+
954
+ return created_subnets, created_route_tables
955
+
956
+
957
+ def ingress_rule_exists(security_group: str, peer: str, port: str):
958
+ for rule in security_group.connections.security_groups:
959
+ if port:
960
+ if rule.peer == peer and rule.connection == port:
961
+ return True
962
+ else:
963
+ if rule.peer == peer:
964
+ return True
965
+ return False
966
+
967
+
968
+ def check_for_existing_user_pool(user_pool_name: str):
969
+ cognito_client = boto3.client("cognito-idp")
970
+ list_pools_response = cognito_client.list_user_pools(
971
+ MaxResults=60
972
+ ) # MaxResults up to 60
973
+
974
+ # ListUserPools might require pagination if you have more than 60 pools
975
+ # This simple example doesn't handle pagination, which could miss your pool
976
+
977
+ existing_user_pool_id = ""
978
+
979
+ for pool in list_pools_response.get("UserPools", []):
980
+ if pool.get("Name") == user_pool_name:
981
+ existing_user_pool_id = pool["Id"]
982
+ print(
983
+ f"Found existing user pool by name '{user_pool_name}' with ID: {existing_user_pool_id}"
984
+ )
985
+ break # Found the one we're looking for
986
+
987
+ if existing_user_pool_id:
988
+ return True, existing_user_pool_id, pool
989
+ else:
990
+ return False, "", ""
991
+
992
+
993
+ def check_for_existing_user_pool_client(user_pool_id: str, user_pool_client_name: str):
994
+ """
995
+ Checks if a Cognito User Pool Client with the given name exists in the specified User Pool.
996
+
997
+ Args:
998
+ user_pool_id: The ID of the Cognito User Pool.
999
+ user_pool_client_name: The name of the User Pool Client to check for.
1000
+
1001
+ Returns:
1002
+ A tuple:
1003
+ - True, client_id, client_details if the client exists.
1004
+ - False, "", {} otherwise.
1005
+ """
1006
+ cognito_client = boto3.client("cognito-idp")
1007
+ next_token = "string"
1008
+
1009
+ while True:
1010
+ try:
1011
+ response = cognito_client.list_user_pool_clients(
1012
+ UserPoolId=user_pool_id, MaxResults=60, NextToken=next_token
1013
+ )
1014
+ except cognito_client.exceptions.ResourceNotFoundException:
1015
+ print(f"Error: User pool with ID '{user_pool_id}' not found.")
1016
+ return False, "", {}
1017
+
1018
+ except cognito_client.exceptions.InvalidParameterException:
1019
+ print(f"Error: No app clients for '{user_pool_id}' found.")
1020
+ return False, "", {}
1021
+
1022
+ except Exception as e:
1023
+ print("Could not check User Pool clients due to:", e)
1024
+
1025
+ for client in response.get("UserPoolClients", []):
1026
+ if client.get("ClientName") == user_pool_client_name:
1027
+ print(
1028
+ f"Found existing user pool client '{user_pool_client_name}' with ID: {client['ClientId']}"
1029
+ )
1030
+ return True, client["ClientId"], client
1031
+
1032
+ next_token = response.get("NextToken")
1033
+ if not next_token:
1034
+ break
1035
+
1036
+ return False, "", {}
1037
+
1038
+
1039
+ def check_for_secret(secret_name: str, secret_value: dict = ""):
1040
+ """
1041
+ Checks if a Secrets Manager secret with the given name exists.
1042
+ If it doesn't exist, it creates the secret.
1043
+
1044
+ Args:
1045
+ secret_name: The name of the Secrets Manager secret.
1046
+ secret_value: A dictionary containing the key-value pairs for the secret.
1047
+
1048
+ Returns:
1049
+ True if the secret existed or was created, False otherwise (due to other errors).
1050
+ """
1051
+ secretsmanager_client = boto3.client("secretsmanager")
1052
+
1053
+ try:
1054
+ # Try to get the secret. If it doesn't exist, a ResourceNotFoundException will be raised.
1055
+ secret_value = secretsmanager_client.get_secret_value(SecretId=secret_name)
1056
+ print("Secret already exists.")
1057
+ return True, secret_value
1058
+ except secretsmanager_client.exceptions.ResourceNotFoundException:
1059
+ print("Secret not found")
1060
+ return False, {}
1061
+ except Exception as e:
1062
+ # Handle other potential exceptions during the get operation
1063
+ print(f"Error checking for secret: {e}")
1064
+ return False, {}
1065
+
1066
+
1067
+ def check_alb_exists(
1068
+ load_balancer_name: str, region_name: str = None
1069
+ ) -> tuple[bool, dict]:
1070
+ """
1071
+ Checks if an Application Load Balancer (ALB) with the given name exists.
1072
+
1073
+ Args:
1074
+ load_balancer_name: The name of the ALB to check.
1075
+ region_name: The AWS region to check in. If None, uses the default
1076
+ session region.
1077
+
1078
+ Returns:
1079
+ A tuple:
1080
+ - The first element is True if the ALB exists, False otherwise.
1081
+ - The second element is the ALB object (dictionary) if found,
1082
+ None otherwise. Specifically, it returns the first element of
1083
+ the LoadBalancers list from the describe_load_balancers response.
1084
+ """
1085
+ if region_name:
1086
+ elbv2_client = boto3.client("elbv2", region_name=region_name)
1087
+ else:
1088
+ elbv2_client = boto3.client("elbv2")
1089
+ try:
1090
+ response = elbv2_client.describe_load_balancers(Names=[load_balancer_name])
1091
+ if response["LoadBalancers"]:
1092
+ return (
1093
+ True,
1094
+ response["LoadBalancers"][0],
1095
+ ) # Return True and the first ALB object
1096
+ else:
1097
+ return False, {}
1098
+ except ClientError as e:
1099
+ # If the error indicates the ALB doesn't exist, return False
1100
+ if e.response["Error"]["Code"] == "LoadBalancerNotFound":
1101
+ return False, {}
1102
+ else:
1103
+ # Re-raise other exceptions
1104
+ raise
1105
+ except Exception as e:
1106
+ print(f"An unexpected error occurred: {e}")
1107
+ return False, {}
1108
+
1109
+
1110
+ def check_fargate_task_definition_exists(
1111
+ task_definition_name: str, region_name: str = None
1112
+ ) -> tuple[bool, dict]:
1113
+ """
1114
+ Checks if a Fargate task definition with the given name exists.
1115
+
1116
+ Args:
1117
+ task_definition_name: The name or ARN of the task definition to check.
1118
+ region_name: The AWS region to check in. If None, uses the default
1119
+ session region.
1120
+
1121
+ Returns:
1122
+ A tuple:
1123
+ - The first element is True if the task definition exists, False otherwise.
1124
+ - The second element is the task definition object (dictionary) if found,
1125
+ None otherwise. Specifically, it returns the first element of the
1126
+ taskDefinitions list from the describe_task_definition response.
1127
+ """
1128
+ if region_name:
1129
+ ecs_client = boto3.client("ecs", region_name=region_name)
1130
+ else:
1131
+ ecs_client = boto3.client("ecs")
1132
+ try:
1133
+ response = ecs_client.describe_task_definition(
1134
+ taskDefinition=task_definition_name
1135
+ )
1136
+ # If describe_task_definition succeeds, it returns the task definition.
1137
+ # We can directly return True and the task definition.
1138
+ return True, response["taskDefinition"]
1139
+ except ClientError as e:
1140
+ # Check for the error code indicating the task definition doesn't exist.
1141
+ if (
1142
+ e.response["Error"]["Code"] == "ClientException"
1143
+ and "Task definition" in e.response["Message"]
1144
+ and "does not exist" in e.response["Message"]
1145
+ ):
1146
+ return False, {}
1147
+ else:
1148
+ # Re-raise other exceptions.
1149
+ raise
1150
+ except Exception as e:
1151
+ print(f"An unexpected error occurred: {e}")
1152
+ return False, {}
1153
+
1154
+
1155
+ def check_ecs_service_exists(
1156
+ cluster_name: str, service_name: str, region_name: str = None
1157
+ ) -> tuple[bool, dict]:
1158
+ """
1159
+ Checks if an ECS service with the given name exists in the specified cluster.
1160
+
1161
+ Args:
1162
+ cluster_name: The name or ARN of the ECS cluster.
1163
+ service_name: The name of the ECS service to check.
1164
+ region_name: The AWS region to check in. If None, uses the default
1165
+ session region.
1166
+
1167
+ Returns:
1168
+ A tuple:
1169
+ - The first element is True if the service exists, False otherwise.
1170
+ - The second element is the service object (dictionary) if found,
1171
+ None otherwise.
1172
+ """
1173
+ if region_name:
1174
+ ecs_client = boto3.client("ecs", region_name=region_name)
1175
+ else:
1176
+ ecs_client = boto3.client("ecs")
1177
+ try:
1178
+ response = ecs_client.describe_services(
1179
+ cluster=cluster_name, services=[service_name]
1180
+ )
1181
+ if response["services"]:
1182
+ return (
1183
+ True,
1184
+ response["services"][0],
1185
+ ) # Return True and the first service object
1186
+ else:
1187
+ return False, {}
1188
+ except ClientError as e:
1189
+ # Check for the error code indicating the service doesn't exist.
1190
+ if e.response["Error"]["Code"] == "ClusterNotFoundException":
1191
+ return False, {}
1192
+ elif e.response["Error"]["Code"] == "ServiceNotFoundException":
1193
+ return False, {}
1194
+ else:
1195
+ # Re-raise other exceptions.
1196
+ raise
1197
+ except Exception as e:
1198
+ print(f"An unexpected error occurred: {e}")
1199
+ return False, {}
1200
+
1201
+
1202
+ def check_cloudfront_distribution_exists(
1203
+ distribution_name: str, region_name: str = None
1204
+ ) -> tuple[bool, dict | None]:
1205
+ """
1206
+ Checks if a CloudFront distribution with the given name exists.
1207
+
1208
+ Args:
1209
+ distribution_name: The name of the CloudFront distribution to check.
1210
+ region_name: The AWS region to check in. If None, uses the default
1211
+ session region. Note: CloudFront is a global service,
1212
+ so the region is usually 'us-east-1', but this parameter
1213
+ is included for completeness.
1214
+
1215
+ Returns:
1216
+ A tuple:
1217
+ - The first element is True if the distribution exists, False otherwise.
1218
+ - The second element is the distribution object (dictionary) if found,
1219
+ None otherwise. Specifically, it returns the first element of the
1220
+ DistributionList from the ListDistributions response.
1221
+ """
1222
+ if region_name:
1223
+ cf_client = boto3.client("cloudfront", region_name=region_name)
1224
+ else:
1225
+ cf_client = boto3.client("cloudfront")
1226
+ try:
1227
+ response = cf_client.list_distributions()
1228
+ if "Items" in response["DistributionList"]:
1229
+ for distribution in response["DistributionList"]["Items"]:
1230
+ # CloudFront doesn't directly filter by name, so we have to iterate.
1231
+ if (
1232
+ distribution["AliasSet"]["Items"]
1233
+ and distribution["AliasSet"]["Items"][0] == distribution_name
1234
+ ):
1235
+ return True, distribution
1236
+ return False, None
1237
+ else:
1238
+ return False, None
1239
+ except ClientError as e:
1240
+ # If the error indicates the Distribution doesn't exist, return False
1241
+ if e.response["Error"]["Code"] == "NoSuchDistribution":
1242
+ return False, None
1243
+ else:
1244
+ # Re-raise other exceptions
1245
+ raise
1246
+ except Exception as e:
1247
+ print(f"An unexpected error occurred: {e}")
1248
+ return False, None
1249
+
1250
+
1251
+ def create_web_acl_with_common_rules(
1252
+ scope: Construct, web_acl_name: str, waf_scope: str = "CLOUDFRONT"
1253
+ ):
1254
+ """
1255
+ Use CDK to create a web ACL based on an AWS common rule set with overrides.
1256
+ This function now expects a 'scope' argument, typically 'self' from your stack,
1257
+ as CfnWebACL requires a construct scope.
1258
+ """
1259
+
1260
+ # Create full list of rules
1261
+ rules = []
1262
+ aws_ruleset_names = [
1263
+ "AWSManagedRulesCommonRuleSet",
1264
+ "AWSManagedRulesKnownBadInputsRuleSet",
1265
+ "AWSManagedRulesAmazonIpReputationList",
1266
+ ]
1267
+
1268
+ # Use a separate counter to assign unique priorities sequentially
1269
+ priority_counter = 1
1270
+
1271
+ for aws_rule_name in aws_ruleset_names:
1272
+ current_rule_action_overrides = None
1273
+
1274
+ # All managed rule groups need an override_action.
1275
+ # 'none' means use the managed rule group's default action.
1276
+ current_override_action = wafv2.CfnWebACL.OverrideActionProperty(none={})
1277
+
1278
+ current_priority = priority_counter
1279
+ priority_counter += 1
1280
+
1281
+ if aws_rule_name == "AWSManagedRulesCommonRuleSet":
1282
+ current_rule_action_overrides = [
1283
+ wafv2.CfnWebACL.RuleActionOverrideProperty(
1284
+ name="SizeRestrictions_BODY",
1285
+ action_to_use=wafv2.CfnWebACL.RuleActionProperty(allow={}),
1286
+ )
1287
+ ]
1288
+ # No need to set current_override_action here, it's already set above.
1289
+ # If you wanted this specific rule to have a *fixed* priority, you'd handle it differently
1290
+ # For now, it will get priority 1 from the counter.
1291
+
1292
+ rule_property = wafv2.CfnWebACL.RuleProperty(
1293
+ name=aws_rule_name,
1294
+ priority=current_priority,
1295
+ statement=wafv2.CfnWebACL.StatementProperty(
1296
+ managed_rule_group_statement=wafv2.CfnWebACL.ManagedRuleGroupStatementProperty(
1297
+ vendor_name="AWS",
1298
+ name=aws_rule_name,
1299
+ rule_action_overrides=current_rule_action_overrides,
1300
+ )
1301
+ ),
1302
+ visibility_config=wafv2.CfnWebACL.VisibilityConfigProperty(
1303
+ cloud_watch_metrics_enabled=True,
1304
+ metric_name=aws_rule_name,
1305
+ sampled_requests_enabled=True,
1306
+ ),
1307
+ override_action=current_override_action, # THIS IS THE CRUCIAL PART FOR ALL MANAGED RULES
1308
+ )
1309
+
1310
+ rules.append(rule_property)
1311
+
1312
+ # Add the rate limit rule
1313
+ rate_limit_priority = priority_counter # Use the next available priority
1314
+ rules.append(
1315
+ wafv2.CfnWebACL.RuleProperty(
1316
+ name="RateLimitRule",
1317
+ priority=rate_limit_priority,
1318
+ statement=wafv2.CfnWebACL.StatementProperty(
1319
+ rate_based_statement=wafv2.CfnWebACL.RateBasedStatementProperty(
1320
+ limit=1000, aggregate_key_type="IP"
1321
+ )
1322
+ ),
1323
+ visibility_config=wafv2.CfnWebACL.VisibilityConfigProperty(
1324
+ cloud_watch_metrics_enabled=True,
1325
+ metric_name="RateLimitRule",
1326
+ sampled_requests_enabled=True,
1327
+ ),
1328
+ action=wafv2.CfnWebACL.RuleActionProperty(block={}),
1329
+ )
1330
+ )
1331
+
1332
+ web_acl = wafv2.CfnWebACL(
1333
+ scope,
1334
+ "WebACL",
1335
+ name=web_acl_name,
1336
+ default_action=wafv2.CfnWebACL.DefaultActionProperty(allow={}),
1337
+ scope=waf_scope,
1338
+ visibility_config=wafv2.CfnWebACL.VisibilityConfigProperty(
1339
+ cloud_watch_metrics_enabled=True,
1340
+ metric_name="webACL",
1341
+ sampled_requests_enabled=True,
1342
+ ),
1343
+ rules=rules,
1344
+ )
1345
+
1346
+ CfnOutput(scope, "WebACLArn", value=web_acl.attr_arn)
1347
+
1348
+ return web_acl
1349
+
1350
+
1351
+ def check_web_acl_exists(
1352
+ web_acl_name: str, scope: str, region_name: str = None
1353
+ ) -> tuple[bool, dict]:
1354
+ """
1355
+ Checks if a Web ACL with the given name and scope exists.
1356
+
1357
+ Args:
1358
+ web_acl_name: The name of the Web ACL to check.
1359
+ scope: The scope of the Web ACL ('CLOUDFRONT' or 'REGIONAL').
1360
+ region_name: The AWS region to check in. Required for REGIONAL scope.
1361
+ If None, uses the default session region. For CLOUDFRONT,
1362
+ the region should be 'us-east-1'.
1363
+
1364
+ Returns:
1365
+ A tuple:
1366
+ - The first element is True if the Web ACL exists, False otherwise.
1367
+ - The second element is the Web ACL object (dictionary) if found,
1368
+ None otherwise.
1369
+ """
1370
+ if scope not in ["CLOUDFRONT", "REGIONAL"]:
1371
+ raise ValueError("Scope must be either 'CLOUDFRONT' or 'REGIONAL'")
1372
+
1373
+ if scope == "REGIONAL" and not region_name:
1374
+ raise ValueError("Region name is required for REGIONAL scope")
1375
+
1376
+ if scope == "CLOUDFRONT":
1377
+ region_name = "us-east-1" # CloudFront scope requires us-east-1
1378
+
1379
+ if region_name:
1380
+ waf_client = boto3.client("wafv2", region_name=region_name)
1381
+ else:
1382
+ waf_client = boto3.client("wafv2")
1383
+ try:
1384
+ response = waf_client.list_web_acls(Scope=scope)
1385
+ if "WebACLs" in response:
1386
+ for web_acl in response["WebACLs"]:
1387
+ if web_acl["Name"] == web_acl_name:
1388
+ # Describe the Web ACL to get the full object.
1389
+ describe_response = waf_client.describe_web_acl(
1390
+ Name=web_acl_name, Scope=scope
1391
+ )
1392
+ return True, describe_response["WebACL"]
1393
+ return False, {}
1394
+ else:
1395
+ return False, {}
1396
+ except ClientError as e:
1397
+ # Check for the error code indicating the web ACL doesn't exist.
1398
+ if e.response["Error"]["Code"] == "ResourceNotFoundException":
1399
+ return False, {}
1400
+ else:
1401
+ # Re-raise other exceptions.
1402
+ raise
1403
+ except Exception as e:
1404
+ print(f"An unexpected error occurred: {e}")
1405
+ return False, {}
1406
+
1407
+
1408
+ def add_alb_https_listener_with_cert(
1409
+ scope: Construct,
1410
+ logical_id: str, # A unique ID for this listener construct
1411
+ alb: elb.ApplicationLoadBalancer,
1412
+ acm_certificate_arn: Optional[
1413
+ str
1414
+ ], # Optional: If None, no HTTPS listener will be created
1415
+ default_target_group: elb.ITargetGroup, # Mandatory: The target group to forward traffic to
1416
+ listener_port_https: int = 443,
1417
+ listener_open_to_internet: bool = False, # Be cautious with True, ensure ALB security group restricts access
1418
+ # --- Cognito Authentication Parameters ---
1419
+ enable_cognito_auth: bool = False,
1420
+ cognito_user_pool: Optional[cognito.IUserPool] = None,
1421
+ cognito_user_pool_client: Optional[cognito.IUserPoolClient] = None,
1422
+ cognito_user_pool_domain: Optional[
1423
+ str
1424
+ ] = None, # E.g., "my-app-domain" for "my-app-domain.auth.region.amazoncognito.com"
1425
+ cognito_auth_scope: Optional[
1426
+ str
1427
+ ] = "openid profile email", # Default recommended scope
1428
+ cognito_auth_on_unauthenticated_request: elb.UnauthenticatedAction = elb.UnauthenticatedAction.AUTHENTICATE,
1429
+ stickiness_cookie_duration=None,
1430
+ # --- End Cognito Parameters ---
1431
+ ) -> Optional[elb.ApplicationListener]:
1432
+ """
1433
+ Conditionally adds an HTTPS listener to an ALB with an ACM certificate,
1434
+ and optionally enables Cognito User Pool authentication.
1435
+
1436
+ Args:
1437
+ scope (Construct): The scope in which to define this construct (e.g., your CDK Stack).
1438
+ logical_id (str): A unique logical ID for the listener construct within the stack.
1439
+ alb (elb.ApplicationLoadBalancer): The Application Load Balancer to add the listener to.
1440
+ acm_certificate_arn (Optional[str]): The ARN of the ACM certificate to attach.
1441
+ If None, the HTTPS listener will NOT be created.
1442
+ default_target_group (elb.ITargetGroup): The default target group for the listener to forward traffic to.
1443
+ This is mandatory for a functional listener.
1444
+ listener_port_https (int): The HTTPS port to listen on (default: 443).
1445
+ listener_open_to_internet (bool): Whether the listener should allow connections from all sources.
1446
+ If False (recommended), ensure your ALB's security group allows
1447
+ inbound traffic on this port from desired sources.
1448
+ enable_cognito_auth (bool): Set to True to enable Cognito User Pool authentication.
1449
+ cognito_user_pool (Optional[cognito.IUserPool]): The Cognito User Pool object. Required if enable_cognito_auth is True.
1450
+ cognito_user_pool_client (Optional[cognito.IUserPoolClient]): The Cognito User Pool App Client object. Required if enable_cognito_auth is True.
1451
+ cognito_user_pool_domain (Optional[str]): The domain prefix for your Cognito User Pool. Required if enable_cognito_auth is True.
1452
+ cognito_auth_scope (Optional[str]): The scope for the Cognito authentication.
1453
+ cognito_auth_on_unauthenticated_request (elb.UnauthenticatedAction): Action for unauthenticated requests.
1454
+ Defaults to AUTHENTICATE (redirect to login).
1455
+
1456
+ Returns:
1457
+ Optional[elb.ApplicationListener]: The created ApplicationListener if successful,
1458
+ None if no ACM certificate ARN was provided.
1459
+ """
1460
+ https_listener = None
1461
+ if acm_certificate_arn:
1462
+ certificates_list = [elb.ListenerCertificate.from_arn(acm_certificate_arn)]
1463
+ print(
1464
+ f"Attempting to add ALB HTTPS listener on port {listener_port_https} with ACM certificate: {acm_certificate_arn}"
1465
+ )
1466
+
1467
+ # Determine the default action based on whether Cognito auth is enabled
1468
+ default_action = None
1469
+ if enable_cognito_auth is True:
1470
+ if not all(
1471
+ [cognito_user_pool, cognito_user_pool_client, cognito_user_pool_domain]
1472
+ ):
1473
+ raise ValueError(
1474
+ "Cognito User Pool, Client, and Domain must be provided if enable_cognito_auth is True."
1475
+ )
1476
+ print(
1477
+ f"Enabling Cognito authentication with User Pool: {cognito_user_pool.user_pool_id}"
1478
+ )
1479
+
1480
+ default_action = elb_act.AuthenticateCognitoAction(
1481
+ next=elb.ListenerAction.forward(
1482
+ [default_target_group]
1483
+ ), # After successful auth, forward to TG
1484
+ user_pool=cognito_user_pool,
1485
+ user_pool_client=cognito_user_pool_client,
1486
+ user_pool_domain=cognito_user_pool_domain,
1487
+ scope=cognito_auth_scope,
1488
+ on_unauthenticated_request=cognito_auth_on_unauthenticated_request,
1489
+ session_timeout=stickiness_cookie_duration,
1490
+ # Additional options you might want to configure:
1491
+ # session_cookie_name="AWSELBCookies"
1492
+ )
1493
+ else:
1494
+ default_action = elb.ListenerAction.forward([default_target_group])
1495
+ print("Cognito authentication is NOT enabled for this listener.")
1496
+
1497
+ # Add the HTTPS listener
1498
+ https_listener = alb.add_listener(
1499
+ logical_id,
1500
+ port=listener_port_https,
1501
+ open=listener_open_to_internet,
1502
+ certificates=certificates_list,
1503
+ default_action=default_action, # Use the determined default action
1504
+ )
1505
+ print(f"ALB HTTPS listener on port {listener_port_https} defined.")
1506
+ else:
1507
+ print("ACM_CERTIFICATE_ARN is not provided. Skipping HTTPS listener creation.")
1508
+
1509
+ return https_listener
1510
+
1511
+
1512
+ def ensure_folder_exists(output_folder: str):
1513
+ """Checks if the specified folder exists, creates it if not."""
1514
+
1515
+ if not os.path.exists(output_folder):
1516
+ # Create the folder if it doesn't exist
1517
+ os.makedirs(output_folder, exist_ok=True)
1518
+ print(f"Created the {output_folder} folder.")
1519
+ else:
1520
+ print(f"The {output_folder} folder already exists.")
1521
+
1522
+
1523
+ def create_basic_config_env(
1524
+ out_dir: str = "config",
1525
+ S3_LOG_CONFIG_BUCKET_NAME=S3_LOG_CONFIG_BUCKET_NAME,
1526
+ S3_OUTPUT_BUCKET_NAME=S3_OUTPUT_BUCKET_NAME,
1527
+ ACCESS_LOG_DYNAMODB_TABLE_NAME=ACCESS_LOG_DYNAMODB_TABLE_NAME,
1528
+ FEEDBACK_LOG_DYNAMODB_TABLE_NAME=FEEDBACK_LOG_DYNAMODB_TABLE_NAME,
1529
+ USAGE_LOG_DYNAMODB_TABLE_NAME=USAGE_LOG_DYNAMODB_TABLE_NAME,
1530
+ ):
1531
+ """
1532
+ Create a basic config.env file for the user to use with their newly deployed redaction app.
1533
+ """
1534
+ variables = {
1535
+ "COGNITO_AUTH": "True",
1536
+ "RUN_AWS_FUNCTIONS": "True",
1537
+ "DISPLAY_FILE_NAMES_IN_LOGS": "False",
1538
+ "SESSION_OUTPUT_FOLDER": "True",
1539
+ "SAVE_LOGS_TO_DYNAMODB": "True",
1540
+ "SHOW_COSTS": "True",
1541
+ "SHOW_WHOLE_DOCUMENT_TEXTRACT_CALL_OPTIONS": "True",
1542
+ "LOAD_PREVIOUS_TEXTRACT_JOBS_S3": "True",
1543
+ "DOCUMENT_REDACTION_BUCKET": S3_LOG_CONFIG_BUCKET_NAME,
1544
+ "TEXTRACT_WHOLE_DOCUMENT_ANALYSIS_BUCKET": S3_OUTPUT_BUCKET_NAME,
1545
+ "ACCESS_LOG_DYNAMODB_TABLE_NAME": ACCESS_LOG_DYNAMODB_TABLE_NAME,
1546
+ "FEEDBACK_LOG_DYNAMODB_TABLE_NAME": FEEDBACK_LOG_DYNAMODB_TABLE_NAME,
1547
+ "USAGE_LOG_DYNAMODB_TABLE_NAME": USAGE_LOG_DYNAMODB_TABLE_NAME,
1548
+ }
1549
+
1550
+ # Write variables to .env file
1551
+ ensure_folder_exists(out_dir + "/")
1552
+ env_file_path = os.path.abspath(os.path.join(out_dir, "config.env"))
1553
+
1554
+ # It's good practice to ensure the file exists before calling set_key repeatedly.
1555
+ # set_key will create it, but for a loop, it might be cleaner to ensure it's empty/exists once.
1556
+ if not os.path.exists(env_file_path):
1557
+ with open(env_file_path, "w"):
1558
+ pass # Create empty file
1559
+
1560
+ for key, value in variables.items():
1561
+ set_key(env_file_path, key, str(value), quote_mode="never")
1562
+
1563
+ return variables
1564
+
1565
+
1566
+ def start_codebuild_build(PROJECT_NAME: str, AWS_REGION: str = AWS_REGION):
1567
+ """
1568
+ Start an existing Codebuild project build
1569
+ """
1570
+
1571
+ # --- Initialize CodeBuild client ---
1572
+ client = boto3.client("codebuild", region_name=AWS_REGION)
1573
+
1574
+ try:
1575
+ print(f"Attempting to start build for project: {PROJECT_NAME}")
1576
+
1577
+ response = client.start_build(projectName=PROJECT_NAME)
1578
+
1579
+ build_id = response["build"]["id"]
1580
+ print(f"Successfully started build with ID: {build_id}")
1581
+ print(f"Build ARN: {response['build']['arn']}")
1582
+ print("Build URL (approximate - construct based on region and ID):")
1583
+ print(
1584
+ f"https://{AWS_REGION}.console.aws.amazon.com/codesuite/codebuild/projects/{PROJECT_NAME}/build/{build_id.split(':')[-1]}/detail"
1585
+ )
1586
+
1587
+ # You can inspect the full response if needed
1588
+ # print("\nFull response:")
1589
+ # import json
1590
+ # print(json.dumps(response, indent=2))
1591
+
1592
+ except client.exceptions.ResourceNotFoundException:
1593
+ print(f"Error: Project '{PROJECT_NAME}' not found in region '{AWS_REGION}'.")
1594
+ except Exception as e:
1595
+ print(f"An unexpected error occurred: {e}")
1596
+
1597
+
1598
+ def upload_file_to_s3(
1599
+ local_file_paths: List[str],
1600
+ s3_key: str,
1601
+ s3_bucket: str,
1602
+ RUN_AWS_FUNCTIONS: str = "1",
1603
+ ):
1604
+ """
1605
+ Uploads a file from local machine to Amazon S3.
1606
+
1607
+ Args:
1608
+ - local_file_path: Local file path(s) of the file(s) to upload.
1609
+ - s3_key: Key (path) to the file in the S3 bucket.
1610
+ - s3_bucket: Name of the S3 bucket.
1611
+
1612
+ Returns:
1613
+ - Message as variable/printed to console
1614
+ """
1615
+ final_out_message = []
1616
+ final_out_message_str = ""
1617
+
1618
+ if RUN_AWS_FUNCTIONS == "1":
1619
+ try:
1620
+ if s3_bucket and local_file_paths:
1621
+
1622
+ s3_client = boto3.client("s3", region_name=AWS_REGION)
1623
+
1624
+ if isinstance(local_file_paths, str):
1625
+ local_file_paths = [local_file_paths]
1626
+
1627
+ for file in local_file_paths:
1628
+ if s3_client:
1629
+ # print(s3_client)
1630
+ try:
1631
+ # Get file name off file path
1632
+ file_name = os.path.basename(file)
1633
+
1634
+ s3_key_full = s3_key + file_name
1635
+ print("S3 key: ", s3_key_full)
1636
+
1637
+ s3_client.upload_file(file, s3_bucket, s3_key_full)
1638
+ out_message = (
1639
+ "File " + file_name + " uploaded successfully!"
1640
+ )
1641
+ print(out_message)
1642
+
1643
+ except Exception as e:
1644
+ out_message = f"Error uploading file(s): {e}"
1645
+ print(out_message)
1646
+
1647
+ final_out_message.append(out_message)
1648
+ final_out_message_str = "\n".join(final_out_message)
1649
+
1650
+ else:
1651
+ final_out_message_str = "Could not connect to AWS."
1652
+ else:
1653
+ final_out_message_str = (
1654
+ "At least one essential variable is empty, could not upload to S3"
1655
+ )
1656
+ except Exception as e:
1657
+ final_out_message_str = "Could not upload files to S3 due to: " + str(e)
1658
+ print(final_out_message_str)
1659
+ else:
1660
+ final_out_message_str = "App not set to run AWS functions"
1661
+
1662
+ return final_out_message_str
1663
+
1664
+
1665
+ # Initialize ECS client
1666
+ def start_ecs_task(cluster_name, service_name):
1667
+ ecs_client = boto3.client("ecs")
1668
+
1669
+ try:
1670
+ # Update the service to set the desired count to 1
1671
+ ecs_client.update_service(
1672
+ cluster=cluster_name, service=service_name, desiredCount=1
1673
+ )
1674
+ return {
1675
+ "statusCode": 200,
1676
+ "body": f"Service {service_name} in cluster {cluster_name} has been updated to 1 task.",
1677
+ }
1678
+ except Exception as e:
1679
+ return {"statusCode": 500, "body": f"Error updating service: {str(e)}"}
cdk/cdk_stack.py ADDED
@@ -0,0 +1,2010 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json # You might still need json if loading task_definition.json
2
+ import os
3
+ from typing import Any, Dict, List
4
+
5
+ from aws_cdk import (
6
+ CfnOutput, # <-- Import CfnOutput directly
7
+ Duration,
8
+ RemovalPolicy,
9
+ SecretValue,
10
+ Stack,
11
+ )
12
+ from aws_cdk import aws_cloudfront as cloudfront
13
+ from aws_cdk import aws_cloudfront_origins as origins
14
+ from aws_cdk import aws_codebuild as codebuild
15
+ from aws_cdk import aws_cognito as cognito
16
+ from aws_cdk import aws_dynamodb as dynamodb # Import the DynamoDB module
17
+ from aws_cdk import aws_ec2 as ec2
18
+ from aws_cdk import aws_ecr as ecr
19
+ from aws_cdk import aws_ecs as ecs
20
+ from aws_cdk import aws_elasticloadbalancingv2 as elbv2
21
+ from aws_cdk import aws_iam as iam
22
+ from aws_cdk import aws_kms as kms
23
+ from aws_cdk import aws_logs as logs
24
+ from aws_cdk import aws_s3 as s3
25
+ from aws_cdk import aws_secretsmanager as secretsmanager
26
+ from aws_cdk import aws_wafv2 as wafv2
27
+ from cdk_config import (
28
+ ACCESS_LOG_DYNAMODB_TABLE_NAME,
29
+ ACM_SSL_CERTIFICATE_ARN,
30
+ ALB_NAME,
31
+ ALB_NAME_SECURITY_GROUP_NAME,
32
+ ALB_TARGET_GROUP_NAME,
33
+ AWS_ACCOUNT_ID,
34
+ AWS_MANAGED_TASK_ROLES_LIST,
35
+ AWS_REGION,
36
+ CDK_PREFIX,
37
+ CLOUDFRONT_DISTRIBUTION_NAME,
38
+ CLOUDFRONT_GEO_RESTRICTION,
39
+ CLUSTER_NAME,
40
+ CODEBUILD_PROJECT_NAME,
41
+ CODEBUILD_ROLE_NAME,
42
+ COGNITO_ACCESS_TOKEN_VALIDITY,
43
+ COGNITO_ID_TOKEN_VALIDITY,
44
+ COGNITO_REDIRECTION_URL,
45
+ COGNITO_REFRESH_TOKEN_VALIDITY,
46
+ COGNITO_USER_POOL_CLIENT_NAME,
47
+ COGNITO_USER_POOL_CLIENT_SECRET_NAME,
48
+ COGNITO_USER_POOL_DOMAIN_PREFIX,
49
+ COGNITO_USER_POOL_NAME,
50
+ CUSTOM_HEADER,
51
+ CUSTOM_HEADER_VALUE,
52
+ CUSTOM_KMS_KEY_NAME,
53
+ DAYS_TO_DISPLAY_WHOLE_DOCUMENT_JOBS,
54
+ ECR_CDK_REPO_NAME,
55
+ ECS_LOG_GROUP_NAME,
56
+ ECS_READ_ONLY_FILE_SYSTEM,
57
+ ECS_SECURITY_GROUP_NAME,
58
+ ECS_SERVICE_NAME,
59
+ ECS_TASK_CPU_SIZE,
60
+ ECS_TASK_EXECUTION_ROLE_NAME,
61
+ ECS_TASK_MEMORY_SIZE,
62
+ ECS_TASK_ROLE_NAME,
63
+ ECS_USE_FARGATE_SPOT,
64
+ EXISTING_IGW_ID,
65
+ EXISTING_LOAD_BALANCER_ARN,
66
+ EXISTING_LOAD_BALANCER_DNS,
67
+ FARGATE_TASK_DEFINITION_NAME,
68
+ FEEDBACK_LOG_DYNAMODB_TABLE_NAME,
69
+ GITHUB_REPO_BRANCH,
70
+ GITHUB_REPO_NAME,
71
+ GITHUB_REPO_USERNAME,
72
+ GRADIO_SERVER_PORT,
73
+ LOAD_BALANCER_WEB_ACL_NAME,
74
+ NAT_GATEWAY_NAME,
75
+ NEW_VPC_CIDR,
76
+ NEW_VPC_DEFAULT_NAME,
77
+ PRIVATE_SUBNET_AVAILABILITY_ZONES,
78
+ PRIVATE_SUBNET_CIDR_BLOCKS,
79
+ PRIVATE_SUBNETS_TO_USE,
80
+ PUBLIC_SUBNET_AVAILABILITY_ZONES,
81
+ PUBLIC_SUBNET_CIDR_BLOCKS,
82
+ PUBLIC_SUBNETS_TO_USE,
83
+ S3_LOG_CONFIG_BUCKET_NAME,
84
+ S3_OUTPUT_BUCKET_NAME,
85
+ SAVE_LOGS_TO_DYNAMODB,
86
+ SINGLE_NAT_GATEWAY_ID,
87
+ TASK_DEFINITION_FILE_LOCATION,
88
+ USAGE_LOG_DYNAMODB_TABLE_NAME,
89
+ USE_CLOUDFRONT,
90
+ USE_CUSTOM_KMS_KEY,
91
+ VPC_NAME,
92
+ WEB_ACL_NAME,
93
+ )
94
+ from cdk_functions import ( # Only keep CDK-native functions
95
+ add_alb_https_listener_with_cert,
96
+ add_custom_policies,
97
+ add_s3_enforce_ssl_policy,
98
+ create_nat_gateway,
99
+ create_subnets,
100
+ create_web_acl_with_common_rules,
101
+ )
102
+ from constructs import Construct
103
+
104
+
105
+ def _get_env_list(env_var_name: str) -> List[str]:
106
+ """Parses a comma-separated environment variable into a list of strings."""
107
+ value = env_var_name[1:-1].strip().replace('"', "").replace("'", "")
108
+ if not value:
109
+ return []
110
+ # Split by comma and filter out any empty strings that might result from extra commas
111
+ return [s.strip() for s in value.split(",") if s.strip()]
112
+
113
+
114
+ # 1. Try to load CIDR/AZs from environment variables
115
+ if PUBLIC_SUBNETS_TO_USE:
116
+ PUBLIC_SUBNETS_TO_USE = _get_env_list(PUBLIC_SUBNETS_TO_USE)
117
+ if PRIVATE_SUBNETS_TO_USE:
118
+ PRIVATE_SUBNETS_TO_USE = _get_env_list(PRIVATE_SUBNETS_TO_USE)
119
+
120
+ if PUBLIC_SUBNET_CIDR_BLOCKS:
121
+ PUBLIC_SUBNET_CIDR_BLOCKS = _get_env_list("PUBLIC_SUBNET_CIDR_BLOCKS")
122
+ if PUBLIC_SUBNET_AVAILABILITY_ZONES:
123
+ PUBLIC_SUBNET_AVAILABILITY_ZONES = _get_env_list("PUBLIC_SUBNET_AVAILABILITY_ZONES")
124
+ if PRIVATE_SUBNET_CIDR_BLOCKS:
125
+ PRIVATE_SUBNET_CIDR_BLOCKS = _get_env_list("PRIVATE_SUBNET_CIDR_BLOCKS")
126
+ if PRIVATE_SUBNET_AVAILABILITY_ZONES:
127
+ PRIVATE_SUBNET_AVAILABILITY_ZONES = _get_env_list(
128
+ "PRIVATE_SUBNET_AVAILABILITY_ZONES"
129
+ )
130
+
131
+ if AWS_MANAGED_TASK_ROLES_LIST:
132
+ AWS_MANAGED_TASK_ROLES_LIST = _get_env_list(AWS_MANAGED_TASK_ROLES_LIST)
133
+
134
+
135
+ class CdkStack(Stack):
136
+
137
+ def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
138
+ super().__init__(scope, construct_id, **kwargs)
139
+
140
+ # --- Helper to get context values ---
141
+ def get_context_bool(key: str, default: bool = False) -> bool:
142
+ value = self.node.try_get_context(key)
143
+ if value is None:
144
+ return default
145
+ if isinstance(value, bool):
146
+ return value
147
+ if isinstance(value, str):
148
+ return value.lower() in ("true", "1", "yes")
149
+ return bool(value)
150
+
151
+ def get_context_str(key: str, default: str = None) -> str:
152
+ return self.node.try_get_context(key) or default
153
+
154
+ def get_context_dict(key: str, default: dict = None) -> dict:
155
+ return self.node.try_get_context(key) or default
156
+
157
+ def get_context_list_of_dicts(key: str) -> List[Dict[str, Any]]:
158
+ ctx_value = self.node.try_get_context(key)
159
+ if not isinstance(ctx_value, list):
160
+ print(
161
+ f"Warning: Context key '{key}' not found or not a list. Returning empty list."
162
+ )
163
+ return []
164
+ # Optional: Add validation that all items in the list are dicts
165
+ return ctx_value
166
+
167
+ self.template_options.description = "Deployment of the 'doc_redaction' PDF, image, and XLSX/CSV redaction app. Git repo available at: https://github.com/seanpedrick-case/doc_redaction."
168
+
169
+ # --- VPC and Subnets (Assuming VPC is always lookup, Subnets are created/returned by create_subnets) ---
170
+ new_vpc_created = False
171
+ if VPC_NAME:
172
+ vpc_id = get_context_str("vpc_id")
173
+ if not vpc_id:
174
+ raise ValueError(
175
+ f"VPC '{VPC_NAME}' was not resolved during pre-check (missing "
176
+ "'vpc_id' in context). Re-run from the cdk/ directory so "
177
+ "precheck.context.json is generated."
178
+ )
179
+ availability_zones = list(
180
+ dict.fromkeys(
181
+ (PUBLIC_SUBNET_AVAILABILITY_ZONES or [])
182
+ + (PRIVATE_SUBNET_AVAILABILITY_ZONES or [])
183
+ )
184
+ )
185
+ if not availability_zones:
186
+ raise ValueError(
187
+ "vpc_id is in context but no subnet availability zones are "
188
+ "configured. Set PUBLIC_SUBNET_AVAILABILITY_ZONES and/or "
189
+ "PRIVATE_SUBNET_AVAILABILITY_ZONES in cdk_config.env."
190
+ )
191
+ vpc = ec2.Vpc.from_vpc_attributes(
192
+ self,
193
+ "VPC",
194
+ vpc_id=vpc_id,
195
+ availability_zones=availability_zones,
196
+ )
197
+ print(f"Using VPC from pre-check context: {vpc_id}")
198
+
199
+ elif NEW_VPC_DEFAULT_NAME:
200
+ new_vpc_created = True
201
+ print(
202
+ f"NEW_VPC_DEFAULT_NAME ('{NEW_VPC_DEFAULT_NAME}') is set. Creating a new VPC."
203
+ )
204
+
205
+ # Configuration for the new VPC
206
+ # You can make these configurable via context as well, e.g.,
207
+ # new_vpc_cidr = self.node.try_get_context("new_vpc_cidr") or "10.0.0.0/24"
208
+ # new_vpc_max_azs = self.node.try_get_context("new_vpc_max_azs") or 2 # Use 2 AZs by default for HA
209
+ # new_vpc_nat_gateways = self.node.try_get_context("new_vpc_nat_gateways") or new_vpc_max_azs # One NAT GW per AZ for HA
210
+ # or 1 for cost savings if acceptable
211
+ if not NEW_VPC_CIDR:
212
+ raise Exception(
213
+ "App has been instructed to create a new VPC but not VPC CDR range provided to variable NEW_VPC_CIDR"
214
+ )
215
+
216
+ print("Provided NEW_VPC_CIDR range:", NEW_VPC_CIDR)
217
+
218
+ new_vpc_cidr = NEW_VPC_CIDR
219
+ new_vpc_max_azs = 2 # Creates resources in 2 AZs. Adjust as needed.
220
+
221
+ # For "a NAT gateway", you can set nat_gateways=1.
222
+ # For resilience (NAT GW per AZ), set nat_gateways=new_vpc_max_azs.
223
+ # The Vpc construct will create NAT Gateway(s) if subnet_type PRIVATE_WITH_EGRESS is used
224
+ # and nat_gateways > 0.
225
+ new_vpc_nat_gateways = (
226
+ 1 # Creates a single NAT Gateway for cost-effectiveness.
227
+ )
228
+ # If you need one per AZ for higher availability, set this to new_vpc_max_azs.
229
+
230
+ vpc = ec2.Vpc(
231
+ self,
232
+ "MyNewLogicalVpc", # This is the CDK construct ID
233
+ vpc_name=NEW_VPC_DEFAULT_NAME,
234
+ ip_addresses=ec2.IpAddresses.cidr(new_vpc_cidr),
235
+ max_azs=new_vpc_max_azs,
236
+ nat_gateways=new_vpc_nat_gateways, # Number of NAT gateways to create
237
+ subnet_configuration=[
238
+ ec2.SubnetConfiguration(
239
+ name="Public", # Name prefix for public subnets
240
+ subnet_type=ec2.SubnetType.PUBLIC,
241
+ cidr_mask=28, # Adjust CIDR mask as needed (e.g., /24 provides ~250 IPs per subnet)
242
+ ),
243
+ ec2.SubnetConfiguration(
244
+ name="Private", # Name prefix for private subnets
245
+ subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS, # Ensures these subnets have NAT Gateway access
246
+ cidr_mask=28, # Adjust CIDR mask as needed
247
+ ),
248
+ # You could also add ec2.SubnetType.PRIVATE_ISOLATED if needed
249
+ ],
250
+ # Internet Gateway is created and configured automatically for PUBLIC subnets.
251
+ # Route tables for public subnets will point to the IGW.
252
+ # Route tables for PRIVATE_WITH_EGRESS subnets will point to the NAT Gateway(s).
253
+ )
254
+ print(
255
+ f"Successfully created new VPC: {vpc.vpc_id} with name '{NEW_VPC_DEFAULT_NAME}'"
256
+ )
257
+ # If nat_gateways > 0, vpc.nat_gateway_ips will contain EIPs if Vpc created them.
258
+ # vpc.public_subnets, vpc.private_subnets, vpc.isolated_subnets are populated.
259
+
260
+ else:
261
+ raise Exception(
262
+ "VPC_NAME for current VPC not found, and NEW_VPC_DEFAULT_NAME not found to create a new VPC"
263
+ )
264
+
265
+ # --- Subnet Handling (Check Context and Create/Import) ---
266
+ # Initialize lists to hold ISubnet objects (L2) and CfnSubnet/CfnRouteTable (L1)
267
+ # We will store ISubnet for consistency, as CfnSubnet has a .subnet_id property
268
+ self.public_subnets: List[ec2.ISubnet] = []
269
+ self.private_subnets: List[ec2.ISubnet] = []
270
+ # Store L1 CfnRouteTables explicitly if you need to reference them later
271
+ self.private_route_tables_cfn: List[ec2.CfnRouteTable] = []
272
+ self.public_route_tables_cfn: List[ec2.CfnRouteTable] = (
273
+ []
274
+ ) # New: to store public RTs
275
+
276
+ names_to_create_private = []
277
+ names_to_create_public = []
278
+
279
+ if not PUBLIC_SUBNETS_TO_USE and not PRIVATE_SUBNETS_TO_USE:
280
+ print(
281
+ "Warning: No public or private subnets specified in *_SUBNETS_TO_USE. Attempting to select from existing VPC subnets."
282
+ )
283
+
284
+ print("vpc.public_subnets:", vpc.public_subnets)
285
+ print("vpc.private_subnets:", vpc.private_subnets)
286
+
287
+ if (
288
+ vpc.public_subnets
289
+ ): # These are already one_per_az if max_azs was used and Vpc created them
290
+ self.public_subnets.extend(vpc.public_subnets)
291
+ else:
292
+ self.node.add_warning("No public subnets found in the VPC.")
293
+
294
+ # Get private subnets with egress specifically
295
+ # selected_private_subnets_with_egress = vpc.select_subnets(subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS)
296
+
297
+ print(
298
+ f"Selected from VPC: {len(self.public_subnets)} public, {len(self.private_subnets)} private_with_egress subnets."
299
+ )
300
+
301
+ if (
302
+ len(self.public_subnets) < 1 or len(self.private_subnets) < 1
303
+ ): # Simplified check for new VPC
304
+ # If new_vpc_max_azs was 1, you'd have 1 of each. If 2, then 2 of each.
305
+ # The original check ' < 2' might be too strict if new_vpc_max_azs=1
306
+ pass # For new VPC, allow single AZ setups if configured that way. The VPC construct ensures one per AZ up to max_azs.
307
+
308
+ if not self.public_subnets and not self.private_subnets:
309
+ print(
310
+ "Error: No public or private subnets could be found in the VPC for automatic selection. "
311
+ "You must either specify subnets in *_SUBNETS_TO_USE or ensure the VPC has discoverable subnets."
312
+ )
313
+ raise RuntimeError("No suitable subnets found for automatic selection.")
314
+ else:
315
+ print(
316
+ f"Automatically selected {len(self.public_subnets)} public and {len(self.private_subnets)} private subnets based on VPC properties."
317
+ )
318
+
319
+ selected_public_subnets = vpc.select_subnets(
320
+ subnet_type=ec2.SubnetType.PUBLIC, one_per_az=True
321
+ )
322
+ private_subnets_egress = vpc.select_subnets(
323
+ subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS, one_per_az=True
324
+ )
325
+
326
+ if private_subnets_egress.subnets:
327
+ self.private_subnets.extend(private_subnets_egress.subnets)
328
+ else:
329
+ self.node.add_warning(
330
+ "No PRIVATE_WITH_EGRESS subnets found in the VPC."
331
+ )
332
+
333
+ try:
334
+ private_subnets_isolated = vpc.select_subnets(
335
+ subnet_type=ec2.SubnetType.PRIVATE_ISOLATED, one_per_az=True
336
+ )
337
+ except Exception as e:
338
+ private_subnets_isolated = []
339
+ print("Could not find any isolated subnets due to:", e)
340
+
341
+ ###
342
+ combined_subnet_objects = []
343
+
344
+ if private_subnets_isolated:
345
+ if private_subnets_egress.subnets:
346
+ # Add the first PRIVATE_WITH_EGRESS subnet
347
+ combined_subnet_objects.append(private_subnets_egress.subnets[0])
348
+ elif not private_subnets_isolated:
349
+ if private_subnets_egress.subnets:
350
+ # Add the first PRIVATE_WITH_EGRESS subnet
351
+ combined_subnet_objects.extend(private_subnets_egress.subnets)
352
+ else:
353
+ self.node.add_warning(
354
+ "No PRIVATE_WITH_EGRESS subnets found to select the first one."
355
+ )
356
+
357
+ # Add all PRIVATE_ISOLATED subnets *except* the first one (if they exist)
358
+ try:
359
+ if len(private_subnets_isolated.subnets) > 1:
360
+ combined_subnet_objects.extend(private_subnets_isolated.subnets[1:])
361
+ elif (
362
+ private_subnets_isolated.subnets
363
+ ): # Only 1 isolated subnet, add a warning if [1:] was desired
364
+ self.node.add_warning(
365
+ "Only one PRIVATE_ISOLATED subnet found, private_subnets_isolated.subnets[1:] will be empty."
366
+ )
367
+ else:
368
+ self.node.add_warning("No PRIVATE_ISOLATED subnets found.")
369
+ except Exception as e:
370
+ print("Could not identify private isolated subnets due to:", e)
371
+
372
+ # Create an ec2.SelectedSubnets object from the combined private subnet list.
373
+ selected_private_subnets = vpc.select_subnets(
374
+ subnets=combined_subnet_objects
375
+ )
376
+
377
+ print("selected_public_subnets:", selected_public_subnets)
378
+ print("selected_private_subnets:", selected_private_subnets)
379
+
380
+ if (
381
+ len(selected_public_subnets.subnet_ids) < 2
382
+ or len(selected_private_subnets.subnet_ids) < 2
383
+ ):
384
+ raise Exception(
385
+ "Need at least two public or private subnets in different availability zones"
386
+ )
387
+
388
+ if not selected_public_subnets and not selected_private_subnets:
389
+ # If no subnets could be found even with automatic selection, raise an error.
390
+ # This ensures the stack doesn't proceed if it absolutely needs subnets.
391
+ print(
392
+ "Error: No existing public or private subnets could be found in the VPC for automatic selection. "
393
+ "You must either specify subnets in *_SUBNETS_TO_USE or ensure the VPC has discoverable subnets."
394
+ )
395
+ raise RuntimeError("No suitable subnets found for automatic selection.")
396
+ else:
397
+ self.public_subnets = selected_public_subnets.subnets
398
+ self.private_subnets = selected_private_subnets.subnets
399
+ print(
400
+ f"Automatically selected {len(self.public_subnets)} public and {len(self.private_subnets)} private subnets based on VPC discovery."
401
+ )
402
+
403
+ print("self.public_subnets:", self.public_subnets)
404
+ print("self.private_subnets:", self.private_subnets)
405
+ # Since subnets are now assigned, we can exit this processing block.
406
+ # The rest of the original code (which iterates *_SUBNETS_TO_USE) will be skipped.
407
+
408
+ checked_public_subnets_ctx = get_context_dict("checked_public_subnets")
409
+ checked_private_subnets_ctx = get_context_dict("checked_private_subnets")
410
+
411
+ public_subnets_data_for_creation_ctx = get_context_list_of_dicts(
412
+ "public_subnets_to_create"
413
+ )
414
+ private_subnets_data_for_creation_ctx = get_context_list_of_dicts(
415
+ "private_subnets_to_create"
416
+ )
417
+
418
+ # --- 3. Process Public Subnets ---
419
+ print("\n--- Processing Public Subnets ---")
420
+ # Import existing public subnets
421
+ if checked_public_subnets_ctx:
422
+ for i, subnet_name in enumerate(PUBLIC_SUBNETS_TO_USE):
423
+ subnet_info = checked_public_subnets_ctx.get(subnet_name)
424
+ if subnet_info and subnet_info.get("exists"):
425
+ subnet_id = subnet_info.get("id")
426
+ if not subnet_id:
427
+ raise RuntimeError(
428
+ f"Context for existing public subnet '{subnet_name}' is missing 'id'."
429
+ )
430
+ subnet_az = subnet_info.get("az")
431
+ if (
432
+ not subnet_az
433
+ and PUBLIC_SUBNET_AVAILABILITY_ZONES
434
+ and i < len(PUBLIC_SUBNET_AVAILABILITY_ZONES)
435
+ ):
436
+ subnet_az = PUBLIC_SUBNET_AVAILABILITY_ZONES[i]
437
+ if not subnet_az:
438
+ raise RuntimeError(
439
+ f"Context for existing public subnet '{subnet_name}' is missing 'az'."
440
+ )
441
+ subnet_attrs = {
442
+ "subnet_id": subnet_id,
443
+ "availability_zone": subnet_az,
444
+ }
445
+ route_table_id = subnet_info.get("route_table_id")
446
+ if route_table_id:
447
+ subnet_attrs["route_table_id"] = route_table_id
448
+ try:
449
+ imported_subnet = ec2.Subnet.from_subnet_attributes(
450
+ self,
451
+ f"ImportedPublicSubnet{subnet_name.replace('-', '')}{i}",
452
+ **subnet_attrs,
453
+ )
454
+ self.public_subnets.append(imported_subnet)
455
+ print(
456
+ f"Imported existing public subnet: {subnet_name} (ID: {subnet_id})"
457
+ )
458
+ except Exception as e:
459
+ raise RuntimeError(
460
+ f"Failed to import public subnet '{subnet_name}' with ID '{subnet_id}'. Error: {e}"
461
+ )
462
+
463
+ # Create new public subnets based on public_subnets_data_for_creation_ctx
464
+ if public_subnets_data_for_creation_ctx:
465
+ names_to_create_public = [
466
+ s["name"] for s in public_subnets_data_for_creation_ctx
467
+ ]
468
+ cidrs_to_create_public = [
469
+ s["cidr"] for s in public_subnets_data_for_creation_ctx
470
+ ]
471
+ azs_to_create_public = [
472
+ s["az"] for s in public_subnets_data_for_creation_ctx
473
+ ]
474
+
475
+ if names_to_create_public:
476
+ print(
477
+ f"Attempting to create {len(names_to_create_public)} new public subnets: {names_to_create_public}"
478
+ )
479
+ newly_created_public_subnets, newly_created_public_rts_cfn = (
480
+ create_subnets(
481
+ self,
482
+ vpc,
483
+ CDK_PREFIX,
484
+ names_to_create_public,
485
+ cidrs_to_create_public,
486
+ azs_to_create_public,
487
+ is_public=True,
488
+ internet_gateway_id=EXISTING_IGW_ID,
489
+ )
490
+ )
491
+ self.public_subnets.extend(newly_created_public_subnets)
492
+ self.public_route_tables_cfn.extend(newly_created_public_rts_cfn)
493
+
494
+ if (
495
+ not self.public_subnets
496
+ and not names_to_create_public
497
+ and not PUBLIC_SUBNETS_TO_USE
498
+ ):
499
+ raise Exception("No public subnets found or created, exiting.")
500
+
501
+ # --- NAT Gateway Creation/Lookup ---
502
+ print("Creating NAT gateway/located existing")
503
+ self.single_nat_gateway_id = None
504
+
505
+ nat_gw_id_from_context = SINGLE_NAT_GATEWAY_ID or get_context_str(
506
+ "id:NatGateway"
507
+ )
508
+
509
+ if nat_gw_id_from_context:
510
+ print(
511
+ f"Using existing NAT Gateway ID from context: {nat_gw_id_from_context}"
512
+ )
513
+ self.single_nat_gateway_id = nat_gw_id_from_context
514
+
515
+ elif (
516
+ new_vpc_created
517
+ and new_vpc_nat_gateways > 0
518
+ and hasattr(vpc, "nat_gateways")
519
+ and vpc.nat_gateways
520
+ ):
521
+ self.single_nat_gateway_id = vpc.nat_gateways[0].gateway_id
522
+ print(
523
+ f"Using NAT Gateway {self.single_nat_gateway_id} created by the new VPC construct."
524
+ )
525
+
526
+ if not self.single_nat_gateway_id:
527
+ print("Creating a new NAT gateway")
528
+
529
+ if hasattr(vpc, "nat_gateways") and vpc.nat_gateways:
530
+ print("Existing NAT gateway found in vpc")
531
+ pass
532
+
533
+ # If not in context, create a new one, but only if we have a public subnet.
534
+ elif self.public_subnets:
535
+ print("NAT Gateway ID not found in context. Creating a new one.")
536
+ # Place the NAT GW in the first available public subnet
537
+ first_public_subnet = self.public_subnets[0]
538
+
539
+ self.single_nat_gateway_id = create_nat_gateway(
540
+ self,
541
+ first_public_subnet,
542
+ nat_gateway_name=NAT_GATEWAY_NAME,
543
+ nat_gateway_id_context_key=SINGLE_NAT_GATEWAY_ID,
544
+ )
545
+ else:
546
+ print(
547
+ "WARNING: No public subnets available and NAT gateway not found in existing VPC. Cannot create a NAT Gateway."
548
+ )
549
+
550
+ # --- 4. Process Private Subnets ---
551
+ print("\n--- Processing Private Subnets ---")
552
+ if checked_private_subnets_ctx:
553
+ for i, subnet_name in enumerate(PRIVATE_SUBNETS_TO_USE):
554
+ subnet_info = checked_private_subnets_ctx.get(subnet_name)
555
+ if subnet_info and subnet_info.get("exists"):
556
+ subnet_id = subnet_info.get("id")
557
+ if not subnet_id:
558
+ raise RuntimeError(
559
+ f"Context for existing private subnet '{subnet_name}' is missing 'id'."
560
+ )
561
+ subnet_az = subnet_info.get("az")
562
+ if (
563
+ not subnet_az
564
+ and PRIVATE_SUBNET_AVAILABILITY_ZONES
565
+ and i < len(PRIVATE_SUBNET_AVAILABILITY_ZONES)
566
+ ):
567
+ subnet_az = PRIVATE_SUBNET_AVAILABILITY_ZONES[i]
568
+ if not subnet_az:
569
+ raise RuntimeError(
570
+ f"Context for existing private subnet '{subnet_name}' is missing 'az'."
571
+ )
572
+ subnet_attrs = {
573
+ "subnet_id": subnet_id,
574
+ "availability_zone": subnet_az,
575
+ }
576
+ route_table_id = subnet_info.get("route_table_id")
577
+ if route_table_id:
578
+ subnet_attrs["route_table_id"] = route_table_id
579
+ try:
580
+ imported_subnet = ec2.Subnet.from_subnet_attributes(
581
+ self,
582
+ f"ImportedPrivateSubnet{subnet_name.replace('-', '')}{i}",
583
+ **subnet_attrs,
584
+ )
585
+ self.private_subnets.append(imported_subnet)
586
+ print(
587
+ f"Imported existing private subnet: {subnet_name} (ID: {subnet_id})"
588
+ )
589
+ except Exception as e:
590
+ raise RuntimeError(
591
+ f"Failed to import private subnet '{subnet_name}' with ID '{subnet_id}'. Error: {e}"
592
+ )
593
+
594
+ # Create new private subnets
595
+ if private_subnets_data_for_creation_ctx:
596
+ names_to_create_private = [
597
+ s["name"] for s in private_subnets_data_for_creation_ctx
598
+ ]
599
+ cidrs_to_create_private = [
600
+ s["cidr"] for s in private_subnets_data_for_creation_ctx
601
+ ]
602
+ azs_to_create_private = [
603
+ s["az"] for s in private_subnets_data_for_creation_ctx
604
+ ]
605
+
606
+ if names_to_create_private:
607
+ print(
608
+ f"Attempting to create {len(names_to_create_private)} new private subnets: {names_to_create_private}"
609
+ )
610
+ # --- CALL THE NEW CREATE_SUBNETS FUNCTION FOR PRIVATE ---
611
+ # Ensure self.single_nat_gateway_id is available before this call
612
+ if not self.single_nat_gateway_id:
613
+ raise ValueError(
614
+ "A single NAT Gateway ID is required for private subnets but was not resolved."
615
+ )
616
+
617
+ newly_created_private_subnets_cfn, newly_created_private_rts_cfn = (
618
+ create_subnets(
619
+ self,
620
+ vpc,
621
+ CDK_PREFIX,
622
+ names_to_create_private,
623
+ cidrs_to_create_private,
624
+ azs_to_create_private,
625
+ is_public=False,
626
+ single_nat_gateway_id=self.single_nat_gateway_id, # Pass the single NAT Gateway ID
627
+ )
628
+ )
629
+ self.private_subnets.extend(newly_created_private_subnets_cfn)
630
+ self.private_route_tables_cfn.extend(newly_created_private_rts_cfn)
631
+ print(
632
+ f"Successfully defined {len(newly_created_private_subnets_cfn)} new private subnets and their route tables for creation."
633
+ )
634
+ else:
635
+ print(
636
+ "No private subnets specified for creation in context ('private_subnets_to_create')."
637
+ )
638
+
639
+ # if not self.private_subnets:
640
+ # raise Exception("No private subnets found or created, exiting.")
641
+
642
+ if (
643
+ not self.private_subnets
644
+ and not names_to_create_private
645
+ and not PRIVATE_SUBNETS_TO_USE
646
+ ):
647
+ # This condition might need adjustment for new VPCs.
648
+ raise Exception("No private subnets found or created, exiting.")
649
+
650
+ # --- 5. Sanity Check and Output ---
651
+ # Output the single NAT Gateway ID for verification
652
+ if self.single_nat_gateway_id:
653
+ CfnOutput(
654
+ self,
655
+ "SingleNatGatewayId",
656
+ value=self.single_nat_gateway_id,
657
+ description="ID of the single NAT Gateway resolved or created.",
658
+ )
659
+ elif (
660
+ NEW_VPC_DEFAULT_NAME
661
+ and (self.node.try_get_context("new_vpc_nat_gateways") or 1) > 0
662
+ ):
663
+ print(
664
+ "INFO: A new VPC was created with NAT Gateway(s). Their routing is handled by the VPC construct. No single_nat_gateway_id was explicitly set for separate output."
665
+ )
666
+ else:
667
+ out_message = "WARNING: No single NAT Gateway was resolved or created explicitly by the script's logic after VPC setup."
668
+ print(out_message)
669
+ raise Exception(out_message)
670
+
671
+ # --- Outputs for other stacks/regions ---
672
+ # These are crucial for cross-stack, cross-region referencing
673
+
674
+ self.params = dict()
675
+ self.params["vpc_id"] = vpc.vpc_id
676
+ self.params["private_subnets"] = self.private_subnets
677
+ self.params["private_route_tables"] = self.private_route_tables_cfn
678
+ self.params["public_subnets"] = self.public_subnets
679
+ self.params["public_route_tables"] = self.public_route_tables_cfn
680
+
681
+ private_subnet_selection = ec2.SubnetSelection(subnets=self.private_subnets)
682
+ public_subnet_selection = ec2.SubnetSelection(subnets=self.public_subnets)
683
+
684
+ for sub in private_subnet_selection.subnets:
685
+ print(
686
+ "private subnet:",
687
+ sub.subnet_id,
688
+ "is in availability zone:",
689
+ sub.availability_zone,
690
+ )
691
+
692
+ for sub in public_subnet_selection.subnets:
693
+ print(
694
+ "public subnet:",
695
+ sub.subnet_id,
696
+ "is in availability zone:",
697
+ sub.availability_zone,
698
+ )
699
+
700
+ print("Private subnet route tables:", self.private_route_tables_cfn)
701
+
702
+ # Add the S3 Gateway Endpoint to the VPC
703
+ if names_to_create_private:
704
+ try:
705
+ s3_gateway_endpoint = vpc.add_gateway_endpoint(
706
+ "S3GatewayEndpoint",
707
+ service=ec2.GatewayVpcEndpointAwsService.S3,
708
+ subnets=[private_subnet_selection],
709
+ )
710
+ except Exception as e:
711
+ print("Could not add S3 gateway endpoint to subnets due to:", e)
712
+
713
+ # Output some useful information
714
+ CfnOutput(
715
+ self,
716
+ "VpcIdOutput",
717
+ value=vpc.vpc_id,
718
+ description="The ID of the VPC where the S3 Gateway Endpoint is deployed.",
719
+ )
720
+ CfnOutput(
721
+ self,
722
+ "S3GatewayEndpointService",
723
+ value=s3_gateway_endpoint.vpc_endpoint_id,
724
+ description="The id for the S3 Gateway Endpoint.",
725
+ ) # Specify the S3 service
726
+
727
+ # --- IAM Roles ---
728
+ if USE_CUSTOM_KMS_KEY == "1":
729
+ kms_key = kms.Key(
730
+ self,
731
+ "RedactionSharedKmsKey",
732
+ alias=CUSTOM_KMS_KEY_NAME,
733
+ removal_policy=RemovalPolicy.DESTROY,
734
+ )
735
+
736
+ custom_sts_kms_policy_dict = {
737
+ "Version": "2012-10-17",
738
+ "Statement": [
739
+ {
740
+ "Sid": "STSCallerIdentity",
741
+ "Effect": "Allow",
742
+ "Action": ["sts:GetCallerIdentity"],
743
+ "Resource": "*",
744
+ },
745
+ {
746
+ "Sid": "KMSAccess",
747
+ "Effect": "Allow",
748
+ "Action": ["kms:Encrypt", "kms:Decrypt", "kms:GenerateDataKey"],
749
+ "Resource": kms_key.key_arn, # Use key_arn, as it's the full ARN, safer than key_id
750
+ },
751
+ ],
752
+ }
753
+ else:
754
+ kms_key = None
755
+
756
+ custom_sts_kms_policy_dict = {
757
+ "Version": "2012-10-17",
758
+ "Statement": [
759
+ {
760
+ "Sid": "STSCallerIdentity",
761
+ "Effect": "Allow",
762
+ "Action": ["sts:GetCallerIdentity"],
763
+ "Resource": "*",
764
+ },
765
+ {
766
+ "Sid": "KMSSecretsManagerDecrypt", # Explicitly add decrypt for default key
767
+ "Effect": "Allow",
768
+ "Action": ["kms:Decrypt"],
769
+ "Resource": f"arn:aws:kms:{AWS_REGION}:{AWS_ACCOUNT_ID}:key/aws/secretsmanager",
770
+ },
771
+ ],
772
+ }
773
+ custom_sts_kms_policy = json.dumps(custom_sts_kms_policy_dict, indent=4)
774
+
775
+ try:
776
+ codebuild_role_name = CODEBUILD_ROLE_NAME
777
+
778
+ if get_context_bool(f"exists:{codebuild_role_name}"):
779
+ # If exists, lookup/import the role using ARN from context
780
+ role_arn = get_context_str(f"arn:{codebuild_role_name}")
781
+ if not role_arn:
782
+ raise ValueError(
783
+ f"Context value 'arn:{codebuild_role_name}' is required if role exists."
784
+ )
785
+ codebuild_role = iam.Role.from_role_arn(
786
+ self, "CodeBuildRole", role_arn=role_arn
787
+ )
788
+ print("Using existing CodeBuild role")
789
+ else:
790
+ # If not exists, create the role
791
+ codebuild_role = iam.Role(
792
+ self,
793
+ "CodeBuildRole", # Logical ID
794
+ role_name=codebuild_role_name, # Explicit resource name
795
+ assumed_by=iam.ServicePrincipal("codebuild.amazonaws.com"),
796
+ )
797
+ codebuild_role.add_managed_policy(
798
+ iam.ManagedPolicy.from_aws_managed_policy_name(
799
+ "EC2InstanceProfileForImageBuilderECRContainerBuilds"
800
+ )
801
+ )
802
+ print("Successfully created new CodeBuild role")
803
+
804
+ task_role_name = ECS_TASK_ROLE_NAME
805
+ if get_context_bool(f"exists:{task_role_name}"):
806
+ role_arn = get_context_str(f"arn:{task_role_name}")
807
+ if not role_arn:
808
+ raise ValueError(
809
+ f"Context value 'arn:{task_role_name}' is required if role exists."
810
+ )
811
+ task_role = iam.Role.from_role_arn(self, "TaskRole", role_arn=role_arn)
812
+ print("Using existing ECS task role")
813
+ else:
814
+ task_role = iam.Role(
815
+ self,
816
+ "TaskRole", # Logical ID
817
+ role_name=task_role_name, # Explicit resource name
818
+ assumed_by=iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
819
+ )
820
+ for role in AWS_MANAGED_TASK_ROLES_LIST:
821
+ print(f"Adding {role} to policy")
822
+ task_role.add_managed_policy(
823
+ iam.ManagedPolicy.from_aws_managed_policy_name(f"{role}")
824
+ )
825
+ task_role = add_custom_policies(
826
+ self, task_role, custom_policy_text=custom_sts_kms_policy
827
+ )
828
+ print("Successfully created new ECS task role")
829
+
830
+ execution_role_name = ECS_TASK_EXECUTION_ROLE_NAME
831
+ if get_context_bool(f"exists:{execution_role_name}"):
832
+ role_arn = get_context_str(f"arn:{execution_role_name}")
833
+ if not role_arn:
834
+ raise ValueError(
835
+ f"Context value 'arn:{execution_role_name}' is required if role exists."
836
+ )
837
+ execution_role = iam.Role.from_role_arn(
838
+ self, "ExecutionRole", role_arn=role_arn
839
+ )
840
+ print("Using existing ECS execution role")
841
+ else:
842
+ execution_role = iam.Role(
843
+ self,
844
+ "ExecutionRole", # Logical ID
845
+ role_name=execution_role_name, # Explicit resource name
846
+ assumed_by=iam.ServicePrincipal("ecs-tasks.amazonaws.com"),
847
+ )
848
+ for role in AWS_MANAGED_TASK_ROLES_LIST:
849
+ execution_role.add_managed_policy(
850
+ iam.ManagedPolicy.from_aws_managed_policy_name(f"{role}")
851
+ )
852
+ execution_role = add_custom_policies(
853
+ self, execution_role, custom_policy_text=custom_sts_kms_policy
854
+ )
855
+ print("Successfully created new ECS execution role")
856
+
857
+ except Exception as e:
858
+ raise Exception("Failed at IAM role step due to:", e)
859
+
860
+ # --- S3 Buckets ---
861
+ try:
862
+ log_bucket_name = S3_LOG_CONFIG_BUCKET_NAME
863
+ if get_context_bool(f"exists:{log_bucket_name}"):
864
+ bucket = s3.Bucket.from_bucket_name(
865
+ self, "LogConfigBucket", bucket_name=log_bucket_name
866
+ )
867
+ print("Using existing S3 bucket", log_bucket_name)
868
+ else:
869
+ log_bucket_lifecycle = [
870
+ s3.LifecycleRule(
871
+ abort_incomplete_multipart_upload_after=Duration.days(7)
872
+ )
873
+ ]
874
+ if USE_CUSTOM_KMS_KEY == "1" and isinstance(kms_key, kms.Key):
875
+ bucket = s3.Bucket(
876
+ self,
877
+ "LogConfigBucket",
878
+ bucket_name=log_bucket_name,
879
+ lifecycle_rules=log_bucket_lifecycle,
880
+ versioned=False,
881
+ removal_policy=RemovalPolicy.DESTROY,
882
+ auto_delete_objects=True,
883
+ encryption=s3.BucketEncryption.KMS,
884
+ encryption_key=kms_key,
885
+ )
886
+ else:
887
+ bucket = s3.Bucket(
888
+ self,
889
+ "LogConfigBucket",
890
+ bucket_name=log_bucket_name,
891
+ lifecycle_rules=log_bucket_lifecycle,
892
+ versioned=False,
893
+ removal_policy=RemovalPolicy.DESTROY,
894
+ auto_delete_objects=True,
895
+ )
896
+
897
+ print("Created S3 bucket", log_bucket_name)
898
+
899
+ # Add policies - this will apply to both created and imported buckets
900
+ # CDK handles idempotent policy additions
901
+ bucket.add_to_resource_policy(
902
+ iam.PolicyStatement(
903
+ effect=iam.Effect.ALLOW,
904
+ principals=[task_role], # Pass the role object directly
905
+ actions=["s3:GetObject", "s3:PutObject"],
906
+ resources=[f"{bucket.bucket_arn}/*"],
907
+ )
908
+ )
909
+ bucket.add_to_resource_policy(
910
+ iam.PolicyStatement(
911
+ effect=iam.Effect.ALLOW,
912
+ principals=[task_role],
913
+ actions=["s3:ListBucket"],
914
+ resources=[bucket.bucket_arn],
915
+ )
916
+ )
917
+
918
+ output_bucket_name = S3_OUTPUT_BUCKET_NAME
919
+ if get_context_bool(f"exists:{output_bucket_name}"):
920
+ output_bucket = s3.Bucket.from_bucket_name(
921
+ self, "OutputBucket", bucket_name=output_bucket_name
922
+ )
923
+ print("Using existing Output bucket", output_bucket_name)
924
+ else:
925
+ if USE_CUSTOM_KMS_KEY == "1" and isinstance(kms_key, kms.Key):
926
+ output_bucket = s3.Bucket(
927
+ self,
928
+ "OutputBucket",
929
+ bucket_name=output_bucket_name,
930
+ lifecycle_rules=[
931
+ s3.LifecycleRule(
932
+ expiration=Duration.days(
933
+ int(DAYS_TO_DISPLAY_WHOLE_DOCUMENT_JOBS)
934
+ )
935
+ )
936
+ ],
937
+ versioned=False,
938
+ removal_policy=RemovalPolicy.DESTROY,
939
+ auto_delete_objects=True,
940
+ encryption=s3.BucketEncryption.KMS,
941
+ encryption_key=kms_key,
942
+ )
943
+ else:
944
+ output_bucket = s3.Bucket(
945
+ self,
946
+ "OutputBucket",
947
+ bucket_name=output_bucket_name,
948
+ lifecycle_rules=[
949
+ s3.LifecycleRule(
950
+ expiration=Duration.days(
951
+ int(DAYS_TO_DISPLAY_WHOLE_DOCUMENT_JOBS)
952
+ )
953
+ )
954
+ ],
955
+ versioned=False,
956
+ removal_policy=RemovalPolicy.DESTROY,
957
+ auto_delete_objects=True,
958
+ )
959
+
960
+ print("Created Output bucket:", output_bucket_name)
961
+
962
+ add_s3_enforce_ssl_policy(bucket)
963
+ add_s3_enforce_ssl_policy(output_bucket)
964
+
965
+ # Add policies to output bucket
966
+ output_bucket.add_to_resource_policy(
967
+ iam.PolicyStatement(
968
+ effect=iam.Effect.ALLOW,
969
+ principals=[task_role],
970
+ actions=["s3:GetObject", "s3:PutObject"],
971
+ resources=[f"{output_bucket.bucket_arn}/*"],
972
+ )
973
+ )
974
+ output_bucket.add_to_resource_policy(
975
+ iam.PolicyStatement(
976
+ effect=iam.Effect.ALLOW,
977
+ principals=[task_role],
978
+ actions=["s3:ListBucket"],
979
+ resources=[output_bucket.bucket_arn],
980
+ )
981
+ )
982
+
983
+ except Exception as e:
984
+ raise Exception("Could not handle S3 buckets due to:", e)
985
+
986
+ # --- Elastic Container Registry ---
987
+ try:
988
+ full_ecr_repo_name = ECR_CDK_REPO_NAME
989
+ if get_context_bool(f"exists:{full_ecr_repo_name}"):
990
+ ecr_repo = ecr.Repository.from_repository_name(
991
+ self, "ECRRepo", repository_name=full_ecr_repo_name
992
+ )
993
+ print("Using existing ECR repository")
994
+ else:
995
+ ecr_repo = ecr.Repository(
996
+ self, "ECRRepo", repository_name=full_ecr_repo_name
997
+ ) # Explicitly set repository_name
998
+ print("Created ECR repository", full_ecr_repo_name)
999
+
1000
+ ecr_image_loc = ecr_repo.repository_uri
1001
+ except Exception as e:
1002
+ raise Exception("Could not handle ECR repo due to:", e)
1003
+
1004
+ # --- CODEBUILD ---
1005
+ try:
1006
+ codebuild_project_name = CODEBUILD_PROJECT_NAME
1007
+ if get_context_bool(f"exists:{codebuild_project_name}"):
1008
+ # Lookup CodeBuild project by ARN from context
1009
+ project_arn = get_context_str(f"arn:{codebuild_project_name}")
1010
+ if not project_arn:
1011
+ raise ValueError(
1012
+ f"Context value 'arn:{codebuild_project_name}' is required if project exists."
1013
+ )
1014
+ codebuild.Project.from_project_arn(
1015
+ self, "CodeBuildProject", project_arn=project_arn
1016
+ )
1017
+ print("Using existing CodeBuild project")
1018
+ else:
1019
+ codebuild.Project(
1020
+ self,
1021
+ "CodeBuildProject", # Logical ID
1022
+ project_name=codebuild_project_name, # Explicit resource name
1023
+ role=codebuild_role,
1024
+ source=codebuild.Source.git_hub(
1025
+ owner=GITHUB_REPO_USERNAME,
1026
+ repo=GITHUB_REPO_NAME,
1027
+ branch_or_ref=GITHUB_REPO_BRANCH,
1028
+ ),
1029
+ environment=codebuild.BuildEnvironment(
1030
+ build_image=codebuild.LinuxBuildImage.STANDARD_7_0,
1031
+ privileged=True,
1032
+ environment_variables={
1033
+ "ECR_REPO_NAME": codebuild.BuildEnvironmentVariable(
1034
+ value=full_ecr_repo_name
1035
+ ),
1036
+ "AWS_DEFAULT_REGION": codebuild.BuildEnvironmentVariable(
1037
+ value=AWS_REGION
1038
+ ),
1039
+ "AWS_ACCOUNT_ID": codebuild.BuildEnvironmentVariable(
1040
+ value=AWS_ACCOUNT_ID
1041
+ ),
1042
+ "APP_MODE": codebuild.BuildEnvironmentVariable(
1043
+ value="gradio"
1044
+ ),
1045
+ },
1046
+ ),
1047
+ build_spec=codebuild.BuildSpec.from_object(
1048
+ {
1049
+ "version": "0.2",
1050
+ "phases": {
1051
+ "pre_build": {
1052
+ "commands": [
1053
+ "echo Logging in to Amazon ECR",
1054
+ "aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com",
1055
+ ]
1056
+ },
1057
+ "build": {
1058
+ "commands": [
1059
+ "echo Building the Docker image",
1060
+ "docker build --build-arg APP_MODE=$APP_MODE --target $APP_MODE -t $ECR_REPO_NAME:latest .",
1061
+ "docker tag $ECR_REPO_NAME:latest $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$ECR_REPO_NAME:latest",
1062
+ ]
1063
+ },
1064
+ "post_build": {
1065
+ "commands": [
1066
+ "echo Pushing the Docker image",
1067
+ "docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$ECR_REPO_NAME:latest",
1068
+ ]
1069
+ },
1070
+ },
1071
+ }
1072
+ ),
1073
+ )
1074
+ print("Successfully created CodeBuild project", codebuild_project_name)
1075
+
1076
+ # Imported projects have role=undefined in CDK; use the actual service
1077
+ # role from context (existing project) or the managed codebuild_role (new).
1078
+ if get_context_bool(f"exists:{codebuild_project_name}"):
1079
+ project_service_role_arn = get_context_str(
1080
+ f"service_role_arn:{codebuild_project_name}"
1081
+ )
1082
+ if project_service_role_arn:
1083
+ ecr_grantee = iam.Role.from_role_arn(
1084
+ self,
1085
+ "CodeBuildProjectServiceRole",
1086
+ role_arn=project_service_role_arn,
1087
+ mutable=True,
1088
+ )
1089
+ else:
1090
+ ecr_grantee = codebuild_role
1091
+ else:
1092
+ ecr_grantee = codebuild_role
1093
+ ecr_repo.grant_pull_push(ecr_grantee)
1094
+
1095
+ except Exception as e:
1096
+ raise Exception("Could not handle Codebuild project due to:", e)
1097
+
1098
+ # --- Security Groups ---
1099
+ try:
1100
+ ecs_security_group_name = ECS_SECURITY_GROUP_NAME
1101
+
1102
+ try:
1103
+ ecs_security_group = ec2.SecurityGroup(
1104
+ self,
1105
+ "ECSSecurityGroup", # Logical ID
1106
+ security_group_name=ecs_security_group_name, # Explicit resource name
1107
+ vpc=vpc,
1108
+ )
1109
+ print(f"Created Security Group: {ecs_security_group_name}")
1110
+ except Exception as e: # If lookup fails, create
1111
+ print("Failed to create ECS security group due to:", e)
1112
+
1113
+ alb_security_group_name = ALB_NAME_SECURITY_GROUP_NAME
1114
+
1115
+ try:
1116
+ alb_security_group = ec2.SecurityGroup(
1117
+ self,
1118
+ "ALBSecurityGroup", # Logical ID
1119
+ security_group_name=alb_security_group_name, # Explicit resource name
1120
+ vpc=vpc,
1121
+ )
1122
+ print(f"Created Security Group: {alb_security_group_name}")
1123
+ except Exception as e: # If lookup fails, create
1124
+ print("Failed to create ALB security group due to:", e)
1125
+
1126
+ # Define Ingress Rules - CDK will manage adding/removing these as needed
1127
+ ec2_port_gradio_server_port = ec2.Port.tcp(
1128
+ int(GRADIO_SERVER_PORT)
1129
+ ) # Ensure port is int
1130
+ ecs_security_group.add_ingress_rule(
1131
+ peer=alb_security_group,
1132
+ connection=ec2_port_gradio_server_port,
1133
+ description="ALB traffic",
1134
+ )
1135
+
1136
+ alb_security_group.add_ingress_rule(
1137
+ peer=ec2.Peer.prefix_list("pl-93a247fa"),
1138
+ connection=ec2.Port.all_traffic(),
1139
+ description="CloudFront traffic",
1140
+ )
1141
+
1142
+ except Exception as e:
1143
+ raise Exception("Could not handle security groups due to:", e)
1144
+
1145
+ # --- DynamoDB tables for logs (optional) ---
1146
+
1147
+ if SAVE_LOGS_TO_DYNAMODB == "True":
1148
+ try:
1149
+ print("Creating DynamoDB tables for logs")
1150
+
1151
+ dynamodb.Table(
1152
+ self,
1153
+ "RedactionAccessDataTable",
1154
+ table_name=ACCESS_LOG_DYNAMODB_TABLE_NAME,
1155
+ partition_key=dynamodb.Attribute(
1156
+ name="id", type=dynamodb.AttributeType.STRING
1157
+ ),
1158
+ billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
1159
+ deletion_protection=True,
1160
+ removal_policy=RemovalPolicy.DESTROY,
1161
+ )
1162
+
1163
+ dynamodb.Table(
1164
+ self,
1165
+ "RedactionFeedbackDataTable",
1166
+ table_name=FEEDBACK_LOG_DYNAMODB_TABLE_NAME,
1167
+ partition_key=dynamodb.Attribute(
1168
+ name="id", type=dynamodb.AttributeType.STRING
1169
+ ),
1170
+ billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
1171
+ deletion_protection=True,
1172
+ removal_policy=RemovalPolicy.DESTROY,
1173
+ )
1174
+
1175
+ dynamodb.Table(
1176
+ self,
1177
+ "RedactionUsageDataTable",
1178
+ table_name=USAGE_LOG_DYNAMODB_TABLE_NAME,
1179
+ partition_key=dynamodb.Attribute(
1180
+ name="id", type=dynamodb.AttributeType.STRING
1181
+ ),
1182
+ billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
1183
+ deletion_protection=True,
1184
+ removal_policy=RemovalPolicy.DESTROY,
1185
+ )
1186
+
1187
+ except Exception as e:
1188
+ raise Exception("Could not create DynamoDB tables due to:", e)
1189
+
1190
+ # --- ALB ---
1191
+ try:
1192
+ load_balancer_name = ALB_NAME
1193
+ if len(load_balancer_name) > 32:
1194
+ load_balancer_name = load_balancer_name[-32:]
1195
+ alb_arn = get_context_str(f"arn:{load_balancer_name}") or (
1196
+ EXISTING_LOAD_BALANCER_ARN or None
1197
+ )
1198
+ alb_dns_name = get_context_str(f"dns:{load_balancer_name}") or (
1199
+ EXISTING_LOAD_BALANCER_DNS or None
1200
+ )
1201
+ if alb_arn and alb_dns_name:
1202
+ alb_security_group_id = (
1203
+ get_context_str(f"security_group_id:{load_balancer_name}")
1204
+ or alb_security_group.security_group_id
1205
+ )
1206
+ alb_attrs = {
1207
+ "load_balancer_arn": alb_arn,
1208
+ "load_balancer_dns_name": alb_dns_name,
1209
+ "security_group_id": alb_security_group_id,
1210
+ "vpc": vpc,
1211
+ }
1212
+ alb_canonical_zone_id = get_context_str(
1213
+ f"canonical_hosted_zone_id:{load_balancer_name}"
1214
+ )
1215
+ if alb_canonical_zone_id:
1216
+ alb_attrs["load_balancer_canonical_hosted_zone_id"] = (
1217
+ alb_canonical_zone_id
1218
+ )
1219
+ alb = elbv2.ApplicationLoadBalancer.from_application_load_balancer_attributes(
1220
+ self,
1221
+ "ALB",
1222
+ **alb_attrs,
1223
+ )
1224
+ print(f"Using existing Application Load Balancer {load_balancer_name}.")
1225
+ else:
1226
+ alb = elbv2.ApplicationLoadBalancer(
1227
+ self,
1228
+ "ALB", # Logical ID
1229
+ load_balancer_name=load_balancer_name, # Explicit resource name
1230
+ vpc=vpc,
1231
+ internet_facing=True,
1232
+ security_group=alb_security_group, # Link to SG
1233
+ vpc_subnets=public_subnet_selection, # Link to subnets
1234
+ drop_invalid_header_fields=True,
1235
+ deletion_protection=True,
1236
+ )
1237
+ print("Successfully created new Application Load Balancer")
1238
+ except Exception as e:
1239
+ raise Exception("Could not handle application load balancer due to:", e)
1240
+
1241
+ # --- Cognito User Pool ---
1242
+ try:
1243
+ if get_context_bool(f"exists:{COGNITO_USER_POOL_NAME}"):
1244
+ # Lookup by ID from context
1245
+ user_pool_id = get_context_str(f"id:{COGNITO_USER_POOL_NAME}")
1246
+ if not user_pool_id:
1247
+ raise ValueError(
1248
+ f"Context value 'id:{COGNITO_USER_POOL_NAME}' is required if User Pool exists."
1249
+ )
1250
+ user_pool = cognito.UserPool.from_user_pool_id(
1251
+ self, "UserPool", user_pool_id=user_pool_id
1252
+ )
1253
+ print(f"Using existing user pool {user_pool_id}.")
1254
+ else:
1255
+ user_pool = cognito.UserPool(
1256
+ self,
1257
+ "UserPool",
1258
+ user_pool_name=COGNITO_USER_POOL_NAME,
1259
+ mfa=cognito.Mfa.OFF, # Adjust as needed
1260
+ sign_in_aliases=cognito.SignInAliases(email=True),
1261
+ deletion_protection=True,
1262
+ removal_policy=RemovalPolicy.DESTROY,
1263
+ ) # Adjust as needed
1264
+ print(f"Created new user pool {user_pool.user_pool_id}.")
1265
+
1266
+ # If you're using a certificate, assume that you will be using the ALB Cognito login features. You need different redirect URLs to accept the token that comes from Cognito authentication.
1267
+ if ACM_SSL_CERTIFICATE_ARN:
1268
+ redirect_uris = [
1269
+ COGNITO_REDIRECTION_URL,
1270
+ COGNITO_REDIRECTION_URL + "/oauth2/idpresponse",
1271
+ ]
1272
+ else:
1273
+ redirect_uris = [COGNITO_REDIRECTION_URL]
1274
+
1275
+ user_pool_client_name = COGNITO_USER_POOL_CLIENT_NAME
1276
+ if get_context_bool(f"exists:{user_pool_client_name}"):
1277
+ # Lookup by ID from context (requires User Pool object)
1278
+ user_pool_client_id = get_context_str(f"id:{user_pool_client_name}")
1279
+ if not user_pool_client_id:
1280
+ raise ValueError(
1281
+ f"Context value 'id:{user_pool_client_name}' is required if User Pool Client exists."
1282
+ )
1283
+ user_pool_client = cognito.UserPoolClient.from_user_pool_client_id(
1284
+ self, "UserPoolClient", user_pool_client_id=user_pool_client_id
1285
+ )
1286
+ print(f"Using existing user pool client {user_pool_client_id}.")
1287
+ else:
1288
+ user_pool_client = cognito.UserPoolClient(
1289
+ self,
1290
+ "UserPoolClient",
1291
+ auth_flows=cognito.AuthFlow(
1292
+ user_srp=True, user_password=True
1293
+ ), # Example: enable SRP for secure sign-in
1294
+ user_pool=user_pool,
1295
+ generate_secret=True,
1296
+ user_pool_client_name=user_pool_client_name,
1297
+ supported_identity_providers=[
1298
+ cognito.UserPoolClientIdentityProvider.COGNITO
1299
+ ],
1300
+ o_auth=cognito.OAuthSettings(
1301
+ flows=cognito.OAuthFlows(authorization_code_grant=True),
1302
+ scopes=[
1303
+ cognito.OAuthScope.OPENID,
1304
+ cognito.OAuthScope.EMAIL,
1305
+ cognito.OAuthScope.PROFILE,
1306
+ ],
1307
+ callback_urls=redirect_uris,
1308
+ ),
1309
+ refresh_token_validity=Duration.minutes(
1310
+ COGNITO_REFRESH_TOKEN_VALIDITY
1311
+ ),
1312
+ id_token_validity=Duration.minutes(COGNITO_ID_TOKEN_VALIDITY),
1313
+ access_token_validity=Duration.minutes(
1314
+ COGNITO_ACCESS_TOKEN_VALIDITY
1315
+ ),
1316
+ )
1317
+
1318
+ CfnOutput(
1319
+ self, "CognitoAppClientId", value=user_pool_client.user_pool_client_id
1320
+ )
1321
+
1322
+ print(
1323
+ f"Created new user pool client {user_pool_client.user_pool_client_id}."
1324
+ )
1325
+
1326
+ # Add a domain to the User Pool (crucial for ALB integration)
1327
+ user_pool_domain = user_pool.add_domain(
1328
+ "UserPoolDomain",
1329
+ cognito_domain=cognito.CognitoDomainOptions(
1330
+ domain_prefix=COGNITO_USER_POOL_DOMAIN_PREFIX
1331
+ ),
1332
+ )
1333
+
1334
+ # Apply removal_policy to the created UserPoolDomain construct
1335
+ user_pool_domain.apply_removal_policy(policy=RemovalPolicy.DESTROY)
1336
+
1337
+ CfnOutput(
1338
+ self, "CognitoUserPoolLoginUrl", value=user_pool_domain.base_url()
1339
+ )
1340
+
1341
+ except Exception as e:
1342
+ raise Exception("Could not handle Cognito resources due to:", e)
1343
+
1344
+ # --- Secrets Manager Secret ---
1345
+ try:
1346
+ secret_name = COGNITO_USER_POOL_CLIENT_SECRET_NAME
1347
+ if get_context_bool(f"exists:{secret_name}"):
1348
+ # Lookup by name
1349
+ secret = secretsmanager.Secret.from_secret_name_v2(
1350
+ self, "CognitoSecret", secret_name=secret_name
1351
+ )
1352
+ print("Using existing Secret.")
1353
+ else:
1354
+ if USE_CUSTOM_KMS_KEY == "1" and isinstance(kms_key, kms.Key):
1355
+ secret = secretsmanager.Secret(
1356
+ self,
1357
+ "CognitoSecret", # Logical ID
1358
+ secret_name=secret_name, # Explicit resource name
1359
+ secret_object_value={
1360
+ "REDACTION_USER_POOL_ID": SecretValue.unsafe_plain_text(
1361
+ user_pool.user_pool_id
1362
+ ), # Use the CDK attribute
1363
+ "REDACTION_CLIENT_ID": SecretValue.unsafe_plain_text(
1364
+ user_pool_client.user_pool_client_id
1365
+ ), # Use the CDK attribute
1366
+ "REDACTION_CLIENT_SECRET": user_pool_client.user_pool_client_secret, # Use the CDK attribute
1367
+ },
1368
+ encryption_key=kms_key,
1369
+ )
1370
+ else:
1371
+ secret = secretsmanager.Secret(
1372
+ self,
1373
+ "CognitoSecret", # Logical ID
1374
+ secret_name=secret_name, # Explicit resource name
1375
+ secret_object_value={
1376
+ "REDACTION_USER_POOL_ID": SecretValue.unsafe_plain_text(
1377
+ user_pool.user_pool_id
1378
+ ), # Use the CDK attribute
1379
+ "REDACTION_CLIENT_ID": SecretValue.unsafe_plain_text(
1380
+ user_pool_client.user_pool_client_id
1381
+ ), # Use the CDK attribute
1382
+ "REDACTION_CLIENT_SECRET": user_pool_client.user_pool_client_secret, # Use the CDK attribute
1383
+ },
1384
+ )
1385
+
1386
+ print(
1387
+ "Created new secret in Secrets Manager for Cognito user pool and related details."
1388
+ )
1389
+
1390
+ except Exception as e:
1391
+ raise Exception("Could not handle Secrets Manager secret due to:", e)
1392
+
1393
+ # --- Fargate Task Definition ---
1394
+ try:
1395
+ fargate_task_definition_name = FARGATE_TASK_DEFINITION_NAME
1396
+
1397
+ read_only_file_system = ECS_READ_ONLY_FILE_SYSTEM == "True"
1398
+
1399
+ if os.path.exists(TASK_DEFINITION_FILE_LOCATION):
1400
+ with open(TASK_DEFINITION_FILE_LOCATION) as f: # Use correct path
1401
+ task_def_params = json.load(f)
1402
+ # Need to ensure taskRoleArn and executionRoleArn in JSON are correct ARN strings
1403
+ else:
1404
+ epheremal_storage_volume_name = "appEphemeralVolume"
1405
+
1406
+ task_def_params = {}
1407
+ task_def_params["taskRoleArn"] = (
1408
+ task_role.role_arn
1409
+ ) # Use CDK role object ARN
1410
+ task_def_params["executionRoleArn"] = (
1411
+ execution_role.role_arn
1412
+ ) # Use CDK role object ARN
1413
+ task_def_params["memory"] = ECS_TASK_MEMORY_SIZE
1414
+ task_def_params["cpu"] = ECS_TASK_CPU_SIZE
1415
+ container_def = {
1416
+ "name": full_ecr_repo_name,
1417
+ "image": ecr_image_loc + ":latest",
1418
+ "essential": True,
1419
+ "portMappings": [
1420
+ {
1421
+ "containerPort": int(GRADIO_SERVER_PORT),
1422
+ "hostPort": int(GRADIO_SERVER_PORT),
1423
+ "protocol": "tcp",
1424
+ "appProtocol": "http",
1425
+ }
1426
+ ],
1427
+ "logConfiguration": {
1428
+ "logDriver": "awslogs",
1429
+ "options": {
1430
+ "awslogs-group": ECS_LOG_GROUP_NAME,
1431
+ "awslogs-region": AWS_REGION,
1432
+ "awslogs-stream-prefix": "ecs",
1433
+ },
1434
+ },
1435
+ "environmentFiles": [
1436
+ {"value": bucket.bucket_arn + "/config.env", "type": "s3"}
1437
+ ],
1438
+ "memoryReservation": int(task_def_params["memory"])
1439
+ - 512, # Reserve some memory for the container
1440
+ "mountPoints": [
1441
+ {
1442
+ "sourceVolume": epheremal_storage_volume_name,
1443
+ "containerPath": "/home/user/app/logs",
1444
+ "readOnly": False,
1445
+ },
1446
+ {
1447
+ "sourceVolume": epheremal_storage_volume_name,
1448
+ "containerPath": "/home/user/app/feedback",
1449
+ "readOnly": False,
1450
+ },
1451
+ {
1452
+ "sourceVolume": epheremal_storage_volume_name,
1453
+ "containerPath": "/home/user/app/usage",
1454
+ "readOnly": False,
1455
+ },
1456
+ {
1457
+ "sourceVolume": epheremal_storage_volume_name,
1458
+ "containerPath": "/home/user/app/input",
1459
+ "readOnly": False,
1460
+ },
1461
+ {
1462
+ "sourceVolume": epheremal_storage_volume_name,
1463
+ "containerPath": "/home/user/app/output",
1464
+ "readOnly": False,
1465
+ },
1466
+ {
1467
+ "sourceVolume": epheremal_storage_volume_name,
1468
+ "containerPath": "/home/user/app/tmp",
1469
+ "readOnly": False,
1470
+ },
1471
+ {
1472
+ "sourceVolume": epheremal_storage_volume_name,
1473
+ "containerPath": "/home/user/app/config",
1474
+ "readOnly": False,
1475
+ },
1476
+ {
1477
+ "sourceVolume": epheremal_storage_volume_name,
1478
+ "containerPath": "/tmp/matplotlib_cache",
1479
+ "readOnly": False,
1480
+ },
1481
+ {
1482
+ "sourceVolume": epheremal_storage_volume_name,
1483
+ "containerPath": "/tmp",
1484
+ "readOnly": False,
1485
+ },
1486
+ {
1487
+ "sourceVolume": epheremal_storage_volume_name,
1488
+ "containerPath": "/var/tmp",
1489
+ "readOnly": False,
1490
+ },
1491
+ {
1492
+ "sourceVolume": epheremal_storage_volume_name,
1493
+ "containerPath": "/tmp/tld",
1494
+ "readOnly": False,
1495
+ },
1496
+ {
1497
+ "sourceVolume": epheremal_storage_volume_name,
1498
+ "containerPath": "/tmp/gradio_tmp",
1499
+ "readOnly": False,
1500
+ },
1501
+ {
1502
+ "sourceVolume": epheremal_storage_volume_name,
1503
+ "containerPath": "/home/user/.paddlex",
1504
+ "readOnly": False,
1505
+ },
1506
+ {
1507
+ "sourceVolume": epheremal_storage_volume_name,
1508
+ "containerPath": "/home/user/.local/share/spacy/data",
1509
+ "readOnly": False,
1510
+ },
1511
+ {
1512
+ "sourceVolume": epheremal_storage_volume_name,
1513
+ "containerPath": "/usr/share/tessdata",
1514
+ "readOnly": False,
1515
+ },
1516
+ ],
1517
+ "readonlyRootFilesystem": read_only_file_system,
1518
+ "user": "1000",
1519
+ }
1520
+ task_def_params["containerDefinitions"] = [container_def]
1521
+
1522
+ log_group_name_from_config = task_def_params["containerDefinitions"][0][
1523
+ "logConfiguration"
1524
+ ]["options"]["awslogs-group"]
1525
+
1526
+ cdk_managed_log_group = logs.LogGroup(
1527
+ self,
1528
+ "MyTaskLogGroup", # CDK Logical ID
1529
+ log_group_name=log_group_name_from_config,
1530
+ retention=logs.RetentionDays.ONE_MONTH,
1531
+ removal_policy=RemovalPolicy.DESTROY,
1532
+ )
1533
+
1534
+ epheremal_storage_volume_cdk_obj = ecs.Volume(
1535
+ name=epheremal_storage_volume_name
1536
+ )
1537
+
1538
+ fargate_task_definition = ecs.FargateTaskDefinition(
1539
+ self,
1540
+ "FargateTaskDefinition", # Logical ID
1541
+ family=fargate_task_definition_name,
1542
+ cpu=int(task_def_params["cpu"]),
1543
+ memory_limit_mib=int(task_def_params["memory"]),
1544
+ task_role=task_role,
1545
+ execution_role=execution_role,
1546
+ runtime_platform=ecs.RuntimePlatform(
1547
+ cpu_architecture=ecs.CpuArchitecture.X86_64,
1548
+ operating_system_family=ecs.OperatingSystemFamily.LINUX,
1549
+ ),
1550
+ ephemeral_storage_gib=21, # Minimum is 21 GiB
1551
+ volumes=[epheremal_storage_volume_cdk_obj],
1552
+ )
1553
+ print("Fargate task definition defined.")
1554
+
1555
+ # Add container definitions to the task definition object
1556
+ if task_def_params["containerDefinitions"]:
1557
+ container_def_params = task_def_params["containerDefinitions"][0]
1558
+
1559
+ if container_def_params.get("environmentFiles"):
1560
+ env_files = []
1561
+ for env_file_param in container_def_params["environmentFiles"]:
1562
+ # Need to parse the ARN to get the bucket object and key
1563
+ env_file_arn_parts = env_file_param["value"].split(":::")
1564
+ bucket_name_and_key = env_file_arn_parts[-1]
1565
+ env_bucket_name, env_key = bucket_name_and_key.split("/", 1)
1566
+
1567
+ env_file = ecs.EnvironmentFile.from_bucket(bucket, env_key)
1568
+
1569
+ env_files.append(env_file)
1570
+
1571
+ container = fargate_task_definition.add_container(
1572
+ container_def_params["name"],
1573
+ image=ecs.ContainerImage.from_registry(
1574
+ container_def_params["image"]
1575
+ ),
1576
+ logging=ecs.LogDriver.aws_logs(
1577
+ stream_prefix=container_def_params["logConfiguration"][
1578
+ "options"
1579
+ ]["awslogs-stream-prefix"],
1580
+ log_group=cdk_managed_log_group,
1581
+ ),
1582
+ secrets={
1583
+ "AWS_USER_POOL_ID": ecs.Secret.from_secrets_manager(
1584
+ secret, "REDACTION_USER_POOL_ID"
1585
+ ),
1586
+ "AWS_CLIENT_ID": ecs.Secret.from_secrets_manager(
1587
+ secret, "REDACTION_CLIENT_ID"
1588
+ ),
1589
+ "AWS_CLIENT_SECRET": ecs.Secret.from_secrets_manager(
1590
+ secret, "REDACTION_CLIENT_SECRET"
1591
+ ),
1592
+ },
1593
+ environment_files=env_files,
1594
+ readonly_root_filesystem=read_only_file_system,
1595
+ user=container_def_params.get("user", "1000"),
1596
+ )
1597
+
1598
+ for port_mapping in container_def_params["portMappings"]:
1599
+ container.add_port_mappings(
1600
+ ecs.PortMapping(
1601
+ container_port=int(port_mapping["containerPort"]),
1602
+ host_port=int(port_mapping["hostPort"]),
1603
+ name="port-" + str(port_mapping["containerPort"]),
1604
+ app_protocol=ecs.AppProtocol.http,
1605
+ protocol=ecs.Protocol.TCP,
1606
+ )
1607
+ )
1608
+
1609
+ container.add_port_mappings(
1610
+ ecs.PortMapping(
1611
+ container_port=80,
1612
+ host_port=80,
1613
+ name="port-80",
1614
+ app_protocol=ecs.AppProtocol.http,
1615
+ protocol=ecs.Protocol.TCP,
1616
+ )
1617
+ )
1618
+
1619
+ if container_def_params.get("mountPoints"):
1620
+ mount_points = []
1621
+ for mount_point in container_def_params["mountPoints"]:
1622
+ mount_points.append(
1623
+ ecs.MountPoint(
1624
+ container_path=mount_point["containerPath"],
1625
+ read_only=mount_point["readOnly"],
1626
+ source_volume=epheremal_storage_volume_name,
1627
+ )
1628
+ )
1629
+ container.add_mount_points(*mount_points)
1630
+
1631
+ except Exception as e:
1632
+ raise Exception("Could not handle Fargate task definition due to:", e)
1633
+
1634
+ # --- ECS Cluster ---
1635
+ try:
1636
+ cluster = ecs.Cluster(
1637
+ self,
1638
+ "ECSCluster", # Logical ID
1639
+ cluster_name=CLUSTER_NAME, # Explicit resource name
1640
+ enable_fargate_capacity_providers=True,
1641
+ vpc=vpc,
1642
+ )
1643
+ print("Successfully created new ECS cluster")
1644
+ except Exception as e:
1645
+ raise Exception("Could not handle ECS cluster due to:", e)
1646
+
1647
+ # --- ECS Service ---
1648
+ try:
1649
+ ecs_service_name = ECS_SERVICE_NAME
1650
+
1651
+ if ECS_USE_FARGATE_SPOT == "True":
1652
+ use_fargate_spot = "FARGATE_SPOT"
1653
+ if ECS_USE_FARGATE_SPOT == "False":
1654
+ use_fargate_spot = "FARGATE"
1655
+
1656
+ # Check if service exists - from_service_arn or from_service_name (needs cluster)
1657
+ try:
1658
+ # from_service_name is useful if you have the cluster object
1659
+ ecs_service = ecs.FargateService.from_service_attributes(
1660
+ self,
1661
+ "ECSService", # Logical ID
1662
+ cluster=cluster, # Requires the cluster object
1663
+ service_name=ecs_service_name,
1664
+ )
1665
+ print(f"Using existing ECS service {ecs_service_name}.")
1666
+ except Exception:
1667
+ # Service will be created with a count of 0, because you haven't yet actually built the initial Docker container with CodeBuild
1668
+ ecs_service = ecs.FargateService(
1669
+ self,
1670
+ "ECSService", # Logical ID
1671
+ service_name=ecs_service_name, # Explicit resource name
1672
+ platform_version=ecs.FargatePlatformVersion.LATEST,
1673
+ capacity_provider_strategies=[
1674
+ ecs.CapacityProviderStrategy(
1675
+ capacity_provider=use_fargate_spot, base=0, weight=1
1676
+ )
1677
+ ],
1678
+ cluster=cluster,
1679
+ task_definition=fargate_task_definition, # Link to TD
1680
+ security_groups=[ecs_security_group], # Link to SG
1681
+ vpc_subnets=ec2.SubnetSelection(
1682
+ subnets=self.private_subnets
1683
+ ), # Link to subnets
1684
+ min_healthy_percent=0,
1685
+ max_healthy_percent=100,
1686
+ desired_count=0,
1687
+ )
1688
+ print("Successfully created new ECS service")
1689
+
1690
+ # Note: Auto-scaling setup would typically go here if needed for the service
1691
+
1692
+ except Exception as e:
1693
+ raise Exception("Could not handle ECS service due to:", e)
1694
+
1695
+ # --- Grant Secret Read Access (Applies to both created and imported roles) ---
1696
+ try:
1697
+ secret.grant_read(task_role)
1698
+ secret.grant_read(execution_role)
1699
+ except Exception as e:
1700
+ raise Exception("Could not grant access to Secrets Manager due to:", e)
1701
+
1702
+ # --- ALB TARGET GROUPS AND LISTENERS ---
1703
+ # This section should primarily define the resources if they are managed by this stack.
1704
+ # CDK handles adding/removing targets and actions on updates.
1705
+ # If they might pre-exist outside the stack, you need lookups.
1706
+ cookie_duration = Duration.hours(8)
1707
+ target_group_name = ALB_TARGET_GROUP_NAME # Explicit resource name
1708
+ cloudfront_distribution_url = "cloudfront_placeholder.net" # Need to replace this afterwards with the actual cloudfront_distribution.domain_name
1709
+
1710
+ try:
1711
+ # --- CREATING TARGET GROUPS AND ADDING THE CLOUDFRONT LISTENER RULE ---
1712
+
1713
+ target_group = elbv2.ApplicationTargetGroup(
1714
+ self,
1715
+ "AppTargetGroup", # Logical ID
1716
+ target_group_name=target_group_name, # Explicit resource name
1717
+ port=int(GRADIO_SERVER_PORT), # Ensure port is int
1718
+ protocol=elbv2.ApplicationProtocol.HTTP,
1719
+ targets=[ecs_service], # Link to ECS Service
1720
+ stickiness_cookie_duration=cookie_duration,
1721
+ vpc=vpc, # Target Groups need VPC
1722
+ )
1723
+ print(f"ALB target group {target_group_name} defined.")
1724
+
1725
+ # First HTTP
1726
+ listener_port = 80
1727
+ # Check if Listener exists - from_listener_arn or lookup by port/ALB
1728
+
1729
+ http_listener = alb.add_listener(
1730
+ "HttpListener", # Logical ID
1731
+ port=listener_port,
1732
+ open=False, # Be cautious with open=True, usually restrict source SG
1733
+ )
1734
+ print(f"ALB listener on port {listener_port} defined.")
1735
+
1736
+ if ACM_SSL_CERTIFICATE_ARN:
1737
+ http_listener.add_action(
1738
+ "DefaultAction", # Logical ID for the default action
1739
+ action=elbv2.ListenerAction.redirect(
1740
+ protocol="HTTPS",
1741
+ host="#{host}",
1742
+ port="443",
1743
+ path="/#{path}",
1744
+ query="#{query}",
1745
+ ),
1746
+ )
1747
+ else:
1748
+ if USE_CLOUDFRONT == "True":
1749
+
1750
+ # The following default action can be added for the listener after a host header rule is added to the listener manually in the Console as suggested in the above comments.
1751
+ http_listener.add_action(
1752
+ "DefaultAction", # Logical ID for the default action
1753
+ action=elbv2.ListenerAction.fixed_response(
1754
+ status_code=403,
1755
+ content_type="text/plain",
1756
+ message_body="Access denied",
1757
+ ),
1758
+ )
1759
+
1760
+ # Add the Listener Rule for the specific CloudFront Host Header
1761
+ http_listener.add_action(
1762
+ "CloudFrontHostHeaderRule",
1763
+ action=elbv2.ListenerAction.forward(
1764
+ target_groups=[target_group],
1765
+ stickiness_duration=cookie_duration,
1766
+ ),
1767
+ priority=1, # Example priority. Adjust as needed. Lower is evaluated first.
1768
+ conditions=[
1769
+ elbv2.ListenerCondition.host_headers(
1770
+ [cloudfront_distribution_url]
1771
+ ) # May have to redefine url in console afterwards if not specified in config file
1772
+ ],
1773
+ )
1774
+
1775
+ else:
1776
+ # Add the Listener Rule for the specific CloudFront Host Header
1777
+ http_listener.add_action(
1778
+ "CloudFrontHostHeaderRule",
1779
+ action=elbv2.ListenerAction.forward(
1780
+ target_groups=[target_group],
1781
+ stickiness_duration=cookie_duration,
1782
+ ),
1783
+ )
1784
+
1785
+ print("Added targets and actions to ALB HTTP listener.")
1786
+
1787
+ # Now the same for HTTPS if you have an ACM certificate
1788
+ if ACM_SSL_CERTIFICATE_ARN:
1789
+ listener_port_https = 443
1790
+ # Check if Listener exists - from_listener_arn or lookup by port/ALB
1791
+
1792
+ https_listener = add_alb_https_listener_with_cert(
1793
+ self,
1794
+ "MyHttpsListener", # Logical ID for the HTTPS listener
1795
+ alb,
1796
+ acm_certificate_arn=ACM_SSL_CERTIFICATE_ARN,
1797
+ default_target_group=target_group,
1798
+ enable_cognito_auth=True,
1799
+ cognito_user_pool=user_pool,
1800
+ cognito_user_pool_client=user_pool_client,
1801
+ cognito_user_pool_domain=user_pool_domain,
1802
+ listener_open_to_internet=True,
1803
+ stickiness_cookie_duration=cookie_duration,
1804
+ )
1805
+
1806
+ if https_listener:
1807
+ CfnOutput(
1808
+ self, "HttpsListenerArn", value=https_listener.listener_arn
1809
+ )
1810
+
1811
+ print(f"ALB listener on port {listener_port_https} defined.")
1812
+
1813
+ # if USE_CLOUDFRONT == 'True':
1814
+ # # Add default action to the listener
1815
+ # https_listener.add_action(
1816
+ # "DefaultAction", # Logical ID for the default action
1817
+ # action=elbv2.ListenerAction.fixed_response(
1818
+ # status_code=403,
1819
+ # content_type="text/plain",
1820
+ # message_body="Access denied",
1821
+ # ),
1822
+ # )
1823
+
1824
+ # # Add the Listener Rule for the specific CloudFront Host Header
1825
+ # https_listener.add_action(
1826
+ # "CloudFrontHostHeaderRuleHTTPS",
1827
+ # action=elbv2.ListenerAction.forward(target_groups=[target_group],stickiness_duration=cookie_duration),
1828
+ # priority=1, # Example priority. Adjust as needed. Lower is evaluated first.
1829
+ # conditions=[
1830
+ # elbv2.ListenerCondition.host_headers([cloudfront_distribution_url])
1831
+ # ]
1832
+ # )
1833
+ # else:
1834
+ # https_listener.add_action(
1835
+ # "CloudFrontHostHeaderRuleHTTPS",
1836
+ # action=elbv2.ListenerAction.forward(target_groups=[target_group],stickiness_duration=cookie_duration))
1837
+
1838
+ print("Added targets and actions to ALB HTTPS listener.")
1839
+
1840
+ except Exception as e:
1841
+ raise Exception(
1842
+ "Could not handle ALB target groups and listeners due to:", e
1843
+ )
1844
+
1845
+ # Create WAF to attach to load balancer
1846
+ try:
1847
+ web_acl_name = LOAD_BALANCER_WEB_ACL_NAME
1848
+ if get_context_bool(f"exists:{web_acl_name}"):
1849
+ # Lookup WAF ACL by ARN from context
1850
+ web_acl_arn = get_context_str(f"arn:{web_acl_name}")
1851
+ if not web_acl_arn:
1852
+ raise ValueError(
1853
+ f"Context value 'arn:{web_acl_name}' is required if Web ACL exists."
1854
+ )
1855
+
1856
+ web_acl = create_web_acl_with_common_rules(
1857
+ self, web_acl_name, waf_scope="REGIONAL"
1858
+ ) # Assuming it takes scope and name
1859
+ print(f"Handled ALB WAF web ACL {web_acl_name}.")
1860
+ else:
1861
+ web_acl = create_web_acl_with_common_rules(
1862
+ self, web_acl_name, waf_scope="REGIONAL"
1863
+ ) # Assuming it takes scope and name
1864
+ print(f"Created ALB WAF web ACL {web_acl_name}.")
1865
+
1866
+ wafv2.CfnWebACLAssociation(
1867
+ self,
1868
+ id="alb_waf_association",
1869
+ resource_arn=alb.load_balancer_arn,
1870
+ web_acl_arn=web_acl.attr_arn,
1871
+ )
1872
+
1873
+ except Exception as e:
1874
+ raise Exception("Could not handle create ALB WAF web ACL due to:", e)
1875
+
1876
+ # --- Outputs for other stacks/regions ---
1877
+
1878
+ self.params = dict()
1879
+ self.params["alb_arn_output"] = alb.load_balancer_arn
1880
+ self.params["alb_security_group_id"] = alb_security_group.security_group_id
1881
+ self.params["alb_dns_name"] = alb.load_balancer_dns_name
1882
+
1883
+ CfnOutput(
1884
+ self,
1885
+ "AlbArnOutput",
1886
+ value=alb.load_balancer_arn,
1887
+ description="ARN of the Application Load Balancer",
1888
+ export_name=f"{self.stack_name}-AlbArn",
1889
+ ) # Export name must be unique within the account/region
1890
+
1891
+ CfnOutput(
1892
+ self,
1893
+ "AlbSecurityGroupIdOutput",
1894
+ value=alb_security_group.security_group_id,
1895
+ description="ID of the ALB's Security Group",
1896
+ export_name=f"{self.stack_name}-AlbSgId",
1897
+ )
1898
+ CfnOutput(self, "ALBName", value=load_balancer_name)
1899
+
1900
+ CfnOutput(self, "RegionalAlbDnsName", value=alb.load_balancer_dns_name)
1901
+
1902
+ CfnOutput(self, "CognitoPoolId", value=user_pool.user_pool_id)
1903
+ # Add other outputs if needed
1904
+
1905
+ CfnOutput(self, "ECRRepoUri", value=ecr_repo.repository_uri)
1906
+
1907
+
1908
+ # --- CLOUDFRONT DISTRIBUTION in separate stack (us-east-1 required) ---
1909
+ class CdkStackCloudfront(Stack):
1910
+
1911
+ def __init__(
1912
+ self,
1913
+ scope: Construct,
1914
+ construct_id: str,
1915
+ alb_arn: str,
1916
+ alb_sec_group_id: str,
1917
+ alb_dns_name: str,
1918
+ **kwargs,
1919
+ ) -> None:
1920
+ super().__init__(scope, construct_id, **kwargs)
1921
+
1922
+ # --- Helper to get context values ---
1923
+ def get_context_bool(key: str, default: bool = False) -> bool:
1924
+ return self.node.try_get_context(key) or default
1925
+
1926
+ def get_context_str(key: str, default: str = None) -> str:
1927
+ return self.node.try_get_context(key) or default
1928
+
1929
+ def get_context_dict(scope: Construct, key: str, default: dict = None) -> dict:
1930
+ return scope.node.try_get_context(key) or default
1931
+
1932
+ print(f"CloudFront Stack: Received ALB ARN: {alb_arn}")
1933
+ print(f"CloudFront Stack: Received ALB Security Group ID: {alb_sec_group_id}")
1934
+
1935
+ if not alb_arn:
1936
+ raise ValueError("ALB ARN must be provided to CloudFront stack")
1937
+ if not alb_sec_group_id:
1938
+ raise ValueError(
1939
+ "ALB Security Group ID must be provided to CloudFront stack"
1940
+ )
1941
+
1942
+ # 2. Import the ALB using its ARN
1943
+ # This imports an existing ALB as a construct in the CloudFront stack's context.
1944
+ # CloudFormation will understand this reference at deploy time.
1945
+ alb = elbv2.ApplicationLoadBalancer.from_application_load_balancer_attributes(
1946
+ self,
1947
+ "ImportedAlb",
1948
+ load_balancer_arn=alb_arn,
1949
+ security_group_id=alb_sec_group_id,
1950
+ load_balancer_dns_name=alb_dns_name,
1951
+ )
1952
+
1953
+ try:
1954
+ web_acl_name = WEB_ACL_NAME
1955
+ if get_context_bool(f"exists:{web_acl_name}"):
1956
+ # Lookup WAF ACL by ARN from context
1957
+ web_acl_arn = get_context_str(f"arn:{web_acl_name}")
1958
+ if not web_acl_arn:
1959
+ raise ValueError(
1960
+ f"Context value 'arn:{web_acl_name}' is required if Web ACL exists."
1961
+ )
1962
+
1963
+ web_acl = create_web_acl_with_common_rules(
1964
+ self, web_acl_name
1965
+ ) # Assuming it takes scope and name
1966
+ print(f"Handled Cloudfront WAF web ACL {web_acl_name}.")
1967
+ else:
1968
+ web_acl = create_web_acl_with_common_rules(
1969
+ self, web_acl_name
1970
+ ) # Assuming it takes scope and name
1971
+ print(f"Created Cloudfront WAF web ACL {web_acl_name}.")
1972
+
1973
+ # Add ALB as CloudFront Origin
1974
+ origin = origins.LoadBalancerV2Origin(
1975
+ alb, # Use the created or looked-up ALB object
1976
+ custom_headers={CUSTOM_HEADER: CUSTOM_HEADER_VALUE},
1977
+ origin_shield_enabled=False,
1978
+ protocol_policy=cloudfront.OriginProtocolPolicy.HTTP_ONLY,
1979
+ )
1980
+
1981
+ if CLOUDFRONT_GEO_RESTRICTION:
1982
+ geo_restrict = cloudfront.GeoRestriction.allowlist(
1983
+ CLOUDFRONT_GEO_RESTRICTION
1984
+ )
1985
+ else:
1986
+ geo_restrict = None
1987
+
1988
+ cloudfront_distribution = cloudfront.Distribution(
1989
+ self,
1990
+ "CloudFrontDistribution", # Logical ID
1991
+ comment=CLOUDFRONT_DISTRIBUTION_NAME, # Use name as comment for easier identification
1992
+ geo_restriction=geo_restrict,
1993
+ default_behavior=cloudfront.BehaviorOptions(
1994
+ origin=origin,
1995
+ viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
1996
+ allowed_methods=cloudfront.AllowedMethods.ALLOW_ALL,
1997
+ cache_policy=cloudfront.CachePolicy.CACHING_DISABLED,
1998
+ origin_request_policy=cloudfront.OriginRequestPolicy.ALL_VIEWER,
1999
+ ),
2000
+ web_acl_id=web_acl.attr_arn,
2001
+ )
2002
+ print(f"Cloudfront distribution {CLOUDFRONT_DISTRIBUTION_NAME} defined.")
2003
+
2004
+ except Exception as e:
2005
+ raise Exception("Could not handle Cloudfront distribution due to:", e)
2006
+
2007
+ # --- Outputs ---
2008
+ CfnOutput(
2009
+ self, "CloudFrontDistributionURL", value=cloudfront_distribution.domain_name
2010
+ )
cdk/check_resources.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from typing import Dict, List
4
+
5
+ from cdk_config import ( # Import necessary config
6
+ ALB_NAME,
7
+ AWS_REGION,
8
+ CDK_CONFIG_PATH,
9
+ CDK_FOLDER,
10
+ CODEBUILD_PROJECT_NAME,
11
+ CODEBUILD_ROLE_NAME,
12
+ COGNITO_USER_POOL_CLIENT_NAME,
13
+ COGNITO_USER_POOL_CLIENT_SECRET_NAME,
14
+ COGNITO_USER_POOL_NAME,
15
+ CONTEXT_FILE,
16
+ ECR_CDK_REPO_NAME,
17
+ ECS_TASK_EXECUTION_ROLE_NAME,
18
+ ECS_TASK_ROLE_NAME,
19
+ PRIVATE_SUBNET_AVAILABILITY_ZONES,
20
+ PRIVATE_SUBNET_CIDR_BLOCKS,
21
+ PRIVATE_SUBNETS_TO_USE,
22
+ PUBLIC_SUBNET_AVAILABILITY_ZONES,
23
+ PUBLIC_SUBNET_CIDR_BLOCKS,
24
+ PUBLIC_SUBNETS_TO_USE,
25
+ S3_LOG_CONFIG_BUCKET_NAME,
26
+ S3_OUTPUT_BUCKET_NAME,
27
+ VPC_NAME,
28
+ WEB_ACL_NAME,
29
+ )
30
+ from cdk_functions import ( # Import your check functions (assuming they use Boto3)
31
+ _get_existing_subnets_in_vpc,
32
+ check_alb_exists,
33
+ check_codebuild_project_exists,
34
+ check_ecr_repo_exists,
35
+ check_for_existing_role,
36
+ check_for_existing_user_pool,
37
+ check_for_existing_user_pool_client,
38
+ check_for_secret,
39
+ check_s3_bucket_exists,
40
+ check_subnet_exists_by_name,
41
+ check_web_acl_exists,
42
+ get_vpc_id_by_name,
43
+ validate_subnet_creation_parameters,
44
+ # Add other check functions as needed
45
+ )
46
+
47
+ cdk_folder = CDK_FOLDER # <FULL_PATH_TO_CDK_FOLDER_HERE>
48
+
49
+ # Full path needed to find config file
50
+ os.environ["CDK_CONFIG_PATH"] = cdk_folder + CDK_CONFIG_PATH
51
+
52
+
53
+ # --- Helper to parse environment variables into lists ---
54
+ def _get_env_list(env_var_name: str) -> List[str]:
55
+ """Parses a comma-separated environment variable into a list of strings."""
56
+ value = env_var_name[1:-1].strip().replace('"', "").replace("'", "")
57
+ if not value:
58
+ return []
59
+ # Split by comma and filter out any empty strings that might result from extra commas
60
+ return [s.strip() for s in value.split(",") if s.strip()]
61
+
62
+
63
+ if PUBLIC_SUBNETS_TO_USE and not isinstance(PUBLIC_SUBNETS_TO_USE, list):
64
+ PUBLIC_SUBNETS_TO_USE = _get_env_list(PUBLIC_SUBNETS_TO_USE)
65
+ if PRIVATE_SUBNETS_TO_USE and not isinstance(PRIVATE_SUBNETS_TO_USE, list):
66
+ PRIVATE_SUBNETS_TO_USE = _get_env_list(PRIVATE_SUBNETS_TO_USE)
67
+ if PUBLIC_SUBNET_CIDR_BLOCKS and not isinstance(PUBLIC_SUBNET_CIDR_BLOCKS, list):
68
+ PUBLIC_SUBNET_CIDR_BLOCKS = _get_env_list(PUBLIC_SUBNET_CIDR_BLOCKS)
69
+ if PUBLIC_SUBNET_AVAILABILITY_ZONES and not isinstance(
70
+ PUBLIC_SUBNET_AVAILABILITY_ZONES, list
71
+ ):
72
+ PUBLIC_SUBNET_AVAILABILITY_ZONES = _get_env_list(PUBLIC_SUBNET_AVAILABILITY_ZONES)
73
+ if PRIVATE_SUBNET_CIDR_BLOCKS and not isinstance(PRIVATE_SUBNET_CIDR_BLOCKS, list):
74
+ PRIVATE_SUBNET_CIDR_BLOCKS = _get_env_list(PRIVATE_SUBNET_CIDR_BLOCKS)
75
+ if PRIVATE_SUBNET_AVAILABILITY_ZONES and not isinstance(
76
+ PRIVATE_SUBNET_AVAILABILITY_ZONES, list
77
+ ):
78
+ PRIVATE_SUBNET_AVAILABILITY_ZONES = _get_env_list(PRIVATE_SUBNET_AVAILABILITY_ZONES)
79
+
80
+ # Check for the existence of elements in your AWS environment to see if it's necessary to create new versions of the same
81
+
82
+
83
+ def check_and_set_context():
84
+ context_data = {}
85
+
86
+ # --- Find the VPC ID first ---
87
+ if VPC_NAME:
88
+ print("VPC_NAME:", VPC_NAME)
89
+ vpc_id, nat_gateways = get_vpc_id_by_name(VPC_NAME)
90
+
91
+ # If you expect only one, or one per AZ and you're creating one per AZ in CDK:
92
+ if nat_gateways:
93
+ # For simplicity, let's just check if *any* NAT exists in the VPC
94
+ # A more robust check would match by subnet, AZ, or a specific tag.
95
+ context_data["exists:NatGateway"] = True
96
+ context_data["id:NatGateway"] = nat_gateways[0][
97
+ "NatGatewayId"
98
+ ] # Store the ID of the first one found
99
+ else:
100
+ context_data["exists:NatGateway"] = False
101
+ context_data["id:NatGateway"] = None
102
+
103
+ if not vpc_id:
104
+ # If the VPC doesn't exist, you might not be able to check/create subnets.
105
+ # Decide how to handle this: raise an error, set a flag, etc.
106
+ raise RuntimeError(
107
+ f"Required VPC '{VPC_NAME}' not found. Cannot proceed with subnet checks."
108
+ )
109
+
110
+ context_data["vpc_id"] = vpc_id # Store VPC ID in context
111
+
112
+ # SUBNET CHECKS
113
+ all_proposed_subnets_data: List[Dict[str, str]] = []
114
+
115
+ # Flag to indicate if full validation mode (with CIDR/AZs) is active
116
+ full_validation_mode = False
117
+
118
+ # Determine if full validation mode is possible/desired
119
+ # It's 'desired' if CIDR/AZs are provided, and their lengths match the name lists.
120
+ public_ready_for_full_validation = (
121
+ len(PUBLIC_SUBNETS_TO_USE) > 0
122
+ and len(PUBLIC_SUBNET_CIDR_BLOCKS) == len(PUBLIC_SUBNETS_TO_USE)
123
+ and len(PUBLIC_SUBNET_AVAILABILITY_ZONES) == len(PUBLIC_SUBNETS_TO_USE)
124
+ )
125
+ private_ready_for_full_validation = (
126
+ len(PRIVATE_SUBNETS_TO_USE) > 0
127
+ and len(PRIVATE_SUBNET_CIDR_BLOCKS) == len(PRIVATE_SUBNETS_TO_USE)
128
+ and len(PRIVATE_SUBNET_AVAILABILITY_ZONES) == len(PRIVATE_SUBNETS_TO_USE)
129
+ )
130
+
131
+ # Activate full validation if *any* type of subnet (public or private) has its full details provided.
132
+ # You might adjust this logic if you require ALL subnet types to have CIDRs, or NONE.
133
+ if public_ready_for_full_validation or private_ready_for_full_validation:
134
+ full_validation_mode = True
135
+
136
+ # If some are ready but others aren't, print a warning or raise an error based on your strictness
137
+ if (
138
+ public_ready_for_full_validation
139
+ and not private_ready_for_full_validation
140
+ and PRIVATE_SUBNETS_TO_USE
141
+ ):
142
+ print(
143
+ "Warning: Public subnets have CIDRs/AZs, but private subnets do not. Only public will be fully validated/created with CIDRs."
144
+ )
145
+ if (
146
+ private_ready_for_full_validation
147
+ and not public_ready_for_full_validation
148
+ and PUBLIC_SUBNETS_TO_USE
149
+ ):
150
+ print(
151
+ "Warning: Private subnets have CIDRs/AZs, but public subnets do not. Only private will be fully validated/created with CIDRs."
152
+ )
153
+
154
+ # Prepare data for validate_subnet_creation_parameters for all subnets that have full details
155
+ if public_ready_for_full_validation:
156
+ for i, name in enumerate(PUBLIC_SUBNETS_TO_USE):
157
+ all_proposed_subnets_data.append(
158
+ {
159
+ "name": name,
160
+ "cidr": PUBLIC_SUBNET_CIDR_BLOCKS[i],
161
+ "az": PUBLIC_SUBNET_AVAILABILITY_ZONES[i],
162
+ }
163
+ )
164
+ if private_ready_for_full_validation:
165
+ for i, name in enumerate(PRIVATE_SUBNETS_TO_USE):
166
+ all_proposed_subnets_data.append(
167
+ {
168
+ "name": name,
169
+ "cidr": PRIVATE_SUBNET_CIDR_BLOCKS[i],
170
+ "az": PRIVATE_SUBNET_AVAILABILITY_ZONES[i],
171
+ }
172
+ )
173
+
174
+ print(f"Target VPC ID for Boto3 lookup: {vpc_id}")
175
+
176
+ # Fetch all existing subnets in the target VPC once to avoid repeated API calls
177
+ try:
178
+ existing_aws_subnets = _get_existing_subnets_in_vpc(vpc_id)
179
+ except Exception as e:
180
+ print(f"Failed to fetch existing VPC subnets. Aborting. Error: {e}")
181
+ raise SystemExit(1) # Exit immediately if we can't get baseline data
182
+
183
+ print("\n--- Running Name-Only Subnet Existence Check Mode ---")
184
+ # Fallback: check only by name using the existing data
185
+ checked_public_subnets = {}
186
+ if PUBLIC_SUBNETS_TO_USE:
187
+ for subnet_name in PUBLIC_SUBNETS_TO_USE:
188
+ print("subnet_name:", subnet_name)
189
+ exists, subnet_id = check_subnet_exists_by_name(
190
+ subnet_name, existing_aws_subnets
191
+ )
192
+ checked_public_subnets[subnet_name] = {
193
+ "exists": exists,
194
+ "id": subnet_id,
195
+ "az": (
196
+ existing_aws_subnets["by_name"].get(subnet_name, {}).get("az")
197
+ if exists
198
+ else None
199
+ ),
200
+ "route_table_id": (
201
+ existing_aws_subnets["by_name"]
202
+ .get(subnet_name, {})
203
+ .get("route_table_id")
204
+ if exists
205
+ else None
206
+ ),
207
+ }
208
+
209
+ # If the subnet exists, remove it from the proposed subnets list
210
+ if checked_public_subnets[subnet_name]["exists"] is True:
211
+ all_proposed_subnets_data = [
212
+ subnet
213
+ for subnet in all_proposed_subnets_data
214
+ if subnet["name"] != subnet_name
215
+ ]
216
+
217
+ context_data["checked_public_subnets"] = checked_public_subnets
218
+
219
+ checked_private_subnets = {}
220
+ if PRIVATE_SUBNETS_TO_USE:
221
+ for subnet_name in PRIVATE_SUBNETS_TO_USE:
222
+ print("subnet_name:", subnet_name)
223
+ exists, subnet_id = check_subnet_exists_by_name(
224
+ subnet_name, existing_aws_subnets
225
+ )
226
+ checked_private_subnets[subnet_name] = {
227
+ "exists": exists,
228
+ "id": subnet_id,
229
+ "az": (
230
+ existing_aws_subnets["by_name"].get(subnet_name, {}).get("az")
231
+ if exists
232
+ else None
233
+ ),
234
+ "route_table_id": (
235
+ existing_aws_subnets["by_name"]
236
+ .get(subnet_name, {})
237
+ .get("route_table_id")
238
+ if exists
239
+ else None
240
+ ),
241
+ }
242
+
243
+ # If the subnet exists, remove it from the proposed subnets list
244
+ if checked_private_subnets[subnet_name]["exists"] is True:
245
+ all_proposed_subnets_data = [
246
+ subnet
247
+ for subnet in all_proposed_subnets_data
248
+ if subnet["name"] != subnet_name
249
+ ]
250
+
251
+ context_data["checked_private_subnets"] = checked_private_subnets
252
+
253
+ print("\nName-only existence subnet check complete.\n")
254
+
255
+ if full_validation_mode:
256
+ print(
257
+ "\n--- Running in Full Subnet Validation Mode (CIDR/AZs provided) ---"
258
+ )
259
+ try:
260
+ validate_subnet_creation_parameters(
261
+ vpc_id, all_proposed_subnets_data, existing_aws_subnets
262
+ )
263
+ print("\nPre-synth validation successful. Proceeding with CDK synth.\n")
264
+
265
+ # Populate context_data for downstream CDK construct creation.
266
+ # Skip subnets that already exist in AWS (imported in the stack).
267
+ context_data["public_subnets_to_create"] = []
268
+ if public_ready_for_full_validation:
269
+ for i, name in enumerate(PUBLIC_SUBNETS_TO_USE):
270
+ if checked_public_subnets.get(name, {}).get("exists"):
271
+ continue
272
+ context_data["public_subnets_to_create"].append(
273
+ {
274
+ "name": name,
275
+ "cidr": PUBLIC_SUBNET_CIDR_BLOCKS[i],
276
+ "az": PUBLIC_SUBNET_AVAILABILITY_ZONES[i],
277
+ "is_public": True,
278
+ }
279
+ )
280
+ context_data["private_subnets_to_create"] = []
281
+ if private_ready_for_full_validation:
282
+ for i, name in enumerate(PRIVATE_SUBNETS_TO_USE):
283
+ if checked_private_subnets.get(name, {}).get("exists"):
284
+ continue
285
+ context_data["private_subnets_to_create"].append(
286
+ {
287
+ "name": name,
288
+ "cidr": PRIVATE_SUBNET_CIDR_BLOCKS[i],
289
+ "az": PRIVATE_SUBNET_AVAILABILITY_ZONES[i],
290
+ "is_public": False,
291
+ }
292
+ )
293
+
294
+ except (ValueError, Exception) as e:
295
+ print(f"\nFATAL ERROR: Subnet parameter validation failed: {e}\n")
296
+ raise SystemExit(1) # Exit if validation fails
297
+
298
+ # Example checks and setting context values
299
+ # IAM Roles
300
+ role_name = CODEBUILD_ROLE_NAME
301
+ exists, role_arn, _ = check_for_existing_role(role_name)
302
+ context_data[f"exists:{role_name}"] = exists
303
+ if exists:
304
+ context_data[f"arn:{role_name}"] = role_arn
305
+
306
+ role_name = ECS_TASK_ROLE_NAME
307
+ exists, role_arn, _ = check_for_existing_role(role_name)
308
+ context_data[f"exists:{role_name}"] = exists
309
+ if exists:
310
+ context_data[f"arn:{role_name}"] = role_arn
311
+
312
+ role_name = ECS_TASK_EXECUTION_ROLE_NAME
313
+ exists, role_arn, _ = check_for_existing_role(role_name)
314
+ context_data[f"exists:{role_name}"] = exists
315
+ if exists:
316
+ context_data[f"arn:{role_name}"] = role_arn
317
+
318
+ # S3 Buckets
319
+ bucket_name = S3_LOG_CONFIG_BUCKET_NAME
320
+ exists, _ = check_s3_bucket_exists(bucket_name)
321
+ context_data[f"exists:{bucket_name}"] = exists
322
+ if exists:
323
+ # You might not need the ARN if using from_bucket_name
324
+ pass
325
+
326
+ output_bucket_name = S3_OUTPUT_BUCKET_NAME
327
+ exists, _ = check_s3_bucket_exists(output_bucket_name)
328
+ context_data[f"exists:{output_bucket_name}"] = exists
329
+ if exists:
330
+ pass
331
+
332
+ # ECR Repository
333
+ repo_name = ECR_CDK_REPO_NAME
334
+ exists, _ = check_ecr_repo_exists(repo_name)
335
+ context_data[f"exists:{repo_name}"] = exists
336
+ if exists:
337
+ pass # from_repository_name is sufficient
338
+
339
+ # CodeBuild Project
340
+ project_name = CODEBUILD_PROJECT_NAME
341
+ exists, project_arn, service_role_arn = check_codebuild_project_exists(project_name)
342
+ context_data[f"exists:{project_name}"] = exists
343
+ if exists:
344
+ context_data[f"arn:{project_name}"] = project_arn
345
+ if service_role_arn:
346
+ context_data[f"service_role_arn:{project_name}"] = service_role_arn
347
+
348
+ # ALB (by name lookup) — context keys use the same 32-char name the stack uses
349
+ alb_name = ALB_NAME[-32:] if len(ALB_NAME) > 32 else ALB_NAME
350
+ exists, alb_object = check_alb_exists(alb_name, region_name=AWS_REGION)
351
+ context_data[f"exists:{alb_name}"] = exists
352
+ if exists:
353
+ print("alb_object:", alb_object)
354
+ context_data[f"arn:{alb_name}"] = alb_object["LoadBalancerArn"]
355
+ context_data[f"dns:{alb_name}"] = alb_object["DNSName"]
356
+ context_data[f"canonical_hosted_zone_id:{alb_name}"] = alb_object[
357
+ "CanonicalHostedZoneId"
358
+ ]
359
+ if alb_object.get("SecurityGroups"):
360
+ context_data[f"security_group_id:{alb_name}"] = alb_object[
361
+ "SecurityGroups"
362
+ ][0]
363
+
364
+ # Cognito User Pool (by name)
365
+ user_pool_name = COGNITO_USER_POOL_NAME
366
+ exists, user_pool_id, _ = check_for_existing_user_pool(user_pool_name)
367
+ context_data[f"exists:{user_pool_name}"] = exists
368
+ if exists:
369
+ context_data[f"id:{user_pool_name}"] = user_pool_id
370
+
371
+ # Cognito User Pool Client (by name and pool ID) - requires User Pool ID from check
372
+ if user_pool_id:
373
+ user_pool_id_for_client_check = user_pool_id # context_data.get(f"id:{user_pool_name}") # Use ID from context
374
+ user_pool_client_name = COGNITO_USER_POOL_CLIENT_NAME
375
+ if user_pool_id_for_client_check:
376
+ exists, client_id, _ = check_for_existing_user_pool_client(
377
+ user_pool_client_name, user_pool_id_for_client_check
378
+ )
379
+ context_data[f"exists:{user_pool_client_name}"] = exists
380
+ if exists:
381
+ context_data[f"id:{user_pool_client_name}"] = client_id
382
+
383
+ # Secrets Manager Secret (by name)
384
+ secret_name = COGNITO_USER_POOL_CLIENT_SECRET_NAME
385
+ exists, _ = check_for_secret(secret_name)
386
+ context_data[f"exists:{secret_name}"] = exists
387
+ # You might not need the ARN if using from_secret_name_v2
388
+
389
+ # WAF Web ACL (by name and scope)
390
+ web_acl_name = WEB_ACL_NAME
391
+ exists, existing_web_acl = check_web_acl_exists(web_acl_name, scope="CLOUDFRONT")
392
+ context_data[f"exists:{web_acl_name}"] = exists
393
+ if exists:
394
+ context_data[f"arn:{web_acl_name}"] = existing_web_acl["ARN"]
395
+
396
+ # Write the context data to the file
397
+ with open(CONTEXT_FILE, "w") as f:
398
+ json.dump(context_data, f, indent=2)
399
+
400
+ print(f"Context data written to {CONTEXT_FILE}")
cdk/lambda_load_dynamo_logs.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Lambda handler to export DynamoDB usage log table to CSV and upload to S3.
3
+
4
+ All inputs are read from environment variables (no argparse).
5
+ Intended to run as an AWS Lambda function; can also be invoked locally
6
+ by setting env vars and calling lambda_handler({}, None).
7
+
8
+ Environment variables (same semantics as load_dynamo_logs.py CLI):
9
+ DYNAMODB_TABLE_NAME - DynamoDB table name (default: redaction_usage)
10
+ AWS_REGION - AWS region (optional; if unset, uses AWS_DEFAULT_REGION,
11
+ then region from Lambda context ARN, then eu-west-2)
12
+ OUTPUT_FOLDER - Local output directory, e.g. /tmp (optional)
13
+ OUTPUT_FILENAME - Local output file name (default: dynamodb_logs_export.csv)
14
+ OUTPUT - Full local output path (overrides folder + filename if set).
15
+ In Lambda only /tmp is writable; relative paths are auto-resolved to /tmp.
16
+ FROM_DATE - Only include entries on/after this date YYYY-MM-DD (optional)
17
+ TO_DATE - Only include entries on/before this date YYYY-MM-DD (optional)
18
+ DATE_ATTRIBUTE - Attribute name for date filtering (default: timestamp)
19
+ S3_OUTPUT_BUCKET - S3 bucket for the output CSV (required for upload)
20
+ S3_OUTPUT_KEY - S3 object key/path for the output CSV (required for upload)
21
+ """
22
+
23
+ import csv
24
+ import datetime
25
+ import os
26
+ from decimal import Decimal
27
+ from io import StringIO
28
+
29
+ import boto3
30
+
31
+
32
+ def _get_region_from_context(context):
33
+ """Extract region from Lambda context invoked_function_arn (arn:aws:lambda:REGION:ACCOUNT:function:NAME)."""
34
+ if context is None:
35
+ return None
36
+ arn = getattr(context, "invoked_function_arn", None)
37
+ if not arn or not isinstance(arn, str):
38
+ return None
39
+ parts = arn.split(":")
40
+ if len(parts) >= 4:
41
+ return parts[3] # region is 4th segment
42
+ return None
43
+
44
+
45
+ def get_config_from_env(context=None):
46
+ """Read all settings from environment variables (same inputs as load_dynamo_logs.py).
47
+ When running in Lambda, context can be passed to derive region from the function ARN if env is not set.
48
+ """
49
+ today = datetime.datetime.now().date()
50
+ one_year_ago = today - datetime.timedelta(days=365)
51
+
52
+ table_name = os.environ.get("DYNAMODB_TABLE_NAME") or os.environ.get(
53
+ "USAGE_LOG_DYNAMODB_TABLE_NAME", "redaction_usage"
54
+ )
55
+ region = (
56
+ os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION") or ""
57
+ ).strip()
58
+ output = os.environ.get("OUTPUT")
59
+ output_folder = os.environ.get("OUTPUT_FOLDER", "output/")
60
+ output_filename = os.environ.get("OUTPUT_FILENAME", "dynamodb_logs_export.csv")
61
+ from_date_str = os.environ.get("FROM_DATE")
62
+ to_date_str = os.environ.get("TO_DATE")
63
+ date_attribute = os.environ.get("DATE_ATTRIBUTE", "timestamp")
64
+ s3_output_bucket = os.environ.get("S3_OUTPUT_BUCKET")
65
+ s3_output_key = os.environ.get("S3_OUTPUT_KEY")
66
+
67
+ if output:
68
+ local_output_path = output
69
+ else:
70
+ folder = output_folder.rstrip("/").rstrip("\\")
71
+ local_output_path = os.path.join(folder, output_filename)
72
+
73
+ # In AWS Lambda only /tmp is writable; resolve relative paths to /tmp to avoid read-only FS errors
74
+ if os.environ.get("AWS_LAMBDA_FUNCTION_NAME"):
75
+ resolved = os.path.abspath(local_output_path)
76
+ if not resolved.startswith("/tmp"):
77
+ local_output_path = os.path.join(
78
+ "/tmp", os.path.basename(local_output_path)
79
+ )
80
+
81
+ # Region: env (AWS_REGION / AWS_DEFAULT_REGION) → Lambda context ARN → hardcoded fallback
82
+ if not region and context is not None:
83
+ region = _get_region_from_context(context) or ""
84
+ if not region:
85
+ region = "FILL IN DEFAULT REGION HERE"
86
+
87
+ from_date = None
88
+ to_date = None
89
+ if from_date_str:
90
+ from_date = datetime.datetime.strptime(from_date_str, "%Y-%m-%d").date()
91
+ if to_date_str:
92
+ to_date = datetime.datetime.strptime(to_date_str, "%Y-%m-%d").date()
93
+ if from_date is None and to_date is None:
94
+ from_date = one_year_ago
95
+ to_date = today
96
+ elif from_date is None:
97
+ from_date = one_year_ago
98
+ elif to_date is None:
99
+ to_date = today
100
+
101
+ return {
102
+ "table_name": table_name,
103
+ "region": region,
104
+ "local_output_path": local_output_path,
105
+ "from_date": from_date,
106
+ "to_date": to_date,
107
+ "date_attribute": date_attribute,
108
+ "s3_output_bucket": s3_output_bucket,
109
+ "s3_output_key": s3_output_key,
110
+ }
111
+
112
+
113
+ # Helper function to convert Decimal to float or int
114
+ def convert_types(item):
115
+ new_item = {}
116
+ for key, value in item.items():
117
+ if isinstance(value, Decimal):
118
+ new_item[key] = int(value) if value % 1 == 0 else float(value)
119
+ elif isinstance(value, str):
120
+ try:
121
+ dt_obj = datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
122
+ new_item[key] = dt_obj.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
123
+ except (ValueError, TypeError):
124
+ new_item[key] = value
125
+ else:
126
+ new_item[key] = value
127
+ return new_item
128
+
129
+
130
+ def _parse_item_date(value):
131
+ """Parse a DynamoDB attribute value to datetime for comparison. Returns None if unparseable."""
132
+ if value is None:
133
+ return None
134
+ if isinstance(value, Decimal):
135
+ try:
136
+ return datetime.datetime.utcfromtimestamp(float(value))
137
+ except (ValueError, OSError):
138
+ return None
139
+ if isinstance(value, (int, float)):
140
+ try:
141
+ return datetime.datetime.utcfromtimestamp(float(value))
142
+ except (ValueError, OSError):
143
+ return None
144
+ if isinstance(value, str):
145
+ for fmt in (
146
+ "%Y-%m-%d %H:%M:%S.%f",
147
+ "%Y-%m-%d %H:%M:%S",
148
+ "%Y-%m-%d",
149
+ "%Y-%m-%dT%H:%M:%S",
150
+ ):
151
+ try:
152
+ return datetime.datetime.strptime(value, fmt)
153
+ except (ValueError, TypeError):
154
+ continue
155
+ try:
156
+ return datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
157
+ except (ValueError, TypeError):
158
+ pass
159
+ return None
160
+
161
+
162
+ def filter_items_by_date(items, from_date, to_date, date_attribute: str):
163
+ """Return items whose date attribute falls within [from_date, to_date] (inclusive)."""
164
+ if from_date is None and to_date is None:
165
+ return items
166
+ start = datetime.datetime.combine(from_date, datetime.time.min)
167
+ end = datetime.datetime.combine(to_date, datetime.time.max)
168
+ filtered = []
169
+ for item in items:
170
+ raw = item.get(date_attribute)
171
+ dt = _parse_item_date(raw)
172
+ if dt is None:
173
+ continue
174
+ if dt.tzinfo:
175
+ dt = dt.replace(tzinfo=None)
176
+ if start <= dt <= end:
177
+ filtered.append(item)
178
+ return filtered
179
+
180
+
181
+ def scan_table(table):
182
+ """Paginated scan of DynamoDB table."""
183
+ items = []
184
+ response = table.scan()
185
+ items.extend(response["Items"])
186
+ while "LastEvaluatedKey" in response:
187
+ response = table.scan(ExclusiveStartKey=response["LastEvaluatedKey"])
188
+ items.extend(response["Items"])
189
+ return items
190
+
191
+
192
+ def export_to_csv_buffer(items, fields_to_drop=None):
193
+ """
194
+ Write items to a CSV in memory; return (csv_string, fieldnames).
195
+ Use for uploading to S3 without writing to disk.
196
+ """
197
+ if not items:
198
+ return "", []
199
+
200
+ drop_set = set(fields_to_drop or [])
201
+ all_keys = set()
202
+ for item in items:
203
+ all_keys.update(item.keys())
204
+ fieldnames = sorted(list(all_keys - drop_set))
205
+
206
+ buf = StringIO()
207
+ writer = csv.DictWriter(
208
+ buf, fieldnames=fieldnames, extrasaction="ignore", restval=""
209
+ )
210
+ writer.writeheader()
211
+ for item in items:
212
+ writer.writerow(convert_types(item))
213
+ return buf.getvalue(), fieldnames
214
+
215
+
216
+ def export_to_csv_file(items, output_path, fields_to_drop=None):
217
+ """Write items to a CSV file (for optional /tmp or local path)."""
218
+ csv_string, _ = export_to_csv_buffer(items, fields_to_drop)
219
+ if not csv_string:
220
+ return
221
+ os.makedirs(os.path.dirname(os.path.abspath(output_path)) or ".", exist_ok=True)
222
+ with open(output_path, "w", newline="", encoding="utf-8-sig") as f:
223
+ f.write(csv_string)
224
+
225
+
226
+ def run_export(config):
227
+ """
228
+ Run the full export: scan DynamoDB, filter by date, write CSV (buffer and/or file), upload to S3.
229
+ """
230
+ table_name = config["table_name"]
231
+ region = config["region"]
232
+ local_output_path = config["local_output_path"]
233
+ from_date = config["from_date"]
234
+ to_date = config["to_date"]
235
+ date_attribute = config["date_attribute"]
236
+ s3_output_bucket = config["s3_output_bucket"]
237
+ s3_output_key = config["s3_output_key"]
238
+
239
+ if from_date > to_date:
240
+ raise ValueError("FROM_DATE must be on or before TO_DATE")
241
+
242
+ dynamodb = boto3.resource("dynamodb", region_name=region or None)
243
+ table = dynamodb.Table(table_name)
244
+
245
+ items = scan_table(table)
246
+ items = filter_items_by_date(items, from_date, to_date, date_attribute)
247
+
248
+ csv_string, fieldnames = export_to_csv_buffer(items, fields_to_drop=[])
249
+ result = {
250
+ "item_count": len(items),
251
+ "from_date": str(from_date),
252
+ "to_date": str(to_date),
253
+ "columns": fieldnames,
254
+ }
255
+
256
+ if csv_string:
257
+ # Optional: write to local path (e.g. /tmp in Lambda)
258
+ try:
259
+ export_to_csv_file(items, local_output_path, fields_to_drop=[])
260
+ result["local_path"] = local_output_path
261
+ except Exception as e:
262
+ result["local_write_error"] = str(e)
263
+
264
+ # Upload to S3 if bucket and key are set
265
+ if s3_output_bucket and s3_output_key:
266
+ s3 = boto3.client("s3", region_name=region or None)
267
+ s3.put_object(
268
+ Bucket=s3_output_bucket,
269
+ Key=s3_output_key,
270
+ Body=csv_string.encode("utf-8-sig"),
271
+ ContentType="text/csv; charset=utf-8",
272
+ )
273
+ result["s3_uri"] = f"s3://{s3_output_bucket}/{s3_output_key}"
274
+ elif s3_output_bucket or s3_output_key:
275
+ result["s3_skip_reason"] = (
276
+ "Both S3_OUTPUT_BUCKET and S3_OUTPUT_KEY must be set"
277
+ )
278
+
279
+ return result
280
+
281
+
282
+ def lambda_handler(event, context):
283
+ """
284
+ AWS Lambda entrypoint. Config is read from environment variables.
285
+
286
+ Event is not required for config; it can be used to override env vars
287
+ (e.g. pass table_name, from_date, to_date, s3_output_bucket, s3_output_key).
288
+ """
289
+ config = get_config_from_env(context=context)
290
+
291
+ # Optional: allow event to override env-based config
292
+ if isinstance(event, dict):
293
+ if event.get("table_name"):
294
+ config["table_name"] = event["table_name"]
295
+ if event.get("region"):
296
+ config["region"] = event["region"]
297
+ if event.get("from_date"):
298
+ config["from_date"] = datetime.datetime.strptime(
299
+ event["from_date"], "%Y-%m-%d"
300
+ ).date()
301
+ if event.get("to_date"):
302
+ config["to_date"] = datetime.datetime.strptime(
303
+ event["to_date"], "%Y-%m-%d"
304
+ ).date()
305
+ if event.get("date_attribute"):
306
+ config["date_attribute"] = event["date_attribute"]
307
+ if event.get("s3_output_bucket"):
308
+ config["s3_output_bucket"] = event["s3_output_bucket"]
309
+ if event.get("s3_output_key"):
310
+ config["s3_output_key"] = event["s3_output_key"]
311
+
312
+ result = run_export(config)
313
+ return {"statusCode": 200, "body": result}
314
+
315
+
316
+ if __name__ == "__main__":
317
+ # Allow running locally with env vars set
318
+ import json
319
+
320
+ result = lambda_handler({}, None)
321
+ print(json.dumps(result, indent=2))
cdk/post_cdk_build_quickstart.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+
3
+ from cdk_config import (
4
+ CLUSTER_NAME,
5
+ CODEBUILD_PROJECT_NAME,
6
+ ECS_SERVICE_NAME,
7
+ S3_LOG_CONFIG_BUCKET_NAME,
8
+ )
9
+ from cdk_functions import (
10
+ create_basic_config_env,
11
+ start_codebuild_build,
12
+ start_ecs_task,
13
+ upload_file_to_s3,
14
+ )
15
+ from tqdm import tqdm
16
+
17
+ # Create basic config.env file that user can use to run the app later. Input is the folder it is saved into.
18
+ create_basic_config_env("config")
19
+
20
+ # Start codebuild build
21
+ print("Starting CodeBuild project.")
22
+ start_codebuild_build(PROJECT_NAME=CODEBUILD_PROJECT_NAME)
23
+
24
+ # Upload config.env file to S3 bucket
25
+ upload_file_to_s3(
26
+ local_file_paths="config/config.env", s3_key="", s3_bucket=S3_LOG_CONFIG_BUCKET_NAME
27
+ )
28
+
29
+ total_seconds = 660 # 11 minutes
30
+ update_interval = 1 # Update every second
31
+
32
+ print("Waiting 11 minutes for the CodeBuild container to build.")
33
+
34
+ # tqdm iterates over a range, and you perform a small sleep in each iteration
35
+ for i in tqdm(range(total_seconds), desc="Building container"):
36
+ time.sleep(update_interval)
37
+
38
+ # Start task on ECS
39
+ print("Starting ECS task")
40
+ start_ecs_task(cluster_name=CLUSTER_NAME, service_name=ECS_SERVICE_NAME)
cdk/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ aws-cdk-lib==2.257.0
2
+ aws-cdk.aws-servicecatalogappregistry-alpha~=2.257.0a0
3
+ boto3<=1.42.91
4
+ pandas<=2.3.3
5
+ nodejs<=0.1.1
6
+ python-dotenv<=1.2.2
cli_redact.py ADDED
The diff for this file is too large to render. See raw diff
 
config/pi_agent.env.example ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Optional Pi agent backend credentials (copy to config/pi_agent.env — do not commit secrets).
2
+ #
3
+ # Used by the pi-agent service in docker-compose_llama_agentic.yml.
4
+ # UI overrides in the Gradio app apply for the current container session only.
5
+
6
+ # Deployment profile: local-docker (default) | hf-space (Hugging Face Docker Space)
7
+ # PI_DEPLOYMENT_PROFILE=local-docker
8
+
9
+ # Default Pi orchestration backend: llama-cpp | google-gemini | amazon-bedrock
10
+ PI_DEFAULT_PROVIDER=llama-cpp
11
+ # PI_DEFAULT_MODEL=unsloth/Qwen3.6-27B-MTP-GGUF
12
+
13
+ # --- HF Space profile (PI_DEPLOYMENT_PROFILE=hf-space) ---
14
+ # PI_DEFAULT_PROVIDER=google-gemini
15
+ # PI_DEFAULT_MODEL=gemini-flash-latest
16
+ # DOC_REDACTION_GRADIO_URL=https://seanpedrickcase-document-redaction.hf.space
17
+ # HF_TOKEN= # auth to private redaction Space (Space secret on Pi Space)
18
+ # DOC_REDACTION_HF_TOKEN= # alias mirrored to HF_TOKEN
19
+
20
+ # Local llama-cpp (default stack)
21
+ # PI_LLAMA_BASE_URL=http://llama-inference:8080/v1
22
+ # PI_LLAMA_MODEL_ID=unsloth/Qwen3.6-27B-MTP-GGUF
23
+
24
+ # Google Gemini (Pi resolves GEMINI_API_KEY; GOOGLE_API_KEY is mirrored at startup)
25
+ # GEMINI_API_KEY=
26
+ # GOOGLE_API_KEY=
27
+
28
+ # AWS Bedrock (uses AWS SDK credential chain — not a single API key)
29
+ # AWS_REGION=eu-west-2
30
+ # AWS_ACCESS_KEY_ID=
31
+ # AWS_SECRET_ACCESS_KEY=
32
+ # AWS_SESSION_TOKEN=
33
+ # AWS_PROFILE=
doc_redaction/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ doc_redaction package.
3
+
4
+ This package layer is intentionally thin for now: it preserves existing
5
+ repo-root entrypoints (e.g. `app.py`, `cli_redact.py`) while providing stable
6
+ import paths for PyPI installs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ __all__ = ["__version__", "choose_and_run_redactor", "run_redaction"]
12
+
13
+ try:
14
+ from importlib.metadata import PackageNotFoundError, version
15
+
16
+ try:
17
+ __version__ = version("doc_redaction")
18
+ except PackageNotFoundError: # pragma: no cover
19
+ __version__ = "0.0.0"
20
+ except Exception: # pragma: no cover
21
+ __version__ = "0.0.0"
22
+
23
+ # Convenience re-exports (package-qualified import surface)
24
+ from doc_redaction.file_redaction import (
25
+ choose_and_run_redactor,
26
+ run_redaction,
27
+ ) # noqa: E402
doc_redaction/api.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stable programmatic API surface matching Gradio `api_name` values.
3
+
4
+ This module provides names that exactly match the Gradio endpoint `api_name`
5
+ strings from `app.py`.
6
+
7
+ By default these names point to the **CLI-first** Python API (`doc_redaction.cli_api`),
8
+ which is the most stable and runnable interface outside Gradio session state.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from doc_redaction.cli_api import (
14
+ apply_review_redactions,
15
+ combine_review_csvs,
16
+ combine_review_pdfs,
17
+ export_review_page_ocr_visualisation,
18
+ export_review_redaction_overlay,
19
+ find_duplicate_pages,
20
+ find_duplicate_tabular,
21
+ load_and_prepare_documents_or_data,
22
+ redact_data,
23
+ redact_document,
24
+ summarise_document,
25
+ verify_redaction_coverage,
26
+ word_level_ocr_text_search,
27
+ )
28
+
29
+ __all__ = [
30
+ "redact_document",
31
+ "load_and_prepare_documents_or_data",
32
+ "apply_review_redactions",
33
+ "export_review_page_ocr_visualisation",
34
+ "export_review_redaction_overlay",
35
+ "verify_redaction_coverage",
36
+ "word_level_ocr_text_search",
37
+ "redact_data",
38
+ "find_duplicate_pages",
39
+ "find_duplicate_tabular",
40
+ "summarise_document",
41
+ "combine_review_csvs",
42
+ "combine_review_pdfs",
43
+ ]
doc_redaction/assets/favicon.png ADDED

Git LFS Details

  • SHA256: 49b53f802a66a482b87a21d4bf11891e2822eb0abe4aa4d69d917c0d8e36c1d8
  • Pointer size: 129 Bytes
  • Size of remote file: 2.51 kB
doc_redaction/cli_api.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CLI-first programmatic API surface.
3
+
4
+ These functions provide a minimal, runnable Python interface that mirrors the
5
+ Gradio `api_name` routes, but executes the underlying workflows via the CLI
6
+ engine (`cli_redact.main(direct_mode_args=...)`).
7
+
8
+ Return values are lists of output file paths created in `output_dir`.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import tempfile
15
+ from pathlib import Path
16
+ from typing import Any, Iterable
17
+
18
+
19
+ def _ensure_list(v: str | list[str] | tuple[str, ...]) -> list[str]:
20
+ if isinstance(v, (list, tuple)):
21
+ return [str(x) for x in v]
22
+ return [str(v)]
23
+
24
+
25
+ def _snapshot_files(folder: str) -> set[str]:
26
+ root = Path(folder)
27
+ if not root.exists():
28
+ return set()
29
+ out: set[str] = set()
30
+ for dirpath, _, filenames in os.walk(root):
31
+ for name in filenames:
32
+ out.add(str(Path(dirpath) / name))
33
+ return out
34
+
35
+
36
+ def _default_output_dir(prefix: str) -> str:
37
+ return tempfile.mkdtemp(prefix=f"doc_redaction_{prefix}_")
38
+
39
+
40
+ def _run_cli(
41
+ *,
42
+ gradio_api_name: str,
43
+ overrides: dict[str, Any],
44
+ output_dir: str | None,
45
+ ) -> list[str]:
46
+ """
47
+ Run cli_redact.main with merged defaults and return newly created files.
48
+ """
49
+ from cli_redact import get_cli_default_args_dict
50
+ from cli_redact import main as cli_main
51
+
52
+ merged = get_cli_default_args_dict()
53
+ merged.update(overrides)
54
+
55
+ if output_dir is None:
56
+ output_dir = _default_output_dir(gradio_api_name)
57
+ merged["output_dir"] = str(output_dir)
58
+
59
+ before = _snapshot_files(str(output_dir))
60
+ cli_main(direct_mode_args=merged)
61
+ after = _snapshot_files(str(output_dir))
62
+
63
+ created = sorted(after - before)
64
+ return created
65
+
66
+
67
+ # ---------------------------------------------------------------------------
68
+ # Implemented via CLI engine (matches agent_routes.py)
69
+ # ---------------------------------------------------------------------------
70
+
71
+
72
+ def redact_document(
73
+ input_files: str | list[str],
74
+ *,
75
+ output_dir: str | None = None,
76
+ ocr_method: str | None = None,
77
+ pii_detector: str | None = None,
78
+ instruction: str | None = None,
79
+ overrides: dict[str, Any] | None = None,
80
+ ) -> list[str]:
81
+ """
82
+ Parity with Gradio `api_name='redact_document'`.
83
+ Runs CLI task `redact` (PDF/PNG/JPG) or relevant workflow based on file type.
84
+ """
85
+ direct: dict[str, Any] = {
86
+ "task": "redact",
87
+ "input_file": _ensure_list(input_files),
88
+ }
89
+ if ocr_method is not None:
90
+ direct["ocr_method"] = ocr_method
91
+ if pii_detector is not None:
92
+ direct["pii_detector"] = pii_detector
93
+ if instruction is not None:
94
+ direct["custom_llm_instructions"] = instruction
95
+ if overrides:
96
+ direct.update(overrides)
97
+ return _run_cli(
98
+ gradio_api_name="redact_document", overrides=direct, output_dir=output_dir
99
+ )
100
+
101
+
102
+ def redact_data(
103
+ input_files: str | list[str],
104
+ *,
105
+ output_dir: str | None = None,
106
+ instruction: str | None = None,
107
+ overrides: dict[str, Any] | None = None,
108
+ ) -> list[str]:
109
+ """Parity with Gradio `api_name='redact_data'` (same CLI task: `redact`)."""
110
+ direct: dict[str, Any] = {"task": "redact", "input_file": _ensure_list(input_files)}
111
+ if instruction is not None:
112
+ direct["custom_llm_instructions"] = instruction
113
+ if overrides:
114
+ direct.update(overrides)
115
+ return _run_cli(
116
+ gradio_api_name="redact_data", overrides=direct, output_dir=output_dir
117
+ )
118
+
119
+
120
+ def find_duplicate_pages(
121
+ input_files: str | list[str],
122
+ *,
123
+ output_dir: str | None = None,
124
+ similarity_threshold: float | None = None,
125
+ min_word_count: int | None = None,
126
+ min_consecutive_pages: int | None = None,
127
+ greedy_match: bool | None = None,
128
+ combine_pages: bool | None = None,
129
+ overrides: dict[str, Any] | None = None,
130
+ ) -> list[str]:
131
+ """Parity with Gradio `api_name='find_duplicate_pages'`."""
132
+ direct: dict[str, Any] = {
133
+ "task": "deduplicate",
134
+ "duplicate_type": "pages",
135
+ "input_file": _ensure_list(input_files),
136
+ }
137
+ if similarity_threshold is not None:
138
+ direct["similarity_threshold"] = similarity_threshold
139
+ if min_word_count is not None:
140
+ direct["min_word_count"] = min_word_count
141
+ if min_consecutive_pages is not None:
142
+ direct["min_consecutive_pages"] = min_consecutive_pages
143
+ if greedy_match is not None:
144
+ direct["greedy_match"] = "True" if greedy_match else "False"
145
+ if combine_pages is not None:
146
+ direct["combine_pages"] = "True" if combine_pages else "False"
147
+ if overrides:
148
+ direct.update(overrides)
149
+ return _run_cli(
150
+ gradio_api_name="find_duplicate_pages", overrides=direct, output_dir=output_dir
151
+ )
152
+
153
+
154
+ def find_duplicate_tabular(
155
+ input_files: str | list[str],
156
+ *,
157
+ output_dir: str | None = None,
158
+ text_columns: list[str] | None = None,
159
+ similarity_threshold: float | None = None,
160
+ min_word_count: int | None = None,
161
+ overrides: dict[str, Any] | None = None,
162
+ ) -> list[str]:
163
+ """Parity with Gradio `api_name='find_duplicate_tabular'`."""
164
+ direct: dict[str, Any] = {
165
+ "task": "deduplicate",
166
+ "duplicate_type": "tabular",
167
+ "input_file": _ensure_list(input_files),
168
+ }
169
+ if text_columns is not None:
170
+ direct["text_columns"] = list(text_columns)
171
+ if similarity_threshold is not None:
172
+ direct["similarity_threshold"] = similarity_threshold
173
+ if min_word_count is not None:
174
+ direct["min_word_count"] = min_word_count
175
+ if overrides:
176
+ direct.update(overrides)
177
+ return _run_cli(
178
+ gradio_api_name="find_duplicate_tabular",
179
+ overrides=direct,
180
+ output_dir=output_dir,
181
+ )
182
+
183
+
184
+ def summarise_document(
185
+ input_files: str | list[str],
186
+ *,
187
+ output_dir: str | None = None,
188
+ overrides: dict[str, Any] | None = None,
189
+ ) -> list[str]:
190
+ """Parity with Gradio `api_name='summarise_document'` (CLI task: `summarise`)."""
191
+ direct: dict[str, Any] = {
192
+ "task": "summarise",
193
+ "input_file": _ensure_list(input_files),
194
+ }
195
+ if overrides:
196
+ direct.update(overrides)
197
+ return _run_cli(
198
+ gradio_api_name="summarise_document", overrides=direct, output_dir=output_dir
199
+ )
200
+
201
+
202
+ def combine_review_pdfs(
203
+ input_files: str | list[str],
204
+ *,
205
+ output_dir: str | None = None,
206
+ overrides: dict[str, Any] | None = None,
207
+ ) -> list[str]:
208
+ """Parity with Gradio `api_name='combine_review_pdfs'` (CLI task: `combine_review_pdfs`)."""
209
+ direct: dict[str, Any] = {
210
+ "task": "combine_review_pdfs",
211
+ "input_file": _ensure_list(input_files),
212
+ }
213
+ if overrides:
214
+ direct.update(overrides)
215
+ return _run_cli(
216
+ gradio_api_name="combine_review_pdfs", overrides=direct, output_dir=output_dir
217
+ )
218
+
219
+
220
+ # ---------------------------------------------------------------------------
221
+ # Implemented without CLI (as per agent_routes.py)
222
+ # ---------------------------------------------------------------------------
223
+
224
+
225
+ def combine_review_csvs(
226
+ input_files: Iterable[str],
227
+ *,
228
+ output_dir: str | None = None,
229
+ ) -> list[str]:
230
+ """Parity with Gradio `api_name='combine_review_csvs'`."""
231
+ from tools.config import OUTPUT_FOLDER
232
+ from tools.helper_functions import merge_csv_files
233
+
234
+ out_dir = str(output_dir or OUTPUT_FOLDER)
235
+ Path(out_dir).mkdir(parents=True, exist_ok=True)
236
+ sep = "/" if not out_dir.endswith(("/", "\\")) else ""
237
+
238
+ return merge_csv_files([str(p) for p in input_files], output_folder=out_dir + sep)
239
+
240
+
241
+ def export_review_redaction_overlay(
242
+ *,
243
+ page_image_path: str,
244
+ boxes: list[dict[str, Any]],
245
+ page_number: int = 1,
246
+ doc_base_name: str = "review",
247
+ review_df_records: list[dict[str, Any]] | None = None,
248
+ label_abbrev_chars: int | None = None,
249
+ ) -> list[str]:
250
+ """Same behaviour as Gradio ``api_name='page_redaction_review_image'``; Agent API route ``export_review_redaction_overlay``."""
251
+ import pandas as pd
252
+
253
+ from tools.config import OUTPUT_FOLDER
254
+ from tools.redaction_review import visualise_review_redaction_boxes
255
+
256
+ annotator: dict[str, Any] = {"image": page_image_path, "boxes": boxes}
257
+ review_df = pd.DataFrame(review_df_records) if review_df_records else pd.DataFrame()
258
+
259
+ out_dir = str(Path(OUTPUT_FOLDER).expanduser().resolve())
260
+ Path(out_dir).mkdir(parents=True, exist_ok=True)
261
+ out_path = visualise_review_redaction_boxes(
262
+ annotator,
263
+ review_df=review_df,
264
+ output_folder=out_dir,
265
+ page_number=page_number,
266
+ doc_base_name=doc_base_name,
267
+ label_abbrev_chars=label_abbrev_chars,
268
+ )
269
+ return [out_path] if out_path else []
270
+
271
+
272
+ def export_review_page_ocr_visualisation(
273
+ *,
274
+ page_image_path: str,
275
+ ocr_results: dict[str, Any],
276
+ page_number: int = 1,
277
+ doc_base_name: str = "review",
278
+ ) -> list[str]:
279
+ """Same behaviour as Gradio ``api_name='page_ocr_review_image'``; Agent API route ``export_review_page_ocr_visualisation``."""
280
+ from PIL import Image
281
+
282
+ from tools.config import OUTPUT_FOLDER
283
+ from tools.file_redaction import visualise_ocr_words_bounding_boxes
284
+
285
+ out_dir = str(Path(OUTPUT_FOLDER).expanduser().resolve())
286
+ Path(out_dir).mkdir(parents=True, exist_ok=True)
287
+
288
+ image_name = f"{str(doc_base_name or 'review')}_page{int(page_number)}.png"
289
+ log_paths: list[str] = []
290
+ log_paths = visualise_ocr_words_bounding_boxes(
291
+ Image.open(page_image_path).convert("RGB"),
292
+ ocr_results,
293
+ image_name=image_name,
294
+ output_folder=out_dir,
295
+ visualisation_folder="review_ocr_visualisations",
296
+ add_legend=True,
297
+ log_files_output_paths=log_paths,
298
+ )
299
+ return list(log_paths)
300
+
301
+
302
+ # ---------------------------------------------------------------------------
303
+ # Gradio-session-only (no single CLI task)
304
+ # ---------------------------------------------------------------------------
305
+
306
+
307
+ def load_and_prepare_documents_or_data(*args: Any, **kwargs: Any) -> list[str]:
308
+ raise NotImplementedError(
309
+ "load_and_prepare_documents_or_data is Gradio-session-state driven and is not exposed as a single CLI task."
310
+ )
311
+
312
+
313
+ def apply_review_redactions(
314
+ pdf_path: str,
315
+ review_csv_path: str,
316
+ *,
317
+ output_dir: str | None = None,
318
+ input_dir: str | None = None,
319
+ text_extract_method: str | None = None,
320
+ efficient_ocr: bool | None = None,
321
+ ) -> list[str]:
322
+ """
323
+ Headless parity with Gradio ``api_name='apply_review_redactions'``.
324
+
325
+ Returns output file paths (redacted PDF, review CSV, logs, etc.).
326
+ """
327
+ from tools.simplified_api import run_apply_review_redactions
328
+
329
+ r = run_apply_review_redactions(
330
+ pdf_path=pdf_path,
331
+ review_csv_path=review_csv_path,
332
+ output_dir=output_dir,
333
+ input_dir=input_dir,
334
+ text_extract_method=text_extract_method,
335
+ efficient_ocr=efficient_ocr,
336
+ )
337
+ return list(r.get("output_paths") or [])
338
+
339
+
340
+ def word_level_ocr_text_search(
341
+ ocr_words_csv_path: str,
342
+ search_text: str,
343
+ *,
344
+ similarity_threshold: float = 1.0,
345
+ use_regex: bool = False,
346
+ review_csv_path: str | None = None,
347
+ ) -> dict:
348
+ """Headless word-level OCR search against ``*_ocr_results_with_words_*.csv``."""
349
+ from tools.verify_redaction_coverage import run_word_level_ocr_text_search
350
+
351
+ return run_word_level_ocr_text_search(
352
+ ocr_words_csv_path,
353
+ search_text,
354
+ similarity_threshold=similarity_threshold,
355
+ use_regex=use_regex,
356
+ review_csv_path=review_csv_path,
357
+ )
358
+
359
+
360
+ def verify_redaction_coverage(
361
+ review_csv_path: str,
362
+ ocr_words_csv_path: str,
363
+ *,
364
+ must_redact: list[str] | None = None,
365
+ must_not_redact: list[str] | None = None,
366
+ redacted_pdf_path: str | None = None,
367
+ total_pages: int | None = None,
368
+ min_word_length: int = 3,
369
+ sample_pixels: bool = False,
370
+ auto_prune_suspicious: bool = False,
371
+ pruned_output_path: str | None = None,
372
+ ) -> dict:
373
+ """Pass 1 programmatic coverage report (no VLM)."""
374
+ from tools.simplified_api import run_verify_redaction_coverage
375
+
376
+ report, _, _ = run_verify_redaction_coverage(
377
+ review_csv_path,
378
+ ocr_words_csv_path,
379
+ must_redact=must_redact,
380
+ must_not_redact=must_not_redact,
381
+ redacted_pdf_path=redacted_pdf_path,
382
+ total_pages=total_pages,
383
+ min_word_length=min_word_length,
384
+ sample_pixels=sample_pixels,
385
+ auto_prune_suspicious=auto_prune_suspicious,
386
+ pruned_output_path=pruned_output_path,
387
+ )
388
+ return report
389
+
390
+
391
+ __all__ = [
392
+ "redact_document",
393
+ "load_and_prepare_documents_or_data",
394
+ "apply_review_redactions",
395
+ "export_review_page_ocr_visualisation",
396
+ "export_review_redaction_overlay",
397
+ "word_level_ocr_text_search",
398
+ "verify_redaction_coverage",
399
+ "redact_data",
400
+ "find_duplicate_pages",
401
+ "find_duplicate_tabular",
402
+ "summarise_document",
403
+ "combine_review_csvs",
404
+ "combine_review_pdfs",
405
+ ]
doc_redaction/cli_redact.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CLI entrypoint for packaging.
3
+
4
+ Re-exports the existing repo-root `cli_redact.py` implementation so that
5
+ `pyproject.toml` console scripts can target a stable package path.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import importlib
11
+ from typing import Any, Dict
12
+
13
+ _root_cli = importlib.import_module("cli_redact")
14
+
15
+ build_cli_argument_parser = getattr(_root_cli, "build_cli_argument_parser")
16
+ get_cli_default_args_dict = getattr(_root_cli, "get_cli_default_args_dict")
17
+
18
+
19
+ def main(direct_mode_args: Dict[str, Any] | None = None):
20
+ # Mirror the root signature but avoid a mutable default.
21
+ if direct_mode_args is None:
22
+ direct_mode_args = {}
23
+ return _root_cli.main(direct_mode_args=direct_mode_args)
24
+
25
+
26
+ __all__ = ["build_cli_argument_parser", "get_cli_default_args_dict", "main"]
doc_redaction/data_anonymise.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Public API wrappers for tabular anonymisation functions.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from tools.data_anonymise import anonymise_files_with_open_text
8
+
9
+ __all__ = ["anonymise_files_with_open_text"]
doc_redaction/example_data/Bold minimalist professional cover letter.docx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c8551ac157f350b2093e5d8c89f68474f613350074201cff6d52d5ed5ec28ff
3
+ size 23992
doc_redaction/example_data/Difficult handwritten note.jpg ADDED

Git LFS Details

  • SHA256: 28896bfa4c4d6ef48222a285c02529dc8967d15d799df5c4b4cf0f62224e7b6c
  • Pointer size: 130 Bytes
  • Size of remote file: 85.1 kB
doc_redaction/example_data/Example-cv-university-graduaty-hr-role-with-photo-2.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:caf00ca5cb06b8019804d1a7eaeceec772607969e8cad6c34d1d583876345b90
3
+ size 116763
doc_redaction/example_data/Lambeth_2030-Our_Future_Our_Lambeth.pdf.csv ADDED
The diff for this file is too large to render. See raw diff
 
doc_redaction/example_data/Partnership-Agreement-Toolkit_0_0.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0db46a784d7aaafb8d02acf8686523dd376400117d07926a5dcb51ceb69e3236
3
+ size 426602