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,399 @@
1
+ from io import StringIO
2
+ from typing import Union, Any, Optional, Generator
3
+ from wowool.annotation import Concept, Annotation, Token, Sentence
4
+ import json
5
+ from wowool.io.provider import InputProvider
6
+ from wowool.io.provider import Factory
7
+ from wowool.diagnostic import Diagnostics
8
+ from wowool.analysis import (
9
+ _filter_pass_thru_concept,
10
+ Analysis,
11
+ AnalysisInputProvider,
12
+ )
13
+ from wowool.analysis import APP_ID as APP_ID_ANALYSIS
14
+ from typing import cast
15
+ from wowool.document.apps.topics import convert_topics, Topic
16
+ from wowool.document.apps.themes import convert_themes, Theme
17
+ from wowool.document.apps.chunks import convert_chunks, Chunk
18
+
19
+ RESULTS = "results"
20
+ DIAGNOSTICS = "diagnostics"
21
+
22
+
23
+ def to_json_convert(obj):
24
+ if isinstance(obj, set):
25
+ return str(list(obj))
26
+ return obj
27
+
28
+
29
+ STR_MISSING_ANALYSIS = "Document has not been processed by a Language"
30
+
31
+
32
+ class Document:
33
+ """
34
+ :class:`Document` is a class that stores the data related to a document. Instances of this class are returned from a Pipeline, a Language or a Domain object.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ data: Optional[Union[str, bytes, InputProvider]] = None,
40
+ id: Optional[str] = None,
41
+ provider_type: Optional[str] = None,
42
+ encoding="utf8",
43
+ metadata=None,
44
+ **kwargs,
45
+ ):
46
+ """
47
+ Initialize a :class:`Document` instance
48
+
49
+ .. literalinclude:: ../../../../common/py/eot/wowool/init_document.py
50
+
51
+ :param data: Data to be processed
52
+ :type data: A ``str``, ``bytes``, or an :class:`InputProvider <wowool.io.InputProviders>`
53
+ :param id: Unique identifier for the document. If not provided, and ``data`` is an :class:`InputProvider <wowool.io.InputProviders>`, then the ``id`` will be set automatically
54
+ :type id: ``str``
55
+ :param type: Document type. Defaults to ``'txt'``
56
+ :type type: ``str``
57
+ :param encoding: Encoding of the ``data``. Defaults to ``'utf8'``
58
+ :type encoding: ``str``
59
+
60
+ :return: An initialized document
61
+ :rtype: :class:`Document`
62
+ """
63
+
64
+ if data is not None:
65
+ if isinstance(data, InputProvider):
66
+ assert id is None, "'id' cannot be set when using 'input_provider'"
67
+ self.input_provider = data
68
+ else:
69
+ self.input_provider = Factory.create(
70
+ id=id,
71
+ data=data,
72
+ provider_type=provider_type,
73
+ encoding=encoding,
74
+ **kwargs,
75
+ )
76
+
77
+ assert isinstance(self.input_provider, InputProvider), f"{type(self.input_provider)} is not derived from InputProvider"
78
+ else:
79
+ assert id is not None, "'id' is required when 'input_provider' is None"
80
+
81
+ self.input_provider = Factory.create(
82
+ id=id,
83
+ data=None,
84
+ provider_type=provider_type,
85
+ encoding=encoding,
86
+ **kwargs,
87
+ )
88
+
89
+ assert self.input_provider, "could not create inputprovider."
90
+ self._apps = {}
91
+ self.kwargs = {**kwargs}
92
+ self.metadata = metadata if metadata != None else {}
93
+
94
+ @property
95
+ def id(self) -> str:
96
+ """
97
+ :return: The unique identifier of the document
98
+ :rtype: ``str``
99
+ """
100
+ return self.input_provider.id
101
+
102
+ @property
103
+ def text(self) -> Union[str, None]:
104
+ """
105
+ :return: The text data of the document
106
+ :rtype: 'str | None'
107
+ """
108
+ return self.input_provider.text if self.input_provider else ""
109
+
110
+ @property
111
+ def analysis(self):
112
+ """
113
+ :return: The :class:`Analysis <wowool.analysis.Analysis>` of the document, containing the :class:`Sentences <wowool.annotation.sentence.Sentence>`, :class:`Tokens <wowool.annotation.token.Token>` and :class:`Concepts <wowool.annotation.concept.Concept>`, or ``None`` if the document has not been processed by a Language
114
+
115
+ .. literalinclude:: ../../../../common/py/eot/wowool/init_document_analysis.py
116
+
117
+ :rtype: :class:`Analysis <wowool.analysis.Analysis>`
118
+ """
119
+ return cast(Analysis, self.results(APP_ID_ANALYSIS))
120
+
121
+ def app_ids(self):
122
+ """
123
+ Iterate over the application identifiers
124
+
125
+ :return: A generator expression yielding application identifiers
126
+ :rtype: ``str``
127
+ """
128
+ for app_id in self._apps:
129
+ yield app_id
130
+
131
+ def has(self, app_id: str) -> bool:
132
+ return self.has_results(app_id)
133
+
134
+ def has_results(self, app_id: str) -> bool:
135
+ """
136
+ :return: Whether the application, as identified by the given application identifier, is in the document
137
+ :rtype: ``bool``
138
+ """
139
+ return app_id in self._apps
140
+
141
+ def add_results(self, app_id: str, results):
142
+ """
143
+ Add the given application results to the document
144
+
145
+ :param app_id: Application identifier
146
+ :type app_id: ``str``
147
+ :param results: Application results
148
+ :type results: A JSON serializable object type
149
+ """
150
+ if app_id in self._apps:
151
+ self._apps[app_id][RESULTS] = results
152
+ else:
153
+ self._apps[app_id] = {RESULTS: results}
154
+ return results
155
+
156
+ def results(self, app_id: str) -> Union[Any, None]:
157
+ """
158
+ :return: The results of the given application. See the different type of :ref:`application results <apps>`
159
+
160
+ :param app_id: Application identifier
161
+ :type app_id: ``str``
162
+ :param defaults: The defaults result to create when the application identifier is not present
163
+ :type default: Any JSON serializable object
164
+ """
165
+ if app_id in self._apps and RESULTS in self._apps[app_id]:
166
+ return self._apps[app_id][RESULTS]
167
+
168
+ def add_diagnostics(self, app_id: str, diagnostics: Diagnostics):
169
+ """
170
+ Add the given application diagnostics to the document
171
+
172
+ :param app_id: Application identifier
173
+ :type app_id: ``str``
174
+ :param diagnostics: Application diagnostics
175
+ :type diagnostics: :class:`Diagnostics <wowool.diagnostic.Diagnostics>`
176
+ """
177
+ if app_id in self._apps:
178
+ self._apps[app_id][DIAGNOSTICS] = diagnostics
179
+ else:
180
+ self._apps[app_id] = {DIAGNOSTICS: diagnostics}
181
+
182
+ def has_diagnostics(self, app_id: str = None) -> bool:
183
+ """
184
+ :param app_id: Application identifier
185
+ :type app_id: ``str`` or ``None``
186
+ :return: Whether the document contains diagnostics for the given application or any diagnostics if no application identifier is provided
187
+ :rtype: ``bool``
188
+ """
189
+ if app_id is None:
190
+ for app_id in self._apps:
191
+ if DIAGNOSTICS in self._apps[app_id]:
192
+ return True
193
+ return False
194
+ else:
195
+ if app_id in self._apps and DIAGNOSTICS in self._apps[app_id]:
196
+ return True
197
+ else:
198
+ return False
199
+
200
+ def diagnostics(self, app_id: str = None) -> Diagnostics:
201
+ """
202
+ :param app_id: Application identifier
203
+ :type app_id: ``str`` or ``None``
204
+
205
+ :return: The diagnostics of the given application. See the different type of :ref:`application results <apps>`
206
+ :rtype: :class:`Diagnostics <wowool.diagnostic.Diagnostics>`
207
+ """
208
+ if app_id is None:
209
+ diagnostics = Diagnostics()
210
+ for _, app_data in self._apps.items():
211
+ if DIAGNOSTICS in app_data:
212
+ diagnostics.extend(app_data[DIAGNOSTICS])
213
+ return diagnostics
214
+ else:
215
+ if app_id in self._apps and DIAGNOSTICS in self._apps[app_id]:
216
+ return self._apps[app_id][DIAGNOSTICS]
217
+ else:
218
+ raise ValueError(f"App '{app_id}' has no diagnostics")
219
+
220
+ def to_json(self) -> dict:
221
+ """
222
+ :return: A dictionary representing a JSON object of the document
223
+ :rtype: ``dict``
224
+ """
225
+ from json import JSONEncoder
226
+
227
+ class Encoder(JSONEncoder):
228
+ def default(self, obj):
229
+ if isinstance(obj, set):
230
+ return str(list(obj))
231
+ else:
232
+ return getattr(obj, "to_json")() if hasattr(obj, "to_json") else super().default(obj)
233
+
234
+ document = {"id": self.id, "apps": self._apps}
235
+ return json.loads(json.dumps(document, cls=Encoder))
236
+
237
+ @staticmethod
238
+ def from_json(document_json: dict):
239
+ assert "id" in document_json, "Invalid Document json format"
240
+ assert "apps" in document_json, "Invalid Document json format"
241
+
242
+ doc = Document(id=document_json["id"])
243
+ doc._apps = document_json["apps"]
244
+
245
+ if APP_ID_ANALYSIS in doc._apps:
246
+ analysis_ = doc._apps[APP_ID_ANALYSIS]
247
+ assert isinstance(analysis_, dict), f"Expected dict, not '{type(analysis_)}'"
248
+ # phforest : this should no be a assert, in case we have errors there will be no results.
249
+ # assert RESULTS in analysis_, f"Missing {RESULTS} in {APP_ID_ANALYSIS}"
250
+ if RESULTS in analysis_:
251
+ analysis = Analysis.parse(analysis_[RESULTS])
252
+ doc.input_provider = AnalysisInputProvider(analysis, doc.id)
253
+ doc.add_results(APP_ID_ANALYSIS, analysis)
254
+
255
+ for _, app_data in doc._apps.items():
256
+ if DIAGNOSTICS in app_data:
257
+ app_data[DIAGNOSTICS] = Diagnostics.from_json(app_data[DIAGNOSTICS])
258
+
259
+ return doc
260
+
261
+ def concepts(self, filter=_filter_pass_thru_concept):
262
+ """
263
+ Access the concepts in the analysis of the document
264
+
265
+ :param filter: Optional filter to select or discard concepts
266
+ :type filter: Functor accepting a :class:`Concept <wowool.annotation.concept.Concept>` and returning a ``bool``
267
+
268
+ :return: A generator expression yielding the concepts in the processed document
269
+ :rtype: :class:`Concepts <wowool.annotation.concept.Concept>`
270
+ """
271
+ return self.analysis.concepts(filter) if self.analysis else iter([])
272
+
273
+ def __repr__(self):
274
+ sz = len(self.text) if self.text else 0
275
+ text = '"' + self.text[:50].strip().replace("\n", " ") + '"' if self.text else None
276
+ return f"""<Document id="{self.id}" size={sz} text={text}>"""
277
+
278
+ def __str__(self):
279
+ with StringIO() as output:
280
+ if self.analysis:
281
+ output.write(str(self.analysis))
282
+ else:
283
+ output.write(self.__repr__())
284
+
285
+ # print the rest of the applications.
286
+ for app_id, app_data in self._apps.items():
287
+ if app_id == APP_ID_ANALYSIS:
288
+ # we already have printed the self.analysis
289
+ continue
290
+
291
+ if RESULTS in app_data:
292
+ output.write(f"{app_id}, {json.dumps(app_data[RESULTS], indent=2)}\n")
293
+ elif DIAGNOSTICS in app_data:
294
+ output.write(f"{app_id}, {app_data[DIAGNOSTICS].to_json()}\n")
295
+
296
+ return output.getvalue()
297
+
298
+ @property
299
+ def entities(self) -> Generator[Concept, Any, None]:
300
+ """
301
+ :return: The entities of the document
302
+ :rtype: ``Generator``
303
+ """
304
+ if self.analysis is not None:
305
+ yield from self.analysis.entities
306
+ else:
307
+ raise ValueError(STR_MISSING_ANALYSIS)
308
+
309
+ @property
310
+ def tokens(self) -> Generator[Token, Any, None]:
311
+ """
312
+ :return: The tokens of the document
313
+ :rtype: ``Generator``
314
+ """
315
+ if self.analysis is not None:
316
+ yield from self.analysis.tokens
317
+ else:
318
+ raise ValueError(STR_MISSING_ANALYSIS)
319
+
320
+ @property
321
+ def annotations(self) -> Generator[Annotation, Any, None]:
322
+ """
323
+ :return: The annotations of the document
324
+ :rtype: ``list``
325
+ """
326
+ if self.analysis is not None:
327
+ yield from self.analysis.annotations
328
+ else:
329
+ raise ValueError(STR_MISSING_ANALYSIS)
330
+
331
+ @property
332
+ def sentences(self) -> Generator[Sentence, Any, None]:
333
+ """
334
+ :return: The annotations of the document
335
+ :rtype: ``list``
336
+ """
337
+
338
+ if self.analysis is not None:
339
+ yield from self.analysis.sentences
340
+ else:
341
+ raise ValueError(STR_MISSING_ANALYSIS)
342
+
343
+ @property
344
+ def topics(self) -> list[Topic] | list:
345
+ """
346
+ :return: The topics of the document
347
+ :rtype: ``list``
348
+ """
349
+ if self.has("wowool_topic_identifier"):
350
+ return convert_topics(self.results("wowool_topic_identifier"))
351
+ else:
352
+ return []
353
+
354
+ @property
355
+ def categories(self) -> list[Theme] | list:
356
+ """
357
+ :return: The categories of the document
358
+ :rtype: ``list``
359
+ """
360
+ if self.has("wowool_semantic_theme"):
361
+ return convert_themes(self.results("wowool_semantic_theme"))
362
+ else:
363
+ return []
364
+
365
+ @property
366
+ def chunks(self) -> list[Chunk] | list:
367
+ """
368
+ :return: The chunks data of the document
369
+ :rtype: ``list``
370
+ """
371
+ if self.has("wowool_chunks"):
372
+ return convert_chunks(self.results("wowool_chunks"))
373
+ else:
374
+ return []
375
+
376
+ @property
377
+ def themes(self) -> list[Theme] | list:
378
+ """
379
+ :return: The categories of the document
380
+ :rtype: ``list``
381
+ """
382
+ return self.categories
383
+
384
+ @property
385
+ def language(self):
386
+ """
387
+ :return: The language of the document
388
+ :rtype: ``str``
389
+ """
390
+ if self.has("wowool_language_identifier"):
391
+ return self.results("wowool_language_identifier")["language"]
392
+ else:
393
+ if self.has(APP_ID_ANALYSIS):
394
+ language = self.results(APP_ID_ANALYSIS).language
395
+ if "@" in language:
396
+ return language.split("@")[0]
397
+ return self.results(APP_ID_ANALYSIS).language
398
+ else:
399
+ return None
@@ -0,0 +1,176 @@
1
+ from pathlib import Path
2
+ from typing import Union, Optional
3
+ from wowool.document.document import Document
4
+ from os import pathconf
5
+ from wowool.utility.path import expand_path
6
+
7
+ PC_NAME_MAX = pathconf("/", "PC_NAME_MAX")
8
+
9
+
10
+ def _resolve__pass_thru(id):
11
+ return id
12
+
13
+
14
+ def data2str(data: Union[str, bytes, None], encoding="utf-8") -> str:
15
+ if isinstance(data, str):
16
+ return data
17
+ elif isinstance(data, bytes):
18
+ return data.decode(encoding)
19
+ elif data == None:
20
+ return ""
21
+ else:
22
+ raise RuntimeError(f"data only supports str|bytes, not {type(data)} {data}")
23
+
24
+
25
+ def _make_str(uid, data, encoding, **kwargs) -> Document:
26
+ from wowool.io.provider.str import StrInputProvider
27
+
28
+ _txt: str = data2str(data, encoding)
29
+ _uid = str(uid) if isinstance(uid, Path) else uid
30
+ return Document(StrInputProvider(_txt, id=_uid))
31
+
32
+
33
+ def _make_file(uid, data, encoding, **kwargs) -> Document:
34
+ from wowool.io.provider.file import FileInputProvider
35
+
36
+ return Document(FileInputProvider(fid=uid, encoding=encoding, **kwargs))
37
+
38
+
39
+ def _make_html(uid, data, encoding) -> Document:
40
+ try:
41
+ from wowool.io.provider.html_v2 import HTMLFileInputProvider
42
+
43
+ return Document(HTMLFileInputProvider(uid, data))
44
+ except Exception as ex:
45
+ raise RuntimeError(f"install the BeautifulSoup(beautifulsoup4) library, 'pip install beautifulsoup4' {ex}")
46
+
47
+
48
+ def _make_docx(uid, data, **kwargs) -> Document:
49
+ assert data is None, "The docx reader does not support data, only files"
50
+ try:
51
+ from wowool.io.provider.docx import DocxFileInputProvider
52
+
53
+ return Document(DocxFileInputProvider(uid))
54
+ except ModuleNotFoundError as ex:
55
+ raise ModuleNotFoundError(f"install the python-docx library, 'pip install python-docx' {ex}")
56
+
57
+
58
+ def _make_pdf(uid, data, **kwargs) -> Document:
59
+ assert data == None, "The pdf reader does not support data, only files"
60
+ try:
61
+ from wowool.io.pdf.provider import PDFFileInputProvider
62
+
63
+ return Document(PDFFileInputProvider(uid))
64
+
65
+ except ModuleNotFoundError as ex:
66
+ raise ModuleNotFoundError(f"install the pdfminer.six library, 'pip install pdfminer.six' {ex}")
67
+
68
+
69
+ def _invalid_type(uid, data, **kwargs):
70
+ raise RuntimeError("Invalid type")
71
+
72
+
73
+ creators = {
74
+ "txt": _make_str,
75
+ "utf8": _make_str,
76
+ "text": _make_str,
77
+ "file": _make_file,
78
+ "html": _make_html,
79
+ "pdf": _make_pdf,
80
+ "docx": _make_docx,
81
+ "_invalid_type": _invalid_type,
82
+ }
83
+
84
+ binary_content_types = set(["pdf", "docx"])
85
+
86
+
87
+ def read_content(fn: Path, input_provider, encoding) -> str:
88
+ with open(fn, "rb") as fh:
89
+ bdata = fh.read()
90
+ if input_provider in binary_content_types:
91
+ return bdata
92
+ return bdata.decode(encoding)
93
+
94
+
95
+ class Factory:
96
+ @staticmethod
97
+ def create(
98
+ id: Union[Path, str],
99
+ data: Optional[Union[str, bytes]] = None,
100
+ provider_type: str = "",
101
+ encoding="utf8",
102
+ **kwargs,
103
+ ) -> Document:
104
+ """
105
+ Class to create a document from input data or from file.
106
+
107
+ .. code-block :: python
108
+
109
+ fn = "test.html"
110
+ doc = Factory.create(fn)
111
+
112
+ .. code-block :: python
113
+
114
+ fn = "test.html"
115
+ with open(fn) as fh:
116
+ html_data = fh.read()
117
+ doc = Factory.create(id = fn, data = html_data, provider_type = "html")
118
+
119
+ """
120
+ _data = data
121
+ if id != None and _data is None:
122
+ fn = Path(id)
123
+ try:
124
+ if fn.exists():
125
+ provider_type = fn.suffix.lower()
126
+ provider_type = provider_type[1:]
127
+ if provider_type == "txt":
128
+ provider_type = "file"
129
+ else:
130
+ provider_type = "txt"
131
+ _data = id
132
+ id = None
133
+ except Exception as ex:
134
+ provider_type = "txt"
135
+ _data = id
136
+ id = None
137
+ else:
138
+ if data != None:
139
+ fn = Path(id)
140
+ if not provider_type:
141
+ if fn.exists():
142
+ provider_type = fn.suffix[1:] if fn.suffix.startswith(".") else "txt"
143
+ else:
144
+ provider_type = "txt"
145
+
146
+ return creators.get(provider_type, _invalid_type)(id, _data, encoding=encoding)
147
+
148
+ @staticmethod
149
+ def split_path_on_wildcards(path_description: Path, pattern: str = "**/*.txt"):
150
+ """
151
+ Split a path description into a folder and a wildcard pattern.
152
+ """
153
+ parts = path_description.parts
154
+
155
+ for index, part in enumerate(parts):
156
+ if "*" in part or "?" in part:
157
+ return Path(*parts[:index]), str(Path(*parts[index:]))
158
+
159
+ return path_description, pattern
160
+
161
+ @staticmethod
162
+ def glob(folder: Path | str, pattern: str = "**/*.txt", provider_type: str = "", resolve=_resolve__pass_thru, **kwargs):
163
+ folder = expand_path(folder)
164
+ if folder.is_file():
165
+ try:
166
+ yield Factory.create(id=resolve(folder), provider_type=provider_type)
167
+ return
168
+ except Exception as ex:
169
+ print(f"Could not create document object, {ex}: {folder}")
170
+ folder, pattern_ = Factory.split_path_on_wildcards(folder, pattern=pattern)
171
+ for fn in folder.glob(pattern_):
172
+ try:
173
+ if fn.is_file():
174
+ yield Factory.create(id=resolve(fn), provider_type=provider_type, **kwargs)
175
+ except Exception as ex:
176
+ print(f"Could not create document object, {ex}: {fn}")
wowool/error.py ADDED
@@ -0,0 +1,2 @@
1
+ class Error(Exception):
2
+ pass
@@ -0,0 +1 @@
1
+ from .console import AppConsole, console
@@ -0,0 +1,29 @@
1
+ from argparse import ArgumentParser as ArgumentParserBase, RawDescriptionHelpFormatter
2
+ from gettext import gettext as _
3
+ from sys import stderr
4
+ from wowool.io.console import console
5
+
6
+
7
+ class ArgumentParser(ArgumentParserBase):
8
+ def __init__(self, *args, **kwargs):
9
+ self.parser = ArgumentParserBase(
10
+ *args, formatter_class=RawDescriptionHelpFormatter, **kwargs
11
+ )
12
+
13
+ def __call__(self, *argv):
14
+ args = self.parse_args(*argv)
15
+ kwargs = dict(args._get_kwargs())
16
+ return kwargs
17
+
18
+ def error(self, message: str):
19
+ self.print_usage(stderr)
20
+ args = {"prog": self.prog, "message": message}
21
+ self.exit(
22
+ 2, _("<prog>%(prog)s</prog>: <error>error</error>: %(message)s\n") % args
23
+ )
24
+
25
+ def _print_message(self, message, file=None):
26
+ if message:
27
+ if file is None:
28
+ file = stderr
29
+ console.print(message, file=file)