wowool-common 3.1.2.dev2__py3-none-any.whl → 3.1.3.dev1__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 (37) hide show
  1. wowool/annotation/__init__.py +1 -0
  2. wowool/annotation/annotation.py +1 -1
  3. wowool/annotation/concept.py +1 -0
  4. wowool/annotation/paragraph.py +2 -2
  5. wowool/apps/info.py +2 -4
  6. wowool/diagnostic.py +1 -1
  7. wowool/document/__init__.py +2 -1
  8. wowool/document/analysis/analysis.py +8 -8
  9. wowool/document/analysis/analysis_parser.py +1 -1
  10. wowool/document/analysis/document.py +49 -22
  11. wowool/document/document.py +46 -7
  12. wowool/document/document_interface.py +9 -16
  13. wowool/document/factory.py +12 -6
  14. wowool/document/serialize.py +1 -1
  15. wowool/io/console/__init__.py +1 -0
  16. wowool/io/provider/docx.py +3 -3
  17. wowool/io/provider/factory.py +5 -3
  18. wowool/io/provider/file.py +6 -6
  19. wowool/io/provider/html_v2.py +5 -3
  20. wowool/io/provider/pdf_no_layout.py +1 -7
  21. wowool/io/provider/raw.py +2 -2
  22. wowool/io/provider/rtf.py +3 -3
  23. wowool/io/provider/str.py +2 -2
  24. wowool/string/__init__.py +2 -3
  25. wowool/utility/apps/decorators.py +0 -1
  26. wowool/utility/default_arguments.py +10 -1
  27. wowool/utility/diagnostics.py +1 -1
  28. wowool/visitor.py +0 -1
  29. wowool/wow.py +5 -8
  30. {wowool_common-3.1.2.dev2.dist-info → wowool_common-3.1.3.dev1.dist-info}/METADATA +1 -1
  31. wowool_common-3.1.3.dev1.dist-info/RECORD +58 -0
  32. wowool/io/provider/html.py +0 -52
  33. wowool/io/provider/pdf.py +0 -320
  34. wowool/io/provider/pdf_old.pydnu +0 -269
  35. wowool_common-3.1.2.dev2.dist-info/RECORD +0 -61
  36. {wowool_common-3.1.2.dev2.dist-info → wowool_common-3.1.3.dev1.dist-info}/WHEEL +0 -0
  37. {wowool_common-3.1.2.dev2.dist-info → wowool_common-3.1.3.dev1.dist-info}/top_level.txt +0 -0
@@ -1,3 +1,4 @@
1
+ # flake8: noqa
1
2
  from wowool.annotation.annotation import Annotation, ErrorAnnotationNotFound
2
3
  from wowool.annotation.token import Token
3
4
  from wowool.annotation.entity import Entity
@@ -114,7 +114,7 @@ class Annotation(BasicAnnotation):
114
114
 
115
115
  @property
116
116
  def index(self) -> int:
117
- assert self._annotation_idx != None
117
+ assert self._annotation_idx is not None
118
118
  return self._annotation_idx
119
119
 
120
120
  @staticmethod
@@ -1 +1,2 @@
1
+ # flake8: noqa
1
2
  from wowool.annotation.entity import Entity as Concept
@@ -155,8 +155,8 @@ class Paragraph(Annotation):
155
155
  from wowool.document.analysis.document import AnalysisDocument
156
156
  from wowool.document.analysis.analysis import Analysis
157
157
 
158
- if original_text is None:
159
- original_text = object.data
158
+ if original_text is None and isinstance(object, AnalysisDocument):
159
+ original_text = object.text
160
160
 
161
161
  if isinstance(object, AnalysisDocument) and object.analysis:
162
162
  yield from Paragraph._document_iter(object.analysis, original_text)
wowool/apps/info.py CHANGED
@@ -1,9 +1,7 @@
1
1
  from logging import getLogger
2
2
  from pathlib import Path
3
3
  import importlib.util
4
-
5
4
  import wowool.apps as applications
6
- from pathlib import Path
7
5
 
8
6
  logger = getLogger(__name__)
9
7
 
@@ -38,7 +36,7 @@ def load_info():
38
36
  config = {**app_module.CONFIG}
39
37
  config["uid"] = folder_name
40
38
  if "name" not in config:
41
- config["name"] = f"{folder_name.replace('_',' ').title()}"
39
+ config["name"] = f"{folder_name.replace('_', ' ').title()}"
42
40
 
43
41
  if "app_id" not in config:
44
42
  config["app_id"] = f"wowool_{folder_name}"
@@ -85,7 +83,7 @@ aliases = load_aliases(info)
85
83
 
86
84
 
87
85
  def is_app_released(app_config: dict) -> bool:
88
- if not "release" in app_config:
86
+ if "release" not in app_config:
89
87
  return True
90
88
  return app_config["release"]
91
89
 
wowool/diagnostic.py CHANGED
@@ -225,7 +225,7 @@ class Diagnostics:
225
225
  for diagnostic in self.items:
226
226
  if int(diagnostic.type) >= int(type):
227
227
  exception = diagnostic.to_exception()
228
- assert isinstance(exception, DiagnosticException), f"Diagnostic did not return an exception"
228
+ assert isinstance(exception, DiagnosticException), "Diagnostic did not return an exception"
229
229
  raise exception
230
230
 
231
231
  def is_greater_or_equal_than(self, type: typing.SupportsInt):
@@ -1,2 +1,3 @@
1
+ # flake8: noqa
1
2
  from wowool.document.document import Document
2
- from wowool.document.document_interface import DocumentInterface
3
+ from wowool.document.document_interface import DocumentInterface, DataType
@@ -4,7 +4,7 @@ from io import StringIO
4
4
  from wowool.annotation.sentence import Sentence
5
5
  from wowool.annotation.entity import Entity
6
6
  from typing import Union
7
- from wowool.document.document_interface import DocumentInterface
7
+ from wowool.document.document_interface import DocumentInterface, DataType, DT_ANALYSIS_JSON
8
8
 
9
9
  APP_ID = "wowool_analysis"
10
10
 
@@ -74,7 +74,7 @@ class Analysis:
74
74
  self._metadata = metadata
75
75
  self._text = None
76
76
 
77
- if document_id != None:
77
+ if document_id is not None:
78
78
  self.id = document_id
79
79
  elif self._cpp:
80
80
  self.id = self._cpp.id()
@@ -95,7 +95,7 @@ class Analysis:
95
95
 
96
96
  :rtype: :class:`Sentence <wowool.annotation.sentence.Sentence>`
97
97
  """
98
- assert self._sentences != None
98
+ assert self._sentences is not None
99
99
  return iter(self._sentences)
100
100
 
101
101
  @_content_access
@@ -124,7 +124,7 @@ class Analysis:
124
124
  :return: The number of sentences in the processed document
125
125
  :rtype: ``int``
126
126
  """
127
- assert self._sentences != None
127
+ assert self._sentences is not None
128
128
  return len(self._sentences)
129
129
 
130
130
  @_content_access
@@ -280,9 +280,9 @@ class Analysis:
280
280
 
281
281
 
282
282
  class AnalysisInputProvider(DocumentInterface):
283
- DATA_TYPE = "analysis/json"
283
+ DATA_TYPE = DT_ANALYSIS_JSON
284
284
 
285
- def __init__(self, data: dict, id: str, metadata: dict | None = None) -> None:
285
+ def __init__(self, data: str, id: str, metadata: dict | None = None) -> None:
286
286
  self._id = id
287
287
  self.analysis_json = data
288
288
  self._metadata = metadata if metadata is not None else {}
@@ -292,11 +292,11 @@ class AnalysisInputProvider(DocumentInterface):
292
292
  return self._id
293
293
 
294
294
  @property
295
- def data_type(self) -> str:
295
+ def data_type(self) -> DataType:
296
296
  return self.DATA_TYPE
297
297
 
298
298
  @property
299
- def data(self) -> str:
299
+ def data(self) -> dict:
300
300
  return self.analysis_json
301
301
 
302
302
  @property
@@ -89,7 +89,7 @@ def parse_document(json_str_or_obj, doc_id=None, cpp_document=None):
89
89
  elif "sentences" in wowool_out:
90
90
  jo_sentences = wowool_out["sentences"]
91
91
 
92
- if jo_sentences == None:
92
+ if jo_sentences is None:
93
93
  raise Exception("Invalid json format. Missing document object.")
94
94
 
95
95
  language = wowool_out["language"] if "language" in wowool_out else "english"
@@ -13,14 +13,24 @@ from typing import cast
13
13
  from wowool.document.analysis.apps.topics import convert_topics, Topic
14
14
  from wowool.document.analysis.apps.themes import convert_themes, Theme
15
15
  from wowool.document.analysis.apps.chunks import convert_chunks, Chunk
16
- from wowool.document.document_interface import DocumentInterface
16
+ from wowool.document.document_interface import DocumentInterface, DataType, DT_TEXT_UTF8
17
17
  from wowool.document.document import Document
18
- from wowool.document.defines import WJ_ID, WJ_DATA, WJ_DATA_TYPE
18
+ from wowool.document.defines import WJ_ID, WJ_DATA, WJ_DATA_TYPE, WJ_METADATA
19
+ from json import JSONEncoder
20
+
19
21
 
20
22
  RESULTS = "results"
21
23
  DIAGNOSTICS = "diagnostics"
22
24
 
23
25
 
26
+ class AnalysisJsonEncoder(JSONEncoder):
27
+ def default(self, obj):
28
+ if isinstance(obj, set):
29
+ return list(obj)
30
+ else:
31
+ return getattr(obj, "to_json")() if hasattr(obj, "to_json") else super().default(obj)
32
+
33
+
24
34
  def to_json_convert(obj):
25
35
  if isinstance(obj, set):
26
36
  return str(list(obj))
@@ -35,6 +45,8 @@ class AnalysisDocument(DocumentInterface):
35
45
  :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.
36
46
  """
37
47
 
48
+ DATA_TYPE = "analysis/json"
49
+
38
50
  def __init__(self, document: DocumentInterface, metadata: dict | None = None):
39
51
  """
40
52
  Initialize a :class:`AnalysisDocument` instance
@@ -42,9 +54,20 @@ class AnalysisDocument(DocumentInterface):
42
54
  super().__init__()
43
55
 
44
56
  self.input_document = document
45
- self._metadata = metadata if metadata != None else {**self.input_document.metadata}
57
+ self._metadata = metadata if metadata is not None else {**self.input_document.metadata}
46
58
  self._apps = {}
47
59
 
60
+ @property
61
+ def text(self) -> str:
62
+ """
63
+ :return: The text data of the document
64
+ :rtype: ``str``
65
+ """
66
+ if self.input_document.data_type == DT_TEXT_UTF8:
67
+ return self.input_document.data
68
+ else:
69
+ raise ValueError(f"The input Document is not a text document, but a [{self.input_document.data_type}]")
70
+
48
71
  @property
49
72
  def id(self) -> str:
50
73
  """
@@ -54,21 +77,22 @@ class AnalysisDocument(DocumentInterface):
54
77
  return self.input_document.id
55
78
 
56
79
  @property
57
- def data_type(self) -> str:
80
+ def data_type(self) -> DataType:
58
81
  """
59
82
  :return: The data type of the document
60
- :rtype: 'str | None'
83
+ :rtype: 'DataType'
61
84
  """
62
- assert self.input_document.data_type is not None, "Document has no data type"
63
- return self.input_document.data_type
85
+ return AnalysisDocument.DATA_TYPE
64
86
 
65
87
  @property
66
- def data(self) -> Union[str, None]:
88
+ def data(self) -> str:
67
89
  """
68
90
  :return: The text data of the document
69
91
  :rtype: 'str | None'
70
92
  """
71
- return self.input_document.data if self.input_document else ""
93
+
94
+ analysis_data = {"apps": self._apps}
95
+ return json.loads(json.dumps(analysis_data, cls=AnalysisJsonEncoder))
72
96
 
73
97
  @property
74
98
  def metadata(self) -> dict:
@@ -198,24 +222,30 @@ class AnalysisDocument(DocumentInterface):
198
222
  class Encoder(JSONEncoder):
199
223
  def default(self, obj):
200
224
  if isinstance(obj, set):
201
- return str(list(obj))
225
+ return list(obj)
202
226
  else:
203
227
  return getattr(obj, "to_json")() if hasattr(obj, "to_json") else super().default(obj)
204
228
 
205
- document = {WJ_ID: self.id, WJ_DATA_TYPE: AnalysisInputProvider.DATA_TYPE, WJ_DATA: {"apps": self._apps}}
229
+ document = {
230
+ WJ_ID: self.id,
231
+ WJ_DATA_TYPE: AnalysisInputProvider.DATA_TYPE,
232
+ WJ_DATA: self.data,
233
+ WJ_METADATA: self.metadata,
234
+ }
206
235
  return json.loads(json.dumps(document, cls=Encoder))
207
236
 
208
237
  @staticmethod
209
238
  def from_dict(document_json: dict) -> "AnalysisDocument":
210
239
  assert WJ_ID in document_json, "Invalid Document json format"
211
240
  assert WJ_DATA_TYPE in document_json, "Invalid Document json format"
212
- assert AnalysisInputProvider.DATA_TYPE in document_json[WJ_DATA_TYPE]
213
- assert WJ_DATA in document_json, "Invalid Document json format"
214
- assert "apps" in document_json[WJ_DATA]
241
+ json_doc = document_json
242
+ assert WJ_DATA in json_doc, "Invalid Document json format"
243
+ assert "apps" in json_doc[WJ_DATA]
215
244
 
216
- doc = AnalysisDocument(Document.create(**document_json))
245
+ input_document = Document.create(**json_doc)
246
+ doc = AnalysisDocument(input_document)
217
247
  assert AnalysisInputProvider.DATA_TYPE == doc.data_type
218
- doc._apps = doc.data["apps"]
248
+ doc._apps = input_document.data["apps"]
219
249
 
220
250
  if APP_ID_ANALYSIS in doc._apps:
221
251
  analysis_ = doc._apps[APP_ID_ANALYSIS]
@@ -246,12 +276,9 @@ class AnalysisDocument(DocumentInterface):
246
276
  return self.analysis.concepts(filter) if self.analysis else iter([])
247
277
 
248
278
  def __repr__(self):
249
- if self.data_type == AnalysisInputProvider.DATA_TYPE:
250
- # we are using the input document
251
- return f"<AnalysisDocument id={self.id} data_type={self.data_type}>"
252
- sz = len(self.data) if self.data else 0
253
- text = '"' + self.data[:50].strip().replace("\n", " ") + '"' if self.data else None
254
- return f"""<AnalysisDocument id="{self.id}" size={sz} text={text}>"""
279
+ sz = len(self.text) if self.text else 0
280
+ text = '"' + self.text[:50].strip().replace("\n", " ") + '"' if self.text else None
281
+ return f"<AnalysisDocument id={self.id} data_type={self.data_type} size={sz} text={text} >"
255
282
 
256
283
  def __str__(self):
257
284
  with StringIO() as output:
@@ -1,7 +1,8 @@
1
- from wowool.document.document_interface import DocumentInterface
1
+ from wowool.document.document_interface import DocumentInterface, DataType
2
2
  from wowool.document.factory import Factory, _resolve__pass_thru, DEFAULT_TEXT_DATA_TYPE
3
3
  from pathlib import Path
4
4
  from wowool.document.defines import WJ_ID, WJ_DATA, WJ_DATA_TYPE, WJ_METADATA
5
+ from typing import Generator, Any
5
6
 
6
7
 
7
8
  class Document(DocumentInterface):
@@ -30,7 +31,7 @@ class Document(DocumentInterface):
30
31
  return self.input_provider.id
31
32
 
32
33
  @property
33
- def data_type(self) -> str:
34
+ def data_type(self) -> DataType:
34
35
  """
35
36
  :return: Document type
36
37
  :rtype: ``str``
@@ -54,9 +55,10 @@ class Document(DocumentInterface):
54
55
  return self._metadata
55
56
 
56
57
  @staticmethod
57
- def deserialize(document: dict):
58
+ def deserialize(document: dict) -> DocumentInterface:
58
59
  """
59
60
  Deserialize a document from JSON format.
61
+
60
62
  :param document: JSON representation of the document.
61
63
  :return: Document object.
62
64
  :rtype: ``Document``
@@ -68,7 +70,7 @@ class Document(DocumentInterface):
68
70
  @staticmethod
69
71
  def from_json(
70
72
  document: dict,
71
- ):
73
+ ) -> DocumentInterface:
72
74
  return Factory.from_json(
73
75
  id=document[WJ_ID], data=document[WJ_DATA], provider_type=document[WJ_DATA_TYPE], metadata=document.get(WJ_METADATA, {})
74
76
  )
@@ -81,7 +83,18 @@ class Document(DocumentInterface):
81
83
  encoding="utf8",
82
84
  raw: bool = False,
83
85
  **kwargs,
84
- ):
86
+ ) -> DocumentInterface:
87
+ """
88
+ Create a document from the given data.
89
+
90
+ :param data: Document content.
91
+ :param id: Unique document identifier.
92
+ :param data_type: Document type.
93
+ :param encoding: Document encoding.
94
+ :param raw: If True, the data is treated as raw bytes.
95
+ :param kwargs: Additional keyword arguments.
96
+ :return: Document object.
97
+ :rtype: ``Document``"""
85
98
  return Factory.create(
86
99
  id=id,
87
100
  data=data,
@@ -98,7 +111,20 @@ class Document(DocumentInterface):
98
111
  data_type: str = "",
99
112
  encoding="utf8",
100
113
  **kwargs,
101
- ):
114
+ ) -> DocumentInterface:
115
+ """Create a document from the given file.
116
+
117
+ :param file: Path to the file.
118
+ :param data: Document content.
119
+ :param data_type: Document type.
120
+ :param encoding: Document encoding.
121
+ :param kwargs: Additional keyword arguments.
122
+ :return: Document object.
123
+ :rtype: ``Document``
124
+ :raises ValueError: If the file is not found.
125
+ :raises TypeError: If the file is not a string or Path object.
126
+ :raises IOError: If there is an error reading the file.
127
+ """
102
128
  return Factory.create(
103
129
  id=file,
104
130
  data=data,
@@ -115,5 +141,18 @@ class Document(DocumentInterface):
115
141
  resolve=_resolve__pass_thru,
116
142
  raw: bool = False,
117
143
  **kwargs,
118
- ):
144
+ ) -> Generator[DocumentInterface, Any, None]:
145
+ """
146
+ Create a document from the given folder.
147
+ This method will search for files matching the given pattern in the specified folder.
148
+
149
+ :param folder: Path to the folder.
150
+ :param pattern: Pattern to match files.
151
+ :param provider_type: Document type.
152
+ :param resolve: Function to resolve the data.
153
+ :param raw: If True, the data is treated as raw bytes.
154
+ :param kwargs: Additional keyword arguments.
155
+ :return: Generator of Document objects.
156
+ :rtype: ``Generator``
157
+ :raises ValueError: If the folder is not found."""
119
158
  yield from Factory.glob(folder, pattern=pattern, provider_type=provider_type, resolve=resolve, raw=raw, **kwargs)
@@ -1,16 +1,19 @@
1
1
  from typing import Protocol, runtime_checkable, Any
2
- from wowool.document.defines import WJ_ID, WJ_DATA, WJ_DATA_TYPE, WJ_METADATA
3
2
  from typing import Literal
4
3
 
4
+ DT_TEXT_UTF8 = "text/utf8"
5
+ DT_HTML_RAW = "html/raw"
6
+ DT_RTF_RAW = "rtf/raw"
7
+ DT_PDF_RAW = "pdf/raw"
8
+ DT_DOCX_RAW = "docx/raw"
9
+ DT_ANALYSIS_JSON = "analysis/json"
10
+
11
+ # cannot use the define above because for the datatype Literal
5
12
  DataType = Literal[
6
13
  "text/utf8",
7
- "text/raw",
8
- "md/utf8",
9
- "html/utf8",
10
14
  "html/raw",
11
- "pdf/utf8",
15
+ "rtf/raw",
12
16
  "pdf/raw",
13
- "docx/utf8",
14
17
  "docx/raw",
15
18
  "analysis/json",
16
19
  ]
@@ -37,13 +40,3 @@ class DocumentInterface(Protocol):
37
40
  @property
38
41
  def metadata(self) -> dict[str, Any]:
39
42
  pass
40
-
41
- def serialize(self):
42
- """
43
- Convert the document to JSON format.
44
- :return: JSON representation of the document.
45
- :rtype: ``dict``
46
- """
47
- from wowool.document.serialize import serialize
48
-
49
- return serialize(self)
@@ -19,7 +19,7 @@ def data2str(data: Union[str, bytes, None], encoding="utf-8") -> str:
19
19
  return data
20
20
  elif isinstance(data, bytes):
21
21
  return data.decode(encoding)
22
- elif data == None:
22
+ elif data is None:
23
23
  return ""
24
24
  else:
25
25
  raise RuntimeError(f"data only supports str|bytes, not {type(data)} {data}")
@@ -202,14 +202,14 @@ class Factory:
202
202
  else:
203
203
  provider_type = DEFAULT_TEXT_DATA_TYPE
204
204
  _data = None
205
- except Exception as ex:
206
- provider_type = DEFAULT_TEXT_DATA_TYPE
205
+ except Exception:
206
+ provider_type = DEFAULT_TEXT_DATA_TYPE if provider_type == "" else provider_type
207
207
  _data = None
208
208
  else:
209
209
  if data is not None:
210
210
  if id is None:
211
211
  id = generate_uuid()
212
- provider_type = DEFAULT_TEXT_DATA_TYPE
212
+ provider_type = DEFAULT_TEXT_DATA_TYPE if provider_type == "" else provider_type
213
213
  else:
214
214
  # assume the id is a file name
215
215
  fn = Path(id)
@@ -237,6 +237,8 @@ class Factory:
237
237
  if "*" in part or "?" in part:
238
238
  return Path(*parts[:index]), str(Path(*parts[index:]))
239
239
 
240
+ if not path_description.exists():
241
+ raise ValueError(f"Path {path_description} does not exist")
240
242
  return path_description, pattern
241
243
 
242
244
  @staticmethod
@@ -263,8 +265,12 @@ class Factory:
263
265
  folder = expand_path(folder)
264
266
  if folder.is_file():
265
267
  try:
266
- yield Factory.create(id=resolve(folder), provider_type=provider_type, raw=raw, metadata=metadata, **kwargs)
267
- return
268
+ fn = Path(folder)
269
+ if fn.exists():
270
+ yield Factory.create(id=resolve(folder), provider_type=provider_type, raw=raw, metadata=metadata, **kwargs)
271
+ return
272
+ else:
273
+ raise ValueError(f"File {folder} does not exist")
268
274
  except Exception as ex:
269
275
  print(f"Could not create document object, {ex}: {folder}")
270
276
  folder, pattern_ = Factory.split_path_on_wildcards(folder, pattern=pattern)
@@ -1,5 +1,5 @@
1
1
  from wowool.document.document_interface import DocumentInterface
2
- from wowool.document.factory import Factory, _resolve__pass_thru, DEFAULT_TEXT_DATA_TYPE
2
+ from wowool.document.factory import Factory
3
3
  from wowool.document.defines import WJ_ID, WJ_DATA, WJ_DATA_TYPE, WJ_METADATA
4
4
  import base64
5
5
 
@@ -1 +1,2 @@
1
+ # flake8: noqa
1
2
  from .console import AppConsole, console
@@ -1,4 +1,4 @@
1
- from wowool.document.document_interface import DocumentInterface
1
+ from wowool.document.document_interface import DocumentInterface, DataType
2
2
  import docx
3
3
 
4
4
 
@@ -11,7 +11,7 @@ def get_heading_markup_level(paragraph):
11
11
 
12
12
  class DocxFileInputProvider(DocumentInterface):
13
13
 
14
- DATA_TYPE = "docx/utf8"
14
+ DATA_TYPE = "text/utf8"
15
15
 
16
16
  def __init__(self, fid, metadata: dict | None = None):
17
17
  self._id = str(fid)
@@ -22,7 +22,7 @@ class DocxFileInputProvider(DocumentInterface):
22
22
  return self._id
23
23
 
24
24
  @property
25
- def data_type(self) -> str:
25
+ def data_type(self) -> DataType:
26
26
  return self.DATA_TYPE
27
27
 
28
28
  @property
@@ -62,8 +62,6 @@ def _make_docx(uid, data, **kwargs) -> DocumentInterface:
62
62
  def _make_pdf(uid, data, **kwargs) -> DocumentInterface:
63
63
  assert data is None, "The pdf reader does not support data, only files"
64
64
  try:
65
- # from wowool.io.provider.pdf import PdfFileInputProvider
66
-
67
65
  from wowool.io.pdf.provider import PDFFileInputProvider
68
66
 
69
67
  return PDFFileInputProvider(uid)
@@ -161,7 +159,11 @@ class Factory:
161
159
  def glob(folder: Path | str, pattern: str = "*.txt", provider_type: str = "", **kwargs):
162
160
  folder = expand_path(folder)
163
161
  if Path(folder).is_file():
164
- yield Factory.create(id=folder, provider_type=provider_type)
162
+ fn = Path(folder)
163
+ if fn.exists():
164
+ yield Factory.create(id=folder, provider_type=provider_type, **kwargs)
165
+ else:
166
+ raise RuntimeError(f"File {folder} does not exist")
165
167
  else:
166
168
  folder, pattern_ = Factory.split_path_on_wildcards(folder, pattern=pattern)
167
169
  for fn in folder.glob(pattern_):
@@ -1,5 +1,5 @@
1
1
  from pathlib import Path
2
- from wowool.document.document_interface import DocumentInterface
2
+ from wowool.document.document_interface import DocumentInterface, DataType
3
3
  import errno
4
4
 
5
5
  global filemagic
@@ -12,7 +12,7 @@ def _strip_upper_ascii(s):
12
12
 
13
13
 
14
14
  class FileInputProvider(DocumentInterface):
15
- DATA_TYPE = "html/utf8"
15
+ DATA_TYPE = "text/utf8"
16
16
 
17
17
  def __init__(self, fid, encoding="utf8", cleanup=None, metadata: dict | None = None):
18
18
  self._id = str(fid)
@@ -35,7 +35,7 @@ class FileInputProvider(DocumentInterface):
35
35
  return self._id
36
36
 
37
37
  @property
38
- def data_type(self) -> str:
38
+ def data_type(self) -> DataType:
39
39
  """
40
40
  :return: Document type
41
41
  :rtype: ``str``
@@ -65,11 +65,11 @@ class FileInputProvider(DocumentInterface):
65
65
  if filemagic is None:
66
66
  try:
67
67
  import magic
68
- except:
68
+
69
+ filemagic = magic.Magic(flags=magic.MAGIC_MIME_ENCODING)
70
+ except ImportError:
69
71
  raise RuntimeError("install the chardet library, 'on macos: brew install libmagic ; pip3 install filemagic'")
70
- import magic
71
72
 
72
- filemagic = magic.Magic(flags=magic.MAGIC_MIME_ENCODING)
73
73
  self.encoding = filemagic.id_filename(self.id())
74
74
  if self.encoding == "binary":
75
75
  # print(f"self.cleanup.................{self.cleanup}")
@@ -1,4 +1,4 @@
1
- from wowool.document import DocumentInterface
1
+ from wowool.document import DocumentInterface, DataType
2
2
  from bs4 import BeautifulSoup
3
3
  import re
4
4
  from enum import Enum
@@ -315,7 +315,7 @@ def cleanup_output(text):
315
315
 
316
316
  class HTMLFileInputProvider(DocumentInterface):
317
317
 
318
- DATA_TYPE = "html/utf8"
318
+ DATA_TYPE = "text/utf8"
319
319
 
320
320
  def __init__(
321
321
  self,
@@ -345,6 +345,8 @@ class HTMLFileInputProvider(DocumentInterface):
345
345
 
346
346
  def _get_text(self, input):
347
347
  if self.use_readability and input:
348
+ if isinstance(input, bytes):
349
+ input = input.decode(self.encoding or "utf-8")
348
350
  try:
349
351
  from readability import Document
350
352
 
@@ -417,7 +419,7 @@ class HTMLFileInputProvider(DocumentInterface):
417
419
  return self._id
418
420
 
419
421
  @property
420
- def data_type(self) -> str:
422
+ def data_type(self) -> DataType:
421
423
  return self.DATA_TYPE
422
424
 
423
425
  @property
@@ -1,17 +1,11 @@
1
- # """
2
- # Extract PDF text using PDFMiner. Adapted from
3
- # http://stackoverflow.com/questions/5725278/python-help-using-pdfminer-as-a-library
4
- # """
5
-
1
+ # flake8: noqa: E402
6
2
 
7
3
  import pdfminer.settings
8
4
  from wowool.io.provider import InputProvider
9
5
 
10
6
  pdfminer.settings.STRICT = False
11
7
  import pdfminer.high_level
12
- import pdfminer.layout
13
8
  from pathlib import Path
14
-
15
9
  from io import StringIO
16
10
 
17
11
 
wowool/io/provider/raw.py CHANGED
@@ -1,5 +1,5 @@
1
1
  from pathlib import Path
2
- from wowool.document.document_interface import DocumentInterface
2
+ from wowool.document.document_interface import DocumentInterface, DataType
3
3
 
4
4
 
5
5
  class RawFileInputProvider(DocumentInterface):
@@ -19,7 +19,7 @@ class RawFileInputProvider(DocumentInterface):
19
19
  return self._id
20
20
 
21
21
  @property
22
- def data_type(self) -> str:
22
+ def data_type(self) -> DataType:
23
23
  """
24
24
  :return: Document type
25
25
  :rtype: ``str``
wowool/io/provider/rtf.py CHANGED
@@ -1,10 +1,10 @@
1
- from wowool.document.document_interface import DocumentInterface
1
+ from wowool.document.document_interface import DocumentInterface, DataType
2
2
  from striprtf.striprtf import rtf_to_text
3
3
 
4
4
 
5
5
  class RTFFileInputProvider(DocumentInterface):
6
6
 
7
- DATA_TYPE = "rtf"
7
+ DATA_TYPE = "text/utf8"
8
8
 
9
9
  def __init__(self, fid, encoding="utf8", metadata: dict | None = None):
10
10
 
@@ -18,7 +18,7 @@ class RTFFileInputProvider(DocumentInterface):
18
18
  return self._id
19
19
 
20
20
  @property
21
- def data_type(self) -> str:
21
+ def data_type(self) -> DataType:
22
22
  return self.DATA_TYPE
23
23
 
24
24
  @property