-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathextract_text.py
More file actions
executable file
·1619 lines (1319 loc) · 51.1 KB
/
extract_text.py
File metadata and controls
executable file
·1619 lines (1319 loc) · 51.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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# cardinal_pythonlib/extract_text.py
"""
===============================================================================
Original code copyright (C) 2009-2022 Rudolf Cardinal (rudolf@pobox.com).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
===============================================================================
**Converts a bunch of stuff to text, either from external files or from
in-memory binary objects (BLOBs).**
Prerequisites:
.. code-block:: bash
sudo apt-get install antiword # required for DOC
sudo apt-get install pdftotext # optional, but best way for PDF
sudo apt-get install strings # strings/strings2 needed as generic fallback
sudo apt-get install strings2 # as above
sudo apt-get install unrtf # required for RTF
pip install chardet # improves character type detection
pip install pdfminer.six # optional, backup optional for PDF
- Author: Rudolf Cardinal (rudolf@pobox.com)
- Created: Feb 2015
- Last update: 24 Sep 2015
See also:
- Word
- https://stackoverflow.com/questions/125222
- https://stackoverflow.com/questions/424822
- PDF
- https://stackoverflow.com/questions/25665
- https://pypi.python.org/pypi/slate
- https://stackoverflow.com/questions/5725278
- RTF
- unrtf
- https://superuser.com/questions/243084/rtf-to-txt-on-unix
- Multi-purpose:
- https://pypi.python.org/pypi/fulltext/
- https://media.readthedocs.org/pdf/textract/latest/textract.pdf
- DOCX
- https://etienned.github.io/posts/extract-text-from-word-docx-simply/
"""
# =============================================================================
# Imports
# =============================================================================
import argparse
import base64
from email import policy
from email.message import EmailMessage
from email.parser import BytesParser
from io import StringIO
import io
import logging
from mimetypes import guess_extension
import os
import re
import shutil
import subprocess
import sys
import textwrap
from typing import (
Any,
BinaryIO,
Dict,
Generator,
Iterable,
Iterator,
List,
Optional,
TYPE_CHECKING,
)
from xml.etree import ElementTree as ElementTree
import zipfile
import bs4
import chardet
from chardet.universaldetector import UniversalDetector
from extract_msg import openMsg
import pdfminer # pip install pdfminer.six
import pdfminer.pdfinterp
import pdfminer.converter
import pdfminer.layout
import pdfminer.pdfpage
import prettytable
from semantic_version import Version
from cardinal_pythonlib.logs import get_brace_style_log_with_null_handler
if TYPE_CHECKING:
from extract_msg import MSGFile
log = get_brace_style_log_with_null_handler(__name__)
# =============================================================================
# Constants
# =============================================================================
AVAILABILITY = "availability"
CONVERTER = "converter"
DEFAULT_WIDTH = 120
DEFAULT_MIN_COL_WIDTH = 15
SYS_ENCODING = sys.getdefaultencoding()
ENCODING = "utf-8"
# =============================================================================
# External tool map
# =============================================================================
tools = {
"antiword": shutil.which("antiword"), # sudo apt-get install antiword
"pdftotext": shutil.which("pdftotext"), # core part of Linux?
"strings": shutil.which("strings"), # part of standard Unix
"strings2": shutil.which("strings2"),
# ... Windows: https://technet.microsoft.com/en-us/sysinternals/strings.aspx # noqa: E501
# ... Windows: http://split-code.com/strings2.html
"unrtf": shutil.which("unrtf"), # sudo apt-get install unrtf
}
def does_unrtf_support_quiet() -> bool:
"""
The unrtf tool supports the '--quiet' argument from a version that I'm not
quite sure of, where ``0.19.3 < version <= 0.21.9``. We check against
0.21.9 here.
"""
required_unrtf_version = Version("0.21.9")
# ... probably: http://hg.savannah.gnu.org/hgweb/unrtf/
# ... 0.21.9 definitely supports --quiet
# ... 0.19.3 definitely doesn't support it
unrtf_filename = shutil.which("unrtf")
if not unrtf_filename:
return False
p = subprocess.Popen(
["unrtf", "--version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
_, err_bytes = p.communicate()
text = err_bytes.decode(sys.getdefaultencoding())
lines = text.split()
if len(lines) < 1:
return False
version_str = lines[0]
unrtf_version = Version(version_str)
return unrtf_version >= required_unrtf_version
UNRTF_SUPPORTS_QUIET = does_unrtf_support_quiet()
def update_external_tools(tooldict: Dict[str, str]) -> None:
"""
Update the global map of tools.
Args:
tooldict: dictionary whose keys are tools names and whose values are
paths to the executables
"""
global tools
tools.update(tooldict)
# =============================================================================
# Text-processing config class
# =============================================================================
class TextProcessingConfig(object):
"""
Class to manage control parameters for text extraction, without having
to pass a lot of mysterious ``**kwargs`` around and lose track of what it
means.
All converter functions take one of these objects as a parameter.
"""
def __init__(
self,
encoding: str = None,
width: int = DEFAULT_WIDTH,
min_col_width: int = DEFAULT_MIN_COL_WIDTH,
plain: bool = False,
semiplain: bool = False,
docx_in_order: bool = True,
horizontal_char: str = "─",
vertical_char: str = "│",
junction_char: str = "┼",
plain_table_start: str = None,
plain_table_end: str = None,
plain_table_col_boundary: str = None,
plain_table_row_boundary: str = None,
rstrip: bool = True,
) -> None:
"""
Args:
encoding:
optional text file encoding to try in addition to
:func:`sys.getdefaultencoding`.
width:
overall word-wrapping width
min_col_width:
minimum column width for tables
plain:
as plain as possible (e.g. for natural language processing);
see :func:`docx_process_table`.
semiplain:
quite plain, but with some ASCII art representation of the
table structure.
docx_in_order:
for DOCX files: if ``True``, process paragraphs and tables in
the order they occur; if ``False``, process all paragraphs
followed by all tables
rstrip:
Right-strip whitespace from all lines?
horizontal_char:
horizontal character to use with PrettyTable, e.g. ``-`` or
``─``
vertical_char:
vertical character to use with PrettyTable, e.g. ``|`` or
``│``
junction_char:
junction character to use with PrettyTable, e.g. ``+`` or
``┼``
plain_table_start:
table start line to use with ``plain=True``
plain_table_end:
table end line to use with ``plain=True``
plain_table_col_boundary:
boundary between columns to use with ``plain==True``
plain_table_row_boundary:
boundary between rows to use with ``plain==True``
Example of a DOCX table processed with:
- ``plain=False, semiplain=False``
.. code-block:: none
┼─────────────┼─────────────┼
│ Row 1 col 1 │ Row 1 col 2 │
┼─────────────┼─────────────┼
│ Row 2 col 1 │ Row 2 col 2 │
┼─────────────┼─────────────┼
- ``plain=False, semiplain=True``
.. code-block:: none
─────────────────────────────
Row 1 col 1
─────────────────────────────
Row 1 col 2
─────────────────────────────
Row 2 col 1
─────────────────────────────
Row 2 col 2
─────────────────────────────
- ``plain=True``
.. code-block:: none
╔═════════════════════════════════════════════════════════════════╗
Row 1 col 1
───────────────────────────────────────────────────────────────────
Row 1 col 2
═══════════════════════════════════════════════════════════════════
Row 2 col 1
───────────────────────────────────────────────────────────────────
Row 2 col 2
╚═════════════════════════════════════════════════════════════════╝
The plain format is probably better, in general, for NLP, and is
definitely clearer with nested tables (for which the word-wrapping
algorithm is imperfect). We avoid "heavy" box drawing as it has a
higher chance of being mangled under Windows.
"""
if plain and semiplain:
log.warning("You specified both plain and semiplain; using plain")
semiplain = False
middlewidth = width - 2 if width > 2 else 77
# double
if plain_table_start is None:
plain_table_start = "╔" + ("═" * middlewidth) + "╗"
if plain_table_end is None:
plain_table_end = "╚" + ("═" * middlewidth) + "╝"
# heavy
if plain_table_row_boundary is None:
plain_table_row_boundary = "═" * (middlewidth + 2)
# light
if plain_table_col_boundary is None:
plain_table_col_boundary = "─" * (middlewidth + 2)
self.encoding = encoding
self.width = width
self.min_col_width = min_col_width
self.plain = plain
self.semiplain = semiplain
self.docx_in_order = docx_in_order
self.horizontal_char = horizontal_char
self.vertical_char = vertical_char
self.junction_char = junction_char
self.plain_table_start = plain_table_start
self.plain_table_end = plain_table_end
self.plain_table_col_boundary = plain_table_col_boundary
self.plain_table_row_boundary = plain_table_row_boundary
self.rstrip = rstrip
_DEFAULT_CONFIG = TextProcessingConfig()
# =============================================================================
# Support functions
# =============================================================================
def get_filelikeobject(filename: str = None, blob: bytes = None) -> BinaryIO:
"""
Open a file-like object.
Guard the use of this function with ``with``.
Args:
filename: for specifying via a filename
blob: for specifying via an in-memory ``bytes`` object
Returns:
a :class:`BinaryIO` object
"""
if not filename and blob is None:
raise ValueError("no filename and no blob")
if filename and blob:
raise ValueError("specify either filename or blob")
if filename:
return open(filename, "rb")
else:
return io.BytesIO(blob)
# noinspection PyUnusedLocal
def get_file_contents(filename: str = None, blob: bytes = None) -> bytes:
"""
Returns the binary contents of a file, or of a BLOB.
"""
if filename is None and blob is None:
raise ValueError("no filename and no blob")
if filename and blob:
raise ValueError("specify either filename or blob")
if blob is not None:
return blob
with open(filename, "rb") as f:
return f.read()
def get_chardet_encoding(binary_contents: bytes) -> Optional[str]:
"""
Guess the character set encoding of the specified ``binary_contents``.
"""
if not binary_contents:
return None
if chardet is None or UniversalDetector is None:
log.warning("chardet not installed; limits detection of encodings")
return None
# METHOD 1
# http://chardet.readthedocs.io/en/latest/
#
# guess = chardet.detect(binary_contents)
#
# METHOD 2: faster with large files
# http://chardet.readthedocs.io/en/latest/
# https://stackoverflow.com/questions/13857856/split-byte-string-into-lines
# noinspection PyCallingNonCallable
detector = UniversalDetector()
for byte_line in binary_contents.split(b"\n"):
detector.feed(byte_line)
if detector.done:
break
guess = detector.result
# Handle result
if "encoding" not in guess:
log.warning("Something went wrong within chardet; no encoding")
return None
return guess["encoding"]
def get_file_contents_text(
filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG,
) -> str:
"""
Returns the string contents of a file, or of a BLOB.
"""
binary_contents = get_file_contents(filename=filename, blob=blob)
# 1. Try the encoding the user specified
if config.encoding:
try:
return binary_contents.decode(config.encoding)
except ValueError: # of which UnicodeDecodeError is more specific
# ... https://docs.python.org/3/library/codecs.html
pass
# 2. Try the system encoding
sysdef = sys.getdefaultencoding()
if sysdef != config.encoding:
try:
return binary_contents.decode(sysdef)
except ValueError:
pass
# 3. Try the best guess from chardet
# http://chardet.readthedocs.io/en/latest/usage.html
if chardet:
guess = chardet.detect(binary_contents)
if guess["encoding"]:
return binary_contents.decode(guess["encoding"])
raise ValueError(
"Unknown encoding ({})".format(
f"filename={filename!r}" if filename else "blob"
)
)
def get_cmd_output(*args: Any, encoding: str = SYS_ENCODING) -> str:
"""
Returns text output of a command.
"""
log.debug("get_cmd_output(): args = {!r}", args)
p = subprocess.Popen(args, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
return stdout.decode(encoding, errors="ignore")
def get_cmd_output_from_stdin(
stdint_content_binary: bytes, *args: Any, encoding: str = SYS_ENCODING
) -> str:
"""
Returns text output of a command, passing binary data in via stdin.
"""
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = p.communicate(input=stdint_content_binary)
return stdout.decode(encoding, errors="ignore")
def rstrip_all_lines(text: str) -> str:
"""
Right-strips all lines in a string and returns the result.
"""
return "\n".join(line.rstrip() for line in text.splitlines())
# =============================================================================
# PDF
# =============================================================================
# noinspection PyUnresolvedReferences,PyUnusedLocal
def convert_pdf_to_txt(
filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG,
) -> str:
"""
Converts a PDF file to text.
Pass either a filename or a binary object.
"""
pdftotext = tools["pdftotext"]
if pdftotext: # External command method
if filename:
return get_cmd_output(pdftotext, filename, "-")
else:
return get_cmd_output_from_stdin(blob, pdftotext, "-", "-")
elif pdfminer: # Memory-hogging method
with get_filelikeobject(filename, blob) as fp:
rsrcmgr = pdfminer.pdfinterp.PDFResourceManager()
str_io = StringIO()
codec = ENCODING
laparams = pdfminer.layout.LAParams()
device = pdfminer.converter.TextConverter(
rsrcmgr, str_io, codec=codec, laparams=laparams
)
interpreter = pdfminer.pdfinterp.PDFPageInterpreter(
rsrcmgr, device
)
password = ""
maxpages = 0
caching = True
pagenos = set()
for page in pdfminer.pdfpage.PDFPage.get_pages(
fp,
pagenos,
maxpages=maxpages,
password=password,
caching=caching,
check_extractable=True,
):
interpreter.process_page(page)
text = str_io.getvalue()
return text
else:
raise AssertionError("No PDF-reading tool available")
def availability_pdf() -> bool:
"""
Is a PDF-to-text tool available?
"""
pdftotext = tools["pdftotext"]
if pdftotext:
return True
elif pdfminer:
log.warning(
"PDF conversion: pdftotext missing; "
"using pdfminer (less efficient)"
)
return True
else:
return False
# =============================================================================
# DOCX
# =============================================================================
# -----------------------------------------------------------------------------
# In a D.I.Y. fashion
# -----------------------------------------------------------------------------
# DOCX specification: https://ecma-international.org/publications-and-standards/standards/ecma-376/ # noqa: E501
DOCX_HEADER_FILE_REGEX = re.compile("word/header[0-9]*.xml")
DOCX_DOCUMENT_FILE_REGEX = re.compile("word/document[0-9]*.xml")
DOCX_FOOTER_FILE_REGEX = re.compile("word/footer[0-9]*.xml")
DOCX_SCHEMA_URL = (
"http://schemas.openxmlformats.org/wordprocessingml/2006/main"
)
def docx_qn(tagroot: str) -> str:
return f"{{{DOCX_SCHEMA_URL}}}{tagroot}"
DOCX_TEXT = docx_qn("t")
DOCX_TABLE = docx_qn(
"tbl"
) # https://github.com/python-openxml/python-docx/blob/master/docx/table.py
DOCX_TAB = docx_qn("tab")
DOCX_NEWLINES = [docx_qn("br"), docx_qn("cr")]
DOCX_NEWPARA = docx_qn("p")
DOCX_TABLE_ROW = docx_qn("tr")
DOCX_TABLE_CELL = docx_qn("tc")
def gen_xml_files_from_docx(fp: BinaryIO) -> Iterator[str]:
"""
Generate XML files (as strings) from a DOCX file.
Args:
fp: :class:`BinaryIO` object for reading the ``.DOCX`` file
Yields:
the string contents of each individual XML file within the ``.DOCX``
file
Raises:
zipfile.BadZipFile: if the zip is unreadable (encrypted?)
"""
try:
z = zipfile.ZipFile(fp)
filelist = z.namelist()
for filename in filelist:
if DOCX_HEADER_FILE_REGEX.match(filename):
yield z.read(filename).decode("utf8")
for filename in filelist:
if DOCX_DOCUMENT_FILE_REGEX.match(filename):
yield z.read(filename).decode("utf8")
for filename in filelist:
if DOCX_FOOTER_FILE_REGEX.match(filename):
yield z.read(filename).decode("utf8")
except zipfile.BadZipFile:
# Clarify the error:
raise zipfile.BadZipFile("File is not a zip file - encrypted DOCX?")
class DocxFragment(object):
"""
Representation of a line, or multiple lines, which may or may not need
word-wrapping.
"""
# noinspection PyShadowingNames
def __init__(self, text: str, wordwrap: bool = True) -> None:
self.text = text
self.wordwrap = wordwrap
def docx_gen_wordwrapped_fragments(
fragments: Iterable[DocxFragment], width: int
) -> Generator[str, None, None]:
"""
Generates word-wrapped fragments.
"""
to_wrap = [] # type: List[DocxFragment]
def yield_wrapped() -> Generator[str, None, None]:
"""
Yield the word-wrapped stuff to date.
"""
nonlocal to_wrap
if to_wrap:
block = "".join(x.text for x in to_wrap)
wrapped = "\n".join(
wordwrap(line, width) for line in block.splitlines()
)
yield wrapped
to_wrap.clear()
for f in fragments:
if f.wordwrap:
# Add it to the current wrapping block.
to_wrap.append(f)
else:
# Yield the wrapped stuff to date
yield from yield_wrapped()
# Yield the new, unwrapped
yield f.text
yield from yield_wrapped() # any leftovers
def docx_wordwrap_fragments(
fragments: Iterable[DocxFragment], width: int
) -> str:
"""
Joins multiple fragments and word-wraps them as necessary.
"""
return "".join(docx_gen_wordwrapped_fragments(fragments, width))
def docx_gen_fragments_from_xml_node(
node: ElementTree.Element, level: int, config: TextProcessingConfig
) -> Generator[DocxFragment, None, None]:
"""
Returns text from an XML node within a DOCX file.
Args:
node: an XML node
level: current level in XML hierarchy (used for recursion; start level
is 0)
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string
"""
tag = node.tag # for speed
log.debug("Level {}, tag {}", level, tag)
if tag == DOCX_TEXT:
log.debug("Text: {!r}", node.text)
yield DocxFragment(node.text or "")
elif tag == DOCX_TAB:
log.debug("Tab")
yield DocxFragment("\t")
elif tag in DOCX_NEWLINES: # rarely used? Mostly "new paragraph"
log.debug("Newline")
yield DocxFragment("\n")
elif tag == DOCX_NEWPARA: # Note that e.g. all table cells start with this
log.debug("New paragraph")
yield DocxFragment("\n\n")
# One or two newlines? Clarity better with two -- word-wrapping means
# that "single" source lines can take up multiple lines in text format.
# So we need a gap between lines to ensure paragraph separation is
# visible -- i.e. two newlines.
if tag == DOCX_TABLE:
log.debug("Table")
yield DocxFragment("\n", wordwrap=False)
yield DocxFragment(
docx_table_from_xml_node(node, level, config), wordwrap=False
)
else:
for child in node:
for fragment in docx_gen_fragments_from_xml_node(
child, level + 1, config
):
yield fragment
def docx_text_from_xml_node(
node: ElementTree.Element, level: int, config: TextProcessingConfig
) -> str:
"""
Returns text from an XML node within a DOCX file.
Args:
node: an XML node
level: current level in XML hierarchy (used for recursion; start level
is 0)
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string
"""
return docx_wordwrap_fragments(
docx_gen_fragments_from_xml_node(node, level, config), config.width
)
def docx_text_from_xml(xml: str, config: TextProcessingConfig) -> str:
"""
Converts an XML tree of a DOCX file to string contents.
Args:
xml: raw XML text
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string
"""
root = ElementTree.fromstring(xml)
return docx_text_from_xml_node(root, 0, config)
class CustomDocxParagraph(object):
"""
Represents a paragraph of text in a DOCX file.
"""
def __init__(self, text: str = "") -> None:
self.text = text or ""
def __repr__(self) -> str:
return f"CustomDocxParagraph(text={self.text!r})"
class CustomDocxTableCell(object):
"""
Represents a cell within a table of a DOCX file.
May contain several paragraphs.
"""
def __init__(self, paragraphs: List[CustomDocxParagraph] = None) -> None:
self.paragraphs = paragraphs or []
def add_paragraph(self, text: str) -> None:
self.paragraphs.append(CustomDocxParagraph(text))
def __repr__(self) -> str:
return f"CustomDocxTableCell(paragraphs={self.paragraphs!r})"
class CustomDocxTableRow(object):
"""
Represents a row within a table of a DOCX file.
May contain several cells (one per column).
"""
def __init__(self, cells: List[CustomDocxTableCell] = None) -> None:
self.cells = cells or []
def add_cell(self, cell: CustomDocxTableCell) -> None:
self.cells.append(cell)
def new_cell(self) -> None:
self.cells.append(CustomDocxTableCell())
def add_paragraph(self, text: str) -> None:
self.cells[-1].add_paragraph(text)
def __repr__(self) -> str:
return f"CustomDocxTableRow(cells={self.cells!r})"
class CustomDocxTable(object):
"""
Represents a table of a DOCX file.
May contain several rows.
"""
def __init__(self, rows: List[CustomDocxTableRow] = None) -> None:
self.rows = rows or []
def add_row(self, row: CustomDocxTableRow) -> None:
self.rows.append(row)
def new_row(self) -> None:
self.rows.append(CustomDocxTableRow())
def new_cell(self) -> None:
self.rows[-1].new_cell()
def add_paragraph(self, text: str) -> None:
self.rows[-1].add_paragraph(text)
def __repr__(self) -> str:
return f"CustomDocxTable(rows={self.rows!r})"
def docx_table_from_xml_node(
table_node: ElementTree.Element, level: int, config: TextProcessingConfig
) -> str:
"""
Converts an XML node representing a DOCX table into a textual
representation.
Args:
table_node: XML node
level: current level in XML hierarchy (used for recursion; start level
is 0)
config: :class:`TextProcessingConfig` control object
Returns:
string representation
"""
table = CustomDocxTable()
for row_node in table_node:
if row_node.tag != DOCX_TABLE_ROW:
continue
table.new_row()
for cell_node in row_node:
if cell_node.tag != DOCX_TABLE_CELL:
continue
table.new_cell()
for para_node in cell_node:
text = docx_text_from_xml_node(para_node, level, config)
if text:
table.add_paragraph(text)
return docx_process_table(table, config)
# -----------------------------------------------------------------------------
# Generic
# -----------------------------------------------------------------------------
def wordwrap(text: str, width: int) -> str:
"""
Word-wraps text.
Args:
text:
text to process (will be treated as a single line)
width:
width to word-wrap to (or 0 to skip word wrapping)
Returns:
wrapped text
.. code-block:: python
from cardinal_pythonlib.extract_text import *
text = "Here is a very long line that may be word-wrapped. " * 50
print(docx_wordwrap(text, 80))
"""
if not text:
return ""
if width:
return "\n".join(textwrap.wrap(text, width=width))
return text
def docx_process_table(
table: CustomDocxTable, config: TextProcessingConfig
) -> str:
"""
Converts a DOCX table to text.
Structure representing a DOCX table:
.. code-block:: none
table
.rows[]
.cells[]
.paragraphs[]
.text
That's the structure of a :class:`docx.table.Table` object, but also of our
homebrew creation, :class:`CustomDocxTable`.
- The ``plain`` and ``semiplain`` options are implemented via the
:class:`TextProcessingConfig`.
- Note also that the grids in DOCX files can have varying number of cells
per row, e.g.
.. code-block:: none
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| 1 | 2 |
+---+---+
"""
def get_cell_text(cell_) -> str:
cellparagraphs = [
paragraph.text.strip() for paragraph in cell_.paragraphs
]
cellparagraphs = [x for x in cellparagraphs if x]
return "\n\n".join(cellparagraphs)
if config.plain:
# ---------------------------------------------------------------------
# Plain -- good for NLP and better for word-wrapping
# ---------------------------------------------------------------------
lines = [config.plain_table_start] # type: List[str]
for r, row in enumerate(table.rows):
if r > 0:
lines.append(config.plain_table_row_boundary)
for c, cell in enumerate(row.cells):
if c > 0:
lines.append(config.plain_table_col_boundary)
lines.append(get_cell_text(cell))
lines.append(config.plain_table_end)
return "\n".join(lines)
else:
# ---------------------------------------------------------------------
# Full table visualization, or semiplain
# ---------------------------------------------------------------------
ncols = 1
# noinspection PyTypeChecker
for row in table.rows:
ncols = max(ncols, len(row.cells))
pt = prettytable.PrettyTable(
field_names=list(range(ncols)),
encoding=ENCODING,
header=False,
border=True,
hrules=prettytable.ALL,
vrules=prettytable.NONE if config.semiplain else prettytable.ALL,
# Can we use UTF-8 special characters?
# Even under Windows, sys.getdefaultencoding() returns "utf-8"
# (under Python 3.6.8, Windows 6.1.7601 = Windows Server 2008 R2).
# The advantage would be that these characters are not likely to
# influence any form of NLP.
horizontal_char=config.horizontal_char, # default "-"
vertical_char=config.vertical_char, # default "|"
junction_char=config.junction_char, # default "+"
)
pt.align = "l"
pt.valign = "t"
pt.max_width = max(config.width // ncols, config.min_col_width)
if config.semiplain:
# noinspection PyTypeChecker
for row in table.rows:
for i, cell in enumerate(row.cells):
n_before = i
n_after = ncols - i - 1
# ... use ncols, not len(row.cells), since "cells per row"
# is not constant, but prettytable wants a fixed
# number. (changed in v0.2.8)
ptrow = (
[""] * n_before
+ [get_cell_text(cell)]
+ [""] * n_after
)
assert len(ptrow) == ncols
pt.add_row(ptrow)
else:
# noinspection PyTypeChecker
for row in table.rows: