wowool-common 3.0.2.dev19__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.

Potentially problematic release.


This version of wowool-common might be problematic. Click here for more details.

Files changed (55) hide show
  1. wowool/analysis.py +289 -0
  2. wowool/analysis_parser.py +102 -0
  3. wowool/annotation/__init__.py +4 -0
  4. wowool/annotation/annotation.py +156 -0
  5. wowool/annotation/concept.py +473 -0
  6. wowool/annotation/paragraph.py +166 -0
  7. wowool/annotation/sentence.py +262 -0
  8. wowool/annotation/token.py +266 -0
  9. wowool/apps/info.py +97 -0
  10. wowool/common/pipeline/__init__.py +1 -0
  11. wowool/common/pipeline/objects.py +45 -0
  12. wowool/common/utilities.py +13 -0
  13. wowool/config.py +67 -0
  14. wowool/diagnostic.py +250 -0
  15. wowool/document/__init__.py +2 -0
  16. wowool/document/apps/chunks.py +22 -0
  17. wowool/document/apps/themes.py +11 -0
  18. wowool/document/apps/topics.py +11 -0
  19. wowool/document/document.py +399 -0
  20. wowool/document/factory.py +176 -0
  21. wowool/error.py +2 -0
  22. wowool/io/console/__init__.py +1 -0
  23. wowool/io/console/argument_parser.py +29 -0
  24. wowool/io/console/console.py +102 -0
  25. wowool/io/provider/__init__.py +4 -0
  26. wowool/io/provider/docx.py +26 -0
  27. wowool/io/provider/factory.py +173 -0
  28. wowool/io/provider/file.py +85 -0
  29. wowool/io/provider/html.py +42 -0
  30. wowool/io/provider/html_v2.py +420 -0
  31. wowool/io/provider/input_provider.py +38 -0
  32. wowool/io/provider/pdf.py +320 -0
  33. wowool/io/provider/pdf_no_layout.py +48 -0
  34. wowool/io/provider/rtf.py +14 -0
  35. wowool/io/provider/str.py +17 -0
  36. wowool/string/__init__.py +153 -0
  37. wowool/tool/woc/create.py +42 -0
  38. wowool/utility/__init__.py +16 -0
  39. wowool/utility/apps/decorators.py +66 -0
  40. wowool/utility/apps/yml_include.py +30 -0
  41. wowool/utility/csv/__init__.py +26 -0
  42. wowool/utility/default_arguments.py +44 -0
  43. wowool/utility/diagnostics.py +24 -0
  44. wowool/utility/iterators/__init__.py +59 -0
  45. wowool/utility/method_registry.py +20 -0
  46. wowool/utility/numbers.py +42 -0
  47. wowool/utility/path/__init__.py +1 -0
  48. wowool/utility/path/path.py +11 -0
  49. wowool/utility/text/cleanup.py +82 -0
  50. wowool/visitor.py +48 -0
  51. wowool/wow.py +424 -0
  52. wowool_common-3.0.2.dev19.dist-info/METADATA +10 -0
  53. wowool_common-3.0.2.dev19.dist-info/RECORD +55 -0
  54. wowool_common-3.0.2.dev19.dist-info/WHEEL +5 -0
  55. wowool_common-3.0.2.dev19.dist-info/top_level.txt +1 -0
@@ -0,0 +1,420 @@
1
+ from wowool.io.provider import InputProvider
2
+ from bs4 import BeautifulSoup
3
+ import re
4
+ from enum import Enum
5
+ import logging
6
+ from html.parser import HTMLParser
7
+
8
+ logger = logging.getLogger(__name__)
9
+ INTERNAL = 0
10
+ logging.addLevelName(INTERNAL, "INTERNAL")
11
+
12
+
13
+ def dict_fmerge(base_dct, merge_dct, add_keys=True):
14
+ rtn_dct = base_dct.copy()
15
+ if add_keys is False:
16
+ merge_dct = {key: merge_dct[key] for key in set(rtn_dct).intersection(set(merge_dct))}
17
+
18
+ rtn_dct.update(
19
+ {
20
+ key: (
21
+ dict_fmerge(rtn_dct[key], merge_dct[key], add_keys=add_keys)
22
+ if isinstance(rtn_dct.get(key), dict) and isinstance(merge_dct[key], dict)
23
+ else merge_dct[key]
24
+ )
25
+ for key in merge_dct.keys()
26
+ }
27
+ )
28
+ return rtn_dct
29
+
30
+
31
+ end_sentence_tag = ".\n\n"
32
+ begin_list_tag = "\n * "
33
+ default_remove = ""
34
+
35
+
36
+ default_config = {
37
+ "tags_begin": {
38
+ "b": default_remove,
39
+ "i": default_remove,
40
+ "u": default_remove,
41
+ "span": default_remove,
42
+ "ul": end_sentence_tag,
43
+ "p": """\n\n""",
44
+ "li": begin_list_tag,
45
+ "title": "#",
46
+ "h1": "\n#",
47
+ "h2": "\n\n##",
48
+ "h3": "\n\n###",
49
+ "h4": "\n\n####",
50
+ "h5": "\n\n#####",
51
+ "h6": "\n\n######",
52
+ },
53
+ "tags_end": {
54
+ "ul": default_remove,
55
+ "b": default_remove,
56
+ "i": default_remove,
57
+ "u": default_remove,
58
+ "span": default_remove,
59
+ "p": end_sentence_tag,
60
+ "li": end_sentence_tag,
61
+ "title": f"{end_sentence_tag}",
62
+ "h1": f"{end_sentence_tag}",
63
+ "h2": f"{end_sentence_tag}",
64
+ "h3": f"{end_sentence_tag}",
65
+ "h4": f"{end_sentence_tag}",
66
+ "h5": f"{end_sentence_tag}",
67
+ "h6": f"{end_sentence_tag}",
68
+ },
69
+ "remove_tags": ["style", "noscript", "footer", "svg", "form", "figure"],
70
+ "remove_class": [
71
+ "copyright",
72
+ "footer",
73
+ "language.*",
74
+ "cookie.*",
75
+ "sitemap.*",
76
+ "nav",
77
+ "quickjump",
78
+ "print",
79
+ "squareAd",
80
+ ],
81
+ "remove_id": [
82
+ "copyright",
83
+ "footer",
84
+ "language.*",
85
+ "cookie.*",
86
+ "sitemap.*",
87
+ "nav",
88
+ "quickjump",
89
+ "print",
90
+ "squareAd",
91
+ ],
92
+ "remove_text": [
93
+ "Visit.*(s|S)ite",
94
+ "Follow.* on .*",
95
+ "Take a look at the .*",
96
+ ],
97
+ }
98
+
99
+ header_tags = {"title", "h1", "h2", "h3", "h4", "h5", "h6"}
100
+
101
+
102
+ def is_last_char(input, char):
103
+ it = reversed(input)
104
+ while (v := next(it, None)) is not None:
105
+ if v == char:
106
+ return True
107
+ elif v == "\n" or v == " ":
108
+ continue
109
+ else:
110
+ return False
111
+ return None
112
+
113
+
114
+ def cleanup_spaces(string):
115
+ split_string = string.split(" ")
116
+
117
+ # To account for leading/trailing spaces that would simply be removed
118
+ beg = " " if not split_string[0] else ""
119
+ end = " " if not split_string[-1] else ""
120
+
121
+ # versus simply ' '.join(item for item in string.split(' ') if item)
122
+ return beg + " ".join(item for item in split_string if item) + end
123
+
124
+
125
+ class Content(Enum):
126
+ NONE = 1
127
+ TEXT = 2
128
+ SCRIPT = 3
129
+
130
+
131
+ class MyHTMLParser(HTMLParser):
132
+ def __init__(self, config, script_handler=None):
133
+ super().__init__()
134
+ self.output = ""
135
+ self.strip_tags = {
136
+ "script": 0,
137
+ "style": 0,
138
+ "footer": 0,
139
+ "noscript": 0,
140
+ "svg": 0,
141
+ "form": 0,
142
+ }
143
+ self.content = Content.TEXT
144
+ self.last_inserted_data = ""
145
+ self.tables = []
146
+ self.table_idx = -1
147
+ self.add_table_data = False
148
+ self.tags_begin = config["tags_begin"]
149
+ self.tags_end = config["tags_end"]
150
+ self.analyzer = None
151
+ self.script_data = ""
152
+ self.script_handler = script_handler
153
+
154
+ def write(self, data, end=""):
155
+ data = re.sub(r"\n ", " ", data)
156
+ data_ending = self.output[-4:]
157
+ current_ending = re.sub(r"(\s|[A-Za-z0-9]|\n)", "", data_ending)
158
+ data_ending = re.sub(r"(\s|\n)", "", data[:3])
159
+ # print(f" ==> [{current_ending}] vs [{data_ending}]")
160
+ if data_ending == current_ending:
161
+ # print("do not add")
162
+ return
163
+ if self.output and len(data) == 1 and self.output[-1] == "\n" and self.output[-1] == data[0]:
164
+ return
165
+
166
+ self.output += data
167
+
168
+ def write_text(self, data):
169
+ # if len(self.output) >= 1 and self.output[-1] == "\n":
170
+ # if data.startswith(".\n"):
171
+ # self.output = f"{self.output[:-1]+' '+data}"
172
+ # else:
173
+ # self.write(data.strip())
174
+ if len(self.output) > 1 and self.output[-1] == "\n":
175
+ self.write(data.strip())
176
+ else:
177
+ self.write(data)
178
+
179
+ def reset_tables(self):
180
+ self.tables.clear()
181
+ self.table_idx = -1
182
+
183
+ def handle_starttag(self, tag, attrs):
184
+ logger.log(INTERNAL, f"beg_{tag=}, [{self.output}]")
185
+ if tag in self.tags_begin:
186
+ self.write(self.tags_begin[tag])
187
+ if tag in header_tags:
188
+ if is_last_char(self.output, ".") is False:
189
+ if self.output[-1] == "\n":
190
+ self.output = self.output.rstrip("\n")
191
+ # self.write(".\n\n")
192
+
193
+ elif tag == "script":
194
+ # print("TAG:Script")
195
+ self.content = Content.SCRIPT
196
+ self.strip_tags[tag] += 1
197
+
198
+ elif tag in self.strip_tags:
199
+ self.strip_tags[tag] += 1
200
+ self.content = Content.NONE
201
+
202
+ elif tag == "table":
203
+ self.tables.append({"headers": [], "idx": -1, "field": None})
204
+ self.table_idx = len(self.tables) - 1
205
+ elif tag == "tr":
206
+ try:
207
+ self.tables[self.table_idx]["idx"] = 0
208
+ except Exception:
209
+ self.reset_tables()
210
+
211
+ elif tag == "th":
212
+ try:
213
+ self.add_table_data = True
214
+ self.tables[self.table_idx]["headers"].append([])
215
+ self.tables[self.table_idx]["idx"] = len(self.tables[self.table_idx]["headers"]) - 1
216
+ except Exception:
217
+ self.reset_tables()
218
+
219
+ elif tag == "td":
220
+ try:
221
+ field = "\n"
222
+ for table in self.tables:
223
+ idx = table["idx"]
224
+ text = table["headers"][idx]
225
+ field += f"{text}:"
226
+ self.tables[self.table_idx]["field"] = field
227
+ except Exception:
228
+ self.reset_tables()
229
+
230
+ else:
231
+ self.write_text(" ")
232
+
233
+ def handle_endtag(self, tag):
234
+ logger.log(INTERNAL, f"end_{tag=}, [{self.output}]")
235
+ if tag in self.tags_end:
236
+ self.write_text(self.tags_end[tag])
237
+ if tag in header_tags:
238
+ if is_last_char(self.output, ".") is False:
239
+ self.write(".\n")
240
+ elif tag == "script":
241
+ if self.script_handler:
242
+ self.write(self.script_handler(self.script_data))
243
+ self.script_data = ""
244
+ self.content = Content.TEXT
245
+ self.strip_tags[tag] -= 1
246
+ elif tag in self.strip_tags:
247
+ self.strip_tags[tag] -= 1
248
+ if self.strip_tags[tag] == 0:
249
+ self.content = Content.TEXT
250
+ elif tag == "table":
251
+ try:
252
+ if self.tables:
253
+ self.tables.pop()
254
+ self.table_idx = len(self.tables) - 1
255
+ else:
256
+ self.table_idx = -1
257
+ except Exception:
258
+ self.reset_tables()
259
+ elif tag == "th":
260
+ try:
261
+ idx = self.tables[self.table_idx]["idx"]
262
+ self.tables[self.table_idx]["headers"][idx] = " ".join(filter(None, self.tables[self.table_idx]["headers"][idx]))
263
+ except Exception:
264
+ self.reset_tables()
265
+ elif tag == "tr":
266
+ self.add_table_data = False
267
+ elif tag == "td":
268
+ try:
269
+ if self.table_idx >= 0:
270
+ # idx = self.tables[self.table_idx]['idx']
271
+ # text = self.tables[self.table_idx]['headers'][idx]
272
+ self.last_inserted_data = ""
273
+ self.write(end_sentence_tag)
274
+ self.tables[self.table_idx]["idx"] += 1
275
+ except Exception:
276
+ self.reset_tables()
277
+ else:
278
+ self.write_text(" ")
279
+
280
+ def handle_data(self, data):
281
+ if self.content == Content.TEXT:
282
+ text = cleanup_spaces(data)
283
+ if text:
284
+ if self.table_idx >= 0:
285
+ try:
286
+ if self.add_table_data:
287
+ idx = self.tables[self.table_idx]["idx"]
288
+ text = text.strip()
289
+ if text:
290
+ self.tables[self.table_idx]["headers"][idx].append(text.strip())
291
+ return
292
+
293
+ if self.tables[self.table_idx]["field"]:
294
+ self.write_text(self.tables[self.table_idx]["field"])
295
+ self.tables[self.table_idx]["field"] = None
296
+ except Exception:
297
+ self.reset_tables()
298
+
299
+ self.write_text(text)
300
+ else:
301
+ self.write_text(" ")
302
+ elif self.content == Content.SCRIPT:
303
+ self.script_data += data
304
+
305
+
306
+ def cleanup_output(text):
307
+ text = re.sub(r"\n.\n", ".\n\n", text)
308
+ text = re.sub(r"\n{3,5}", "\n\n", text)
309
+ text = text.replace("\n.\n", "\n")
310
+ return text
311
+
312
+
313
+ class HTMLFileInputProvider(InputProvider):
314
+ def __init__(
315
+ self,
316
+ fid,
317
+ html_data=None,
318
+ config=None,
319
+ merge=True,
320
+ encoding="utf8",
321
+ script_handler=None,
322
+ use_readability: bool = True,
323
+ **kwargs,
324
+ ):
325
+ InputProvider.__init__(self, str(fid))
326
+ if config:
327
+ if merge:
328
+ self.config = dict_fmerge(default_config, config)
329
+ else:
330
+ self.config = config
331
+ else:
332
+ self.config = default_config
333
+ self.encoding = encoding
334
+ self.html_data = html_data
335
+ self._text = None
336
+ self.script_handler = script_handler
337
+ self.use_readability = use_readability
338
+
339
+ def _get_text(self, input):
340
+ if self.use_readability and input:
341
+ try:
342
+ from readability import Document
343
+
344
+ readability_doc = Document(input)
345
+ title = readability_doc.title()
346
+ input = f"<title>{title}</title>" if title != "[no-title]" else ""
347
+ input += readability_doc.summary(True)
348
+
349
+ except ModuleNotFoundError as ex:
350
+ logger.error(
351
+ f"Readability is probably not installed, install the package using 'pip install readability-lxml lxml_html_clean.' {ex}"
352
+ )
353
+ except ValueError:
354
+ # going brute force
355
+ pass
356
+ except Exception as ex:
357
+ logger.exception(ex)
358
+
359
+ soup = BeautifulSoup(input, "html.parser")
360
+
361
+ if "remove_tags" in self.config:
362
+ remove_tags = self.config["remove_tags"]
363
+ if self.script_handler:
364
+ del remove_tags[0]
365
+ # kill all script and style elements
366
+ for script in soup(remove_tags):
367
+ script.extract() # rip it out
368
+
369
+ if "remove_class" in self.config:
370
+ remove_class = self.config["remove_class"]
371
+ remove_pattern = re.compile("|".join(remove_class))
372
+ remove_pattern = f"^({remove_pattern})$"
373
+ for element in soup.find_all(class_=remove_pattern):
374
+ element.extract() # rip it out
375
+
376
+ if "remove_id" in self.config:
377
+ remove_id = self.config["remove_id"]
378
+ remove_pattern = re.compile("|".join(remove_id))
379
+ remove_pattern = f"^({remove_pattern})$"
380
+ for element in soup.find_all(id=remove_pattern):
381
+ element.extract() # rip it out
382
+
383
+ if "remove_text" in self.config:
384
+ remove_text = self.config["remove_text"]
385
+ remove_pattern = re.compile("|".join(remove_text))
386
+ remove_pattern = f"^({remove_pattern})$"
387
+ for element in soup.find_all(string=remove_pattern):
388
+ element.parent.extract() # rip it out
389
+
390
+ if "remove_parent_text" in self.config:
391
+ remove_parent_text = self.config["remove_parent_text"]
392
+ remove_pattern = re.compile("|".join(remove_parent_text))
393
+ remove_pattern = f"^({remove_pattern})$"
394
+ for element in soup.find_all(string=remove_pattern):
395
+ element.parent.parent.extract() # rip it out
396
+
397
+ # cleanup html
398
+ input_data = soup.prettify(formatter="html")
399
+
400
+ # remove spaces in front of tags
401
+ input_data = re.sub(r"\n^\s+", r" ", input_data, flags=re.MULTILINE)
402
+ parser = MyHTMLParser(self.config, self.script_handler)
403
+ parser.feed(input_data)
404
+ # .decode("unicode_escape")
405
+ output = cleanup_output(parser.output)
406
+ return output
407
+
408
+ @property
409
+ def text(self):
410
+ if self._text is not None:
411
+ return self._text
412
+ elif self.html_data is not None:
413
+ _text = self._get_text(self.html_data)
414
+ return _text
415
+ else:
416
+ # read from file
417
+ with open(self.id, "r", encoding=self.encoding) as fh:
418
+ html_data = fh.read()
419
+ _text = self._get_text(html_data)
420
+ return _text
@@ -0,0 +1,38 @@
1
+ class InputProvider:
2
+ """
3
+ :class:`InputProvider` is an interface utility to handle data input.
4
+ """
5
+
6
+ def __init__(self, doc_id: str):
7
+ """
8
+ Initialize an :class:`InputProvider` instance
9
+
10
+ :param doc_id: Unique document identifier
11
+ :type doc_id: ``str``
12
+
13
+ :rtype: :class:`InputProvider`
14
+ """
15
+ super(InputProvider, self).__init__()
16
+ self.doc_id = doc_id
17
+
18
+ @property
19
+ def id(self) -> str:
20
+ """
21
+ :return: Unique document identifier
22
+ :rtype: ``str``
23
+ """
24
+ return self.doc_id
25
+
26
+ @property
27
+ def text(self) -> str:
28
+ """
29
+ :return: Text content of the document
30
+ :rtype: ``str``
31
+ """
32
+ raise NotImplementedError()
33
+
34
+ def __repr__(self):
35
+ return self.id
36
+
37
+ def __str__(self):
38
+ return self.text