intellireading-cli 2.1.1__tar.gz → 2.1.2__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ __pycache__/
2
+ *.pyc
3
+ *.pyo
4
+ .venv/
5
+ *.json
6
+ !renovate.json
7
+ .debug
8
+ .coverage
9
+ coverage/
10
+ coverage.xml
11
+ htmlcov/
12
+ dist/
13
+ build/
14
+ *.egg-info/
15
+ .mypy_cache/
16
+ .pytest_cache/
17
+ .ruff_cache/
18
+ app/
19
+ .env
20
+ tests/test_files/output
21
+ bin/act
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: intellireading-cli
3
- Version: 2.1.1
3
+ Version: 2.1.2
4
4
  Summary: Intellireading-cli is a Python library with a set of tools to improve your reading experience
5
5
  Project-URL: Documentation, https://go.hugobatista.com/gh/intellireading-cli#readme
6
6
  Project-URL: Issues, https://go.hugobatista.com/gh/intellireading-cli/issues
@@ -42,6 +42,7 @@ Description-Content-Type: text/markdown
42
42
  [![Deploy to ghcr.io](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/build-and-publish-to-ghcr.yml/badge.svg)](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/build-and-publish-to-ghcr.yml)
43
43
  [![Lint](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/lint.yml/badge.svg)](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/lint.yml)
44
44
  [![Test](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/test.yml/badge.svg)](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/test.yml)
45
+ [![Renovate](https://img.shields.io/badge/renovate-enabled-brightgreen?logo=renovatebot)](https://docs.renovatebot.com)
45
46
  [![GitMCP](https://img.shields.io/endpoint?url=https://gitmcp.io/badge/hugobatista/intellireading-cli)](https://gitmcp.io/hugobatista/intellireading-cli)
46
47
 
47
48
  Intellireading is a CLI tool with commands to accelerate your reading experience. It can also be used as a Python library.
@@ -192,7 +193,7 @@ from intellireading.client import (
192
193
  metaguide_epub_stream,
193
194
  metaguide_xhtml_stream,
194
195
  metaguide_dir,
195
- is_file_metaguided
196
+ is_file_metaguided,
196
197
  )
197
198
 
198
199
  # Metaguide an EPUB file
@@ -217,11 +218,7 @@ from intellireading.client import metaguide_epub_file
217
218
  metaguide_epub_file("mybook.epub", "mybook_metaguided.epub")
218
219
 
219
220
  # Remove metaguiding (experimental)
220
- metaguide_epub_file(
221
- "mybook_metaguided.epub",
222
- "mybook_original.epub",
223
- remove_metaguiding=True
224
- )
221
+ metaguide_epub_file("mybook_metaguided.epub", "mybook_original.epub", remove_metaguiding=True)
225
222
  ```
226
223
 
227
224
  **`metaguide_epub_stream(input_stream: BytesIO, *, remove_metaguiding: bool = False) -> BytesIO`**
@@ -257,11 +254,7 @@ from intellireading.client import metaguide_xhtml_file
257
254
  metaguide_xhtml_file("article.html", "article_metaguided.html")
258
255
 
259
256
  # Remove metaguiding
260
- metaguide_xhtml_file(
261
- "article_metaguided.html",
262
- "article_restored.html",
263
- remove_metaguiding=True
264
- )
257
+ metaguide_xhtml_file("article_metaguided.html", "article_restored.html", remove_metaguiding=True)
265
258
  ```
266
259
 
267
260
  **`metaguide_xhtml_stream(input_file_stream: BytesIO, *, remove_metaguiding: bool = False) -> BytesIO`**
@@ -282,9 +275,9 @@ html_content = """
282
275
  </html>
283
276
  """
284
277
 
285
- input_stream = BytesIO(html_content.encode('utf-8'))
278
+ input_stream = BytesIO(html_content.encode("utf-8"))
286
279
  output_stream = metaguide_xhtml_stream(input_stream)
287
- metaguided_content = output_stream.read().decode('utf-8')
280
+ metaguided_content = output_stream.read().decode("utf-8")
288
281
  ```
289
282
 
290
283
  #### Directory Functions
@@ -331,18 +324,19 @@ from intellireading.client import metaguide_epub_stream
331
324
 
332
325
  app = Flask(__name__)
333
326
 
334
- @app.route('/metaguide', methods=['POST'])
327
+
328
+ @app.route("/metaguide", methods=["POST"])
335
329
  def metaguide_upload():
336
- file = request.files['epub']
337
- if file and file.filename.endswith('.epub'):
330
+ file = request.files["epub"]
331
+ if file and file.filename.endswith(".epub"):
338
332
  input_stream = BytesIO(file.read())
339
333
  output_stream = metaguide_epub_stream(input_stream)
340
-
334
+
341
335
  return send_file(
342
336
  output_stream,
343
337
  as_attachment=True,
344
338
  download_name=f"metaguided_{file.filename}",
345
- mimetype='application/epub+zip'
339
+ mimetype="application/epub+zip",
346
340
  )
347
341
  return "Invalid file", 400
348
342
  ```
@@ -353,21 +347,23 @@ def metaguide_upload():
353
347
  import os
354
348
  from intellireading.client import metaguide_dir, is_file_metaguided
355
349
 
350
+
356
351
  def batch_process_library(library_path):
357
352
  """Process an entire library of EPUB files"""
358
353
  processed_path = os.path.join(library_path, "metaguided")
359
-
354
+
360
355
  # Process all files
361
356
  metaguide_dir(library_path, processed_path)
362
-
357
+
363
358
  # Verify results
364
359
  for root, dirs, files in os.walk(processed_path):
365
360
  for file in files:
366
- if file.endswith('.epub'):
361
+ if file.endswith(".epub"):
367
362
  filepath = os.path.join(root, file)
368
363
  if is_file_metaguided(filepath):
369
364
  print(f"✓ Successfully metaguided: {file}")
370
365
 
366
+
371
367
  batch_process_library("/path/to/my/books")
372
368
  ```
373
369
 
@@ -385,3 +381,22 @@ except FileNotFoundError as e:
385
381
  except Exception as e:
386
382
  print(f"Unexpected error: {e}")
387
383
  ```
384
+
385
+ ## Dependency updates
386
+
387
+ Dependencies are updated automatically by [Renovate](https://docs.renovatebot.com).
388
+ The configuration lives in [`renovate.json`](renovate.json).
389
+
390
+ Updates that pass the 30-day minimum release age are proposed as pull requests.
391
+ Major updates are labelled `major-update`, security updates are labelled `security`,
392
+ and `ghcr.io/astral-sh/uv` version bumps wait for approval in the Dependency Dashboard.
393
+
394
+ To run Renovate locally as a dry run:
395
+
396
+ ```bash
397
+ act workflow_dispatch -W .github/workflows/renovate.yml \
398
+ --env RENOVATE_DRY_RUN=full \
399
+ --env RENOVATE_REPOSITORIES=hugobatista/intellireading-cli \
400
+ --env LOG_LEVEL=info \
401
+ -s RENOVATE_TOKEN=<token>
402
+ ```
@@ -6,6 +6,7 @@
6
6
  [![Deploy to ghcr.io](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/build-and-publish-to-ghcr.yml/badge.svg)](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/build-and-publish-to-ghcr.yml)
7
7
  [![Lint](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/lint.yml/badge.svg)](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/lint.yml)
8
8
  [![Test](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/test.yml/badge.svg)](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/test.yml)
9
+ [![Renovate](https://img.shields.io/badge/renovate-enabled-brightgreen?logo=renovatebot)](https://docs.renovatebot.com)
9
10
  [![GitMCP](https://img.shields.io/endpoint?url=https://gitmcp.io/badge/hugobatista/intellireading-cli)](https://gitmcp.io/hugobatista/intellireading-cli)
10
11
 
11
12
  Intellireading is a CLI tool with commands to accelerate your reading experience. It can also be used as a Python library.
@@ -156,7 +157,7 @@ from intellireading.client import (
156
157
  metaguide_epub_stream,
157
158
  metaguide_xhtml_stream,
158
159
  metaguide_dir,
159
- is_file_metaguided
160
+ is_file_metaguided,
160
161
  )
161
162
 
162
163
  # Metaguide an EPUB file
@@ -181,11 +182,7 @@ from intellireading.client import metaguide_epub_file
181
182
  metaguide_epub_file("mybook.epub", "mybook_metaguided.epub")
182
183
 
183
184
  # Remove metaguiding (experimental)
184
- metaguide_epub_file(
185
- "mybook_metaguided.epub",
186
- "mybook_original.epub",
187
- remove_metaguiding=True
188
- )
185
+ metaguide_epub_file("mybook_metaguided.epub", "mybook_original.epub", remove_metaguiding=True)
189
186
  ```
190
187
 
191
188
  **`metaguide_epub_stream(input_stream: BytesIO, *, remove_metaguiding: bool = False) -> BytesIO`**
@@ -221,11 +218,7 @@ from intellireading.client import metaguide_xhtml_file
221
218
  metaguide_xhtml_file("article.html", "article_metaguided.html")
222
219
 
223
220
  # Remove metaguiding
224
- metaguide_xhtml_file(
225
- "article_metaguided.html",
226
- "article_restored.html",
227
- remove_metaguiding=True
228
- )
221
+ metaguide_xhtml_file("article_metaguided.html", "article_restored.html", remove_metaguiding=True)
229
222
  ```
230
223
 
231
224
  **`metaguide_xhtml_stream(input_file_stream: BytesIO, *, remove_metaguiding: bool = False) -> BytesIO`**
@@ -246,9 +239,9 @@ html_content = """
246
239
  </html>
247
240
  """
248
241
 
249
- input_stream = BytesIO(html_content.encode('utf-8'))
242
+ input_stream = BytesIO(html_content.encode("utf-8"))
250
243
  output_stream = metaguide_xhtml_stream(input_stream)
251
- metaguided_content = output_stream.read().decode('utf-8')
244
+ metaguided_content = output_stream.read().decode("utf-8")
252
245
  ```
253
246
 
254
247
  #### Directory Functions
@@ -295,18 +288,19 @@ from intellireading.client import metaguide_epub_stream
295
288
 
296
289
  app = Flask(__name__)
297
290
 
298
- @app.route('/metaguide', methods=['POST'])
291
+
292
+ @app.route("/metaguide", methods=["POST"])
299
293
  def metaguide_upload():
300
- file = request.files['epub']
301
- if file and file.filename.endswith('.epub'):
294
+ file = request.files["epub"]
295
+ if file and file.filename.endswith(".epub"):
302
296
  input_stream = BytesIO(file.read())
303
297
  output_stream = metaguide_epub_stream(input_stream)
304
-
298
+
305
299
  return send_file(
306
300
  output_stream,
307
301
  as_attachment=True,
308
302
  download_name=f"metaguided_{file.filename}",
309
- mimetype='application/epub+zip'
303
+ mimetype="application/epub+zip",
310
304
  )
311
305
  return "Invalid file", 400
312
306
  ```
@@ -317,21 +311,23 @@ def metaguide_upload():
317
311
  import os
318
312
  from intellireading.client import metaguide_dir, is_file_metaguided
319
313
 
314
+
320
315
  def batch_process_library(library_path):
321
316
  """Process an entire library of EPUB files"""
322
317
  processed_path = os.path.join(library_path, "metaguided")
323
-
318
+
324
319
  # Process all files
325
320
  metaguide_dir(library_path, processed_path)
326
-
321
+
327
322
  # Verify results
328
323
  for root, dirs, files in os.walk(processed_path):
329
324
  for file in files:
330
- if file.endswith('.epub'):
325
+ if file.endswith(".epub"):
331
326
  filepath = os.path.join(root, file)
332
327
  if is_file_metaguided(filepath):
333
328
  print(f"✓ Successfully metaguided: {file}")
334
329
 
330
+
335
331
  batch_process_library("/path/to/my/books")
336
332
  ```
337
333
 
@@ -349,3 +345,22 @@ except FileNotFoundError as e:
349
345
  except Exception as e:
350
346
  print(f"Unexpected error: {e}")
351
347
  ```
348
+
349
+ ## Dependency updates
350
+
351
+ Dependencies are updated automatically by [Renovate](https://docs.renovatebot.com).
352
+ The configuration lives in [`renovate.json`](renovate.json).
353
+
354
+ Updates that pass the 30-day minimum release age are proposed as pull requests.
355
+ Major updates are labelled `major-update`, security updates are labelled `security`,
356
+ and `ghcr.io/astral-sh/uv` version bumps wait for approval in the Dependency Dashboard.
357
+
358
+ To run Renovate locally as a dry run:
359
+
360
+ ```bash
361
+ act workflow_dispatch -W .github/workflows/renovate.yml \
362
+ --env RENOVATE_DRY_RUN=full \
363
+ --env RENOVATE_REPOSITORIES=hugobatista/intellireading-cli \
364
+ --env LOG_LEVEL=info \
365
+ -s RENOVATE_TOKEN=<token>
366
+ ```
@@ -41,6 +41,32 @@ dependencies = [
41
41
  [project.scripts]
42
42
  intellireading = "intellireading.client:entrypoint"
43
43
 
44
+ [tool.uv]
45
+ required-version = ">=0.11.18"
46
+ exclude-newer = "30 days"
47
+
48
+ [[tool.uv.index]]
49
+ name = "pypi"
50
+ url = "https://pypi.org/simple"
51
+ explicit = true
52
+
53
+ [dependency-groups]
54
+ lint = [
55
+ "mypy>=1.0.0",
56
+ "ruff>=0.0.243",
57
+ "types-regex",
58
+ ]
59
+ test = [
60
+ "coverage[toml]>=6.5",
61
+ "pytest",
62
+ "pytest-cov",
63
+ ]
64
+ dev = [
65
+ "hatch>=1.16.5",
66
+ {include-group = "lint"},
67
+ {include-group = "test"},
68
+ ]
69
+
44
70
  [project.urls]
45
71
  Documentation = "https://go.hugobatista.com/gh/intellireading-cli#readme"
46
72
  Issues = "https://go.hugobatista.com/gh/intellireading-cli/issues"
@@ -57,61 +83,24 @@ packages = ["src/intellireading"]
57
83
  exclude = ["tests"]
58
84
 
59
85
  [tool.hatch.build.targets.sdist]
60
- packages = ["src/intellireading"]
61
- exclude = ["tests"]
86
+ only-include = ["src/intellireading", "README.md"]
62
87
 
63
88
  [tool.hatch.envs.default]
64
- installer = "uv"
65
- dependencies = [
66
- "coverage[toml]>=6.5",
67
- "pytest",
68
- ]
69
- [tool.hatch.envs.default.scripts]
70
- test = "pytest {args:tests} -v"
71
- test-cov = "coverage run -m pytest {args:tests} -v"
72
- cov-report = [
73
- "- coverage combine",
74
- "coverage report",
75
- "coverage html",
76
- ]
77
- cov = [
78
- "test-cov",
79
- "cov-report",
80
- ]
89
+ type = "virtual"
90
+ path = ".venv"
81
91
 
82
- [[tool.hatch.envs.all.matrix]]
83
- python = ["3.13"]
84
-
85
- [tool.hatch.envs.lint]
86
- detached = true
87
- dependencies = [
88
- "black>=23.1.0",
89
- "mypy>=1.0.0",
90
- "ruff>=0.0.243",
91
- ]
92
- [tool.hatch.envs.lint.scripts]
93
- typing = "mypy --ignore-missing-imports --install-types --non-interactive {args:src/intellireading tests}"
94
- style = [
95
- "ruff check {args:.}",
96
- "black --check --diff {args:.}",
97
- ]
98
- fmt = [
99
- "black {args:.}",
100
- "ruff --fix {args:.}",
101
- "style",
102
- ]
103
- all = [
104
- "style",
105
- "typing",
106
- ]
107
-
108
- [tool.black]
109
- target-version = ["py37"]
110
- line-length = 120
111
- skip-string-normalization = true
92
+ [tool.hatch.envs.default.scripts]
93
+ lint = "ruff check . --fix"
94
+ format = "ruff format ."
95
+ lint-check = "ruff check ."
96
+ format-check = "ruff format --check ."
97
+ test = "pytest"
98
+ typecheck = "mypy"
99
+ validate = ["lint", "format", "test", "typecheck"]
100
+ check = ["lint-check", "format-check", "test", "typecheck"]
112
101
 
113
102
  [tool.ruff]
114
- target-version = "py37"
103
+ target-version = "py313"
115
104
  line-length = 120
116
105
  lint.select = [
117
106
  "A",
@@ -169,6 +158,9 @@ ban-relative-imports = "all"
169
158
  # Tests can use magic values, assertions, and relative imports
170
159
  "tests/**/*" = ["PLR2004", "S101", "TID252"]
171
160
 
161
+ [tool.ruff.format]
162
+ quote-style = "double"
163
+
172
164
  [tool.coverage.run]
173
165
  source_pkgs = ["intellireading", "tests"]
174
166
  branch = true
@@ -182,8 +174,36 @@ intellireading = ["src/intellireading", "*/intellireading-cli/src/intellireading
182
174
  tests = ["tests", "*/intellireading-cli/tests"]
183
175
 
184
176
  [tool.coverage.report]
177
+ show_missing = true
178
+ skip_covered = false
179
+ fail_under = 75
185
180
  exclude_lines = [
186
- "no cov",
181
+ "pragma: no cover",
182
+ "raise AssertionError",
183
+ "raise NotImplementedError",
187
184
  "if __name__ == .__main__.:",
188
185
  "if TYPE_CHECKING:",
189
186
  ]
187
+
188
+ [tool.pytest.ini_options]
189
+ addopts = "--tb=short --strict-markers --cov --cov-report=term-missing"
190
+ pythonpath = ["src"]
191
+ testpaths = ["tests"]
192
+
193
+ [tool.mypy]
194
+ python_version = "3.13"
195
+ strict = true
196
+ incremental = false
197
+ check_untyped_defs = true
198
+ mypy_path = ["src"]
199
+ files = ["src/intellireading"]
200
+ exclude = ["tests/"]
201
+
202
+ [[tool.mypy.overrides]]
203
+ module = ["lxml.*"]
204
+ ignore_missing_imports = true
205
+
206
+ [[tool.mypy.overrides]]
207
+ module = "tests.*"
208
+ disallow_untyped_defs = false
209
+ disallow_incomplete_defs = false
@@ -0,0 +1 @@
1
+ __version__ = "2.1.2"
@@ -1,4 +1,5 @@
1
1
  import click
2
+ from intellireading.client.__about_cli__ import __version__
2
3
  from intellireading.client.commands import (
3
4
  metaguide_epub_cmd,
4
5
  metaguide_xhtml_cmd,
@@ -11,6 +12,7 @@ from intellireading.client.commands import (
11
12
  chain=True,
12
13
  help="A set of tools designed to improve your reading experience.",
13
14
  )
15
+ @click.version_option(version=__version__)
14
16
  @click.option(
15
17
  "--log_level",
16
18
  default="WARNING",
@@ -18,7 +20,7 @@ from intellireading.client.commands import (
18
20
  help="The log level to use for logging (default: INFO). Possible values: DEBUG, INFO, WARNING, ERROR, CRITICAL",
19
21
  )
20
22
  @click.pass_context
21
- def cli(ctx: click.Context, log_level: str):
23
+ def cli(ctx: click.Context, log_level: str) -> None:
22
24
  ctx.ensure_object(dict)
23
25
 
24
26
  import logging
@@ -32,7 +34,7 @@ cli.add_command(metaguide_dir_cmd)
32
34
  cli.add_command(metaguide_xhtml_cmd)
33
35
 
34
36
 
35
- def entrypoint():
37
+ def entrypoint() -> None:
36
38
  cli(obj={})
37
39
 
38
40
 
@@ -2,7 +2,8 @@ import click
2
2
  import logging
3
3
  import sys
4
4
  from intellireading.client.metaguiding import metaguide_epub_file, metaguide_dir, metaguide_xhtml_file
5
- from typing import Callable, Any
5
+ from typing import Any, cast
6
+ from collections.abc import Callable
6
7
 
7
8
  _logger = logging.getLogger(__name__)
8
9
 
@@ -52,7 +53,7 @@ _remove_metaguiding_option = click.option(
52
53
  )
53
54
 
54
55
 
55
- def _exit_with_exception(exception: Exception, exit_code: int = 1, fg: str = "red"):
56
+ def _exit_with_exception(exception: Exception, exit_code: int = 1, fg: str = "red") -> None:
56
57
  """Exit the program with an exception and exit code"""
57
58
  try:
58
59
  _logger.exception(exception)
@@ -78,9 +79,9 @@ def _get_from_ctx_if_none(
78
79
  if value:
79
80
  return value
80
81
  elif ctx.obj.get(ctx_key):
81
- return ctx.obj[ctx_key]
82
+ return cast(str, ctx.obj[ctx_key])
82
83
  else:
83
- result = ctx.invoke(invoke_func, **kwargs)
84
+ result: str = ctx.invoke(invoke_func, **kwargs)
84
85
  return result
85
86
 
86
87
 
@@ -92,7 +93,7 @@ def _get_from_ctx_if_none(
92
93
  @_input_file_option
93
94
  @_output_file_option
94
95
  @_remove_metaguiding_option
95
- def metaguide_epub_cmd(ctx: click.Context, input_file: str, output_file: str, *, remove_metaguiding: bool):
96
+ def metaguide_epub_cmd(ctx: click.Context, input_file: str, output_file: str, *, remove_metaguiding: bool) -> None:
96
97
  """Applies or removes metaguiding to the provided epub/kepub file"""
97
98
 
98
99
  try:
@@ -123,7 +124,7 @@ def metaguide_epub_cmd(ctx: click.Context, input_file: str, output_file: str, *,
123
124
  @_input_dir_option
124
125
  @_output_dir_option
125
126
  @_remove_metaguiding_option
126
- def metaguide_dir_cmd(ctx: click.Context, input_dir: str, output_dir: str, *, remove_metaguiding: bool):
127
+ def metaguide_dir_cmd(ctx: click.Context, input_dir: str, output_dir: str, *, remove_metaguiding: bool) -> None:
127
128
  """Applies metaguiding to the provided directory, recursively, for all epubs and xhtml files found in the directory
128
129
  input_dir: str
129
130
  The input directory
@@ -161,7 +162,7 @@ def metaguide_dir_cmd(ctx: click.Context, input_dir: str, output_dir: str, *, re
161
162
  @_input_file_option
162
163
  @_output_file_option
163
164
  @_remove_metaguiding_option
164
- def metaguide_xhtml_cmd(ctx: click.Context, input_file: str, output_file: str, *, remove_metaguiding: bool):
165
+ def metaguide_xhtml_cmd(ctx: click.Context, input_file: str, output_file: str, *, remove_metaguiding: bool) -> None:
165
166
  """Applies or removes metaguiding to the provided xhtml file"""
166
167
 
167
168
  try:
@@ -4,7 +4,8 @@ import os
4
4
  import sys
5
5
  import traceback
6
6
  import zipfile
7
- from typing import Generator
7
+ from collections.abc import Generator
8
+ from typing import cast
8
9
  import math
9
10
  import regex as re
10
11
 
@@ -146,7 +147,7 @@ class RegExBoldMetaguider:
146
147
  parser = etree.XMLParser(resolve_entities=False)
147
148
  doc = etree.fromstring(xhtml_document, parser=parser).getroottree()
148
149
  docinfo = doc.docinfo
149
- return docinfo.encoding
150
+ return cast(str | None, docinfo.encoding)
150
151
  except etree.XMLSyntaxError:
151
152
  return None
152
153
 
@@ -169,15 +170,17 @@ class RegExBoldMetaguider:
169
170
  if not xhtml_document.startswith(b"<?xml "):
170
171
  return None
171
172
 
172
- xml_header_end = xhtml_document.find(b"?>") + 1
173
- if xml_header_end == 0:
174
- msg = "Invalid XHTML document. Could not find closing XML element."
175
- raise ValueError(msg)
173
+ xml_header_end = xhtml_document.find(b"?>")
174
+ if xml_header_end == -1:
175
+ # a truncated XML header is invalid, but should not prevent the remaining
176
+ # encoding detectors (BOM and lxml) from running
177
+ _logger.debug("XML header has no closing '?>'. Trying other encoding detection methods.")
178
+ return None
176
179
 
177
- header = xhtml_document[:xml_header_end].decode("utf-8")
180
+ header = xhtml_document[: xml_header_end + 2].decode("utf-8")
178
181
  match = re.search(r'encoding=(["\'])([a-zA-Z][a-zA-Z0-9-]{0,38}[a-zA-Z0-9])\1', header)
179
182
  if match:
180
- return match.group(2)
183
+ return cast(str, match.group(2))
181
184
  else:
182
185
  # although the XML header is present, it does not contain an encoding
183
186
  # this is not a valid XHTML document, but we can still try to detect the encoding on a later stage
@@ -212,7 +215,6 @@ class RegExBoldMetaguider:
212
215
 
213
216
 
214
217
  class _EpubItemFile:
215
-
216
218
  def __init__(self, filename: str | None = None, content: bytes = b"") -> None:
217
219
  self.filename = filename
218
220
  self.content = content
@@ -234,7 +236,7 @@ class _EpubItemFile:
234
236
  def __str__(self) -> str:
235
237
  return f"{self.filename} ({len(self.content)} bytes)"
236
238
 
237
- def metaguide(self, metaguider: RegExBoldMetaguider, *, remove_metaguiding: bool = False):
239
+ def metaguide(self, metaguider: RegExBoldMetaguider, *, remove_metaguiding: bool = False) -> None:
238
240
  if not remove_metaguiding and self.metaguided:
239
241
  _logger.warning(f"File {self.filename} already metaguided, skipping")
240
242
  elif self.is_toc_document:
@@ -251,7 +253,7 @@ class _EpubItemFile:
251
253
  _metaguider = RegExBoldMetaguider()
252
254
 
253
255
 
254
- def _get_epub_item_files_from_zip(input_zip: zipfile.ZipFile) -> list:
256
+ def _get_epub_item_files_from_zip(input_zip: zipfile.ZipFile) -> list[_EpubItemFile]:
255
257
  def read_compressed_file(input_zip: zipfile.ZipFile, filename: str) -> _EpubItemFile:
256
258
  return _EpubItemFile(filename, input_zip.read(filename))
257
259
 
@@ -262,15 +264,15 @@ def _get_epub_item_files_from_zip(input_zip: zipfile.ZipFile) -> list:
262
264
 
263
265
  def _process_epub_item_files(
264
266
  epub_item_files: list[_EpubItemFile], *, remove_metaguiding: bool = False
265
- ) -> Generator[_EpubItemFile, None, None]:
267
+ ) -> Generator[_EpubItemFile]:
266
268
  for epub_item_file in epub_item_files:
267
269
  _logger.debug(f"Processing file '{epub_item_file.filename}' remove_metaguiding={remove_metaguiding}")
268
270
  epub_item_file.metaguide(_metaguider, remove_metaguiding=remove_metaguiding)
269
271
  yield epub_item_file
270
272
 
271
273
 
272
- def _write_item_files_to_zip(epub_item_files, output_zip):
273
- def write_compressed_file(output_zip: zipfile.ZipFile, epub_item_file: _EpubItemFile):
274
+ def _write_item_files_to_zip(epub_item_files: list[_EpubItemFile], output_zip: zipfile.ZipFile) -> None:
275
+ def write_compressed_file(output_zip: zipfile.ZipFile, epub_item_file: _EpubItemFile) -> None:
274
276
  if epub_item_file.filename is None:
275
277
  msg = "EpubItemFile.filename is None"
276
278
  raise ValueError(msg)
@@ -283,14 +285,14 @@ def _write_item_files_to_zip(epub_item_files, output_zip):
283
285
  write_compressed_file(output_zip, _epub_item_file)
284
286
 
285
287
 
286
- def _ensure_file_exists(input_file: str):
288
+ def _ensure_file_exists(input_file: str) -> None:
287
289
  if not os.path.isfile(input_file):
288
290
  exception_message = f"Input file '{input_file}' does not exist"
289
291
  _logger.error(exception_message)
290
292
  raise ValueError(exception_message)
291
293
 
292
294
 
293
- def _ensure_allowed_extension(input_file: str, extensions: list[str]):
295
+ def _ensure_allowed_extension(input_file: str, extensions: list[str]) -> None:
294
296
  file_extension = os.path.splitext(input_file)[-1].upper()
295
297
  if file_extension not in extensions:
296
298
  exception_message = f"Input file '{input_file}' extension is not in {extensions}"
@@ -326,7 +328,7 @@ def _check_flag_file(
326
328
  return is_already_metaguided, flag_file
327
329
 
328
330
 
329
- def metaguide_epub_file(input_file: str, output_file: str, *, remove_metaguiding: bool = False):
331
+ def metaguide_epub_file(input_file: str, output_file: str, *, remove_metaguiding: bool = False) -> None:
330
332
  """Metaguide an epub file
331
333
  input_file: str
332
334
  The input epub file
@@ -400,7 +402,7 @@ def metaguide_epub_stream(input_stream: BytesIO, *, remove_metaguiding: bool = F
400
402
  return output_stream
401
403
 
402
404
 
403
- def metaguide_xhtml_file(input_file: str, output_file: str, *, remove_metaguiding: bool = False):
405
+ def metaguide_xhtml_file(input_file: str, output_file: str, *, remove_metaguiding: bool = False) -> None:
404
406
  """Metaguide an xhtml file
405
407
  input_file: str
406
408
  The input xhtml file
@@ -438,7 +440,7 @@ def metaguide_xhtml_stream(input_file_stream: BytesIO, *, remove_metaguiding: bo
438
440
  return output_file_stream
439
441
 
440
442
 
441
- def metaguide_dir(input_dir: str, output_dir: str, *, remove_metaguiding: bool = False):
443
+ def metaguide_dir(input_dir: str, output_dir: str, *, remove_metaguiding: bool = False) -> None:
442
444
  """Metaguides all epubs and xhtml found in a directory (recursively)
443
445
  input_dir: str
444
446
  The input epub/xhtml directory
@@ -450,7 +452,7 @@ def metaguide_dir(input_dir: str, output_dir: str, *, remove_metaguiding: bool =
450
452
 
451
453
  # get a list of all the files in the directory, and the child directories if recursive
452
454
  # verify if the file is a file and if it has the correct extension
453
- def get_files(directory, recursive):
455
+ def get_files(directory: str, *, recursive: bool) -> Generator[str]:
454
456
  for filename in os.listdir(directory):
455
457
  input_filename = os.path.join(directory, filename)
456
458
 
@@ -458,7 +460,7 @@ def metaguide_dir(input_dir: str, output_dir: str, *, remove_metaguiding: bool =
458
460
  if os.path.isfile(input_filename) and (extension in _EPUB_EXTENSIONS or extension in _XHTML_EXTENSIONS):
459
461
  yield input_filename
460
462
  elif os.path.isdir(input_filename) and recursive:
461
- yield from get_files(input_filename, recursive)
463
+ yield from get_files(input_filename, recursive=recursive)
462
464
 
463
465
  _logger.info(f"Processing files in {input_dir} to {output_dir} (recursively)")
464
466
 
@@ -471,7 +473,7 @@ def metaguide_dir(input_dir: str, output_dir: str, *, remove_metaguiding: bool =
471
473
  _logger.info(f"Creating {output_dir}")
472
474
  os.makedirs(output_dir)
473
475
 
474
- for input_filename in get_files(input_dir, True):
476
+ for input_filename in get_files(input_dir, recursive=True):
475
477
  output_filename = os.path.join(output_dir, os.path.basename(input_filename))
476
478
  _logger.debug(f"Processing {input_filename} to {output_filename}")
477
479
 
@@ -1,8 +0,0 @@
1
- __pycache__
2
- *.venv
3
- *.json
4
- .debug
5
- .coverage
6
- dist/*
7
- app/*
8
- tests/test_files/output
@@ -1 +0,0 @@
1
- __version__ = "2.1.1"