intellireading-cli 2.0.0__tar.gz → 2.1.0__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.
- {intellireading_cli-2.0.0 → intellireading_cli-2.1.0}/PKG-INFO +43 -16
- {intellireading_cli-2.0.0 → intellireading_cli-2.1.0}/README.md +37 -11
- intellireading_cli-2.1.0/intellireading/client/__about_cli__.py +1 -0
- intellireading_cli-2.1.0/intellireading/client/__init__.py +10 -0
- {intellireading_cli-2.0.0 → intellireading_cli-2.1.0}/intellireading/client/commands.py +40 -25
- intellireading_cli-2.1.0/intellireading/client/metaguiding.py +521 -0
- {intellireading_cli-2.0.0 → intellireading_cli-2.1.0}/pyproject.toml +10 -6
- intellireading_cli-2.0.0/intellireading/client/__about__.py +0 -1
- intellireading_cli-2.0.0/intellireading/client/__init__.py +0 -4
- intellireading_cli-2.0.0/intellireading/client/metaguiding.py +0 -181
- intellireading_cli-2.0.0/intellireading/client/regex.py +0 -126
- {intellireading_cli-2.0.0 → intellireading_cli-2.1.0}/.gitignore +0 -0
- {intellireading_cli-2.0.0 → intellireading_cli-2.1.0}/LICENSE +0 -0
- {intellireading_cli-2.0.0 → intellireading_cli-2.1.0}/intellireading/client/__main__.py +0 -0
- {intellireading_cli-2.0.0 → intellireading_cli-2.1.0}/intellireading/client/app.py +0 -0
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: intellireading-cli
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.1.0
|
|
4
4
|
Summary: Intellireading-cli is a Python library with a set of tools to improve your reading experience
|
|
5
|
-
Project-URL: Documentation, https://
|
|
6
|
-
Project-URL: Issues, https://
|
|
7
|
-
Project-URL: Source, https://
|
|
8
|
-
Author:
|
|
5
|
+
Project-URL: Documentation, https://go.hugobatista.com/gh/intellireading-cli#readme
|
|
6
|
+
Project-URL: Issues, https://go.hugobatista.com/gh/intellireading-cli/issues
|
|
7
|
+
Project-URL: Source, https://go.hugobatista.com/gh/intellireading-cli
|
|
8
|
+
Author: Hugo Batista
|
|
9
9
|
License-Expression: GPL-3.0
|
|
10
10
|
License-File: LICENSE
|
|
11
11
|
Keywords: adhd,calibre,dyslexia,ebook,epub,kepub,kindle,kobo,speed-reading
|
|
@@ -29,16 +29,17 @@ Classifier: Topic :: Utilities
|
|
|
29
29
|
Requires-Python: >=3.13
|
|
30
30
|
Requires-Dist: click>=8.1.7
|
|
31
31
|
Requires-Dist: lxml>=4.9.2
|
|
32
|
+
Requires-Dist: regex>=2024.11.6
|
|
32
33
|
Description-Content-Type: text/markdown
|
|
33
34
|
|
|
34
|
-

|
|
35
36
|
# Standalone tool and library
|
|
36
37
|
|
|
37
38
|
[](https://pypi.org/project/intellireading-cli)
|
|
38
39
|
[](https://pypi.org/project/intellireading-cli)
|
|
39
|
-
[](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/build-and-publish-to-ghcr.yml)
|
|
41
|
+
[](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/lint.yml)
|
|
42
|
+
[](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/test.yml)
|
|
42
43
|
|
|
43
44
|
|
|
44
45
|
Intellireading is a CLI tool with commands to accelerate your reading experience. It can also be used as a python library.
|
|
@@ -47,16 +48,16 @@ Currently, it supports metaguiding an EPUB, KEPUB, XHTML, or HTML file (more fea
|
|
|
47
48
|
> intellireading metaguide-epub --input_file mybook.epub --output_file mybook_metaguided.epub
|
|
48
49
|
```
|
|
49
50
|
Example of a text converted to a metaguided text:
|
|
50
|
-

|
|
51
52
|
|
|
52
53
|
|
|
53
54
|
This repo is part of the [Intellireading](https://intellireading.com/) project, which aims to help people with dyslexia, ADHD, or anyone who wants to improve their reading focus and speed.
|
|
54
55
|
|
|
55
|
-
## [Other Intellireading Code Repositories](https://
|
|
56
|
-
- [Intellireading website](https://
|
|
57
|
-
- [
|
|
58
|
-
- [CLI Tool](https://
|
|
59
|
-
- [Calibre Plugins](https://
|
|
56
|
+
## [Other Intellireading Code Repositories](https://go.hugobatista.com/ghstars/lists/intellireading)
|
|
57
|
+
- [Intellireading website](https://go.hugobatista.com/gh/intellireading-www), which allows anyone to convert an Epub to the metaguided version.
|
|
58
|
+
- [API Server](https://go.hugobatista.com/gh/intellireading-api_server), that support the Intellireading website.
|
|
59
|
+
- [CLI Tool](https://go.hugobatista.com/gh/intellireading-cli). A standalone tool and library that can be used to metaguide epub files.
|
|
60
|
+
- [Calibre Plugins](https://go.hugobatista.com/gh/intellireading-calibre-plugins). A set of plugins that can be used to metaguide epub files using Calibre.
|
|
60
61
|
|
|
61
62
|
|
|
62
63
|
## What is Epub Metaguiding?
|
|
@@ -87,7 +88,7 @@ To install it, you can use pip:
|
|
|
87
88
|
### From source code
|
|
88
89
|
You can also install it from the source code:
|
|
89
90
|
```console
|
|
90
|
-
> git clone https://
|
|
91
|
+
> git clone https://go.hugobatista.com/gh/intellireading-cli.git
|
|
91
92
|
> cd intellireading-cli
|
|
92
93
|
> pip install .
|
|
93
94
|
> intellireading --help
|
|
@@ -150,3 +151,29 @@ To metaguide all files in a directory, use the `metaguide-dir` command. The comm
|
|
|
150
151
|
> intellireading metaguide-dir --input_dir mydir --output_dir mydir_metaguided
|
|
151
152
|
```
|
|
152
153
|
|
|
154
|
+
## Experimental Features
|
|
155
|
+
Some features are still experimental and may not work as expected. Use them with caution.
|
|
156
|
+
|
|
157
|
+
### Remove metaguiding
|
|
158
|
+
The remove metaguiding feature allows you to remove metaguiding from previous metaguided files. This implementation is still experimental and may not work as expected, since it is not possible to recover the original text. The current implementation tries to remove the metaguiding by removing the bold tags from the text, but that may imply in some original text format loss.
|
|
159
|
+
|
|
160
|
+
#### Remove metaguiding from an EPUB file
|
|
161
|
+
To remove metaguiding from an EPUB file, use the --remove_metaguiding flag. The command requires the path to the EPUB file and the output file. The output file will be an epub file without metaguiding.
|
|
162
|
+
|
|
163
|
+
```console
|
|
164
|
+
> intellireading metaguide-epub --remove_metaguiding --input_file mybook_metaguided.epub --output_file mybook.epub
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
#### Remove metaguiding from a XHTML file
|
|
168
|
+
To remove metaguiding from a XHTML file, use the --remove_metaguiding flag. The command requires the path to the XHTML file and the output file. The output file will be an xhtml file without metaguiding.
|
|
169
|
+
|
|
170
|
+
```console
|
|
171
|
+
> intellireading metaguide-xhtml --remove_metaguiding --input_file mybook_metaguided.xhtml --output_file mybook.xhtml
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
#### Remove metaguiding from all files in a directory
|
|
175
|
+
To remove metaguiding from all files in a directory, use the --remove_metaguiding flag. The command requires the path to the directory and the output directory. The output directory will contain all files without metaguiding, including epub, xhtml and html files.
|
|
176
|
+
|
|
177
|
+
```console
|
|
178
|
+
> intellireading metaguide-dir --remove_metaguiding --input_dir mydir_metaguided --output_dir mydir
|
|
179
|
+
```
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-

|
|
2
2
|
# Standalone tool and library
|
|
3
3
|
|
|
4
4
|
[](https://pypi.org/project/intellireading-cli)
|
|
5
5
|
[](https://pypi.org/project/intellireading-cli)
|
|
6
|
-
[](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/build-and-publish-to-ghcr.yml)
|
|
7
|
+
[](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/lint.yml)
|
|
8
|
+
[](https://go.hugobatista.com/gh/intellireading-cli/actions/workflows/test.yml)
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
Intellireading is a CLI tool with commands to accelerate your reading experience. It can also be used as a python library.
|
|
@@ -14,16 +14,16 @@ Currently, it supports metaguiding an EPUB, KEPUB, XHTML, or HTML file (more fea
|
|
|
14
14
|
> intellireading metaguide-epub --input_file mybook.epub --output_file mybook_metaguided.epub
|
|
15
15
|
```
|
|
16
16
|
Example of a text converted to a metaguided text:
|
|
17
|
-

|
|
18
18
|
|
|
19
19
|
|
|
20
20
|
This repo is part of the [Intellireading](https://intellireading.com/) project, which aims to help people with dyslexia, ADHD, or anyone who wants to improve their reading focus and speed.
|
|
21
21
|
|
|
22
|
-
## [Other Intellireading Code Repositories](https://
|
|
23
|
-
- [Intellireading website](https://
|
|
24
|
-
- [
|
|
25
|
-
- [CLI Tool](https://
|
|
26
|
-
- [Calibre Plugins](https://
|
|
22
|
+
## [Other Intellireading Code Repositories](https://go.hugobatista.com/ghstars/lists/intellireading)
|
|
23
|
+
- [Intellireading website](https://go.hugobatista.com/gh/intellireading-www), which allows anyone to convert an Epub to the metaguided version.
|
|
24
|
+
- [API Server](https://go.hugobatista.com/gh/intellireading-api_server), that support the Intellireading website.
|
|
25
|
+
- [CLI Tool](https://go.hugobatista.com/gh/intellireading-cli). A standalone tool and library that can be used to metaguide epub files.
|
|
26
|
+
- [Calibre Plugins](https://go.hugobatista.com/gh/intellireading-calibre-plugins). A set of plugins that can be used to metaguide epub files using Calibre.
|
|
27
27
|
|
|
28
28
|
|
|
29
29
|
## What is Epub Metaguiding?
|
|
@@ -54,7 +54,7 @@ To install it, you can use pip:
|
|
|
54
54
|
### From source code
|
|
55
55
|
You can also install it from the source code:
|
|
56
56
|
```console
|
|
57
|
-
> git clone https://
|
|
57
|
+
> git clone https://go.hugobatista.com/gh/intellireading-cli.git
|
|
58
58
|
> cd intellireading-cli
|
|
59
59
|
> pip install .
|
|
60
60
|
> intellireading --help
|
|
@@ -117,3 +117,29 @@ To metaguide all files in a directory, use the `metaguide-dir` command. The comm
|
|
|
117
117
|
> intellireading metaguide-dir --input_dir mydir --output_dir mydir_metaguided
|
|
118
118
|
```
|
|
119
119
|
|
|
120
|
+
## Experimental Features
|
|
121
|
+
Some features are still experimental and may not work as expected. Use them with caution.
|
|
122
|
+
|
|
123
|
+
### Remove metaguiding
|
|
124
|
+
The remove metaguiding feature allows you to remove metaguiding from previous metaguided files. This implementation is still experimental and may not work as expected, since it is not possible to recover the original text. The current implementation tries to remove the metaguiding by removing the bold tags from the text, but that may imply in some original text format loss.
|
|
125
|
+
|
|
126
|
+
#### Remove metaguiding from an EPUB file
|
|
127
|
+
To remove metaguiding from an EPUB file, use the --remove_metaguiding flag. The command requires the path to the EPUB file and the output file. The output file will be an epub file without metaguiding.
|
|
128
|
+
|
|
129
|
+
```console
|
|
130
|
+
> intellireading metaguide-epub --remove_metaguiding --input_file mybook_metaguided.epub --output_file mybook.epub
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
#### Remove metaguiding from a XHTML file
|
|
134
|
+
To remove metaguiding from a XHTML file, use the --remove_metaguiding flag. The command requires the path to the XHTML file and the output file. The output file will be an xhtml file without metaguiding.
|
|
135
|
+
|
|
136
|
+
```console
|
|
137
|
+
> intellireading metaguide-xhtml --remove_metaguiding --input_file mybook_metaguided.xhtml --output_file mybook.xhtml
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
#### Remove metaguiding from all files in a directory
|
|
141
|
+
To remove metaguiding from all files in a directory, use the --remove_metaguiding flag. The command requires the path to the directory and the output directory. The output directory will contain all files without metaguiding, including epub, xhtml and html files.
|
|
142
|
+
|
|
143
|
+
```console
|
|
144
|
+
> intellireading metaguide-dir --remove_metaguiding --input_dir mydir_metaguided --output_dir mydir
|
|
145
|
+
```
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "2.1.0"
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import click
|
|
2
2
|
import logging
|
|
3
3
|
import sys
|
|
4
|
-
from intellireading.client.metaguiding import
|
|
4
|
+
from intellireading.client.metaguiding import metaguide_epub_file, metaguide_dir, metaguide_xhtml_file
|
|
5
5
|
from typing import Callable, Any
|
|
6
|
-
from io import BytesIO
|
|
7
6
|
|
|
8
7
|
_logger = logging.getLogger(__name__)
|
|
9
8
|
|
|
@@ -44,6 +43,14 @@ _input_dir_option = click.option(
|
|
|
44
43
|
help="The directory to read from",
|
|
45
44
|
)
|
|
46
45
|
|
|
46
|
+
_remove_metaguiding_option = click.option(
|
|
47
|
+
"--remove_metaguiding",
|
|
48
|
+
is_flag=True,
|
|
49
|
+
show_default=True,
|
|
50
|
+
default=False,
|
|
51
|
+
help="Remove metaguiding from the files (EXPERIMENTAL)",
|
|
52
|
+
)
|
|
53
|
+
|
|
47
54
|
|
|
48
55
|
def _exit_with_exception(exception: Exception, exit_code: int = 1, fg: str = "red"):
|
|
49
56
|
"""Exit the program with an exception and exit code"""
|
|
@@ -79,28 +86,29 @@ def _get_from_ctx_if_none(
|
|
|
79
86
|
|
|
80
87
|
@click.command(
|
|
81
88
|
"metaguide-epub",
|
|
82
|
-
help="Applies metaguiding to the provided epub/kepub file",
|
|
89
|
+
help="Applies or removes metaguiding to the provided epub/kepub file",
|
|
83
90
|
)
|
|
84
91
|
@click.pass_context
|
|
85
92
|
@_input_file_option
|
|
86
93
|
@_output_file_option
|
|
87
|
-
|
|
88
|
-
|
|
94
|
+
@_remove_metaguiding_option
|
|
95
|
+
def metaguide_epub_cmd(ctx: click.Context, input_file: str, output_file: str, *, remove_metaguiding: bool):
|
|
96
|
+
"""Applies or removes metaguiding to the provided epub/kepub file"""
|
|
89
97
|
|
|
90
98
|
try:
|
|
91
99
|
ctx.ensure_object(dict)
|
|
92
|
-
|
|
100
|
+
if remove_metaguiding:
|
|
101
|
+
click.secho("Removing metaguiding from epub...", fg="yellow")
|
|
102
|
+
else:
|
|
103
|
+
click.secho("Metaguiding epub...", fg="yellow")
|
|
93
104
|
|
|
94
105
|
input_file = _get_from_ctx_if_none(ctx, "output_file", input_file, lambda: click.prompt("The input file"))
|
|
95
106
|
click.echo(f"Input file: {input_file}")
|
|
96
107
|
output_file = _get_from_ctx_if_none(ctx, "output_file", output_file, lambda: click.prompt("The output file"))
|
|
97
108
|
click.echo(f"Output file: {output_file}")
|
|
98
109
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
output_file_stream = metaguide_epub(input_file_stream)
|
|
102
|
-
with open(output_file, "wb") as output_writer:
|
|
103
|
-
output_writer.write(output_file_stream.read())
|
|
110
|
+
metaguide_epub_file(input_file, output_file, remove_metaguiding=remove_metaguiding)
|
|
111
|
+
|
|
104
112
|
# store the output file in the context for chaining commands
|
|
105
113
|
ctx.obj["output_file"] = output_file
|
|
106
114
|
except Exception as e:
|
|
@@ -109,22 +117,28 @@ def metaguide_epub_cmd(ctx: click.Context, input_file: str, output_file: str):
|
|
|
109
117
|
|
|
110
118
|
@click.command(
|
|
111
119
|
"metaguide-dir",
|
|
112
|
-
help="Applies metaguiding to the provided directory, recursively, for all epubs and xhtml files",
|
|
120
|
+
help="Applies or removes metaguiding to the provided directory, recursively, for all epubs and xhtml files",
|
|
113
121
|
)
|
|
114
122
|
@click.pass_context
|
|
115
123
|
@_input_dir_option
|
|
116
124
|
@_output_dir_option
|
|
117
|
-
|
|
125
|
+
@_remove_metaguiding_option
|
|
126
|
+
def metaguide_dir_cmd(ctx: click.Context, input_dir: str, output_dir: str, *, remove_metaguiding: bool):
|
|
118
127
|
"""Applies metaguiding to the provided directory, recursively, for all epubs and xhtml files found in the directory
|
|
119
128
|
input_dir: str
|
|
120
129
|
The input directory
|
|
121
130
|
output_dir: str
|
|
122
131
|
The output directory
|
|
132
|
+
remove_metaguiding: bool
|
|
133
|
+
If True, removes metaguiding from the files
|
|
123
134
|
"""
|
|
124
135
|
|
|
125
136
|
try:
|
|
126
137
|
ctx.ensure_object(dict)
|
|
127
|
-
|
|
138
|
+
if remove_metaguiding:
|
|
139
|
+
click.secho("Removing metaguiding from directory...", fg="yellow")
|
|
140
|
+
else:
|
|
141
|
+
click.secho("Metaguiding directory...", fg="yellow")
|
|
128
142
|
input_dir = _get_from_ctx_if_none(ctx, "input_dir", input_dir, lambda: click.prompt("The input directory"))
|
|
129
143
|
click.echo(f"Input directory: {input_dir}")
|
|
130
144
|
output_dir = _get_from_ctx_if_none(ctx, "output_dir", output_dir, lambda: click.prompt("The output directory"))
|
|
@@ -132,37 +146,38 @@ def metaguide_dir_cmd(ctx: click.Context, input_dir: str, output_dir: str):
|
|
|
132
146
|
|
|
133
147
|
# check if we have the same input and output directories
|
|
134
148
|
if input_dir == output_dir:
|
|
135
|
-
_exit_with_exception(ValueError("Input and output directories
|
|
149
|
+
_exit_with_exception(ValueError("Input and output directories cannot be the same. Exiting..."), fg="red")
|
|
136
150
|
|
|
137
|
-
metaguide_dir(input_dir, output_dir)
|
|
151
|
+
metaguide_dir(input_dir, output_dir, remove_metaguiding=remove_metaguiding)
|
|
138
152
|
except Exception as e:
|
|
139
153
|
_exit_with_exception(e)
|
|
140
154
|
|
|
141
155
|
|
|
142
156
|
@click.command(
|
|
143
157
|
"metaguide-xhtml",
|
|
144
|
-
help="Applies metaguiding to the provided xhtml file",
|
|
158
|
+
help="Applies or removes metaguiding to the provided xhtml file",
|
|
145
159
|
)
|
|
146
160
|
@click.pass_context
|
|
147
161
|
@_input_file_option
|
|
148
162
|
@_output_file_option
|
|
149
|
-
|
|
150
|
-
|
|
163
|
+
@_remove_metaguiding_option
|
|
164
|
+
def metaguide_xhtml_cmd(ctx: click.Context, input_file: str, output_file: str, *, remove_metaguiding: bool):
|
|
165
|
+
"""Applies or removes metaguiding to the provided xhtml file"""
|
|
151
166
|
|
|
152
167
|
try:
|
|
153
168
|
ctx.ensure_object(dict)
|
|
154
|
-
|
|
169
|
+
if remove_metaguiding:
|
|
170
|
+
click.secho("Removing metaguiding from xhtml...", fg="yellow")
|
|
171
|
+
else:
|
|
172
|
+
click.secho("Metaguiding xhtml...", fg="yellow")
|
|
155
173
|
|
|
156
174
|
input_file = _get_from_ctx_if_none(ctx, "output_file", input_file, lambda: click.prompt("The input file"))
|
|
157
175
|
click.echo(f"Input file: {input_file}")
|
|
158
176
|
output_file = _get_from_ctx_if_none(ctx, "output_file", output_file, lambda: click.prompt("The output file"))
|
|
159
177
|
click.echo(f"Output file: {output_file}")
|
|
160
178
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
output_file_stream = metaguide_xhtml(input_file_stream)
|
|
164
|
-
with open(output_file, "wb") as output_writer:
|
|
165
|
-
output_writer.write(output_file_stream.read())
|
|
179
|
+
metaguide_xhtml_file(input_file, output_file, remove_metaguiding=remove_metaguiding)
|
|
180
|
+
|
|
166
181
|
# store the output file in the context for chaining commands
|
|
167
182
|
ctx.obj["output_file"] = output_file
|
|
168
183
|
except Exception as e:
|
|
@@ -0,0 +1,521 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from io import BytesIO
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
import traceback
|
|
6
|
+
import zipfile
|
|
7
|
+
from typing import Generator
|
|
8
|
+
import math
|
|
9
|
+
import regex as re
|
|
10
|
+
|
|
11
|
+
# relative import is used to ensure that when this module gets copied to another location
|
|
12
|
+
# it still works
|
|
13
|
+
from .__about_cli__ import __version__ as cli_version # noqa: TID252
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
_logger = logging.getLogger(__name__)
|
|
17
|
+
_METAGUIDED_FLAG_FILENAME = "intellireading.metaguide"
|
|
18
|
+
_EPUB_EXTENSIONS = [".EPUB", ".KEPUB"]
|
|
19
|
+
_XHTML_EXTENSIONS = [".XHTML", ".HTML", ".HTM"]
|
|
20
|
+
_TOC_FILENAMES = ["nav.xhtml", "nav.html", "toc.xhtml", "toc.html"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _generate_flag_file_content() -> bytes:
|
|
24
|
+
"""Generate the content for the metaguiding flag file.
|
|
25
|
+
This includes version, process name, and call graph information.
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
bytes: The encoded content of the flag file.
|
|
29
|
+
"""
|
|
30
|
+
try:
|
|
31
|
+
# Get process name - fallback to 'unknown' if sys.argv is not available
|
|
32
|
+
try:
|
|
33
|
+
process_name = os.path.basename(sys.argv[0])
|
|
34
|
+
except (AttributeError, IndexError):
|
|
35
|
+
process_name = "unknown"
|
|
36
|
+
_logger.warning("Could not determine process name, using 'unknown'")
|
|
37
|
+
|
|
38
|
+
# Get call stack information - handle potential traceback errors
|
|
39
|
+
try:
|
|
40
|
+
call_frames = traceback.extract_stack()
|
|
41
|
+
# Skip the last frame (current function) and metaguide_epub_stream frame
|
|
42
|
+
relevant_frames = call_frames[:-2]
|
|
43
|
+
call_graph_path = " -> ".join(
|
|
44
|
+
f"{os.path.basename(frame.filename)}:{frame.name}" for frame in relevant_frames
|
|
45
|
+
)
|
|
46
|
+
except Exception as e:
|
|
47
|
+
call_graph_path = "unknown"
|
|
48
|
+
_logger.warning(f"Could not generate call graph: {e}")
|
|
49
|
+
|
|
50
|
+
# Build and return the flag content
|
|
51
|
+
flag_lines = [f"version: {cli_version}", f"process: {process_name}", f"call_graph: {call_graph_path}"]
|
|
52
|
+
return "\n".join(flag_lines).encode()
|
|
53
|
+
except Exception as e:
|
|
54
|
+
# If anything goes wrong, return a minimal flag file rather than failing
|
|
55
|
+
_logger.error(f"Error generating flag file content: {e}")
|
|
56
|
+
return f"version: {cli_version}\nprocess: unknown\ncall_graph: error".encode()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class RegExBoldMetaguider:
|
|
60
|
+
_body_regex = re.compile(r"<body[^>]*>(.*)</body>", re.DOTALL)
|
|
61
|
+
_text_block_regex = re.compile(r"(?<!<b[^>]*)>[^\S]*[^\s<][^<]*[^\S\n]*<")
|
|
62
|
+
_bolded_text_block_regex = re.compile(r"<b>\b\w{1}\b</b>|<b>\b\w+\b</b>(?:\b\w+\b)")
|
|
63
|
+
_word_pattern_regex = re.compile(r"\b\w+\b", re.UNICODE)
|
|
64
|
+
_entity_ref_regex = re.compile(r"(&[#a-zA-Z][a-zA-Z0-9]*;)")
|
|
65
|
+
_bolded_word_regex = re.compile(r"<b>(.*?)</b>")
|
|
66
|
+
|
|
67
|
+
def __init__(self, fallback_encoding: str = "utf-8") -> None:
|
|
68
|
+
self._fallback_encoding = fallback_encoding
|
|
69
|
+
|
|
70
|
+
def _bold_word(self, word: str) -> str:
|
|
71
|
+
# this is the function that is called for each word
|
|
72
|
+
|
|
73
|
+
# if the word is an empty string, whitespace or new line, return it
|
|
74
|
+
if not word.strip():
|
|
75
|
+
return word
|
|
76
|
+
|
|
77
|
+
word_length = len(word)
|
|
78
|
+
midpoint = 1 if word_length in (1, 3) else math.ceil(word_length / 2)
|
|
79
|
+
return f"<b>{word[:midpoint]}</b>{word[midpoint:]}" # Bold the first half of the word
|
|
80
|
+
|
|
81
|
+
def _unbold_word(self, word: str) -> str:
|
|
82
|
+
# if the word is an empty string, whitespace or new line, return it
|
|
83
|
+
if not word.strip():
|
|
84
|
+
return word
|
|
85
|
+
|
|
86
|
+
# short-circuit if the word is not bolded
|
|
87
|
+
if "<b>" not in word:
|
|
88
|
+
return word
|
|
89
|
+
|
|
90
|
+
# remove the <b></b> tags
|
|
91
|
+
return self._bolded_word_regex.sub(r"\1", word)
|
|
92
|
+
|
|
93
|
+
def _bold_node_text_part(self, part: str) -> str:
|
|
94
|
+
# is this part an entity reference?
|
|
95
|
+
if self._entity_ref_regex.match(part):
|
|
96
|
+
return part
|
|
97
|
+
return self._word_pattern_regex.sub(lambda m: self._bold_word(m.group()), part)
|
|
98
|
+
|
|
99
|
+
def _unbold_node_text_part(self, part: str) -> str:
|
|
100
|
+
# skip if it's an entity reference
|
|
101
|
+
if self._entity_ref_regex.match(part):
|
|
102
|
+
_logger.debug(f"Skipping entity reference: {part}")
|
|
103
|
+
return part
|
|
104
|
+
# remove bold tags on all words found
|
|
105
|
+
result = self._unbold_word(part)
|
|
106
|
+
return result
|
|
107
|
+
|
|
108
|
+
def _bold_text_node(self, node: str) -> str:
|
|
109
|
+
# this is the function that is called for each text node
|
|
110
|
+
node_text = node[1:-1]
|
|
111
|
+
_logger.debug(f"Bold text node: {node_text}")
|
|
112
|
+
|
|
113
|
+
# split the node_text into parts based on the entity references
|
|
114
|
+
node_text_parts = self._entity_ref_regex.split(node_text)
|
|
115
|
+
|
|
116
|
+
new_node_text = "".join(map(self._bold_node_text_part, node_text_parts))
|
|
117
|
+
|
|
118
|
+
if node_text != new_node_text:
|
|
119
|
+
return ">" + new_node_text + "<"
|
|
120
|
+
return node
|
|
121
|
+
|
|
122
|
+
def _bold_document(self, html: str, *, remove_metaguiding: bool = False) -> str:
|
|
123
|
+
# get the body. If there is no body, return the original html
|
|
124
|
+
match = self._body_regex.search(html)
|
|
125
|
+
if not match:
|
|
126
|
+
return html
|
|
127
|
+
|
|
128
|
+
body = match.group(1)
|
|
129
|
+
if not remove_metaguiding:
|
|
130
|
+
# find all text nodes in the body and trigger the bolding of the words
|
|
131
|
+
body = self._text_block_regex.sub(
|
|
132
|
+
lambda m: self._bold_text_node(m.group()),
|
|
133
|
+
body,
|
|
134
|
+
)
|
|
135
|
+
else:
|
|
136
|
+
body = self._bolded_text_block_regex.sub(lambda m: self._unbold_node_text_part(m.group()), body)
|
|
137
|
+
|
|
138
|
+
_logger.debug(f"Bolded body: {body}")
|
|
139
|
+
|
|
140
|
+
html = html.replace(match.group(1), body)
|
|
141
|
+
return html
|
|
142
|
+
|
|
143
|
+
def _get_encoding_using_lxml(self, xhtml_document: bytes) -> str | None:
|
|
144
|
+
from lxml import etree
|
|
145
|
+
|
|
146
|
+
parser = etree.XMLParser(resolve_entities=False)
|
|
147
|
+
doc = etree.fromstring(xhtml_document, parser=parser).getroottree()
|
|
148
|
+
docinfo = doc.docinfo
|
|
149
|
+
return docinfo.encoding
|
|
150
|
+
|
|
151
|
+
def _get_encoding_using_bom(self, xhtml_document: bytes) -> str | None:
|
|
152
|
+
if xhtml_document.startswith(b"\xef\xbb\xbf"):
|
|
153
|
+
return "utf-8"
|
|
154
|
+
elif xhtml_document.startswith(b"\xff\xfe"):
|
|
155
|
+
return "utf-16-le"
|
|
156
|
+
elif xhtml_document.startswith(b"\xfe\xff"):
|
|
157
|
+
return "utf-16-be"
|
|
158
|
+
elif xhtml_document.startswith(b"\x00\x00\xfe\xff"):
|
|
159
|
+
return "utf-32-be"
|
|
160
|
+
elif xhtml_document.startswith(b"\xff\xfe\x00\x00"):
|
|
161
|
+
return "utf-32-le"
|
|
162
|
+
else:
|
|
163
|
+
return None
|
|
164
|
+
|
|
165
|
+
def _get_encoding_using_xml_header(self, xhtml_document: bytes) -> str | None:
|
|
166
|
+
# if the document does not start with an XML header, return None. This is not a xml document
|
|
167
|
+
if not xhtml_document.startswith(b"<?xml "):
|
|
168
|
+
return None
|
|
169
|
+
|
|
170
|
+
xml_header_end = xhtml_document.find(b"?>") + 1
|
|
171
|
+
if xml_header_end == 0:
|
|
172
|
+
msg = "Invalid XHTML document. Could not find closing XML element."
|
|
173
|
+
raise ValueError(msg)
|
|
174
|
+
|
|
175
|
+
header = xhtml_document[:xml_header_end].decode("utf-8")
|
|
176
|
+
match = re.search(r'encoding=(["\'])([a-zA-Z][a-zA-Z0-9-]{0,38}[a-zA-Z0-9])\1', header)
|
|
177
|
+
if match:
|
|
178
|
+
return match.group(2)
|
|
179
|
+
else:
|
|
180
|
+
# although the XML header is present, it does not contain an encoding
|
|
181
|
+
# this is not a valid XHTML document, but we can still try to detect the encoding on a later stage
|
|
182
|
+
# and we will not raise an exception
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
def _get_encoding(self, xhtml_document: bytes) -> str:
|
|
186
|
+
encoding = self._get_encoding_using_xml_header(xhtml_document)
|
|
187
|
+
|
|
188
|
+
if not encoding:
|
|
189
|
+
_logger.debug(
|
|
190
|
+
"Could not detect the encoding of the XHTML document using the XML header. "
|
|
191
|
+
"Trying to detect the encoding using the BOM."
|
|
192
|
+
)
|
|
193
|
+
encoding = self._get_encoding_using_bom(xhtml_document)
|
|
194
|
+
|
|
195
|
+
if not encoding:
|
|
196
|
+
_logger.debug(
|
|
197
|
+
"Could not detect the encoding of the XHTML document. Trying to detect the encoding using lxml."
|
|
198
|
+
)
|
|
199
|
+
encoding = self._get_encoding_using_lxml(xhtml_document)
|
|
200
|
+
|
|
201
|
+
return encoding or self._fallback_encoding
|
|
202
|
+
|
|
203
|
+
def metaguide_xhtml_document(self, xhtml_document: bytes, *, remove_metaguiding: bool = False) -> bytes:
|
|
204
|
+
# if none of the methods to detect the encoding work, use utf-8
|
|
205
|
+
encoding = self._get_encoding(xhtml_document) or "utf-8"
|
|
206
|
+
|
|
207
|
+
html = xhtml_document.decode(encoding)
|
|
208
|
+
bolded_html = self._bold_document(html, remove_metaguiding=remove_metaguiding)
|
|
209
|
+
return bolded_html.encode(encoding)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class _EpubItemFile:
|
|
213
|
+
|
|
214
|
+
def __init__(self, filename: str | None = None, content: bytes = b"") -> None:
|
|
215
|
+
self.filename = filename
|
|
216
|
+
self.content = content
|
|
217
|
+
_extension = (self.filename and os.path.splitext(self.filename)[-1].upper()) or None
|
|
218
|
+
|
|
219
|
+
# some epub have files with html extension but they are xml files
|
|
220
|
+
self.is_xhtml_document = _extension in _XHTML_EXTENSIONS
|
|
221
|
+
# check whether the file is a table of contents or navigation file
|
|
222
|
+
# by checking the filename against a list of known TOC filenames
|
|
223
|
+
# this is a heuristic and may not be 100% accurate.
|
|
224
|
+
# Separate the directory check from the filename check
|
|
225
|
+
self.is_toc_document = False
|
|
226
|
+
if self.filename:
|
|
227
|
+
# Normalize the filename to lowercase for comparison and remove the directory part
|
|
228
|
+
filename_base = os.path.basename(self.filename.lower())
|
|
229
|
+
self.is_toc_document = filename_base in _TOC_FILENAMES
|
|
230
|
+
self.metaguided = False # flag to indicate if the file has been metaguided. Useful for multi-threading
|
|
231
|
+
|
|
232
|
+
def __str__(self) -> str:
|
|
233
|
+
return f"{self.filename} ({len(self.content)} bytes)"
|
|
234
|
+
|
|
235
|
+
def metaguide(self, metaguider: RegExBoldMetaguider, *, remove_metaguiding: bool = False):
|
|
236
|
+
if not remove_metaguiding and self.metaguided:
|
|
237
|
+
_logger.warning(f"File {self.filename} already metaguided, skipping")
|
|
238
|
+
elif self.is_toc_document:
|
|
239
|
+
_logger.debug(f"Skipping nav/toc file {self.filename}")
|
|
240
|
+
elif self.is_xhtml_document:
|
|
241
|
+
_logger.debug(f"Metaguiding file {self.filename}")
|
|
242
|
+
self.content = metaguider.metaguide_xhtml_document(self.content, remove_metaguiding=remove_metaguiding)
|
|
243
|
+
self.metaguided = True
|
|
244
|
+
_logger.debug(f"Metaguided file {self.filename}")
|
|
245
|
+
else:
|
|
246
|
+
_logger.debug(f"Skipping file {self.filename}")
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
_metaguider = RegExBoldMetaguider()
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _get_epub_item_files_from_zip(input_zip: zipfile.ZipFile) -> list:
|
|
253
|
+
def read_compressed_file(input_zip: zipfile.ZipFile, filename: str) -> _EpubItemFile:
|
|
254
|
+
return _EpubItemFile(filename, input_zip.read(filename))
|
|
255
|
+
|
|
256
|
+
epub_item_files = [read_compressed_file(input_zip, f.filename) for f in input_zip.infolist()]
|
|
257
|
+
_logger.debug(f"Read {len(epub_item_files)} files from input file")
|
|
258
|
+
return epub_item_files
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _process_epub_item_files(
|
|
262
|
+
epub_item_files: list[_EpubItemFile], *, remove_metaguiding: bool = False
|
|
263
|
+
) -> Generator[_EpubItemFile, None, None]:
|
|
264
|
+
for epub_item_file in epub_item_files:
|
|
265
|
+
_logger.debug(f"Processing file '{epub_item_file.filename}' remove_metaguiding={remove_metaguiding}")
|
|
266
|
+
epub_item_file.metaguide(_metaguider, remove_metaguiding=remove_metaguiding)
|
|
267
|
+
yield epub_item_file
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _write_item_files_to_zip(epub_item_files, output_zip):
|
|
271
|
+
def write_compressed_file(output_zip: zipfile.ZipFile, epub_item_file: _EpubItemFile):
|
|
272
|
+
if epub_item_file.filename is None:
|
|
273
|
+
msg = "EpubItemFile.filename is None"
|
|
274
|
+
raise ValueError(msg)
|
|
275
|
+
|
|
276
|
+
_logger.debug(f"Writing file {epub_item_file.filename} to output zip {output_zip.filename}")
|
|
277
|
+
with output_zip.open(epub_item_file.filename, mode="w") as compressed_output_file:
|
|
278
|
+
compressed_output_file.write(epub_item_file.content)
|
|
279
|
+
|
|
280
|
+
for _epub_item_file in epub_item_files:
|
|
281
|
+
write_compressed_file(output_zip, _epub_item_file)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _ensure_file_exists(input_file: str):
|
|
285
|
+
if not os.path.isfile(input_file):
|
|
286
|
+
exception_message = f"Input file '{input_file}' does not exist"
|
|
287
|
+
_logger.error(exception_message)
|
|
288
|
+
raise ValueError(exception_message)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _ensure_allowed_extension(input_file: str, extensions: list[str]):
|
|
292
|
+
file_extension = os.path.splitext(input_file)[-1].upper()
|
|
293
|
+
if file_extension not in extensions:
|
|
294
|
+
exception_message = f"Input file '{input_file}' extension is not in {extensions}"
|
|
295
|
+
_logger.error(exception_message)
|
|
296
|
+
raise ValueError(exception_message)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _check_flag_file(
|
|
300
|
+
epub_item_files: list[_EpubItemFile], *, remove_metaguiding: bool = False
|
|
301
|
+
) -> tuple[bool, _EpubItemFile | None]:
|
|
302
|
+
"""Check if an epub file is already metaguided by looking for the flag file.
|
|
303
|
+
|
|
304
|
+
Args:
|
|
305
|
+
epub_item_files: List of files in the epub
|
|
306
|
+
remove_metaguiding: Whether we're removing metaguiding
|
|
307
|
+
|
|
308
|
+
Returns:
|
|
309
|
+
Tuple of (is_already_metaguided, flag_file)
|
|
310
|
+
"""
|
|
311
|
+
flag_file = next((f for f in epub_item_files if f.filename == _METAGUIDED_FLAG_FILENAME), None)
|
|
312
|
+
is_already_metaguided = not remove_metaguiding and flag_file is not None
|
|
313
|
+
|
|
314
|
+
if is_already_metaguided:
|
|
315
|
+
try:
|
|
316
|
+
_logger.debug("Epub already metaguided, flag file content:")
|
|
317
|
+
if flag_file:
|
|
318
|
+
_logger.debug(flag_file.content.decode("utf-8"))
|
|
319
|
+
else:
|
|
320
|
+
_logger.debug("Flag file found but content could not be read")
|
|
321
|
+
except Exception as e:
|
|
322
|
+
_logger.debug(f"Could not decode flag file content: {e}")
|
|
323
|
+
|
|
324
|
+
return is_already_metaguided, flag_file
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def metaguide_epub_file(input_file: str, output_file: str, *, remove_metaguiding: bool = False):
|
|
328
|
+
"""Metaguide an epub file
|
|
329
|
+
input_file: str
|
|
330
|
+
The input epub file
|
|
331
|
+
output_file: str
|
|
332
|
+
The output epub file
|
|
333
|
+
remove_metaguiding: bool
|
|
334
|
+
If True, removes metaguiding from the epub file
|
|
335
|
+
"""
|
|
336
|
+
|
|
337
|
+
_logger.debug(f"Processing file '{input_file}' to output '{output_file}'")
|
|
338
|
+
_ensure_file_exists(input_file)
|
|
339
|
+
_ensure_allowed_extension(input_file, _EPUB_EXTENSIONS)
|
|
340
|
+
|
|
341
|
+
with open(input_file, "rb") as input_reader:
|
|
342
|
+
input_file_stream = BytesIO(input_reader.read())
|
|
343
|
+
output_file_stream = metaguide_epub_stream(input_file_stream, remove_metaguiding=remove_metaguiding)
|
|
344
|
+
with open(output_file, "wb") as output_writer:
|
|
345
|
+
output_writer.write(output_file_stream.read())
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def metaguide_epub_stream(input_stream: BytesIO, *, remove_metaguiding: bool = False) -> BytesIO:
|
|
349
|
+
"""Metaguide an epub input stream
|
|
350
|
+
input_file_stream: BytesIO
|
|
351
|
+
The input epub file stream
|
|
352
|
+
remove_metaguiding: bool
|
|
353
|
+
If True, removes metaguiding from the epub file
|
|
354
|
+
return: BytesIO
|
|
355
|
+
The metaguided epub file stream
|
|
356
|
+
"""
|
|
357
|
+
output_stream = BytesIO()
|
|
358
|
+
|
|
359
|
+
if remove_metaguiding:
|
|
360
|
+
_logger.debug("Removing metaguiding from epub")
|
|
361
|
+
else:
|
|
362
|
+
_logger.debug("Metaguiding epub")
|
|
363
|
+
|
|
364
|
+
_logger.debug("Getting item files")
|
|
365
|
+
with zipfile.ZipFile(input_stream, "r", compression=zipfile.ZIP_DEFLATED, allowZip64=True) as input_zip:
|
|
366
|
+
with zipfile.ZipFile(output_stream, "w", compression=zipfile.ZIP_DEFLATED, allowZip64=True) as output_zip:
|
|
367
|
+
_logger.debug("Processing zip: Getting item files")
|
|
368
|
+
epub_item_files = _get_epub_item_files_from_zip(input_zip)
|
|
369
|
+
|
|
370
|
+
# Check if the file is already metaguided
|
|
371
|
+
is_already_metaguided, _ = _check_flag_file(epub_item_files, remove_metaguiding=remove_metaguiding)
|
|
372
|
+
|
|
373
|
+
if is_already_metaguided:
|
|
374
|
+
_logger.debug("Copying files while preserving structure...")
|
|
375
|
+
# Even for already metaguided files, we need to properly process through zip mechanisms
|
|
376
|
+
for item in input_zip.filelist:
|
|
377
|
+
with input_zip.open(item.filename) as source, output_zip.open(item.filename, "w") as target:
|
|
378
|
+
_logger.debug(f"Copying file {item.filename} with original compression")
|
|
379
|
+
target.write(source.read())
|
|
380
|
+
else:
|
|
381
|
+
processed_item_files = list(
|
|
382
|
+
_process_epub_item_files(epub_item_files, remove_metaguiding=remove_metaguiding)
|
|
383
|
+
)
|
|
384
|
+
|
|
385
|
+
if remove_metaguiding:
|
|
386
|
+
# remove the metaguided flag file
|
|
387
|
+
filtered_files = filter(lambda f: f.filename != _METAGUIDED_FLAG_FILENAME, processed_item_files)
|
|
388
|
+
processed_item_files = list(filtered_files)
|
|
389
|
+
else:
|
|
390
|
+
_logger.debug("Processing zip: Adding metaguided flag file")
|
|
391
|
+
flag_content = _generate_flag_file_content()
|
|
392
|
+
processed_item_files.append(_EpubItemFile(_METAGUIDED_FLAG_FILENAME, flag_content))
|
|
393
|
+
|
|
394
|
+
_logger.debug("Processing zip: Writing output zip")
|
|
395
|
+
_write_item_files_to_zip(processed_item_files, output_zip)
|
|
396
|
+
|
|
397
|
+
output_stream.seek(0)
|
|
398
|
+
return output_stream
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def metaguide_xhtml_file(input_file: str, output_file: str, *, remove_metaguiding: bool = False):
|
|
402
|
+
"""Metaguide an xhtml file
|
|
403
|
+
input_file: str
|
|
404
|
+
The input xhtml file
|
|
405
|
+
output_file: str
|
|
406
|
+
The output xhtml file
|
|
407
|
+
remove_metaguiding: bool
|
|
408
|
+
If True, removes metaguiding from the xhtml file
|
|
409
|
+
"""
|
|
410
|
+
_logger.debug(f"Processing file '{input_file}' to output '{output_file}'")
|
|
411
|
+
_ensure_file_exists(input_file)
|
|
412
|
+
_ensure_allowed_extension(input_file, _XHTML_EXTENSIONS)
|
|
413
|
+
|
|
414
|
+
with open(input_file, "rb") as input_reader:
|
|
415
|
+
input_file_stream = BytesIO(input_reader.read())
|
|
416
|
+
output_file_stream = metaguide_xhtml_stream(input_file_stream, remove_metaguiding=remove_metaguiding)
|
|
417
|
+
output_file_stream.seek(0)
|
|
418
|
+
with open(output_file, "wb") as output_writer:
|
|
419
|
+
output_writer.write(output_file_stream.read())
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def metaguide_xhtml_stream(input_file_stream: BytesIO, *, remove_metaguiding: bool = False) -> BytesIO:
|
|
423
|
+
"""Metaguide an xhtml input stream
|
|
424
|
+
input_file_stream: BytesIO
|
|
425
|
+
The input xhtml file stream
|
|
426
|
+
remove_metaguiding: bool
|
|
427
|
+
If True, removes metaguiding from the xhtml file
|
|
428
|
+
return: BytesIO
|
|
429
|
+
The metaguided xhtml file stream
|
|
430
|
+
"""
|
|
431
|
+
output_file_stream = BytesIO()
|
|
432
|
+
output_file_stream.write(
|
|
433
|
+
_metaguider.metaguide_xhtml_document(input_file_stream.read(), remove_metaguiding=remove_metaguiding)
|
|
434
|
+
)
|
|
435
|
+
output_file_stream.seek(0)
|
|
436
|
+
return output_file_stream
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def metaguide_dir(input_dir: str, output_dir: str, *, remove_metaguiding: bool = False):
|
|
440
|
+
"""Metaguides all epubs and xhtml found in a directory (recursively)
|
|
441
|
+
input_dir: str
|
|
442
|
+
The input epub/xhtml directory
|
|
443
|
+
output_dir: str
|
|
444
|
+
The output epub/xhtml directory
|
|
445
|
+
remove_metaguiding: bool
|
|
446
|
+
If True, removes metaguiding from the files
|
|
447
|
+
"""
|
|
448
|
+
|
|
449
|
+
# get a list of all the files in the directory, and the child directories if recursive
|
|
450
|
+
# verify if the file is a file and if it has the correct extension
|
|
451
|
+
def get_files(directory, recursive):
|
|
452
|
+
for filename in os.listdir(directory):
|
|
453
|
+
input_filename = os.path.join(directory, filename)
|
|
454
|
+
|
|
455
|
+
extension = os.path.splitext(input_filename)[-1].upper()
|
|
456
|
+
if os.path.isfile(input_filename) and (extension in _EPUB_EXTENSIONS or extension in _XHTML_EXTENSIONS):
|
|
457
|
+
yield input_filename
|
|
458
|
+
elif os.path.isdir(input_filename) and recursive:
|
|
459
|
+
yield from get_files(input_filename, recursive)
|
|
460
|
+
|
|
461
|
+
_logger.info(f"Processing files in {input_dir} to {output_dir} (recursively)")
|
|
462
|
+
|
|
463
|
+
files_processed = 0
|
|
464
|
+
files_skipped = 0
|
|
465
|
+
files_with_errors = 0
|
|
466
|
+
|
|
467
|
+
# check if the output directory exists and if not create it
|
|
468
|
+
if not os.path.exists(output_dir):
|
|
469
|
+
_logger.info(f"Creating {output_dir}")
|
|
470
|
+
os.makedirs(output_dir)
|
|
471
|
+
|
|
472
|
+
for input_filename in get_files(input_dir, True):
|
|
473
|
+
output_filename = os.path.join(output_dir, os.path.basename(input_filename))
|
|
474
|
+
_logger.debug(f"Processing {input_filename} to {output_filename}")
|
|
475
|
+
|
|
476
|
+
# verify if the output file already exists
|
|
477
|
+
if os.path.isfile(output_filename):
|
|
478
|
+
_logger.warning(f"Skipping {input_filename} because {output_filename} already exists")
|
|
479
|
+
files_skipped += 1
|
|
480
|
+
continue
|
|
481
|
+
|
|
482
|
+
try:
|
|
483
|
+
with open(input_filename, "rb") as input_reader:
|
|
484
|
+
input_file_stream = BytesIO(input_reader.read())
|
|
485
|
+
if os.path.splitext(input_filename)[-1].upper() in _EPUB_EXTENSIONS:
|
|
486
|
+
output_file_stream = metaguide_epub_stream(input_file_stream, remove_metaguiding=remove_metaguiding)
|
|
487
|
+
else:
|
|
488
|
+
output_file_stream = metaguide_xhtml_stream(
|
|
489
|
+
input_file_stream, remove_metaguiding=remove_metaguiding
|
|
490
|
+
)
|
|
491
|
+
with open(output_filename, "wb") as output_writer:
|
|
492
|
+
output_writer.write(output_file_stream.read())
|
|
493
|
+
files_processed += 1
|
|
494
|
+
except Exception as e: # pylint: disable=broad-except
|
|
495
|
+
# pylint: disable=logging-fstring-interpolation
|
|
496
|
+
files_with_errors += 1
|
|
497
|
+
_logger.exception(f"Error processing {input_filename}", e)
|
|
498
|
+
continue
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def is_file_metaguided(filepath: str) -> bool:
|
|
502
|
+
"""Check if a file has already been metaguided.
|
|
503
|
+
|
|
504
|
+
Args:
|
|
505
|
+
filepath: Path to the epub file to check
|
|
506
|
+
|
|
507
|
+
Returns:
|
|
508
|
+
bool: True if the file has already been metaguided, False otherwise
|
|
509
|
+
|
|
510
|
+
Raises:
|
|
511
|
+
ValueError: If the file doesn't exist or has an invalid extension
|
|
512
|
+
"""
|
|
513
|
+
_ensure_file_exists(filepath)
|
|
514
|
+
_ensure_allowed_extension(filepath, _EPUB_EXTENSIONS)
|
|
515
|
+
|
|
516
|
+
with open(filepath, "rb") as input_reader:
|
|
517
|
+
input_file_stream = BytesIO(input_reader.read())
|
|
518
|
+
with zipfile.ZipFile(input_file_stream, "r", compression=zipfile.ZIP_DEFLATED, allowZip64=True) as input_zip:
|
|
519
|
+
epub_item_files = _get_epub_item_files_from_zip(input_zip)
|
|
520
|
+
is_metaguided, _ = _check_flag_file(epub_item_files)
|
|
521
|
+
return is_metaguided
|
|
@@ -11,7 +11,7 @@ requires-python = ">=3.13"
|
|
|
11
11
|
license = "GPL-3.0"
|
|
12
12
|
keywords = ["kepub","epub", "calibre", "ebook","kindle","kobo","speed-reading", "dyslexia", "adhd"]
|
|
13
13
|
authors = [
|
|
14
|
-
{ name = "
|
|
14
|
+
{ name = "Hugo Batista"},
|
|
15
15
|
]
|
|
16
16
|
classifiers = [
|
|
17
17
|
"Operating System :: OS Independent",
|
|
@@ -35,18 +35,19 @@ classifiers = [
|
|
|
35
35
|
dependencies = [
|
|
36
36
|
"click>=8.1.7",
|
|
37
37
|
"lxml>=4.9.2",
|
|
38
|
+
"regex >= 2024.11.6",
|
|
38
39
|
]
|
|
39
40
|
|
|
40
41
|
[project.scripts]
|
|
41
42
|
intellireading = "intellireading.client:entrypoint"
|
|
42
43
|
|
|
43
44
|
[project.urls]
|
|
44
|
-
Documentation = "https://
|
|
45
|
-
Issues = "https://
|
|
46
|
-
Source = "https://
|
|
45
|
+
Documentation = "https://go.hugobatista.com/gh/intellireading-cli#readme"
|
|
46
|
+
Issues = "https://go.hugobatista.com/gh/intellireading-cli/issues"
|
|
47
|
+
Source = "https://go.hugobatista.com/gh/intellireading-cli"
|
|
47
48
|
|
|
48
49
|
[tool.hatch.version]
|
|
49
|
-
path = "src/intellireading/client/
|
|
50
|
+
path = "src/intellireading/client/__about_cli__.py"
|
|
50
51
|
|
|
51
52
|
[tool.hatch.build.targets.wheel]
|
|
52
53
|
packages = ["src/intellireading"]
|
|
@@ -57,6 +58,7 @@ packages = ["src/intellireading"]
|
|
|
57
58
|
exclude = ["tests"]
|
|
58
59
|
|
|
59
60
|
[tool.hatch.envs.default]
|
|
61
|
+
installer = "uv"
|
|
60
62
|
dependencies = [
|
|
61
63
|
"coverage[toml]>=6.5",
|
|
62
64
|
"pytest",
|
|
@@ -146,6 +148,8 @@ lint.ignore = [
|
|
|
146
148
|
"C901", "PLR0911", "PLR0912", "PLR0913", "PLR0915",
|
|
147
149
|
# Ignore Import block is un-sorted or un-formatted
|
|
148
150
|
"I001",
|
|
151
|
+
# Ignore `import` should be at the top-level of a file
|
|
152
|
+
"PLC0415",
|
|
149
153
|
]
|
|
150
154
|
lint.unfixable = [
|
|
151
155
|
# Don't touch unused imports
|
|
@@ -167,7 +171,7 @@ source_pkgs = ["intellireading", "tests"]
|
|
|
167
171
|
branch = true
|
|
168
172
|
parallel = true
|
|
169
173
|
omit = [
|
|
170
|
-
"src/intellireading/
|
|
174
|
+
"src/intellireading/__about_cli__.py",
|
|
171
175
|
]
|
|
172
176
|
|
|
173
177
|
[tool.coverage.paths]
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "2.0.0"
|
|
@@ -1,181 +0,0 @@
|
|
|
1
|
-
import logging
|
|
2
|
-
from io import BytesIO
|
|
3
|
-
import os
|
|
4
|
-
from intellireading.client.regex import RegExBoldMetaguider
|
|
5
|
-
import zipfile
|
|
6
|
-
from typing import Generator
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
_logger = logging.getLogger(__name__)
|
|
10
|
-
_metaguider = RegExBoldMetaguider()
|
|
11
|
-
_METAGUIDED_FLAG_FILENAME = "intellireading.metaguide"
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
class _EpubItemFile:
|
|
15
|
-
_logger = logging.getLogger(__name__)
|
|
16
|
-
|
|
17
|
-
def __init__(self, filename: str | None = None, content: bytes = b"") -> None:
|
|
18
|
-
self.filename = filename
|
|
19
|
-
self.content = content
|
|
20
|
-
_extension = (self.filename and os.path.splitext(self.filename)[-1].upper()) or None
|
|
21
|
-
|
|
22
|
-
# some epub have files with html extension but they are xml files
|
|
23
|
-
self.is_xhtml_document = _extension in (".HTM", ".HTML", ".XHTML")
|
|
24
|
-
self.metaguided = False # flag to indicate if the file has been metaguided. Useful for multi-threading
|
|
25
|
-
|
|
26
|
-
def __str__(self) -> str:
|
|
27
|
-
return f"{self.filename} ({len(self.content)} bytes)"
|
|
28
|
-
|
|
29
|
-
def metaguide(self, metaguider: RegExBoldMetaguider):
|
|
30
|
-
if self.metaguided:
|
|
31
|
-
self._logger.warning("File %s already metaguided, skipping", self.filename)
|
|
32
|
-
elif self.is_xhtml_document:
|
|
33
|
-
self._logger.debug("Process (begin): %s", self.filename)
|
|
34
|
-
self.content = metaguider.metaguide_xhtml_document(self.content)
|
|
35
|
-
self.metaguided = True
|
|
36
|
-
self._logger.debug("Process (end): %s", self.filename)
|
|
37
|
-
else:
|
|
38
|
-
self._logger.debug("Skipping file %s", self.filename)
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
def _get_epub_item_files_from_zip(input_zip: zipfile.ZipFile) -> list:
|
|
42
|
-
def _read_compressed_file(input_zip: zipfile.ZipFile, filename: str) -> _EpubItemFile:
|
|
43
|
-
return _EpubItemFile(filename, input_zip.read(filename))
|
|
44
|
-
|
|
45
|
-
_epub_item_files = [_read_compressed_file(input_zip, f.filename) for f in input_zip.infolist()]
|
|
46
|
-
_logger.debug("Read %d files from input file", len(_epub_item_files))
|
|
47
|
-
return _epub_item_files
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
def _process_epub_item_files(epub_item_files: list[_EpubItemFile]) -> Generator[_EpubItemFile, None, None]:
|
|
51
|
-
for _epub_item_file in epub_item_files:
|
|
52
|
-
_logger.debug(f"Processing file '{_epub_item_file.filename}'")
|
|
53
|
-
_epub_item_file.metaguide(_metaguider)
|
|
54
|
-
yield _epub_item_file
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
def _write_item_files_to_zip(epub_item_files, output_zip):
|
|
58
|
-
def _write_compressed_file(output_zip: zipfile.ZipFile, epub_item_file: _EpubItemFile):
|
|
59
|
-
if epub_item_file.filename is None:
|
|
60
|
-
msg = "EpubItemFile.filename is None"
|
|
61
|
-
raise ValueError(msg)
|
|
62
|
-
|
|
63
|
-
_logger.debug(
|
|
64
|
-
"Writing file %s to output zip %s",
|
|
65
|
-
epub_item_file.filename,
|
|
66
|
-
output_zip.filename,
|
|
67
|
-
)
|
|
68
|
-
with output_zip.open(epub_item_file.filename, mode="w") as _compressed_output_file:
|
|
69
|
-
_compressed_output_file.write(epub_item_file.content)
|
|
70
|
-
|
|
71
|
-
for _epub_item_file in epub_item_files:
|
|
72
|
-
_write_compressed_file(output_zip, _epub_item_file)
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
def metaguide_epub(input_stream: BytesIO) -> BytesIO:
|
|
76
|
-
"""Metaguide an epub file
|
|
77
|
-
input_file_stream: BytesIO
|
|
78
|
-
The input epub file stream
|
|
79
|
-
return: BytesIO
|
|
80
|
-
The metaguided epub file stream
|
|
81
|
-
"""
|
|
82
|
-
output_stream = BytesIO()
|
|
83
|
-
|
|
84
|
-
_logger.debug("Metaguiding epub: Getting item files")
|
|
85
|
-
with zipfile.ZipFile(input_stream, "r", compression=zipfile.ZIP_DEFLATED, allowZip64=True) as input_zip:
|
|
86
|
-
with zipfile.ZipFile(output_stream, "w", compression=zipfile.ZIP_DEFLATED, allowZip64=True) as output_zip:
|
|
87
|
-
_logger.debug("Processing zip: Getting item files")
|
|
88
|
-
_epub_item_files = _get_epub_item_files_from_zip(input_zip)
|
|
89
|
-
|
|
90
|
-
# check if we have _METAGUIDED_FLAG_FILENAME in the epub
|
|
91
|
-
# if we do, this file has been metaguided already
|
|
92
|
-
if any(f.filename == _METAGUIDED_FLAG_FILENAME for f in _epub_item_files):
|
|
93
|
-
_logger.debug("Epub already metaguided, skipping...")
|
|
94
|
-
# copy the input stream to the output stream
|
|
95
|
-
input_stream.seek(0)
|
|
96
|
-
output_stream.write(input_stream.read())
|
|
97
|
-
else:
|
|
98
|
-
processed_item_files = _process_epub_item_files(_epub_item_files)
|
|
99
|
-
_logger.debug("Processing zip: Writing output zip")
|
|
100
|
-
_write_item_files_to_zip(processed_item_files, output_zip)
|
|
101
|
-
# write the metaguided file flag to the zip
|
|
102
|
-
output_zip.writestr(_METAGUIDED_FLAG_FILENAME, b"")
|
|
103
|
-
|
|
104
|
-
output_stream.seek(0)
|
|
105
|
-
return output_stream
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
def metaguide_xhtml(input_file_stream: BytesIO) -> BytesIO:
|
|
109
|
-
"""Metaguide an xhtml file
|
|
110
|
-
input_file_stream: BytesIO
|
|
111
|
-
The input xhtml file stream
|
|
112
|
-
return: BytesIO
|
|
113
|
-
The metaguided xhtml file stream
|
|
114
|
-
"""
|
|
115
|
-
output_file_stream = BytesIO()
|
|
116
|
-
output_file_stream.write(_metaguider.metaguide_xhtml_document(input_file_stream.read()))
|
|
117
|
-
output_file_stream.seek(0)
|
|
118
|
-
return output_file_stream
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
def metaguide_dir(input_dir: str, output_dir: str) -> None:
|
|
122
|
-
"""Metaguides all epubs and xhtml found in a directory (recursively)
|
|
123
|
-
input_dir: str
|
|
124
|
-
The input epub/xhtml directory
|
|
125
|
-
output_dir: str
|
|
126
|
-
The output epub/xhtml directory
|
|
127
|
-
"""
|
|
128
|
-
|
|
129
|
-
# get a list of all the files in the directory, and the child directories if recursive
|
|
130
|
-
# verify if the file is a file and if it has the correct extension
|
|
131
|
-
def _get_files(directory, recursive):
|
|
132
|
-
for filename in os.listdir(directory):
|
|
133
|
-
input_filename = os.path.join(directory, filename)
|
|
134
|
-
|
|
135
|
-
extension = os.path.splitext(input_filename)[-1].upper()
|
|
136
|
-
if os.path.isfile(input_filename) and (extension in [".EPUB", "*.KEPUB", ".XHTML", ".HTML", ".HTM"]):
|
|
137
|
-
yield input_filename
|
|
138
|
-
elif os.path.isdir(input_filename) and recursive:
|
|
139
|
-
yield from _get_files(input_filename, recursive)
|
|
140
|
-
|
|
141
|
-
_logger.info(
|
|
142
|
-
"Processing files in %s to %s (recursively)",
|
|
143
|
-
input_dir,
|
|
144
|
-
output_dir,
|
|
145
|
-
)
|
|
146
|
-
|
|
147
|
-
files_processed = 0
|
|
148
|
-
files_skipped = 0
|
|
149
|
-
files_with_errors = 0
|
|
150
|
-
|
|
151
|
-
# check if the output directory exists and if not create it
|
|
152
|
-
if not os.path.exists(output_dir):
|
|
153
|
-
_logger.info("Creating %s", output_dir)
|
|
154
|
-
os.makedirs(output_dir)
|
|
155
|
-
|
|
156
|
-
for input_filename in _get_files(input_dir, True):
|
|
157
|
-
output_filename = os.path.join(output_dir, os.path.basename(input_filename))
|
|
158
|
-
|
|
159
|
-
_logger.debug("Processing %s to %s", input_filename, output_filename)
|
|
160
|
-
|
|
161
|
-
# verify if the output file already exists
|
|
162
|
-
if os.path.isfile(output_filename):
|
|
163
|
-
_logger.warning("Skipping %s because %s already exists", input_filename, output_filename)
|
|
164
|
-
files_skipped += 1
|
|
165
|
-
continue
|
|
166
|
-
|
|
167
|
-
try:
|
|
168
|
-
with open(input_filename, "rb") as input_reader:
|
|
169
|
-
input_file_stream = BytesIO(input_reader.read())
|
|
170
|
-
if input_filename.upper().endswith(".EPUB") or input_filename.upper().endswith(".KEPUB"):
|
|
171
|
-
output_file_stream = metaguide_epub(input_file_stream)
|
|
172
|
-
else:
|
|
173
|
-
output_file_stream = metaguide_xhtml(input_file_stream)
|
|
174
|
-
with open(output_filename, "wb") as output_writer:
|
|
175
|
-
output_writer.write(output_file_stream.read())
|
|
176
|
-
files_processed += 1
|
|
177
|
-
except Exception as e: # pylint: disable=broad-except
|
|
178
|
-
# pylint: disable=logging-fstring-interpolation
|
|
179
|
-
files_with_errors += 1
|
|
180
|
-
_logger.exception(f"Error processing {input_filename}", e)
|
|
181
|
-
continue
|
|
@@ -1,126 +0,0 @@
|
|
|
1
|
-
import math
|
|
2
|
-
import re
|
|
3
|
-
import logging
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
class RegExBoldMetaguider:
|
|
7
|
-
_body_regex = re.compile(r"<body[^>]*>(.*)</body>", re.DOTALL)
|
|
8
|
-
_text_block_regex = re.compile(r"(?<!<b)>[^\S]*[^\s<][^<]*[^\S\n]*<")
|
|
9
|
-
_word_pattern_regex = re.compile(r"\b\w+\b", re.UNICODE)
|
|
10
|
-
_entity_ref_regex = re.compile(r"(&[#a-zA-Z][a-zA-Z0-9]*;)")
|
|
11
|
-
_logger = logging.getLogger(__name__)
|
|
12
|
-
|
|
13
|
-
def __init__(self, fallback_encoding: str = "utf-8") -> None:
|
|
14
|
-
self._fallback_encoding = fallback_encoding
|
|
15
|
-
|
|
16
|
-
def _bold_word(self, word: str) -> str:
|
|
17
|
-
# this is the function that is called for each word
|
|
18
|
-
|
|
19
|
-
# if the word is an empty string, whitespace or new line, return it
|
|
20
|
-
if not word.strip():
|
|
21
|
-
return word
|
|
22
|
-
|
|
23
|
-
_length = len(word)
|
|
24
|
-
midpoint = 1 if _length in (1, 3) else math.ceil(len(word) / 2)
|
|
25
|
-
return f"<b>{word[:midpoint]}</b>{word[midpoint:]}" # Bold the first half of the word
|
|
26
|
-
|
|
27
|
-
def _bold_node_text_part(self, part: str) -> str:
|
|
28
|
-
# is this part an entity reference?
|
|
29
|
-
if self._entity_ref_regex.match(part):
|
|
30
|
-
return part
|
|
31
|
-
return self._word_pattern_regex.sub(lambda m: self._bold_word(m.group()), part)
|
|
32
|
-
|
|
33
|
-
def _bold_text_node(self, node: str) -> str:
|
|
34
|
-
# this is the function that is called for each text node
|
|
35
|
-
node_text = node[1:-1]
|
|
36
|
-
|
|
37
|
-
# split the node_text into parts based on the entity references
|
|
38
|
-
node_text_parts = self._entity_ref_regex.split(node_text)
|
|
39
|
-
|
|
40
|
-
new_node_text = "".join(map(self._bold_node_text_part, node_text_parts))
|
|
41
|
-
|
|
42
|
-
if node_text != new_node_text:
|
|
43
|
-
return ">" + new_node_text + "<"
|
|
44
|
-
return node
|
|
45
|
-
|
|
46
|
-
def _bold_document(self, html: str) -> str:
|
|
47
|
-
# get the body. If there is no body, return the original html
|
|
48
|
-
match = self._body_regex.search(html)
|
|
49
|
-
if match:
|
|
50
|
-
body = match.group(1)
|
|
51
|
-
else:
|
|
52
|
-
return html
|
|
53
|
-
|
|
54
|
-
# find all text nodes in the body and trigger the bolding of the words
|
|
55
|
-
body = self._text_block_regex.sub(lambda m: self._bold_text_node(m.group()), body)
|
|
56
|
-
|
|
57
|
-
html = html.replace(match.group(1), body)
|
|
58
|
-
return html
|
|
59
|
-
|
|
60
|
-
def _get_encoding_using_lxml(self, xhtml_document: bytes) -> str | None:
|
|
61
|
-
from lxml import etree
|
|
62
|
-
|
|
63
|
-
_parser = etree.XMLParser(resolve_entities=False)
|
|
64
|
-
_doc = etree.fromstring(xhtml_document, parser=_parser).getroottree() # noqa: S320
|
|
65
|
-
_docinfo = _doc.docinfo
|
|
66
|
-
return _docinfo.encoding
|
|
67
|
-
|
|
68
|
-
def _get_encoding_using_bom(self, xhtml_document: bytes) -> str | None:
|
|
69
|
-
if xhtml_document.startswith(b"\xef\xbb\xbf"):
|
|
70
|
-
return "utf-8"
|
|
71
|
-
elif xhtml_document.startswith(b"\xff\xfe"):
|
|
72
|
-
return "utf-16-le"
|
|
73
|
-
elif xhtml_document.startswith(b"\xfe\xff"):
|
|
74
|
-
return "utf-16-be"
|
|
75
|
-
elif xhtml_document.startswith(b"\x00\x00\xfe\xff"):
|
|
76
|
-
return "utf-32-be"
|
|
77
|
-
elif xhtml_document.startswith(b"\xff\xfe\x00\x00"):
|
|
78
|
-
return "utf-32-le"
|
|
79
|
-
else:
|
|
80
|
-
return None
|
|
81
|
-
|
|
82
|
-
def _get_encoding_using_xml_header(self, xhtml_document: bytes) -> str | None:
|
|
83
|
-
# if the document does not start with an XML header, return None. This is not a xml document
|
|
84
|
-
if not xhtml_document.startswith(b"<?xml "):
|
|
85
|
-
return None
|
|
86
|
-
|
|
87
|
-
xml_header_end = xhtml_document.find(b"?>") + 1
|
|
88
|
-
if xml_header_end == 0:
|
|
89
|
-
msg = "Invalid XHTML document. Could not find closing XML element."
|
|
90
|
-
raise ValueError(msg)
|
|
91
|
-
|
|
92
|
-
header = xhtml_document[:xml_header_end].decode("utf-8")
|
|
93
|
-
match = re.search(r'encoding=(["\'])([a-zA-Z][a-zA-Z0-9-]{0,38}[a-zA-Z0-9])\1', header)
|
|
94
|
-
if match:
|
|
95
|
-
return match.group(2)
|
|
96
|
-
else:
|
|
97
|
-
# although the XML header is present, it does not contain an encoding
|
|
98
|
-
# this is not a valid XHTML document, but we can still try to detect the encoding on a later stage
|
|
99
|
-
# and we will not raise an exception
|
|
100
|
-
return None
|
|
101
|
-
|
|
102
|
-
def _get_encoding(self, xhtml_document: bytes) -> str:
|
|
103
|
-
_encoding = self._get_encoding_using_xml_header(xhtml_document)
|
|
104
|
-
|
|
105
|
-
if not _encoding:
|
|
106
|
-
self._logger.debug(
|
|
107
|
-
"Could not detect the encoding of the XHTML document using the XML header. "
|
|
108
|
-
"Trying to detect the encoding using the BOM."
|
|
109
|
-
)
|
|
110
|
-
_encoding = self._get_encoding_using_bom(xhtml_document)
|
|
111
|
-
|
|
112
|
-
if not _encoding:
|
|
113
|
-
self._logger.debug(
|
|
114
|
-
"Could not detect the encoding of the XHTML document. Trying to detect the encoding using lxml."
|
|
115
|
-
)
|
|
116
|
-
_encoding = self._get_encoding_using_lxml(xhtml_document)
|
|
117
|
-
|
|
118
|
-
return _encoding or self._fallback_encoding
|
|
119
|
-
|
|
120
|
-
def metaguide_xhtml_document(self, xhtml_document: bytes) -> bytes:
|
|
121
|
-
# if none of the methods to detect the encoding work, use utf-8
|
|
122
|
-
_encoding = self._get_encoding(xhtml_document) or "utf-8"
|
|
123
|
-
|
|
124
|
-
_html = xhtml_document.decode(_encoding)
|
|
125
|
-
_bolded_html = self._bold_document(_html)
|
|
126
|
-
return _bolded_html.encode(_encoding)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|