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,30 @@
1
+ import yaml
2
+ import csv
3
+
4
+
5
+ class CustomLoader(yaml.SafeLoader):
6
+ def __init__(self, stream):
7
+ super(CustomLoader, self).__init__(stream)
8
+
9
+ def include(self, node):
10
+ filename = node.value
11
+ with open(filename, "r") as f:
12
+ return yaml.load(f, CustomLoader)
13
+
14
+ def cvs_load(self, node):
15
+ filename = node.value
16
+ retval = []
17
+ with open(filename, "r") as csvfile:
18
+ csv_reader = csv.reader(csvfile)
19
+ header = next(csv_reader)
20
+ for row in csv_reader:
21
+ retval.append({name: row[i] for i, name in enumerate(header)})
22
+ return retval
23
+
24
+
25
+ CustomLoader.add_constructor("!include", CustomLoader.include)
26
+ CustomLoader.add_constructor("!csv", CustomLoader.cvs_load)
27
+
28
+
29
+ def custom_yaml_load(stream):
30
+ return yaml.load(stream, Loader=CustomLoader)
@@ -0,0 +1,26 @@
1
+ def to_csv(csvfile, headers, data):
2
+ import csv
3
+ from io import TextIOBase
4
+
5
+ if isinstance(csvfile, TextIOBase):
6
+ csvfile_hd = csvfile
7
+ else:
8
+ csvfile_hd = open(str(csvfile), "w")
9
+
10
+ csvwriter = csv.writer(csvfile_hd)
11
+ csvwriter.writerow(headers)
12
+
13
+ # writing the data rows
14
+ rows = []
15
+ for row in data:
16
+ csv_row = []
17
+ for field in headers:
18
+ if field in row:
19
+ csv_row.append(row[field])
20
+ else:
21
+ csv_row.append("")
22
+ rows.append(csv_row)
23
+ csvwriter.writerows(rows)
24
+
25
+ if not isinstance(csvfile, TextIOBase):
26
+ csvfile_hd.close()
@@ -0,0 +1,44 @@
1
+ from wowool.document.factory import Factory
2
+ from typing import Optional, Union
3
+ from pathlib import Path
4
+ from wowool.utility.path import expand_path
5
+ from wowool.document.factory import Factory as DocumentCollection
6
+
7
+
8
+ def make_document_collection(
9
+ text: Optional[Union[list, str]] = None,
10
+ file: Optional[Union[Path, str]] = None,
11
+ cleanup: Optional[bool] = None,
12
+ encoding="utf-8",
13
+ pattern="**/*.txt",
14
+ **kwargs,
15
+ ):
16
+ stripped = None
17
+ if cleanup:
18
+ stripped = lambda s: "".join(i for i in s if 31 < ord(i) < 127 or ord(i) == 0xD or ord(i) == 0xA)
19
+
20
+ if file:
21
+ options = {}
22
+ options["encoding"] = encoding
23
+ if cleanup:
24
+ options["cleanup"] = stripped
25
+ fn = expand_path(file)
26
+
27
+ return DocumentCollection.glob(fn, stripped=stripped)
28
+ # folder, pattern_ = Factory.split_path_on_wildcards(fn)
29
+ # if folder.exists():
30
+ # if folder.is_dir():
31
+ # doc_collection.extend(Factory.glob(fn, pattern_))
32
+ # else:
33
+ # doc_collection.append(Factory.create(file, **options))
34
+ # else:
35
+ # raise RuntimeError(f"File or folder not found. '{fn}'")
36
+ if text:
37
+ doc_collection = []
38
+ if isinstance(text, str):
39
+ doc_collection.append(Factory.create(text))
40
+ elif isinstance(text, list):
41
+ for text_ in text:
42
+ doc_collection.append(Factory.create(text_))
43
+
44
+ return doc_collection
@@ -0,0 +1,24 @@
1
+ from wowool.document.document import Document
2
+ from wowool.io.console import AppConsole
3
+ import logging
4
+ import sys
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+
9
+ def print_diagnostics(doc: Document, console: AppConsole = None, file=sys.stderr):
10
+ if console == None:
11
+ from wowool.io.console import console
12
+
13
+ for app_id in doc.app_ids():
14
+ if doc.has_diagnostics(app_id):
15
+ console.print(f"diagnostics={app_id} ", file=file)
16
+ for item in doc.diagnostics(app_id):
17
+ console.print(" " + item.rich(), file=file)
18
+
19
+
20
+ def log_diagnostics(doc: Document):
21
+ for app_id in doc.app_ids():
22
+ if doc.has_diagnostics(app_id):
23
+ for item in doc.diagnostics(app_id):
24
+ logger.log(item.type, f"{app_id}: {item.message}")
@@ -0,0 +1,59 @@
1
+ def iterate_prv_nxt(my_list):
2
+ """
3
+ create a iterator that returns.
4
+ prev, current and the next
5
+ """
6
+ prv, cur, nxt = None, iter(my_list), iter(my_list)
7
+ next(nxt, None)
8
+ idx = 0
9
+
10
+ while True:
11
+ try:
12
+ if prv:
13
+ yield idx, next(prv), next(cur), next(nxt, None)
14
+ else:
15
+ yield idx, None, next(cur), next(nxt, None)
16
+ prv = iter(my_list)
17
+ idx += 1
18
+ except StopIteration:
19
+ break
20
+
21
+
22
+ def iterate_nxt(my_list):
23
+ """
24
+ create a iterator that returns.
25
+ current and the next
26
+ """
27
+ cur, nxt = iter(my_list), iter(my_list)
28
+ next(nxt, None)
29
+ idx = 0
30
+
31
+ while True:
32
+ try:
33
+ yield idx, next(cur), next(nxt, None)
34
+ idx += 1
35
+ except StopIteration:
36
+ break
37
+
38
+
39
+ def iterate_prv(my_list):
40
+ """
41
+ create a iterator that returns.
42
+ prev, current and the next
43
+ """
44
+ (
45
+ prv,
46
+ cur,
47
+ ) = None, iter(my_list)
48
+
49
+ idx = 0
50
+ while True:
51
+ try:
52
+ if prv:
53
+ yield idx, next(prv), next(cur)
54
+ else:
55
+ yield idx, None, next(cur)
56
+ prv = iter(my_list)
57
+ idx += 1
58
+ except StopIteration:
59
+ break
@@ -0,0 +1,20 @@
1
+ import types
2
+ from typing import Callable, Dict
3
+
4
+
5
+ jump_table: Dict[str, Callable] = {}
6
+
7
+
8
+ def register(command: str = None) -> Callable:
9
+ def decorator(func: Callable) -> Callable:
10
+ if command:
11
+ jump_table[command] = func
12
+ else:
13
+ jump_table[func.__name__] = func
14
+ return func
15
+
16
+ return decorator
17
+
18
+
19
+ def get_bound_jump_table(self) -> Dict[str, Callable]:
20
+ return {command: types.MethodType(func, self) for command, func in jump_table.items()}
@@ -0,0 +1,42 @@
1
+ from locale import atof, setlocale, LC_NUMERIC
2
+ import re
3
+
4
+ number_parts = re.compile("[\\.,]")
5
+
6
+
7
+ def unique(seq):
8
+ retval = []
9
+ for word in seq:
10
+ if word not in retval:
11
+ retval.append(word)
12
+ return retval
13
+
14
+
15
+ def set_number_local(comma):
16
+ if comma == ".":
17
+ locale = "en_US.UTF-8"
18
+ setlocale(LC_NUMERIC, locale)
19
+ return locale
20
+ # print('en_US.UTF-8')
21
+ elif comma == ",":
22
+ locale = "nl_BE.UTF-8"
23
+ setlocale(LC_NUMERIC, locale)
24
+ return locale
25
+
26
+
27
+ def digit_sep_to_comma(digit_sep):
28
+ if digit_sep == ".":
29
+ return ","
30
+ return "."
31
+
32
+
33
+ def to_float(literal):
34
+ sep_sequence = number_parts.findall(literal)
35
+ sep_sequence = sep_sequence[-2:]
36
+ if len(sep_sequence) == 2 and sep_sequence[0] == sep_sequence[1]:
37
+ set_number_local(digit_sep_to_comma(sep_sequence[0]))
38
+ else:
39
+ separators = unique(sep_sequence)
40
+ if separators:
41
+ set_number_local(separators[-1])
42
+ return atof(literal)
@@ -0,0 +1 @@
1
+ from wowool.utility.path.path import expand_path # noqa: F401
@@ -0,0 +1,11 @@
1
+ from pathlib import Path
2
+ from os.path import expandvars
3
+
4
+
5
+ def expand_path(path: str | Path, resolve: bool = True) -> Path:
6
+ if isinstance(path, str):
7
+ path = path.strip('"')
8
+ fn = Path(expandvars(path)).expanduser()
9
+ if resolve:
10
+ fn = fn.resolve()
11
+ return fn
@@ -0,0 +1,82 @@
1
+ import re
2
+ from logging import getLogger
3
+ from bs4 import BeautifulSoup, Comment
4
+
5
+ logger = getLogger(__name__)
6
+
7
+
8
+ remove_tags = ["script", "style", "noscript", "footer", "svg", "form"]
9
+
10
+
11
+ def cleanup_scripts(input: str):
12
+ soup = BeautifulSoup(input, "html.parser")
13
+ for script in soup(remove_tags):
14
+ script.extract() # rip it out
15
+
16
+ comments = soup.find_all(string=lambda text: isinstance(text, Comment))
17
+ # Iterate over the comments and print them
18
+ for comment in comments:
19
+ comment.extract()
20
+
21
+ html_data = soup.prettify(formatter="minimal")
22
+ return html_data
23
+
24
+
25
+ class SkipDocument(Exception):
26
+ pass
27
+
28
+
29
+ def cleanup_text(text: str, filters: list, strip_lines=True, exceptions=[]):
30
+ lines = text.splitlines()
31
+ new_lines = []
32
+ for line in lines:
33
+ exclude = None
34
+ if strip_lines:
35
+ line = line.strip()
36
+ for exception in exceptions:
37
+ if "starts_with" in exception:
38
+ if line.startswith(exception["starts_with"]):
39
+ raise SkipDocument(f"""Exception filter {exception["starts_with"]}""")
40
+ elif "regex" in exception:
41
+ if "regex_" not in exception:
42
+ exception["regex_"] = re.compile(exception["regex"])
43
+ m = exception["regex_"].search(line)
44
+ if m:
45
+ raise SkipDocument(f"""Exception filter {exception["regex"]}""")
46
+ for filter in filters:
47
+ if "starts_with" in filter:
48
+ if line.startswith(filter["starts_with"]):
49
+ # print("removing line starts_with ", line)
50
+ if "remove" in filter:
51
+ exclude = filter["remove"]
52
+ else:
53
+ exclude = "line"
54
+ elif "regex" in filter:
55
+ pattern = re.compile(filter["regex"])
56
+ m = pattern.search(line)
57
+ if m:
58
+ if "remove" in filter:
59
+ if filter["remove"] == "match":
60
+ substring = filter["sub"] if "sub" in filter else ""
61
+ line = pattern.sub(substring, line)
62
+ else:
63
+ exclude = filter["remove"]
64
+ else:
65
+ exclude = "line"
66
+ elif "match" in filter:
67
+ if line == filter["match"]:
68
+ exclude = "line"
69
+ else:
70
+ raise ValueError("Unknown filter, posibel values are starts_with, regex")
71
+ if exclude:
72
+ break
73
+
74
+ if not exclude:
75
+ new_lines.append(line)
76
+ elif exclude == "line":
77
+ logger.debug(f"Removing line {line}")
78
+ pass
79
+ elif exclude == "eof":
80
+ logger.debug(f"Removing until eof {line}")
81
+ break
82
+ return "\n".join(new_lines)
wowool/visitor.py ADDED
@@ -0,0 +1,48 @@
1
+ from wowool.annotation import Token
2
+ from wowool.annotation import Concept
3
+ from wowool.annotation import Sentence
4
+ from wowool.annotation.token import MorphData
5
+ from wowool.document.document import Document
6
+
7
+
8
+ # TODO: make visit a member method of the base class
9
+ def Visit(object, parent):
10
+ """
11
+ Visit the a annotation object like Document or Sentence and call back using
12
+ the functions __token__ or __concept__ or __sentence__
13
+
14
+ .. code-block:: python
15
+ :linenos:
16
+
17
+ import wowool
18
+ from wowool.native import Language
19
+ from wowool.native import Domain
20
+
21
+ class MyVisitor:
22
+ def __token__(self, token):
23
+ print(token)
24
+
25
+ analyzer = Language(domains='english-entity.dom')
26
+ entities = Domain(domains='english-entity.dom')
27
+ doc = analyzer("Philippe Forest works in EyeOnText.")
28
+ wowool.Visit(doc, MyVisitor)
29
+ """
30
+ visit_concept = hasattr(parent, "__concept__")
31
+ visit_token = hasattr(parent, "__token__")
32
+ visit_init_sentence = hasattr(parent, "__init_sentence__")
33
+ visit_uninit_sentence = hasattr(parent, "__uninit_sentence__")
34
+
35
+ if visit_token and isinstance(object, Token):
36
+ parent.__token__(object)
37
+ elif visit_concept and isinstance(object, Concept):
38
+ parent.__concept__(object)
39
+ elif isinstance(object, Sentence):
40
+ if visit_init_sentence:
41
+ parent.__init_sentence__(object)
42
+ for aa in object:
43
+ Visit(aa, parent)
44
+ if visit_uninit_sentence:
45
+ parent.__uninit_sentence__(object)
46
+ elif isinstance(object, Document):
47
+ for aa in object:
48
+ Visit(aa, parent)