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,320 @@
1
+ #!/usr/bin/python3
2
+
3
+ import os
4
+ from binascii import b2a_hex
5
+ import pandas as pd
6
+ from pdfminer.pdfparser import PDFParser
7
+ from pdfminer.pdfdocument import PDFDocument, PDFNoOutlines
8
+ from pdfminer.pdfpage import PDFPage
9
+ from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
10
+ from pdfminer.converter import PDFPageAggregator
11
+ from pdfminer.layout import LAParams, LTTextBox, LTTextLine, LTFigure, LTImage, LTChar, LTPage
12
+ from pathlib import Path
13
+ from io import StringIO
14
+ from dataclasses import dataclass
15
+ from typing import Any
16
+ from .input_provider import InputProvider
17
+
18
+
19
+ def with_pdf(pdf_doc, fn, pdf_pwd, *args):
20
+ """Open the pdf document, and apply the function, returning the results"""
21
+ result = None
22
+ try:
23
+ # open the pdf file
24
+ fp = open(pdf_doc, "rb")
25
+ # create a parser object associated with the file object
26
+ parser = PDFParser(fp)
27
+ # create a PDFDocument object that stores the document structure
28
+ doc = PDFDocument(parser, pdf_pwd)
29
+ # connect the parser and document objects
30
+ parser.set_document(doc)
31
+
32
+ if doc.is_extractable:
33
+ # apply the function and return the result
34
+ result = fn(doc, *args)
35
+
36
+ # close the pdf file
37
+ fp.close()
38
+ except IOError:
39
+ # the file doesn't exist or similar problem
40
+ pass
41
+ return result
42
+
43
+
44
+ # Table of Contents
45
+ def _parse_toc(doc):
46
+ """With an open PDFDocument object, get the table of contents (toc) data
47
+ [this is a higher-order function to be passed to with_pdf()]"""
48
+ toc = []
49
+ try:
50
+ outlines = doc.get_outlines()
51
+ for level, title, dest, a, se in outlines:
52
+ toc.append((level, title))
53
+ except PDFNoOutlines:
54
+ pass
55
+ return toc
56
+
57
+
58
+ def get_toc(pdf_doc, pdf_pwd=""):
59
+ """Return the table of contents (toc), if any, for this pdf file"""
60
+ return with_pdf(pdf_doc, _parse_toc, pdf_pwd)
61
+
62
+
63
+ # Extracting Images
64
+ def write_file(folder, filename, filedata, flags="w"):
65
+ """Write the file data to the folder and filename combination
66
+ (flags: 'w' for write text, 'wb' for write binary, use 'a' instead of 'w' for append)"""
67
+ if os.path.isdir(folder):
68
+ file_obj = open(os.path.join(folder, filename), flags)
69
+ file_obj.write(filedata)
70
+ file_obj.close()
71
+
72
+
73
+ # Extracting Text
74
+ def to_bytestring(s, enc="utf-8"):
75
+ """Convert the given unicode string to a bytestring, using the standard encoding,
76
+ unless it's already a bytestring"""
77
+ if s:
78
+ if isinstance(s, str):
79
+ return s
80
+ else:
81
+ return s.encode(enc)
82
+
83
+
84
+ def update_page_text(df, lt_obj, pct=0.2):
85
+ """
86
+ Use the bbox x0,x1 values within pct% to produce lists of associated text within the hash
87
+
88
+ df:
89
+ cols = [x0, y0, x1, y1, class, objs, str]
90
+ """
91
+ if df is None:
92
+ df = pd.DataFrame(columns=["x0", "y0", "x1", "y1", "class", "objs", "str"])
93
+
94
+ if isinstance(lt_obj, (LTTextLine, LTTextBox)):
95
+ store_new_line(df, lt_obj, pct)
96
+ else:
97
+ raise NotImplementedError(lt_obj)
98
+ return df
99
+
100
+
101
+ def store_new_line(df, lt_obj, pct):
102
+ """
103
+ store a new line to df
104
+ """
105
+ x0, y0, x1, y1 = lt_obj.bbox
106
+ candidates = df[
107
+ (df["class"] == lt_obj.__class__)
108
+ & (df["x0"] >= x0 * (1 - pct))
109
+ & (df["x0"] <= x0 * (1 + pct))
110
+ & (df["x1"] >= x1 * (1 - pct))
111
+ & (df["x1"] <= x1 * (1 + pct))
112
+ & (df["y1"] <= y0)
113
+ ]
114
+
115
+ if candidates.shape[0] > 0:
116
+ target = candidates.iloc[0]
117
+ df.at[target.name, "y0"] = y0
118
+ df.at[target.name, "y1"] = y1
119
+ df.at[target.name, "x0"] = x0
120
+ df.at[target.name, "x1"] = x1
121
+ df.at[target.name, "objs"].append(lt_obj)
122
+ df.at[target.name, "str"].append(to_bytestring(lt_obj.get_text()))
123
+ else:
124
+ df.loc[0 if pd.isnull(df.index.max()) else df.index.max() + 1] = [
125
+ *lt_obj.bbox,
126
+ lt_obj.__class__,
127
+ [lt_obj],
128
+ [to_bytestring(lt_obj.get_text())],
129
+ ]
130
+ return df
131
+
132
+
133
+ @dataclass
134
+ class WordInfo:
135
+ text: str
136
+ top: float = 0.0
137
+ bottom: float = 0.0
138
+ x0: float = 0.0
139
+ x1: float = 0.0
140
+ top: float = 0.0
141
+ height: float = 0.0
142
+ width: float = 0.0
143
+ direction: str = ""
144
+ doctop: float = 0.0
145
+ upright: bool = True
146
+ lt_obj: Any | None = None
147
+
148
+ def __post_init__(self):
149
+ self.height = round(self.height)
150
+
151
+
152
+ def make_word(lt_obj):
153
+ w = WordInfo(text=lt_obj.get_text())
154
+ w.x0 = lt_obj.x0
155
+ w.x1 = lt_obj.x1
156
+ w.top = lt_obj.y0
157
+ w.bottom = lt_obj.y1
158
+ w.height = w.bottom - w.top
159
+ w.lt_obj = lt_obj
160
+ return w
161
+
162
+
163
+ @dataclass
164
+ class PageInfo:
165
+ out: str = ""
166
+ new_line: bool = True
167
+ line_count_from_title = 0
168
+
169
+ def add_new_line(self):
170
+ self.out += "\n"
171
+ self.new_line = True
172
+
173
+ def add_text(self, text):
174
+ self.out += text
175
+ self.new_line = False
176
+
177
+ def add_space(self):
178
+ self.out += " "
179
+ self.new_line = False
180
+
181
+
182
+ def sort_text_and_lines(lt_objs):
183
+ objs = []
184
+ for lt_obj in lt_objs:
185
+ if isinstance(lt_obj, (LTTextLine, LTChar)):
186
+ objs.append(make_word(lt_obj))
187
+ # lt_obj._objs = sort_text_and_lines(lt_obj._objs)
188
+
189
+ sorted_words = sorted(objs, key=lambda x: (x.top, x.x0))
190
+ out = ""
191
+ for word in sorted_words:
192
+ out += word.text + " "
193
+
194
+ return WordInfo(text=out)
195
+
196
+
197
+ def parse_lt_objs(lt_objs, page_number):
198
+ """Iterate through the list of LT* objects and capture the text or image data contained in each"""
199
+ generator = lt_objs
200
+
201
+ pctx = PageInfo()
202
+
203
+ for lt_obj in generator:
204
+ print(f"{lt_obj=}")
205
+ if isinstance(lt_obj, LTTextBox):
206
+ # process every line in the text box.
207
+ p = sort_text_and_lines(lt_obj._objs)
208
+ pctx.add_text(p.text)
209
+ pctx.add_new_line()
210
+
211
+ elif isinstance(lt_obj, (LTTextLine, LTChar)):
212
+ w = make_word(lt_obj)
213
+ pctx.add_text(w.text)
214
+ # if w.text == "this":
215
+ # print(w.text)
216
+ pctx.add_space()
217
+ # print(f"{w.text=}")
218
+ # pctx.add_new_line()
219
+
220
+ # elif isinstance(lt_obj, LTFigure):
221
+ # # LTFigure objects are containers for other LT* objects, so recurse through the children
222
+ # text_content.append(parse_lt_objs(lt_obj, page_number, images_folder, text_content, return_df=return_df))
223
+ else:
224
+ print(f"NOT PROCESSED: lt_obj {lt_obj.bbox} -> {type(lt_obj)}")
225
+
226
+ print("------->>>>>>>", pctx.out)
227
+ return pctx
228
+
229
+
230
+ # Processing Pages
231
+ def _parse_pages(doc, images_folder, return_df=False):
232
+ """With an open PDFDocument object, get the pages and parse each one
233
+ [this is a higher-order function to be passed to with_pdf()]"""
234
+ rsrcmgr = PDFResourceManager()
235
+ laparams = LAParams(all_texts=True)
236
+ # laparams = LAParams(detect_vertical=True, all_texts=True)
237
+ # all_texts will enable layout analysis in LTFigure objs
238
+ device = PDFPageAggregator(rsrcmgr, laparams=laparams)
239
+ interpreter = PDFPageInterpreter(rsrcmgr, device)
240
+
241
+ generator = enumerate(PDFPage.create_pages(doc))
242
+
243
+ out = ""
244
+ for i, page in generator:
245
+ interpreter.process_page(page)
246
+ # receive the LTPage object for this page
247
+ layout = device.get_result()
248
+ # layout is an LTPage object which may contain child objects like LTTextBox, LTFigure, LTImage, etc.
249
+ p = parse_lt_objs(
250
+ layout,
251
+ (i + 1),
252
+ )
253
+ out += p.out
254
+
255
+ return out
256
+
257
+
258
+ def _get_page_size(doc, images_folder):
259
+ """With an open PDFDocument object, get the pages and parse each one
260
+ [this is a higher-order function to be passed to with_pdf()]"""
261
+ rsrcmgr = PDFResourceManager()
262
+ laparams = LAParams(detect_vertical=True, all_texts=True)
263
+ # all_texts will enable layout analysis in LTFigure objs
264
+ device = PDFPageAggregator(rsrcmgr, laparams=laparams)
265
+ interpreter = PDFPageInterpreter(rsrcmgr, device)
266
+
267
+ sizes = []
268
+ for i, page in enumerate(PDFPage.create_pages(doc)):
269
+ interpreter.process_page(page)
270
+ # receive the LTPage object for this page
271
+ layout = device.get_result()
272
+ # layout is an LTPage object which may contain child objects like LTTextBox, LTFigure, LTImage, etc.
273
+ sizes.append(layout.cropbox)
274
+ return sizes
275
+
276
+
277
+ def get_pages(pdf_doc, pdf_pwd="", images_folder="/tmp", return_df=False):
278
+ """Process each of the pages in this pdf file and return a list of strings representing the text found in each page"""
279
+ return with_pdf(pdf_doc, _parse_pages, pdf_pwd, images_folder, return_df)
280
+
281
+
282
+ def get_sizes(pdf_doc, pdf_pwd=""):
283
+ """get the sizes of each page"""
284
+ return with_pdf(pdf_doc, _get_page_size, pdf_pwd)
285
+
286
+
287
+ # =============================================================================================================================
288
+
289
+
290
+ def pdf_to_text(pdfname, codec="utf-8"):
291
+ # PDFMiner boilerplate
292
+ sio = StringIO()
293
+ pages = get_pages(pdfname)
294
+
295
+ sio.write("".join(pages))
296
+ text = sio.getvalue()
297
+ sio.close()
298
+ return text
299
+
300
+
301
+ class PdfFileInputProvider(InputProvider):
302
+ def __init__(self, fid):
303
+ InputProvider.__init__(self, str(fid))
304
+ fn = Path(self.id)
305
+ self.cfn = fn.with_suffix("._txt")
306
+
307
+ @property
308
+ def text(self):
309
+ if self.cfn.exists():
310
+ with open(self.cfn) as fd:
311
+ return fd.read()
312
+ else:
313
+ try:
314
+ with open(self.cfn, "w") as fd:
315
+ data = pdf_to_text(self.id)
316
+ fd.write(data)
317
+ return data
318
+ except Exception as ex:
319
+ print("Cannot create cache file", ex)
320
+ return pdf_to_text(self.id)
@@ -0,0 +1,48 @@
1
+ # """
2
+ # Extract PDF text using PDFMiner. Adapted from
3
+ # http://stackoverflow.com/questions/5725278/python-help-using-pdfminer-as-a-library
4
+ # """
5
+
6
+
7
+ import pdfminer.settings
8
+ from wowool.io.provider import InputProvider
9
+
10
+ pdfminer.settings.STRICT = False
11
+ import pdfminer.high_level
12
+ import pdfminer.layout
13
+ from pathlib import Path
14
+
15
+ from io import StringIO
16
+
17
+
18
+ def pdf_to_text(pdfname, codec="utf-8"):
19
+ # PDFMiner boilerplate
20
+ sio = StringIO()
21
+ fp = open(pdfname, "rb")
22
+ pdfminer.high_level.extract_text_to_fp(fp, sio, codec="utf-8", layoutmode="normal", line_margin=0.5, word_margin=1)
23
+ text = sio.getvalue()
24
+ sio.close()
25
+
26
+ return text
27
+
28
+
29
+ class PdfFileInputProvider(InputProvider):
30
+ def __init__(self, fid):
31
+ InputProvider.__init__(self, fid)
32
+ fn = Path(self.id())
33
+ self.cfn = fn.with_suffix("._txt")
34
+
35
+ @property
36
+ def text(self, **kwargs):
37
+ if self.cfn.exists():
38
+ with open(self.cfn) as fd:
39
+ return fd.read()
40
+ else:
41
+ try:
42
+ with open(self.cfn, "w") as fd:
43
+ data = pdf_to_text(self.id())
44
+ fd.write(data)
45
+ return data
46
+ except Exception as ex:
47
+ print("Cannot create cache file", ex)
48
+ return pdf_to_text(self.id())
@@ -0,0 +1,14 @@
1
+ from .input_provider import InputProvider
2
+ from striprtf.striprtf import rtf_to_text
3
+
4
+
5
+ class RTFFileInputProvider(InputProvider):
6
+ def __init__(self, fid, encoding="utf8"):
7
+ InputProvider.__init__(self, str(fid))
8
+ self.encoding = encoding
9
+
10
+ @property
11
+ def text(self, **kwargs):
12
+ with open(self.id(), "r") as f:
13
+ data = f.read()
14
+ return rtf_to_text(data, errors="ignore", encoding=self.encoding)
@@ -0,0 +1,17 @@
1
+ from .input_provider import InputProvider
2
+ from typing import Optional
3
+
4
+
5
+ class StrInputProvider(InputProvider):
6
+ # leave the kwargs in as we do not know which args are sent the they are created by the Factory
7
+ def __init__(self, text: str, id: Optional[str] = None, **kwargs):
8
+ uid = id
9
+ if uid is None:
10
+ uid = "stream_id_" + str(abs(hash(text)))
11
+
12
+ InputProvider.__init__(self, uid)
13
+ self._text = text
14
+
15
+ @property
16
+ def text(self) -> str:
17
+ return self._text
@@ -0,0 +1,153 @@
1
+ import re
2
+ from wowool.document import Document
3
+
4
+
5
+ _URI_WORDS = re.compile(r"\w+")
6
+
7
+
8
+ def normalize(name: str):
9
+ try:
10
+ import unidecode
11
+
12
+ """Remove accented characters"""
13
+ return unidecode.unidecode(name)
14
+ except ModuleNotFoundError:
15
+ return name
16
+
17
+
18
+ def to_text(annotations: list) -> str:
19
+ """Convert a list of annotations into a string taking care of offset.
20
+ But will remove duplicate spaces or convert whitespace into spaces."""
21
+ prev_end_offset = None
22
+ text = ""
23
+ for a in annotations:
24
+ if a.is_token:
25
+ if prev_end_offset:
26
+ if prev_end_offset != a.begin_offset:
27
+ text += " "
28
+
29
+ text += a.literal
30
+ prev_end_offset = a.end_offset
31
+ elif a.is_sentence:
32
+ if len(text) > 0:
33
+ text += " "
34
+ text += to_text(a.annotations)
35
+ return text
36
+
37
+
38
+ def _camelize(name, separator=""):
39
+ """
40
+ Capitalize the first letter of every part of a multiword.
41
+ remove spaces and replace with the separator
42
+ """
43
+ parts = _URI_WORDS.findall(name)
44
+ parts_new = []
45
+ for idx in range(len(parts)):
46
+ parts[idx] = parts[idx].capitalize()
47
+ return separator.join(parts).strip()
48
+
49
+
50
+ def camelize(name: str, separator: str = ""):
51
+ """
52
+ Camelize but first remove accents if any.
53
+ """
54
+ return _camelize(normalize(name), separator)
55
+
56
+
57
+ def initial_caps(name):
58
+ """
59
+ Capitalize the first letter of every part of a multiword.
60
+ """
61
+ return camelize(name, separator=" ")
62
+
63
+
64
+ def to_uri(name: str, separator="") -> str:
65
+ """
66
+ same as camelize but also remove spaces.
67
+ """
68
+ return camelize(name, separator)
69
+
70
+
71
+ GUESSER_PROPERTIES = {"cleanup", "guess", "typo"}
72
+
73
+
74
+ def canonicalize(obj, stem: bool = False, dates=True, spelling=True) -> str:
75
+ """
76
+ replace the literal or the stem by there canonical.
77
+
78
+ :param obj: the annotation to be converted.
79
+ :type obj: Annotation
80
+ :param stem: replace using the stem or the literal.
81
+ :type stem: bool
82
+
83
+ :rtype: str
84
+ """
85
+ from io import StringIO
86
+ from wowool.annotation import Sentence, Concept
87
+
88
+ if isinstance(obj, Sentence):
89
+ concept = obj[0] if obj[0].is_concept else obj
90
+ elif isinstance(obj, Concept):
91
+ concept = obj
92
+ else:
93
+ raise RuntimeError("obj type can not be wowool.utility.canonicalize")
94
+
95
+ with StringIO() as output:
96
+ skip_until_offset = 0
97
+ annotation_count = len(concept.annotations)
98
+ prev_token = None
99
+ for annotation_idx in range(annotation_count):
100
+ annotation = concept.annotations[annotation_idx]
101
+ if annotation.begin_offset < skip_until_offset:
102
+ prev_token = annotation
103
+ continue
104
+ else:
105
+ skip_until_offset = 0
106
+
107
+ if annotation.is_token:
108
+ # print(f"T:[{annotation.begin_offset},{annotation.end_offset}]:{annotation.literal} prev:{prev_token}")
109
+ if prev_token:
110
+ # print(f" -- pe:{prev_token.end_offset} != ab:{annotation.begin_offset}")
111
+ if prev_token.end_offset != annotation.begin_offset:
112
+ output.write(" ")
113
+ if stem:
114
+ output.write(annotation.stem)
115
+ elif spelling and bool(GUESSER_PROPERTIES.intersection(annotation.properties)):
116
+ output.write(annotation.stem)
117
+ else:
118
+ output.write(annotation.literal)
119
+
120
+ prev_token = annotation
121
+
122
+ elif annotation.is_concept:
123
+ if "canonical" in annotation.attributes:
124
+ if prev_token:
125
+ if prev_token.end_offset != annotation.begin_offset:
126
+ output.write(" ")
127
+ output.write((annotation.attributes["canonical"][0]))
128
+ skip_until_offset = annotation.end_offset
129
+ elif dates and annotation.uri == "Date" and "abs_date" in annotation.attributes:
130
+ if prev_token:
131
+ if prev_token.end_offset != annotation.begin_offset:
132
+ output.write(" ")
133
+ output.write((annotation.attributes["abs_date"][0]))
134
+ skip_until_offset = annotation.end_offset
135
+
136
+ return output.getvalue()
137
+
138
+
139
+ def search_and_replace(document: Document, expression: str, replacestring: str) -> str:
140
+ from io import StringIO
141
+ from wowool.annotation import Concept
142
+
143
+ with StringIO() as strm:
144
+ assert document.text
145
+ dtext = document.text
146
+ offset_ = 0
147
+ for concept in Concept.iter(document, lambda c: c.uri == expression):
148
+ strm.write(dtext[offset_ : concept.begin_offset])
149
+ strm.write(replacestring)
150
+ offset_ = concept.end_offset
151
+
152
+ strm.write(dtext[offset_:])
153
+ return strm.getvalue()
@@ -0,0 +1,42 @@
1
+ from pathlib import Path
2
+
3
+
4
+ def create_project(fn_project: Path, language: str = "english") -> Path:
5
+ """create a project skeleton with a project file (.wopr)"""
6
+ assert language, "language should not be None"
7
+ ffn = fn_project.expanduser().resolve()
8
+ fn_wopr = ffn / Path(ffn.stem).with_suffix(".wopr")
9
+ project_root = fn_wopr.parent
10
+ project_name = fn_wopr.stem
11
+ project_name_initcap = project_name.capitalize()
12
+ if project_name_initcap.endswith("s"):
13
+ # beers -> become Beer
14
+ project_name_initcap = project_name_initcap[:-1]
15
+
16
+ if project_root.exists():
17
+ raise RuntimeError(f"The project '{fn_project}' already exists")
18
+
19
+ project_root.mkdir(parents=True)
20
+ with open(fn_wopr, "w") as fh:
21
+ fh.write(
22
+ f"""{{
23
+ "domain": "{project_name}",
24
+ "language": "{language}",
25
+ "concepts": ["{project_name_initcap}"],
26
+ "sources": ["src/{project_name}.wow"]
27
+ }}
28
+ """
29
+ )
30
+ fp_project_src = project_root / "src"
31
+ fp_project_src.mkdir(parents=True)
32
+ fn_project_src = fp_project_src / f"{project_name}.wow"
33
+
34
+ with open(fn_project_src, "w") as fh:
35
+ fh.write(
36
+ f"""
37
+ lexicon:(input="normalized_stem") {{
38
+ {project_name},
39
+ }}={project_name_initcap}@(example_att = "some stuff");
40
+ """
41
+ )
42
+ return fn_wopr
@@ -0,0 +1,16 @@
1
+ from functools import partial
2
+ from sys import stderr
3
+
4
+
5
+ def clean_up_empty_keywords(kwargs):
6
+ keys = [k for k in kwargs]
7
+ for key in keys:
8
+ if not kwargs[key]:
9
+ del kwargs[key]
10
+
11
+
12
+ def is_valid_kwargs(kwargs, key):
13
+ return key in kwargs and kwargs[key]
14
+
15
+
16
+ printerr = partial(print, file=stderr)
@@ -0,0 +1,66 @@
1
+ import logging
2
+ from wowool.diagnostic import Diagnostics, Diagnostic, DiagnosticType
3
+ from wowool.document.document import Document
4
+ from functools import wraps
5
+ from wowool.analysis import APP_ID as APP_ID_ANALYSIS
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ def exceptions_to_diagnostics(fn):
11
+ @wraps(fn)
12
+ def wrapper(self, document: Document, *args, **kwargs):
13
+ diagnostics = Diagnostics()
14
+ app_id = self.ID if hasattr(self, "ID") else f"{type(self)}"
15
+ try:
16
+ document = fn(self, document, *args, diagnostics=diagnostics, **kwargs)
17
+ except Exception as ex:
18
+ logger.exception(ex)
19
+ diagnostics.add(Diagnostic(document.id, f"Exception {ex}", DiagnosticType.Critical))
20
+ if diagnostics:
21
+ document.add_diagnostics(app_id, diagnostics)
22
+ return document
23
+
24
+ return wrapper
25
+
26
+
27
+ def requires_app(app_id):
28
+ def decorator(fn):
29
+ @wraps(fn)
30
+ def wrapper(self, document: Document, diagnostics: Diagnostics, *args, **kwargs):
31
+ if not document.has(app_id):
32
+ diagnostics.add(Diagnostic(document.id, f"Missing {app_id}", DiagnosticType.Critical))
33
+ return document
34
+
35
+ result = fn(self, document, *args, diagnostics=diagnostics, **kwargs)
36
+ return result
37
+
38
+ return wrapper
39
+
40
+ return decorator
41
+
42
+
43
+ def requires_analysis(fn):
44
+ @wraps(fn)
45
+ def wrapper(self, document: Document, diagnostics: Diagnostics, *args, **kwargs):
46
+ if not document.has_results(APP_ID_ANALYSIS):
47
+ diagnostics.add(Diagnostic(document.id, f"Missing language component ({APP_ID_ANALYSIS})", DiagnosticType.Critical))
48
+ app_id = self.ID if hasattr(self, "ID") else f"{type(self)}"
49
+ return document
50
+ document = fn(self, document, *args, diagnostics=diagnostics, **kwargs)
51
+ return document
52
+
53
+ return wrapper
54
+
55
+
56
+ def check_requires_concepts(app_id, document: Document, diagnostics: Diagnostics, required_concepts, msg=None):
57
+ if (
58
+ not document.metadata
59
+ or "concepts" in document.metadata
60
+ and (document.metadata["concepts"] & required_concepts) != required_concepts
61
+ ):
62
+ if msg is None:
63
+ missing_concepts = required_concepts - (document.metadata["concepts"] & required_concepts)
64
+ msg = f"Missing a domain that can produce any of these required concepts: {missing_concepts}, add a domain domain in your pipeline."
65
+ diagnostics.add(Diagnostic(document.id, msg, DiagnosticType.Warning))
66
+ document.add_diagnostics(app_id, diagnostics)