-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstant.py
More file actions
640 lines (547 loc) · 22.1 KB
/
constant.py
File metadata and controls
640 lines (547 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
from collections.abc import Callable
from typing import Any, Literal, Protocol, TypeVar, cast
from nutrient_dws.inputs import FileInputWithUrl
from nutrient_dws.types.build_actions import (
ApplyInstantJsonAction,
ApplyRedactionsAction,
ApplyXfdfAction,
ApplyXfdfActionOptions,
BaseCreateRedactionsOptions,
BuildAction,
CreateRedactionsActionPreset,
CreateRedactionsActionRegex,
CreateRedactionsActionText,
CreateRedactionsStrategyOptionsPreset,
CreateRedactionsStrategyOptionsRegex,
CreateRedactionsStrategyOptionsText,
FlattenAction,
ImageWatermarkAction,
ImageWatermarkActionOptions,
OcrAction,
RotateAction,
SearchPreset,
TextWatermarkAction,
TextWatermarkActionOptions,
)
from nutrient_dws.types.build_output import (
HTMLOutput,
ImageOutput,
ImageOutputOptions,
JSONContentOutput,
JSONContentOutputOptions,
MarkdownOutput,
OfficeOutput,
PDFAOutput,
PDFAOutputOptions,
PDFOutput,
PDFOutputOptions,
PDFUAOutput,
PDFUAOutputOptions,
)
from nutrient_dws.types.file_handle import FileHandle
from nutrient_dws.types.misc import OcrLanguage, WatermarkDimension
# Default dimension for watermarks
DEFAULT_DIMENSION: WatermarkDimension = {"value": 100, "unit": "%"}
T = TypeVar("T")
class ActionWithFileInput(Protocol):
"""Internal action type that holds FileInput for deferred registration."""
__needsFileRegistration: bool
fileInput: FileInputWithUrl
createAction: Callable[[FileHandle], BuildAction]
class BuildActions:
"""Factory functions for creating common build actions."""
@staticmethod
def ocr(language: OcrLanguage | list[OcrLanguage]) -> OcrAction:
"""Create an OCR action.
Args:
language: Language(s) for OCR
Returns:
OcrAction object
"""
return {
"type": "ocr",
"language": language,
}
@staticmethod
def rotate(rotateBy: Literal[90, 180, 270]) -> RotateAction:
"""Create a rotation action.
Args:
rotateBy: Rotation angle (90, 180, or 270)
Returns:
RotateAction object
"""
return {
"type": "rotate",
"rotateBy": rotateBy,
}
@staticmethod
def watermark_text(
text: str, options: TextWatermarkActionOptions | None = None
) -> TextWatermarkAction:
"""Create a text watermark action.
Args:
text: Watermark text
options: Watermark options
width: Width dimension of the watermark (value and unit, e.g. {value: 100, unit: '%'})
height: Height dimension of the watermark (value and unit, e.g. {value: 100, unit: '%'})
top: Top position of the watermark (value and unit)
right: Right position of the watermark (value and unit)
bottom: Bottom position of the watermark (value and unit)
left: Left position of the watermark (value and unit)
rotation: Rotation of the watermark in counterclockwise degrees (default: 0)
opacity: Watermark opacity (0 is fully transparent, 1 is fully opaque)
fontFamily: Font family for the text (e.g. 'Helvetica')
fontSize: Size of the text in points
fontColor: Foreground color of the text (e.g. '#ffffff')
fontStyle: Text style array ('bold', 'italic', or both)
Returns:
TextWatermarkAction object
"""
if options is None:
options = {
"width": DEFAULT_DIMENSION,
"height": DEFAULT_DIMENSION,
"rotation": 0,
}
return {
"type": "watermark",
"text": text,
**options,
"rotation": options.get("rotation", 0),
"width": options.get("width", DEFAULT_DIMENSION),
"height": options.get("height", DEFAULT_DIMENSION),
}
@staticmethod
def watermark_image(
image: FileInputWithUrl, options: ImageWatermarkActionOptions | None = None
) -> ActionWithFileInput:
"""Create an image watermark action.
Args:
image: Watermark image
options: Watermark options
width: Width dimension of the watermark (value and unit, e.g. {value: 100, unit: '%'})
height: Height dimension of the watermark (value and unit, e.g. {value: 100, unit: '%'})
top: Top position of the watermark (value and unit)
right: Right position of the watermark (value and unit)
bottom: Bottom position of the watermark (value and unit)
left: Left position of the watermark (value and unit)
rotation: Rotation of the watermark in counterclockwise degrees (default: 0)
opacity: Watermark opacity (0 is fully transparent, 1 is fully opaque)
Returns:
ActionWithFileInput object
"""
if options is None:
options = {
"width": DEFAULT_DIMENSION,
"height": DEFAULT_DIMENSION,
"rotation": 0,
}
class ImageWatermarkActionWithFileInput(ActionWithFileInput):
__needsFileRegistration = True
def __init__(
self, file_input: FileInputWithUrl, opts: ImageWatermarkActionOptions
):
self.fileInput = file_input
self.options = opts
def createAction(self, fileHandle: FileHandle) -> ImageWatermarkAction:
return {
"type": "watermark",
"image": fileHandle,
**self.options,
"rotation": self.options.get("rotation", 0),
"width": self.options.get("width", DEFAULT_DIMENSION),
"height": self.options.get("height", DEFAULT_DIMENSION),
}
return ImageWatermarkActionWithFileInput(image, options)
@staticmethod
def flatten(annotation_ids: list[str | int] | None = None) -> FlattenAction:
"""Create a flatten action.
Args:
annotation_ids: Optional annotation IDs to flatten (all if not specified)
Returns:
FlattenAction object
"""
result: FlattenAction = {"type": "flatten"}
if annotation_ids is not None:
result["annotationIds"] = annotation_ids
return result
@staticmethod
def apply_instant_json(file: FileInputWithUrl) -> ActionWithFileInput:
"""Create an apply Instant JSON action.
Args:
file: Instant JSON file input
Returns:
ActionWithFileInput object
"""
class ApplyInstantJsonActionWithFileInput(ActionWithFileInput):
__needsFileRegistration = True
def __init__(self, file_input: FileInputWithUrl):
self.fileInput = file_input
def createAction(self, fileHandle: FileHandle) -> ApplyInstantJsonAction:
return {
"type": "applyInstantJson",
"file": fileHandle,
}
return ApplyInstantJsonActionWithFileInput(file)
@staticmethod
def apply_xfdf(
file: FileInputWithUrl, options: ApplyXfdfActionOptions | None = None
) -> ActionWithFileInput:
"""Create an apply XFDF action.
Args:
file: XFDF file input
options: Apply Xfdf options
ignorePageRotation: If true, ignores page rotation when applying XFDF data (default: false)
richTextEnabled: If true, plain text annotations will be converted to rich text annotations. If false, all text annotations will be plain text annotations (default: true)
Returns:
ActionWithFileInput object
"""
class ApplyXfdfActionWithFileInput(ActionWithFileInput):
__needsFileRegistration = True
def __init__(
self, file_input: FileInputWithUrl, opts: ApplyXfdfActionOptions | None
):
self.fileInput = file_input
self.options = opts or {}
def createAction(self, fileHandle: FileHandle) -> ApplyXfdfAction:
return {
"type": "applyXfdf",
"file": fileHandle,
**self.options,
}
return ApplyXfdfActionWithFileInput(file, options)
@staticmethod
def create_redactions_text(
text: str,
options: BaseCreateRedactionsOptions | None = None,
strategy_options: CreateRedactionsStrategyOptionsText | None = None,
) -> CreateRedactionsActionText:
"""Create redactions with text search.
Args:
text: Text to search and redact
options: Redaction options
content: Visual aspects of the redaction annotation (background color, overlay text, etc.)
strategy_options: Redaction strategy options
includeAnnotations: If true, redaction annotations are created on top of annotations whose content match the provided text (default: true)
caseSensitive: If true, the search will be case sensitive (default: false)
start: The index of the page from where to start the search (default: 0)
limit: Starting from start, the number of pages to search (default: to the end of the document)
Returns:
CreateRedactionsAction object
"""
result: dict[str, Any] = {
"type": "createRedactions",
"strategy": "text",
"strategyOptions": {
"text": text,
**(strategy_options or {}),
},
**(options or {}),
}
return cast("CreateRedactionsActionText", result)
@staticmethod
def create_redactions_regex(
regex: str,
options: BaseCreateRedactionsOptions | None = None,
strategy_options: CreateRedactionsStrategyOptionsRegex | None = None,
) -> CreateRedactionsActionRegex:
"""Create redactions with regex pattern.
Args:
regex: Regex pattern to search and redact
options: Redaction options
content: Visual aspects of the redaction annotation (background color, overlay text, etc.)
strategy_options: Redaction strategy options
includeAnnotations: If true, redaction annotations are created on top of annotations whose content match the provided regex (default: true)
caseSensitive: If true, the search will be case sensitive (default: true)
start: The index of the page from where to start the search (default: 0)
limit: Starting from start, the number of pages to search (default: to the end of the document)
Returns:
CreateRedactionsAction object
"""
result: dict[str, Any] = {
"type": "createRedactions",
"strategy": "regex",
"strategyOptions": {
"regex": regex,
**(strategy_options or {}),
},
**(options or {}),
}
return cast("CreateRedactionsActionRegex", result)
@staticmethod
def create_redactions_preset(
preset: SearchPreset,
options: BaseCreateRedactionsOptions | None = None,
strategy_options: CreateRedactionsStrategyOptionsPreset | None = None,
) -> CreateRedactionsActionPreset:
"""Create redactions with preset pattern.
Args:
preset: Preset pattern to search and redact (e.g. 'email-address', 'credit-card-number', 'social-security-number', etc.)
options: Redaction options
content: Visual aspects of the redaction annotation (background color, overlay text, etc.)
strategy_options: Redaction strategy options
includeAnnotations: If true, redaction annotations are created on top of annotations whose content match the provided preset (default: true)
start: The index of the page from where to start the search (default: 0)
limit: Starting from start, the number of pages to search (default: to the end of the document)
Returns:
CreateRedactionsAction object
"""
result: dict[str, Any] = {
"type": "createRedactions",
"strategy": "preset",
"strategyOptions": {
"preset": preset,
**(strategy_options or {}),
},
**(options or {}),
}
return cast("CreateRedactionsActionPreset", result)
@staticmethod
def apply_redactions() -> ApplyRedactionsAction:
"""Apply previously created redactions.
Returns:
ApplyRedactionsAction object
"""
return {
"type": "applyRedactions",
}
class BuildOutputs:
"""Factory functions for creating output configurations."""
@staticmethod
def pdf(options: PDFOutputOptions | None = None) -> PDFOutput:
"""PDF output configuration.
Args:
options: PDF output options
metadata: Document metadata
labels: Page labels
user_password: User password for the PDF
owner_password: Owner password for the PDF
user_permissions: User permissions
optimize: PDF optimization options
Returns:
PDFOutput object
"""
result: dict[str, Any] = {"type": "pdf"}
if options:
if "metadata" in options:
result["metadata"] = options["metadata"]
if "labels" in options:
result["labels"] = options["labels"]
if "user_password" in options:
result["user_password"] = options["user_password"]
if "owner_password" in options:
result["owner_password"] = options["owner_password"]
if "user_permissions" in options:
result["user_permissions"] = options["user_permissions"]
if "optimize" in options:
result["optimize"] = options["optimize"]
return cast("PDFOutput", result)
@staticmethod
def pdfa(options: PDFAOutputOptions | None = None) -> PDFAOutput:
"""PDF/A output configuration.
Args:
options: PDF/A output options
conformance: PDF/A conformance level
vectorization: Enable vectorization
rasterization: Enable rasterization
metadata: Document metadata
labels: Page labels
user_password: User password for the PDF
owner_password: Owner password for the PDF
user_permissions: User permissions
optimize: PDF optimization options
Returns:
PDFAOutput object
"""
result: dict[str, Any] = {"type": "pdfa"}
if options:
if "conformance" in options:
result["conformance"] = options["conformance"]
if "vectorization" in options:
result["vectorization"] = options["vectorization"]
if "rasterization" in options:
result["rasterization"] = options["rasterization"]
if "metadata" in options:
result["metadata"] = options["metadata"]
if "labels" in options:
result["labels"] = options["labels"]
if "user_password" in options:
result["user_password"] = options["user_password"]
if "owner_password" in options:
result["owner_password"] = options["owner_password"]
if "user_permissions" in options:
result["user_permissions"] = options["user_permissions"]
if "optimize" in options:
result["optimize"] = options["optimize"]
return cast("PDFAOutput", result)
@staticmethod
def pdfua(options: PDFUAOutputOptions | None = None) -> PDFUAOutput:
"""PDF/UA output configuration.
Args:
options: PDF/UA output options
metadata: Document metadata
labels: Page labels
user_password: User password for the PDF
owner_password: Owner password for the PDF
user_permissions: User permissions
optimize: PDF optimization options
Returns:
PDFUAOutput object
"""
result: dict[str, Any] = {"type": "pdfua"}
if options:
if "metadata" in options:
result["metadata"] = options["metadata"]
if "labels" in options:
result["labels"] = options["labels"]
if "user_password" in options:
result["user_password"] = options["user_password"]
if "owner_password" in options:
result["owner_password"] = options["owner_password"]
if "user_permissions" in options:
result["user_permissions"] = options["user_permissions"]
if "optimize" in options:
result["optimize"] = options["optimize"]
return cast("PDFUAOutput", result)
@staticmethod
def image(
format: Literal["png", "jpeg", "jpg", "webp"],
options: ImageOutputOptions | None = None,
) -> ImageOutput:
"""Image output configuration.
Args:
format: Image format type
options: Image output options
pages: Page range to convert
width: Width of the output image
height: Height of the output image
dpi: DPI of the output image
Returns:
ImageOutput object
"""
result: dict[str, Any] = {
"type": "image",
"format": format,
}
if options:
if "pages" in options:
result["pages"] = options["pages"]
if "width" in options:
result["width"] = options["width"]
if "height" in options:
result["height"] = options["height"]
if "dpi" in options:
result["dpi"] = options["dpi"]
return cast("ImageOutput", result)
@staticmethod
def jsonContent(
options: JSONContentOutputOptions | None = None,
) -> JSONContentOutput:
"""JSON content output configuration.
Args:
options: JSON content extraction options
plainText: Extract plain text
structuredText: Extract structured text
keyValuePairs: Extract key-value pairs
tables: Extract tables
language: Language(s) for OCR
Returns:
JSONContentOutput object
"""
result: dict[str, Any] = {"type": "json-content"}
if options:
if "plainText" in options:
result["plainText"] = options["plainText"]
if "structuredText" in options:
result["structuredText"] = options["structuredText"]
if "keyValuePairs" in options:
result["keyValuePairs"] = options["keyValuePairs"]
if "tables" in options:
result["tables"] = options["tables"]
if "language" in options:
result["language"] = options["language"]
return cast("JSONContentOutput", result)
@staticmethod
def office(type: Literal["docx", "xlsx", "pptx"]) -> OfficeOutput:
"""Office document output configuration.
Args:
type: Office document type
Returns:
OfficeOutput object
"""
return {
"type": type,
}
@staticmethod
def html(layout: Literal["page", "reflow"]) -> HTMLOutput:
"""HTML output configuration.
Args:
layout: The layout type to use for conversion to HTML
Returns:
HTMLOutput object
"""
return {
"type": "html",
"layout": layout,
}
@staticmethod
def markdown() -> MarkdownOutput:
"""Markdown output configuration.
Returns:
MarkdownOutput object
"""
return {
"type": "markdown",
}
@staticmethod
def getMimeTypeForOutput(
output: PDFOutput
| PDFAOutput
| PDFUAOutput
| ImageOutput
| OfficeOutput
| HTMLOutput
| MarkdownOutput,
) -> dict[str, str]:
"""Get MIME type and filename for a given output configuration.
Args:
output: The output configuration
Returns:
Dictionary with mimeType and optional filename
"""
output_type = output.get("type", "pdf")
if output_type in ["pdf", "pdfa", "pdfua"]:
return {"mimeType": "application/pdf", "filename": "output.pdf"}
elif output_type == "image":
format = output.get("format", "png")
if format == "jpg":
return {"mimeType": "image/jpeg", "filename": "output.jpg"}
else:
return {"mimeType": f"image/{format}", "filename": f"output.{format}"}
elif output_type == "docx":
return {
"mimeType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"filename": "output.docx",
}
elif output_type == "xlsx":
return {
"mimeType": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"filename": "output.xlsx",
}
elif output_type == "pptx":
return {
"mimeType": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"filename": "output.pptx",
}
elif output_type == "html":
return {
"mimeType": "text/html",
"filename": "output.html",
}
elif output_type == "markdown":
return {
"mimeType": "text/markdown",
"filename": "output.md",
}
else:
return {"mimeType": "application/octet-stream", "filename": "output"}