plasmapdf 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- plasmapdf/__about__.py +4 -0
- plasmapdf/__init__.py +3 -0
- plasmapdf/models/PdfDataLayer.py +453 -0
- plasmapdf/models/__init__.py +0 -0
- plasmapdf/models/types.py +319 -0
- plasmapdf/utils/__init__.py +0 -0
- plasmapdf/utils/utils.py +64 -0
- plasmapdf-0.0.1.dist-info/METADATA +174 -0
- plasmapdf-0.0.1.dist-info/RECORD +11 -0
- plasmapdf-0.0.1.dist-info/WHEEL +4 -0
- plasmapdf-0.0.1.dist-info/licenses/LICENSE.txt +9 -0
plasmapdf/__about__.py
ADDED
plasmapdf/__init__.py
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
# Copyright (C) 2022 John Scrudato / Gordium Knot Inc. d/b/a OpenSource.Legal
|
|
2
|
+
#
|
|
3
|
+
# This program is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU Affero General Public License as
|
|
5
|
+
# published by the Free Software Foundation, either version 3 of the
|
|
6
|
+
# License, or (at your option) any later version.
|
|
7
|
+
|
|
8
|
+
# This program is distributed in the hope that it will be useful,
|
|
9
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
10
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
11
|
+
# GNU Affero General Public License for more details.
|
|
12
|
+
|
|
13
|
+
# You should have received a copy of the GNU Affero General Public License
|
|
14
|
+
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
15
|
+
import logging
|
|
16
|
+
import uuid
|
|
17
|
+
|
|
18
|
+
import pandas as pd
|
|
19
|
+
|
|
20
|
+
from plasmapdf.models.types import (
|
|
21
|
+
OpenContractsAnnotationPythonType,
|
|
22
|
+
OpenContractsSinglePageAnnotationType,
|
|
23
|
+
PageAwareTextSpan,
|
|
24
|
+
PawlsPagePythonType,
|
|
25
|
+
SpanAnnotation,
|
|
26
|
+
TextSpan,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger(__name__)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def __consolidate_common_equivalent_chars(string):
|
|
33
|
+
|
|
34
|
+
# OCR sometimes uses characters similar to what we're looking for in place of actual char.
|
|
35
|
+
# Here we do some quick, naive cleanup of this by replacing some more exotic chars that look
|
|
36
|
+
# like common chars with their common equivalents.
|
|
37
|
+
|
|
38
|
+
# Things that commonly look like apostrophes
|
|
39
|
+
for i in "’'´":
|
|
40
|
+
string = string.replace(i, "'")
|
|
41
|
+
|
|
42
|
+
# Things that commonly look like periods
|
|
43
|
+
for i in "⋅":
|
|
44
|
+
string = string.replace(i, ".")
|
|
45
|
+
|
|
46
|
+
return string
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class PdfDataLayer:
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
pawls_tokens,
|
|
53
|
+
page_dataframe,
|
|
54
|
+
lines_dataframe,
|
|
55
|
+
tokens_dataframe,
|
|
56
|
+
doc_text,
|
|
57
|
+
doc_tokens,
|
|
58
|
+
page_tokens,
|
|
59
|
+
human_friendly_full_text,
|
|
60
|
+
):
|
|
61
|
+
self.pawls_tokens = pawls_tokens
|
|
62
|
+
self.page_dataframe = page_dataframe
|
|
63
|
+
self.lines_dataframe = lines_dataframe
|
|
64
|
+
self.tokens_dataframe = tokens_dataframe
|
|
65
|
+
self.doc_text = doc_text
|
|
66
|
+
self.doc_tokens = doc_tokens
|
|
67
|
+
self.page_tokens = page_tokens
|
|
68
|
+
self.human_friendly_full_text = human_friendly_full_text
|
|
69
|
+
self.log = ""
|
|
70
|
+
self.pawls_annotations = {}
|
|
71
|
+
self.span_annotations: dict[str, any] = {}
|
|
72
|
+
|
|
73
|
+
def get_raw_text_from_span(self, span: TextSpan) -> str:
|
|
74
|
+
return self.doc_text[span["start"] : span["end"]]
|
|
75
|
+
|
|
76
|
+
def convert_doc_span_to_opencontract_annotation_json(
|
|
77
|
+
self,
|
|
78
|
+
span: TextSpan,
|
|
79
|
+
padding: float = 0.1,
|
|
80
|
+
max_bbox_vertical_margin: float = 1,
|
|
81
|
+
max_bbox_horizontal_margin: float = 5,
|
|
82
|
+
) -> dict[int, OpenContractsSinglePageAnnotationType]:
|
|
83
|
+
|
|
84
|
+
"""
|
|
85
|
+
Given the start and end index of a string in the document, return the PAWLS tokens for the annotation, split
|
|
86
|
+
across pages. For a given page, the annotation will look like:
|
|
87
|
+
{
|
|
88
|
+
"bounds": {
|
|
89
|
+
"top": top,
|
|
90
|
+
"bottom": bottom,
|
|
91
|
+
"left": left,
|
|
92
|
+
"right": right
|
|
93
|
+
},
|
|
94
|
+
"rawText": page_text,
|
|
95
|
+
"tokensJsons": page_tokens
|
|
96
|
+
}
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
span_start = span["start"]
|
|
100
|
+
span_end = span["end"]
|
|
101
|
+
|
|
102
|
+
# logger.info(f"Get tokens in char range {span_start} - {span_end}")
|
|
103
|
+
tokens = self.tokens_dataframe[
|
|
104
|
+
(
|
|
105
|
+
(self.tokens_dataframe["Char_Start"] >= span_start)
|
|
106
|
+
& (self.tokens_dataframe["Char_Start"] <= span_end)
|
|
107
|
+
)
|
|
108
|
+
| (
|
|
109
|
+
(self.tokens_dataframe["Char_End"] >= span_start)
|
|
110
|
+
& (self.tokens_dataframe["Char_End"] <= span_end)
|
|
111
|
+
)
|
|
112
|
+
]
|
|
113
|
+
|
|
114
|
+
return_annotations = {}
|
|
115
|
+
page_tokens = []
|
|
116
|
+
page_text = ""
|
|
117
|
+
|
|
118
|
+
last_page = -1
|
|
119
|
+
|
|
120
|
+
bbox_top = -1
|
|
121
|
+
bbox_bottom = -1
|
|
122
|
+
bbox_left = -1
|
|
123
|
+
bbox_right = -1
|
|
124
|
+
|
|
125
|
+
for token in tokens.iterrows():
|
|
126
|
+
|
|
127
|
+
token_page = token[1]["Page"]
|
|
128
|
+
|
|
129
|
+
# logger.info(f"Handle token page: {token_page}")
|
|
130
|
+
|
|
131
|
+
if last_page == -1:
|
|
132
|
+
last_page = token_page
|
|
133
|
+
|
|
134
|
+
token_page_id = token[1]["Token_Id"]
|
|
135
|
+
token_obj = self.page_tokens[token_page][token_page_id]
|
|
136
|
+
token_height = token_obj["height"]
|
|
137
|
+
token_width = token_obj["width"]
|
|
138
|
+
|
|
139
|
+
###########################################################################
|
|
140
|
+
# #
|
|
141
|
+
# Check / Update Bounding Box #
|
|
142
|
+
# #
|
|
143
|
+
# Top Left Corner is 0,0. Y increases as you move down page. #
|
|
144
|
+
# Update bounding box to include token in it #
|
|
145
|
+
###########################################################################
|
|
146
|
+
token_top = token_obj["y"]
|
|
147
|
+
if bbox_top == -1:
|
|
148
|
+
bbox_top = token_top
|
|
149
|
+
elif token_top < bbox_top:
|
|
150
|
+
bbox_top = token_top
|
|
151
|
+
|
|
152
|
+
token_bottom = token_top + token_height
|
|
153
|
+
if bbox_bottom == -1:
|
|
154
|
+
bbox_bottom = token_bottom
|
|
155
|
+
elif token_bottom > bbox_bottom:
|
|
156
|
+
bbox_bottom = token_bottom
|
|
157
|
+
|
|
158
|
+
token_left = token_obj["x"]
|
|
159
|
+
if bbox_left == -1:
|
|
160
|
+
bbox_left = token_left
|
|
161
|
+
elif token_left < bbox_left:
|
|
162
|
+
bbox_left = token_left
|
|
163
|
+
|
|
164
|
+
token_right = token_left + token_width
|
|
165
|
+
if bbox_right == -1:
|
|
166
|
+
bbox_right = token_right
|
|
167
|
+
elif token_right > bbox_right:
|
|
168
|
+
bbox_right = token_right
|
|
169
|
+
|
|
170
|
+
# If we changed pages... reset bounds and add bounding box to tracker
|
|
171
|
+
if token_page != last_page:
|
|
172
|
+
|
|
173
|
+
bbox_height = bbox_bottom - bbox_top
|
|
174
|
+
logger.info(f"Height: {bbox_height}")
|
|
175
|
+
bbox_width = bbox_right - bbox_left
|
|
176
|
+
logger.info(f"Width: {bbox_width}")
|
|
177
|
+
|
|
178
|
+
return_annotations[last_page] = {
|
|
179
|
+
"bounds": {
|
|
180
|
+
"top": bbox_top - (padding * bbox_height),
|
|
181
|
+
"bottom": bbox_bottom + (padding * bbox_height),
|
|
182
|
+
"left": bbox_left - (padding * bbox_width),
|
|
183
|
+
"right": bbox_right + (padding * bbox_width),
|
|
184
|
+
},
|
|
185
|
+
"rawText": page_text,
|
|
186
|
+
"tokensJsons": page_tokens,
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
# Reset tracking vars
|
|
190
|
+
last_page = token_page
|
|
191
|
+
page_text = token_obj["text"]
|
|
192
|
+
page_tokens = [{"pageIndex": token_page, "tokenIndex": token_page_id}]
|
|
193
|
+
|
|
194
|
+
bbox_top = -1
|
|
195
|
+
bbox_bottom = -1
|
|
196
|
+
bbox_left = -1
|
|
197
|
+
bbox_right = -1
|
|
198
|
+
|
|
199
|
+
else:
|
|
200
|
+
|
|
201
|
+
page_text += (
|
|
202
|
+
token_obj["text"] if page_text == "" else (" " + token_obj["text"])
|
|
203
|
+
)
|
|
204
|
+
page_tokens.append(
|
|
205
|
+
{"pageIndex": token_page, "tokenIndex": token_page_id}
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
bbox_height = bbox_bottom - bbox_top
|
|
209
|
+
logger.info(f"Height: {bbox_height}")
|
|
210
|
+
bbox_width = bbox_right - bbox_left
|
|
211
|
+
logger.info(f"Width: {bbox_width}")
|
|
212
|
+
|
|
213
|
+
bbox_vertical_margin = padding * bbox_height / 2
|
|
214
|
+
if bbox_vertical_margin > max_bbox_vertical_margin:
|
|
215
|
+
bbox_vertical_margin = max_bbox_vertical_margin
|
|
216
|
+
|
|
217
|
+
bbox_horizontal_margin = padding * bbox_width / 2
|
|
218
|
+
if bbox_horizontal_margin > max_bbox_horizontal_margin:
|
|
219
|
+
bbox_horizontal_margin = max_bbox_horizontal_margin
|
|
220
|
+
|
|
221
|
+
return_annotations[last_page] = {
|
|
222
|
+
"bounds": {
|
|
223
|
+
"top": bbox_top - bbox_vertical_margin,
|
|
224
|
+
"bottom": bbox_bottom + bbox_vertical_margin,
|
|
225
|
+
"left": bbox_left - bbox_horizontal_margin,
|
|
226
|
+
"right": bbox_right + bbox_horizontal_margin,
|
|
227
|
+
},
|
|
228
|
+
"rawText": page_text,
|
|
229
|
+
"tokensJsons": page_tokens,
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
return return_annotations
|
|
233
|
+
|
|
234
|
+
# TODO - This doesn't appear to work properly and is ONLY used to determine the
|
|
235
|
+
# TODO - first page of a given annotation? Get rid of this if possible.
|
|
236
|
+
# TODO - Just extra code to maintain. It's useless.
|
|
237
|
+
def split_span_on_pages(self, span: TextSpan) -> list[PageAwareTextSpan]:
|
|
238
|
+
|
|
239
|
+
span_start = span["start"]
|
|
240
|
+
print(f"Span start: {span_start}")
|
|
241
|
+
span_end = span["end"]
|
|
242
|
+
print(f"Span end: {span_end}")
|
|
243
|
+
|
|
244
|
+
print(f"Split lines for char range {span_start} - {span_end}")
|
|
245
|
+
|
|
246
|
+
pages = self.page_dataframe[
|
|
247
|
+
(
|
|
248
|
+
(span_start >= self.page_dataframe["Start"])
|
|
249
|
+
& (span_start <= self.page_dataframe["End"])
|
|
250
|
+
)
|
|
251
|
+
| (
|
|
252
|
+
(span_start < self.page_dataframe["Start"])
|
|
253
|
+
& (span_end > self.page_dataframe["End"])
|
|
254
|
+
)
|
|
255
|
+
| (
|
|
256
|
+
(span_end >= self.page_dataframe["Start"])
|
|
257
|
+
& (span_end <= self.page_dataframe["End"])
|
|
258
|
+
)
|
|
259
|
+
]
|
|
260
|
+
|
|
261
|
+
print(f"Pages: {pages}")
|
|
262
|
+
|
|
263
|
+
# logger.info(f"Resulting pages: {pages}")
|
|
264
|
+
|
|
265
|
+
page_split_spans: list[PageAwareTextSpan] = []
|
|
266
|
+
|
|
267
|
+
for page in pages.iterrows():
|
|
268
|
+
|
|
269
|
+
print(f"Look at page # {page[0]} with start "
|
|
270
|
+
f"{page[1]['Start']} and end "
|
|
271
|
+
f"{page[1]['End']}")
|
|
272
|
+
|
|
273
|
+
# Calculate the start of target span... if the span starts
|
|
274
|
+
# before this page, use the page start index. Otherwise, use the
|
|
275
|
+
# page start index.
|
|
276
|
+
if span_start <= page[1]["Start"]:
|
|
277
|
+
span_page_start = page[1]["Start"]
|
|
278
|
+
else:
|
|
279
|
+
span_page_start = span_start
|
|
280
|
+
|
|
281
|
+
# Calculate the end of this page's span... if the span ends after this
|
|
282
|
+
# page, use the page end index. Otherwise, if span ends on this page,
|
|
283
|
+
# use the span's end index
|
|
284
|
+
if span_end > page[1]["End"]:
|
|
285
|
+
span_page_end = page[1]["End"]
|
|
286
|
+
else:
|
|
287
|
+
span_page_end = span_end
|
|
288
|
+
|
|
289
|
+
page_split_spans.append(
|
|
290
|
+
{
|
|
291
|
+
"original_span_id": span["id"],
|
|
292
|
+
"page": page[0],
|
|
293
|
+
"start": span_page_start,
|
|
294
|
+
"end": span_page_end,
|
|
295
|
+
"text": self.human_friendly_full_text[
|
|
296
|
+
span_page_start:span_page_end
|
|
297
|
+
],
|
|
298
|
+
}
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
return page_split_spans
|
|
302
|
+
|
|
303
|
+
def create_opencontract_annotation_from_span(
|
|
304
|
+
self,
|
|
305
|
+
span_annotation: SpanAnnotation,
|
|
306
|
+
) -> OpenContractsAnnotationPythonType:
|
|
307
|
+
|
|
308
|
+
span = span_annotation["span"]
|
|
309
|
+
annotation_label = span_annotation["annotation_label"]
|
|
310
|
+
|
|
311
|
+
id = uuid.uuid4().__str__()
|
|
312
|
+
annotation_json = self.convert_doc_span_to_opencontract_annotation_json(span)
|
|
313
|
+
raw_text = self.get_raw_text_from_span(span)
|
|
314
|
+
page = self.split_span_on_pages(span)[0]["page"] # TODO - this is not working
|
|
315
|
+
|
|
316
|
+
return {
|
|
317
|
+
"id": id,
|
|
318
|
+
"annotationLabel": annotation_label,
|
|
319
|
+
"rawText": raw_text,
|
|
320
|
+
"page": page,
|
|
321
|
+
"annotation_json": annotation_json,
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def makePdfTranslationLayerFromPawlsTokens(
|
|
326
|
+
pawls_tokens: list[PawlsPagePythonType],
|
|
327
|
+
) -> PdfDataLayer:
|
|
328
|
+
|
|
329
|
+
page_tokens = {}
|
|
330
|
+
doc_tokens = []
|
|
331
|
+
tokens = []
|
|
332
|
+
pages = []
|
|
333
|
+
lines: list[tuple[int, int, int, int]] = []
|
|
334
|
+
doc_text = ""
|
|
335
|
+
human_friendly_text = ""
|
|
336
|
+
line_start_char = 0
|
|
337
|
+
|
|
338
|
+
# We want the last token height to carry over from previous pages, so we have a token
|
|
339
|
+
# height that is useful to compare to if the page starts with whitespace (token height of 0)
|
|
340
|
+
last_token_height = -1
|
|
341
|
+
|
|
342
|
+
for page_num, page in enumerate(pawls_tokens):
|
|
343
|
+
|
|
344
|
+
# logger.info(f"Looking at page_num {page_num}:\n\n{page}")
|
|
345
|
+
|
|
346
|
+
# We DO want to reset y pos on every page, which will be set to y of first token.
|
|
347
|
+
last_y = -1
|
|
348
|
+
|
|
349
|
+
line_text = ""
|
|
350
|
+
page_tokens[page_num] = []
|
|
351
|
+
|
|
352
|
+
for page_token_index, token in enumerate(page["tokens"]):
|
|
353
|
+
|
|
354
|
+
token_text = __consolidate_common_equivalent_chars(token["text"])
|
|
355
|
+
page_tokens[page_num].append(token)
|
|
356
|
+
doc_tokens.append(token)
|
|
357
|
+
|
|
358
|
+
new_y = round(token["y"], 0)
|
|
359
|
+
new_token_height = round(token["height"], 0)
|
|
360
|
+
|
|
361
|
+
if last_y == -1:
|
|
362
|
+
last_y = round(token["y"], 0)
|
|
363
|
+
|
|
364
|
+
if last_token_height == -1:
|
|
365
|
+
|
|
366
|
+
# Not really sure how to handle situations where the token height is 0 at the beginning... just
|
|
367
|
+
# try 1 pixel, I guess?
|
|
368
|
+
last_token_height = new_token_height if new_token_height > 0 else 1
|
|
369
|
+
|
|
370
|
+
# Tesseract line positions seem a bit erratic, honestly. Figuring out when a token is on the same line is
|
|
371
|
+
# not as easy as checking if y positions are the same as they are often off by a couple pixels. This is
|
|
372
|
+
# dependent on document, font size, OCR quality, and more... Decent heuristic I came up with was to look
|
|
373
|
+
# at two consecutive tokens, take the max token height and then see if the y difference was more than some
|
|
374
|
+
# percentage of the larger of the two token heights (to account for things like periods or dashes or
|
|
375
|
+
# whatever next to a word). Seems to work pretty well, though I am *SURE* it will fail in some cases. Easy
|
|
376
|
+
# enough fix there... just don't give a cr@p about line height and newlines and always use a space. That's
|
|
377
|
+
# actually probably fine for ML purposes.
|
|
378
|
+
# logger.info(f"Token: {token['text']} (len {len(token['text'])})")
|
|
379
|
+
# logger.info(f"Line y difference: {abs(new_y - last_y)}")
|
|
380
|
+
# logger.info(f"Compared to averaged token height: {0.5 * max(new_token_height, last_token_height)}")
|
|
381
|
+
|
|
382
|
+
if abs(new_y - last_y) > (0.5 * max(new_token_height, last_token_height)):
|
|
383
|
+
|
|
384
|
+
human_friendly_text += (
|
|
385
|
+
("\n" + token_text) if len(human_friendly_text) > 0 else token_text
|
|
386
|
+
)
|
|
387
|
+
|
|
388
|
+
lines.append(
|
|
389
|
+
(
|
|
390
|
+
page_num,
|
|
391
|
+
len(lines),
|
|
392
|
+
line_start_char,
|
|
393
|
+
len(line_text) + line_start_char,
|
|
394
|
+
)
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
line_start_char = len(doc_text) + 1 # Accounting for newline
|
|
398
|
+
line_text = token_text
|
|
399
|
+
|
|
400
|
+
else:
|
|
401
|
+
line_text += " " if len(line_text) > 0 else ""
|
|
402
|
+
line_text += token_text
|
|
403
|
+
|
|
404
|
+
human_friendly_text += (
|
|
405
|
+
(" " + token_text) if len(human_friendly_text) > 0 else token_text
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
start_length = len(doc_text)
|
|
409
|
+
doc_text += " " if len(doc_text) > 0 else ""
|
|
410
|
+
doc_text += token_text
|
|
411
|
+
end_length = len(doc_text)
|
|
412
|
+
|
|
413
|
+
tokens.append(
|
|
414
|
+
[page_num, len(page_tokens[page_num]) - 1, start_length + 1, end_length]
|
|
415
|
+
)
|
|
416
|
+
|
|
417
|
+
last_y = new_y
|
|
418
|
+
|
|
419
|
+
# We want to compare line heights of non-whitespace chars. If the current token
|
|
420
|
+
# is a whitespace char, its height will be 0, so just leave the last_token_height in place.
|
|
421
|
+
if new_token_height > 0:
|
|
422
|
+
last_token_height = new_token_height
|
|
423
|
+
|
|
424
|
+
pages.append(
|
|
425
|
+
[
|
|
426
|
+
page_num,
|
|
427
|
+
(0 if page_num == 0 else pages[page_num - 1][2]),
|
|
428
|
+
len(doc_text),
|
|
429
|
+
]
|
|
430
|
+
)
|
|
431
|
+
|
|
432
|
+
# logger.info(f"Pages: {pages}")
|
|
433
|
+
|
|
434
|
+
page_dim_df = pd.DataFrame(pages, columns=["Page", "Start", "End"], dtype=object)
|
|
435
|
+
line_dim_df = pd.DataFrame(
|
|
436
|
+
lines, columns=["Page", "Line", "Char_Start", "Char_End"], dtype=object
|
|
437
|
+
)
|
|
438
|
+
token_dim_df = pd.DataFrame(
|
|
439
|
+
tokens, columns=["Page", "Token_Id", "Char_Start", "Char_End"], dtype=object
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
# logger.info(f"page_text: {doc_text}")
|
|
443
|
+
|
|
444
|
+
return PdfDataLayer(
|
|
445
|
+
pawls_tokens=pawls_tokens,
|
|
446
|
+
page_dataframe=page_dim_df,
|
|
447
|
+
lines_dataframe=line_dim_df,
|
|
448
|
+
tokens_dataframe=token_dim_df,
|
|
449
|
+
doc_text=doc_text,
|
|
450
|
+
doc_tokens=doc_tokens,
|
|
451
|
+
page_tokens=page_tokens,
|
|
452
|
+
human_friendly_full_text=human_friendly_text,
|
|
453
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
# Copyright (C) 2022 John Scrudato / Gordium Knot Inc. d/b/a OpenSource.Legal
|
|
2
|
+
#
|
|
3
|
+
# This program is free software: you can redistribute it and/or modify
|
|
4
|
+
# it under the terms of the GNU Affero General Public License as
|
|
5
|
+
# published by the Free Software Foundation, either version 3 of the
|
|
6
|
+
# License, or (at your option) any later version.
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
# This program is distributed in the hope that it will be useful,
|
|
10
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
11
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
12
|
+
# GNU Affero General Public License for more details.
|
|
13
|
+
|
|
14
|
+
# You should have received a copy of the GNU Affero General Public License
|
|
15
|
+
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
16
|
+
import enum
|
|
17
|
+
from typing import Optional, Union
|
|
18
|
+
from typing_extensions import TypedDict
|
|
19
|
+
|
|
20
|
+
from typing_extensions import NotRequired
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class JobStatus(str, enum.Enum):
|
|
24
|
+
|
|
25
|
+
CREATED = "CREATED"
|
|
26
|
+
QUEUED = "QUEUED"
|
|
27
|
+
RUNNING = "RUNNING"
|
|
28
|
+
COMPLETED = "COMPLETED"
|
|
29
|
+
FAILED = "FAILED"
|
|
30
|
+
|
|
31
|
+
@classmethod
|
|
32
|
+
def choices(cls):
|
|
33
|
+
return [(key, key) for key in cls]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class TaskStatus(str, enum.Enum):
|
|
37
|
+
SUCCESS = "SUCCESS"
|
|
38
|
+
FAILURE = "FAILURE"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class LabelType(str, enum.Enum):
|
|
42
|
+
DOC_TYPE_LABEL = "DOC_TYPE_LABEL"
|
|
43
|
+
TOKEN_LABEL = "TOKEN_LABEL"
|
|
44
|
+
RELATIONSHIP_LABEL = "RELATIONSHIP_LABEL"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class PermissionTypes(str, enum.Enum):
|
|
48
|
+
CREATE = "CREATE"
|
|
49
|
+
READ = "READ"
|
|
50
|
+
EDIT = "EDIT"
|
|
51
|
+
UPDATE = "UPDATE"
|
|
52
|
+
DELETE = "DELETE"
|
|
53
|
+
PERMISSION = "PERMISSION"
|
|
54
|
+
PUBLISH = "PUBLISH"
|
|
55
|
+
CRUD = "CRUD"
|
|
56
|
+
ALL = "ALL"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class AnnotationLabelPythonType(TypedDict):
|
|
60
|
+
id: str
|
|
61
|
+
color: str
|
|
62
|
+
description: str
|
|
63
|
+
icon: str
|
|
64
|
+
text: str
|
|
65
|
+
label_type: LabelType
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class LabelLookupPythonType(TypedDict):
|
|
69
|
+
"""
|
|
70
|
+
We need to inject these objs into our pipeline so tha tasks can
|
|
71
|
+
look up text or doc label pks by their *name* without needing to
|
|
72
|
+
hit the database across some unknown number N tasks later in the
|
|
73
|
+
pipeline. We preload the lookups as this lets us look them up only
|
|
74
|
+
once with only a very small memory cost.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
text_labels: dict[Union[str, int], AnnotationLabelPythonType] # noqa # fmt: off
|
|
78
|
+
doc_labels: dict[Union[str, int], AnnotationLabelPythonType] # noqa # fmt: off
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class PawlsPageBoundaryPythonType(TypedDict):
|
|
82
|
+
"""
|
|
83
|
+
This is what a PAWLS Page Boundary obj looks like
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
width: float
|
|
87
|
+
height: float
|
|
88
|
+
index: int
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class PawlsTokenPythonType(TypedDict):
|
|
92
|
+
"""
|
|
93
|
+
This is what an actual PAWLS token looks like.
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
x: float
|
|
97
|
+
y: float
|
|
98
|
+
width: float
|
|
99
|
+
height: float
|
|
100
|
+
text: str
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class PawlsPagePythonType(TypedDict):
|
|
104
|
+
"""
|
|
105
|
+
Pawls files are comprised of lists of jsons that correspond to the
|
|
106
|
+
necessary tokens and page information for a given page. This describes
|
|
107
|
+
the data shape for each of those page objs.
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
page: PawlsPageBoundaryPythonType
|
|
111
|
+
tokens: list[PawlsTokenPythonType]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class BoundingBoxPythonType(TypedDict):
|
|
115
|
+
"""
|
|
116
|
+
Bounding box for pdf box on a pdf page
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
top: int
|
|
120
|
+
bottom: int
|
|
121
|
+
left: int
|
|
122
|
+
right: int
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class TokenIdPythonType(TypedDict):
|
|
126
|
+
"""
|
|
127
|
+
These are how tokens are referenced in annotation jsons.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
pageIndex: int
|
|
131
|
+
tokenIndex: int
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class OpenContractsSinglePageAnnotationType(TypedDict):
|
|
135
|
+
"""
|
|
136
|
+
This is the data shapee for our actual annotations on a given page of a pdf.
|
|
137
|
+
In practice, annotations are always assumed to be multi-page, and this means
|
|
138
|
+
our annotation jsons are stored as a dict map of page #s to the annotation data:
|
|
139
|
+
|
|
140
|
+
Dict[int, OpenContractsSinglePageAnnotationType]
|
|
141
|
+
|
|
142
|
+
"""
|
|
143
|
+
|
|
144
|
+
bounds: BoundingBoxPythonType
|
|
145
|
+
tokensJsons: list[TokenIdPythonType]
|
|
146
|
+
rawText: str
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class OpenContractsAnnotationPythonType(TypedDict):
|
|
150
|
+
"""
|
|
151
|
+
Data type for individual Open Contract annotation data type converted
|
|
152
|
+
into JSON. Note the models have a number of additional fields that are not
|
|
153
|
+
relevant for import/export purposes.
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
id: Optional[Union[str, int]] # noqa # fmt: off
|
|
157
|
+
annotationLabel: str
|
|
158
|
+
rawText: str
|
|
159
|
+
page: int
|
|
160
|
+
annotation_json: dict[
|
|
161
|
+
Union[int, str], OpenContractsSinglePageAnnotationType
|
|
162
|
+
] # noqa # fmt: off
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class TextSpan(TypedDict):
|
|
166
|
+
"""
|
|
167
|
+
Stores start and end indices of a span
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
id: str
|
|
171
|
+
start: int
|
|
172
|
+
end: int
|
|
173
|
+
text: str
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class SpanAnnotation(TypedDict):
|
|
177
|
+
span: TextSpan
|
|
178
|
+
annotation_label: str
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class AnnotationGroup(TypedDict):
|
|
182
|
+
labelled_spans: list[SpanAnnotation]
|
|
183
|
+
doc_labels: list[str]
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class AnnotatedDocumentData(AnnotationGroup):
|
|
187
|
+
doc_id: int
|
|
188
|
+
# labelled_spans and doc_labels incorporated via AnnotationGroup
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class PageAwareTextSpan(TypedDict):
|
|
192
|
+
"""
|
|
193
|
+
Given an arbitrary start and end index in a doc, want to be able to split it
|
|
194
|
+
across pages, and we'll need page index information in additional to just
|
|
195
|
+
start and end indices.
|
|
196
|
+
"""
|
|
197
|
+
|
|
198
|
+
original_span_id: NotRequired[str | None]
|
|
199
|
+
page: int
|
|
200
|
+
start: int
|
|
201
|
+
end: int
|
|
202
|
+
text: str
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
class OpenContractsDocAnnotations(TypedDict):
|
|
206
|
+
|
|
207
|
+
# Can have multiple doc labels. Want array of doc label ids, which will be
|
|
208
|
+
# mapped to proper objects after import.
|
|
209
|
+
doc_labels: list[str]
|
|
210
|
+
|
|
211
|
+
# The annotations are stored in a list of JSONS matching OpenContractsAnnotationPythonType
|
|
212
|
+
labelled_text: list[OpenContractsAnnotationPythonType]
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class OpenContractDocAnnotationExport(OpenContractsDocAnnotations):
|
|
216
|
+
|
|
217
|
+
"""
|
|
218
|
+
Eech individual documents annotations are exported and imported into
|
|
219
|
+
and out of jsons with this form. Inherits doc_labels and labelled_text
|
|
220
|
+
from OpenContractsDocAnnotations
|
|
221
|
+
"""
|
|
222
|
+
|
|
223
|
+
# Document title
|
|
224
|
+
title: str
|
|
225
|
+
|
|
226
|
+
# Document text
|
|
227
|
+
content: str
|
|
228
|
+
|
|
229
|
+
# Documents PAWLS parse file contents (serialized)
|
|
230
|
+
pawls_file_content: list[PawlsPagePythonType]
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class OpenContractCorpusTemplateType(TypedDict):
|
|
234
|
+
title: str
|
|
235
|
+
description: str
|
|
236
|
+
icon_data: Optional[str]
|
|
237
|
+
icon_name: Optional[str]
|
|
238
|
+
creator: str
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class OpenContractCorpusType(OpenContractCorpusTemplateType):
|
|
242
|
+
id: int
|
|
243
|
+
label_set: str
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
class OpenContractsLabelSetType(TypedDict):
|
|
247
|
+
id: Union[int, str] # noqa # fmt: off
|
|
248
|
+
title: str
|
|
249
|
+
description: str
|
|
250
|
+
icon_data: Optional[str]
|
|
251
|
+
icon_name: Optional[str]
|
|
252
|
+
creator: str
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
class OpenContractsExportDataJsonPythonType(TypedDict):
|
|
256
|
+
"""
|
|
257
|
+
This is the type of the data.json that goes into our export zips and
|
|
258
|
+
carries the annotations and annotation information
|
|
259
|
+
"""
|
|
260
|
+
|
|
261
|
+
# Lookup of pdf filename to the corresponding Annotation data
|
|
262
|
+
annotated_docs: dict[str, OpenContractDocAnnotationExport]
|
|
263
|
+
|
|
264
|
+
# Requisite labels, mapped from label name to label data
|
|
265
|
+
doc_labels: dict[str, AnnotationLabelPythonType]
|
|
266
|
+
|
|
267
|
+
# Requisite text labels, mapped from label name to label data
|
|
268
|
+
text_labels: dict[str, AnnotationLabelPythonType]
|
|
269
|
+
|
|
270
|
+
# Stores the corpus (todo - make sure the icon gets stored as base64)
|
|
271
|
+
corpus: OpenContractCorpusType
|
|
272
|
+
|
|
273
|
+
# Stores the label set (todo - make sure the icon gets stored as base64)
|
|
274
|
+
label_set: OpenContractsLabelSetType
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
class OpenContractsDocAnalysisResult(TypedDict):
|
|
278
|
+
doc_id: Union[int, str] # noqa # fmt: off
|
|
279
|
+
task_status: TaskStatus
|
|
280
|
+
task_message: str
|
|
281
|
+
annotations: Optional[OpenContractsDocAnnotations]
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
class OpenContractsGeneratedCorpusPythonType(TypedDict):
|
|
285
|
+
"""
|
|
286
|
+
Meant to be the output of a backend job annotating docs. This can be imported
|
|
287
|
+
using a slightly tweaked packaging script similar to what was done for the
|
|
288
|
+
export importing pipeline, but it's actually simpler and faster as we're
|
|
289
|
+
not recreating the documents.
|
|
290
|
+
"""
|
|
291
|
+
|
|
292
|
+
annotated_docs: dict[Union[str, int], OpenContractsDocAnnotations]
|
|
293
|
+
|
|
294
|
+
# Requisite labels, mapped from label name to label data
|
|
295
|
+
doc_labels: dict[Union[str, int], AnnotationLabelPythonType]
|
|
296
|
+
|
|
297
|
+
# Requisite text labels, mapped from label name to label data
|
|
298
|
+
text_labels: dict[Union[str, int], AnnotationLabelPythonType]
|
|
299
|
+
|
|
300
|
+
# Stores the label set (todo - make sure the icon gets stored as base64)
|
|
301
|
+
label_set: OpenContractsLabelSetType
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
class StoreJobResultsReturnType(TypedDict):
|
|
305
|
+
job_id: Union[int, str]
|
|
306
|
+
job_status: JobStatus
|
|
307
|
+
results: OpenContractsGeneratedCorpusPythonType # noqa # fmt: off
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
class AnalyzerMetaDataType(TypedDict):
|
|
311
|
+
id: str
|
|
312
|
+
description: str
|
|
313
|
+
title: str
|
|
314
|
+
dependencies: list[str]
|
|
315
|
+
author_name: str
|
|
316
|
+
author_email: str
|
|
317
|
+
more_details_url: str
|
|
318
|
+
icon_base_64_data: str
|
|
319
|
+
icon_name: str
|
|
File without changes
|
plasmapdf/utils/utils.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Union, cast
|
|
3
|
+
from typing_extensions import TypedDict
|
|
4
|
+
|
|
5
|
+
from pydantic import TypeAdapter, ValidationError
|
|
6
|
+
|
|
7
|
+
from plasmapdf.models.types import (
|
|
8
|
+
OpenContractsDocAnalysisResult,
|
|
9
|
+
OpenContractsGeneratedCorpusPythonType, AnnotationLabelPythonType, OpenContractsLabelSetType,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def is_dict_instance_of_typed_dict(instance: dict, typed_dict: type[TypedDict]):
|
|
16
|
+
# validate with pydantic
|
|
17
|
+
try:
|
|
18
|
+
|
|
19
|
+
TypeAdapter(typed_dict).validate_python(instance)
|
|
20
|
+
return True
|
|
21
|
+
|
|
22
|
+
except ValidationError as exc:
|
|
23
|
+
print(f"ERROR: Invalid schema: {exc}")
|
|
24
|
+
return False
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def package_job_results_to_oc_generated_corpus_type(
|
|
28
|
+
job_results: dict[Union[int, str], OpenContractsDocAnalysisResult],
|
|
29
|
+
possible_span_labels: list[AnnotationLabelPythonType],
|
|
30
|
+
possible_doc_labels: list[AnnotationLabelPythonType],
|
|
31
|
+
possible_relationship_labels: list[AnnotationLabelPythonType],
|
|
32
|
+
suggested_label_set: OpenContractsLabelSetType
|
|
33
|
+
) -> OpenContractsGeneratedCorpusPythonType:
|
|
34
|
+
|
|
35
|
+
oc_corpus_type_dict: OpenContractsGeneratedCorpusPythonType = {
|
|
36
|
+
"annotated_docs": {
|
|
37
|
+
result["doc_id"]: result["annotations"]
|
|
38
|
+
for result in list(job_results.values())
|
|
39
|
+
},
|
|
40
|
+
"doc_labels": {
|
|
41
|
+
label["id"]: label for label in possible_doc_labels
|
|
42
|
+
},
|
|
43
|
+
"text_labels": {
|
|
44
|
+
label["id"]: label for label in possible_span_labels
|
|
45
|
+
},
|
|
46
|
+
"label_set": suggested_label_set,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
logger.info(
|
|
50
|
+
f"package_job_results_to_oc_generated_corpus_type() - oc_corpus_type_dict: {oc_corpus_type_dict}"
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
if not is_dict_instance_of_typed_dict(
|
|
54
|
+
oc_corpus_type_dict, OpenContractsGeneratedCorpusPythonType
|
|
55
|
+
):
|
|
56
|
+
raise ValueError(
|
|
57
|
+
"Job return value does not conform to OpenContractsGeneratedCorpusPythonType"
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
logger.info(
|
|
61
|
+
f"package_job_results_to_oc_generated_corpus_type() - OK... return transformed data... {oc_corpus_type_dict}"
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
return oc_corpus_type_dict
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: plasmapdf
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Project-URL: Documentation, https://github.com/JSv4/plasmapdf#readme
|
|
5
|
+
Project-URL: Issues, https://github.com/JSv4/plasmapdf/issues
|
|
6
|
+
Project-URL: Source, https://github.com/JSv4/plasmapdf
|
|
7
|
+
Author-email: JSv4 <scrudato@umich.edu>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE.txt
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Programming Language :: Python
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
18
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
19
|
+
Requires-Python: >=3.8
|
|
20
|
+
Requires-Dist: numpy
|
|
21
|
+
Requires-Dist: pandas
|
|
22
|
+
Requires-Dist: pydantic
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# PlasmaPDF Quick Start Guide
|
|
26
|
+
|
|
27
|
+
PlasmaPDF is a Python library for working with PDF documents, particularly focused on handling annotations and data
|
|
28
|
+
extraction. This guide will walk you through the basic usage of the library.
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
To install PlasmaPDF, use pip:
|
|
33
|
+
|
|
34
|
+
```
|
|
35
|
+
pip install plasmapdf
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Basic Usage
|
|
39
|
+
|
|
40
|
+
### 1. Importing the Library
|
|
41
|
+
|
|
42
|
+
Start by importing the necessary components:
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from plasmapdf.models.PdfDataLayer import makePdfTranslationLayerFromPawlsTokens
|
|
46
|
+
from plasmapdf.models.types import TextSpan, SpanAnnotation, PawlsPagePythonType
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### 2. Creating a PdfDataLayer
|
|
50
|
+
|
|
51
|
+
The core of plasmaPDF is the `PdfDataLayer` class. You create an instance of this class using
|
|
52
|
+
the `makePdfTranslationLayerFromPawlsTokens` function:
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
pawls_tokens: list[PawlsPagePythonType] = [
|
|
56
|
+
{
|
|
57
|
+
"page": {"width": 612, "height": 792, "index": 0},
|
|
58
|
+
"tokens": [
|
|
59
|
+
{"x": 72, "y": 72, "width": 50, "height": 12, "text": "Hello"},
|
|
60
|
+
{"x": 130, "y": 72, "width": 50, "height": 12, "text": "World"}
|
|
61
|
+
]
|
|
62
|
+
}
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
pdf_data_layer = makePdfTranslationLayerFromPawlsTokens(pawls_tokens)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### 3. Working with Text Spans
|
|
69
|
+
|
|
70
|
+
You can extract raw text from a span in the document:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
span = TextSpan(id="1", start=0, end=11, text="Hello World")
|
|
74
|
+
raw_text = pdf_data_layer.get_raw_text_from_span(span)
|
|
75
|
+
print(raw_text) # Output: "Hello World"
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### 4. Creating Annotations
|
|
79
|
+
|
|
80
|
+
To create an annotation:
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
span_annotation = SpanAnnotation(span=span, annotation_label="GREETING")
|
|
84
|
+
oc_annotation = pdf_data_layer.create_opencontract_annotation_from_span(span_annotation)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### 5. Accessing Document Information
|
|
88
|
+
|
|
89
|
+
You can access various pieces of information about the document:
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
print(pdf_data_layer.doc_text) # Full document text
|
|
93
|
+
print(pdf_data_layer.human_friendly_full_text) # Human-readable version of the text
|
|
94
|
+
print(pdf_data_layer.page_dataframe) # DataFrame with page information
|
|
95
|
+
print(pdf_data_layer.tokens_dataframe) # DataFrame with token information
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Advanced Usage
|
|
99
|
+
|
|
100
|
+
### Working with Multi-Page Documents
|
|
101
|
+
|
|
102
|
+
PlasmaPDF can handle multi-page documents. When you create the `PdfDataLayer`, make sure to include tokens for all
|
|
103
|
+
pages:
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
multi_page_pawls_tokens = [
|
|
107
|
+
{
|
|
108
|
+
"page": {"width": 612, "height": 792, "index": 0},
|
|
109
|
+
"tokens": [...]
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
"page": {"width": 612, "height": 792, "index": 1},
|
|
113
|
+
"tokens": [...]
|
|
114
|
+
}
|
|
115
|
+
]
|
|
116
|
+
|
|
117
|
+
pdf_data_layer = makePdfTranslationLayerFromPawlsTokens(multi_page_pawls_tokens)
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Splitting Spans Across Pages
|
|
121
|
+
|
|
122
|
+
If you have a span that potentially crosses page boundaries, you can split it:
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
long_span = TextSpan(id="2", start=0, end=1000, text="...")
|
|
126
|
+
page_aware_spans = pdf_data_layer.split_span_on_pages(long_span)
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Creating OpenContracts Annotations
|
|
130
|
+
|
|
131
|
+
To create an annotation in the OpenContracts format:
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
span = TextSpan(id="3", start=0, end=20, text="Important clause here")
|
|
135
|
+
span_annotation = SpanAnnotation(span=span, annotation_label="IMPORTANT_CLAUSE")
|
|
136
|
+
oc_annotation = pdf_data_layer.create_opencontract_annotation_from_span(span_annotation)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Utility Functions
|
|
140
|
+
|
|
141
|
+
PlasmaPDF includes utility functions for working with job results:
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
from plasmapdf.utils.utils import package_job_results_to_oc_generated_corpus_type
|
|
145
|
+
|
|
146
|
+
# Assume you have job_results, possible_span_labels, possible_doc_labels,
|
|
147
|
+
# possible_relationship_labels, and suggested_label_set
|
|
148
|
+
|
|
149
|
+
corpus = package_job_results_to_oc_generated_corpus_type(
|
|
150
|
+
job_results,
|
|
151
|
+
possible_span_labels,
|
|
152
|
+
possible_doc_labels,
|
|
153
|
+
possible_relationship_labels,
|
|
154
|
+
suggested_label_set
|
|
155
|
+
)
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
This function packages job results into the OpenContracts corpus format.
|
|
159
|
+
|
|
160
|
+
## Testing
|
|
161
|
+
|
|
162
|
+
PlasmaPDF comes with a suite of unit tests. You can run these tests to ensure everything is working correctly:
|
|
163
|
+
|
|
164
|
+
```
|
|
165
|
+
hatch test
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
This will run all the tests in the `tests` directory.
|
|
169
|
+
|
|
170
|
+
## Conclusion
|
|
171
|
+
|
|
172
|
+
This quick start guide covers the basics of using PlasmaPDF. For more detailed information, refer to the full
|
|
173
|
+
documentation or explore the source code. If you encounter any issues or have questions, please refer to the project's
|
|
174
|
+
issue tracker or documentation.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
plasmapdf/__about__.py,sha256=gjNCMipyjzqERslkKJVtUQKHbR1sTafJjqqQYiXZHho,124
|
|
2
|
+
plasmapdf/__init__.py,sha256=a_4-PUMffcJXmmc5ovP8TykF3xw5VjTMktwBiaIkwUw,101
|
|
3
|
+
plasmapdf/models/PdfDataLayer.py,sha256=8H4-7NWg7sUCgdYWc0a8lm0Qi-rbaNCSVkN1bTDj2Y8,16919
|
|
4
|
+
plasmapdf/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
plasmapdf/models/types.py,sha256=ieyrbWFqxg54uXMGAsS1f4gzva46p_aQng60Z-Oiwsk,8861
|
|
6
|
+
plasmapdf/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
plasmapdf/utils/utils.py,sha256=Oytal8oNrE2jOllJxBN_5I0dMEGI2Ijj4PhCiB9kWfs,2134
|
|
8
|
+
plasmapdf-0.0.1.dist-info/METADATA,sha256=BeRDtsr376G6doBKQweEJNcv4DaNYLpQa6LjrYS0PfA,5134
|
|
9
|
+
plasmapdf-0.0.1.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
|
|
10
|
+
plasmapdf-0.0.1.dist-info/licenses/LICENSE.txt,sha256=ZiTkDktNtR41GZjhEhG4MsXuhrrnEpiUQRewzRhULKE,1099
|
|
11
|
+
plasmapdf-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024-present JSv4 <scrudato@umich.edu>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|