intellireading-cli 2.0.0__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.
- intellireading/client/__about__.py +1 -0
- intellireading/client/__init__.py +4 -0
- intellireading/client/__main__.py +4 -0
- intellireading/client/app.py +40 -0
- intellireading/client/commands.py +169 -0
- intellireading/client/metaguiding.py +181 -0
- intellireading/client/regex.py +126 -0
- intellireading_cli-2.0.0.dist-info/METADATA +152 -0
- intellireading_cli-2.0.0.dist-info/RECORD +12 -0
- intellireading_cli-2.0.0.dist-info/WHEEL +4 -0
- intellireading_cli-2.0.0.dist-info/entry_points.txt +2 -0
- intellireading_cli-2.0.0.dist-info/licenses/LICENSE +674 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "2.0.0"
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import click
|
|
2
|
+
from intellireading.client.commands import (
|
|
3
|
+
metaguide_epub_cmd,
|
|
4
|
+
metaguide_xhtml_cmd,
|
|
5
|
+
metaguide_dir_cmd,
|
|
6
|
+
)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@click.group(
|
|
10
|
+
name="Intellireading",
|
|
11
|
+
chain=True,
|
|
12
|
+
help="A set of tools designed to improve your reading experience.",
|
|
13
|
+
)
|
|
14
|
+
@click.option(
|
|
15
|
+
"--log_level",
|
|
16
|
+
default="WARNING",
|
|
17
|
+
type=click.Choice(["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]),
|
|
18
|
+
help="The log level to use for logging (default: INFO). Possible values: DEBUG, INFO, WARNING, ERROR, CRITICAL",
|
|
19
|
+
)
|
|
20
|
+
@click.pass_context
|
|
21
|
+
def cli(ctx: click.Context, log_level: str):
|
|
22
|
+
ctx.ensure_object(dict)
|
|
23
|
+
|
|
24
|
+
import logging
|
|
25
|
+
|
|
26
|
+
logging.basicConfig(level=log_level)
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
cli.add_command(metaguide_epub_cmd)
|
|
31
|
+
cli.add_command(metaguide_dir_cmd)
|
|
32
|
+
cli.add_command(metaguide_xhtml_cmd)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def entrypoint():
|
|
36
|
+
cli(obj={})
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
if __name__ == "__main__":
|
|
40
|
+
entrypoint()
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import click
|
|
2
|
+
import logging
|
|
3
|
+
import sys
|
|
4
|
+
from intellireading.client.metaguiding import metaguide_epub, metaguide_dir, metaguide_xhtml
|
|
5
|
+
from typing import Callable, Any
|
|
6
|
+
from io import BytesIO
|
|
7
|
+
|
|
8
|
+
_logger = logging.getLogger(__name__)
|
|
9
|
+
|
|
10
|
+
# TODO: somewhere in this file, logging should be configured. use the following snippet to do so:
|
|
11
|
+
# from monitoring.logutils import init_logging_from_file
|
|
12
|
+
# init_logging_from_file("logging.conf")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
_output_file_option = click.option(
|
|
16
|
+
"--output_file",
|
|
17
|
+
type=click.Path(exists=False),
|
|
18
|
+
prompt="The output file",
|
|
19
|
+
prompt_required=False,
|
|
20
|
+
help="The file to write",
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
_input_file_option = click.option(
|
|
24
|
+
"--input_file",
|
|
25
|
+
type=click.Path(exists=False), # although it should exists, chaining commands will fail if it does not
|
|
26
|
+
prompt="The input file",
|
|
27
|
+
prompt_required=False,
|
|
28
|
+
help="The file to read",
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
_output_dir_option = click.option(
|
|
32
|
+
"--output_dir",
|
|
33
|
+
type=click.Path(exists=False),
|
|
34
|
+
prompt="The output directory",
|
|
35
|
+
prompt_required=False,
|
|
36
|
+
help="The directory to write to",
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
_input_dir_option = click.option(
|
|
40
|
+
"--input_dir",
|
|
41
|
+
type=click.Path(exists=False), # although it should exists, chaining commands will fail if it does not
|
|
42
|
+
prompt="The input directory",
|
|
43
|
+
prompt_required=False,
|
|
44
|
+
help="The directory to read from",
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _exit_with_exception(exception: Exception, exit_code: int = 1, fg: str = "red"):
|
|
49
|
+
"""Exit the program with an exception and exit code"""
|
|
50
|
+
try:
|
|
51
|
+
_logger.exception(exception)
|
|
52
|
+
click.secho(
|
|
53
|
+
"An error occurred. See the log for more details. (--log_level ERROR). Exiting... "
|
|
54
|
+
f"(Exception Type: {type(exception).__name__}); (Exception: {exception})",
|
|
55
|
+
fg=fg,
|
|
56
|
+
)
|
|
57
|
+
finally:
|
|
58
|
+
sys.exit(exit_code)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _get_from_ctx_if_none(
|
|
62
|
+
ctx: click.Context,
|
|
63
|
+
ctx_key: str,
|
|
64
|
+
value: str | None,
|
|
65
|
+
invoke_func: Callable[..., str] = lambda: "",
|
|
66
|
+
**kwargs: Any,
|
|
67
|
+
) -> str:
|
|
68
|
+
"""Get a value from the context if it is None,
|
|
69
|
+
otherwise invoke a function to get the value."""
|
|
70
|
+
ctx.ensure_object(dict)
|
|
71
|
+
if value:
|
|
72
|
+
return value
|
|
73
|
+
elif ctx.obj.get(ctx_key):
|
|
74
|
+
return ctx.obj[ctx_key]
|
|
75
|
+
else:
|
|
76
|
+
result = ctx.invoke(invoke_func, **kwargs)
|
|
77
|
+
return result
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@click.command(
|
|
81
|
+
"metaguide-epub",
|
|
82
|
+
help="Applies metaguiding to the provided epub/kepub file",
|
|
83
|
+
)
|
|
84
|
+
@click.pass_context
|
|
85
|
+
@_input_file_option
|
|
86
|
+
@_output_file_option
|
|
87
|
+
def metaguide_epub_cmd(ctx: click.Context, input_file: str, output_file: str):
|
|
88
|
+
"""Applies metaguiding to the provided epub/kepub file"""
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
ctx.ensure_object(dict)
|
|
92
|
+
click.secho("Metaguiding epub...", fg="yellow")
|
|
93
|
+
|
|
94
|
+
input_file = _get_from_ctx_if_none(ctx, "output_file", input_file, lambda: click.prompt("The input file"))
|
|
95
|
+
click.echo(f"Input file: {input_file}")
|
|
96
|
+
output_file = _get_from_ctx_if_none(ctx, "output_file", output_file, lambda: click.prompt("The output file"))
|
|
97
|
+
click.echo(f"Output file: {output_file}")
|
|
98
|
+
|
|
99
|
+
with open(input_file, "rb") as input_reader:
|
|
100
|
+
input_file_stream = BytesIO(input_reader.read())
|
|
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())
|
|
104
|
+
# store the output file in the context for chaining commands
|
|
105
|
+
ctx.obj["output_file"] = output_file
|
|
106
|
+
except Exception as e:
|
|
107
|
+
_exit_with_exception(e)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@click.command(
|
|
111
|
+
"metaguide-dir",
|
|
112
|
+
help="Applies metaguiding to the provided directory, recursively, for all epubs and xhtml files",
|
|
113
|
+
)
|
|
114
|
+
@click.pass_context
|
|
115
|
+
@_input_dir_option
|
|
116
|
+
@_output_dir_option
|
|
117
|
+
def metaguide_dir_cmd(ctx: click.Context, input_dir: str, output_dir: str):
|
|
118
|
+
"""Applies metaguiding to the provided directory, recursively, for all epubs and xhtml files found in the directory
|
|
119
|
+
input_dir: str
|
|
120
|
+
The input directory
|
|
121
|
+
output_dir: str
|
|
122
|
+
The output directory
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
try:
|
|
126
|
+
ctx.ensure_object(dict)
|
|
127
|
+
click.secho("Metaguiding directory...", fg="yellow")
|
|
128
|
+
input_dir = _get_from_ctx_if_none(ctx, "input_dir", input_dir, lambda: click.prompt("The input directory"))
|
|
129
|
+
click.echo(f"Input directory: {input_dir}")
|
|
130
|
+
output_dir = _get_from_ctx_if_none(ctx, "output_dir", output_dir, lambda: click.prompt("The output directory"))
|
|
131
|
+
click.echo(f"Output directory: {output_dir}")
|
|
132
|
+
|
|
133
|
+
# check if we have the same input and output directories
|
|
134
|
+
if input_dir == output_dir:
|
|
135
|
+
_exit_with_exception(ValueError("Input and output directories are the same. Exiting..."), fg="red")
|
|
136
|
+
|
|
137
|
+
metaguide_dir(input_dir, output_dir)
|
|
138
|
+
except Exception as e:
|
|
139
|
+
_exit_with_exception(e)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@click.command(
|
|
143
|
+
"metaguide-xhtml",
|
|
144
|
+
help="Applies metaguiding to the provided xhtml file",
|
|
145
|
+
)
|
|
146
|
+
@click.pass_context
|
|
147
|
+
@_input_file_option
|
|
148
|
+
@_output_file_option
|
|
149
|
+
def metaguide_xhtml_cmd(ctx: click.Context, input_file: str, output_file: str):
|
|
150
|
+
"""Applies metaguiding to the provided xhtml file"""
|
|
151
|
+
|
|
152
|
+
try:
|
|
153
|
+
ctx.ensure_object(dict)
|
|
154
|
+
click.secho("Metaguiding xhtml...", fg="yellow")
|
|
155
|
+
|
|
156
|
+
input_file = _get_from_ctx_if_none(ctx, "output_file", input_file, lambda: click.prompt("The input file"))
|
|
157
|
+
click.echo(f"Input file: {input_file}")
|
|
158
|
+
output_file = _get_from_ctx_if_none(ctx, "output_file", output_file, lambda: click.prompt("The output file"))
|
|
159
|
+
click.echo(f"Output file: {output_file}")
|
|
160
|
+
|
|
161
|
+
with open(input_file, "rb") as input_reader:
|
|
162
|
+
input_file_stream = BytesIO(input_reader.read())
|
|
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())
|
|
166
|
+
# store the output file in the context for chaining commands
|
|
167
|
+
ctx.obj["output_file"] = output_file
|
|
168
|
+
except Exception as e:
|
|
169
|
+
_exit_with_exception(e)
|
|
@@ -0,0 +1,181 @@
|
|
|
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
|
|
@@ -0,0 +1,126 @@
|
|
|
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)
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: intellireading-cli
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: Intellireading-cli is a Python library with a set of tools to improve your reading experience
|
|
5
|
+
Project-URL: Documentation, https://github.com/0x6f677548/intellireading-cli#readme
|
|
6
|
+
Project-URL: Issues, https://github.com/0x6f677548/intellireading-cli/issues
|
|
7
|
+
Project-URL: Source, https://github.com/0x6f677548/intellireading-cli
|
|
8
|
+
Author: 0x6f677546 (Hugo Batista)
|
|
9
|
+
License-Expression: GPL-3.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: adhd,calibre,dyslexia,ebook,epub,kepub,kindle,kobo,speed-reading
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Education
|
|
15
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
16
|
+
Classifier: Intended Audience :: Information Technology
|
|
17
|
+
Classifier: Intended Audience :: Science/Research
|
|
18
|
+
Classifier: Intended Audience :: System Administrators
|
|
19
|
+
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
|
|
20
|
+
Classifier: Operating System :: OS Independent
|
|
21
|
+
Classifier: Programming Language :: Python
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
24
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
25
|
+
Classifier: Topic :: Education :: Computer Aided Instruction (CAI)
|
|
26
|
+
Classifier: Topic :: Software Development
|
|
27
|
+
Classifier: Topic :: Text Processing :: Markup :: XML
|
|
28
|
+
Classifier: Topic :: Utilities
|
|
29
|
+
Requires-Python: >=3.13
|
|
30
|
+
Requires-Dist: click>=8.1.7
|
|
31
|
+
Requires-Dist: lxml>=4.9.2
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+

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

|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
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
|
+
## [Other Intellireading Code Repositories](https://github.com/stars/0x6f677548/lists/intellireading)
|
|
56
|
+
- [Intellireading website](https://www.github.com/0x6f677548/intellireading-www), which allows anyone to convert an Epub to the metaguided version.
|
|
57
|
+
- [Backend Servers](https://www.github.com/0x6f677548/intellireading-backend), that support the Intellireading website.
|
|
58
|
+
- [CLI Tool](https://www.github.com/0x6f677548/intellireading-cli). A standalone tool and library that can be used to metaguide epub files.
|
|
59
|
+
- [Calibre Plugins](https://www.github.com/0x6f677548/intellireading-calibre-plugins). A set of plugins that can be used to metaguide epub files using Calibre.
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
## What is Epub Metaguiding?
|
|
63
|
+
**Metagu**iding **i**s **a** **techn**ique **th**at **ca**n **b**e **us**ed **t**o **impr**ove **yo**ur **read**ing **foc**us **an**d **spe**ed **(some**times **cal**led **Bio**nic **Readi**ng). **I**t **i**s **bas**ed **o**n **th**e **id**ea **th**at **yo**u **ca**n **us**e **a** **vis**ual **gui**de **t**o **he**lp **yo**ur **ey**es **foc**us **o**n **th**e **te**xt **yo**u **ar**e **read**ing. **I**n **th**is **cas**e, **th**e **vis**ual **gui**de **i**s **do**ne **b**y **bold**ing **a** **pa**rt **o**f **th**e **tex**t, **crea**ting **vis**ual **anch**ors **th**at **yo**ur **ey**es **ca**n **us**e **t**o **foc**us **o**n **th**e **tex**t. **Th**is **i**s **simi**lar **t**o **th**e **wa**y **a** **fin**ger **ca**n **b**e **us**ed **t**o **gui**de **yo**ur **ey**es **alo**ng **a** **li**ne **o**f **tex**t, **whi**ch **ha**s **be**en **sho**wn **t**o **impr**ove **read**ing **spe**ed **an**d **foc**us. ([**stu**dy: **"Do**es **finger-t**racking **poi**nt **t**o **chi**ld **read**ing **strate**gies"](https://ceur-ws.org/Vol-2769/paper_60.pdf))
|
|
64
|
+
|
|
65
|
+
**Howe**ver, **unl**ike **a** **fing**er, **th**e **vis**ual **gui**de **i**s **no**t **distra**cting, **an**d **i**t **ca**n **b**e **us**ed **t**o **gui**de **yo**ur **ey**es **alo**ng **mult**iple **lin**es **o**f **te**xt **a**t **onc**e. **Th**is **all**ows **yo**u **t**o **re**ad **fast**er, **an**d **wi**th **le**ss **effo**rt.
|
|
66
|
+
|
|
67
|
+
**Metagu**iding **i**s **partic**ulary **use**ful **fo**r **peo**ple **wi**th **dysl**exia **o**r **ADH**D, **bu**t **i**t **ca**n **b**e **us**ed **b**y **any**one **wh**o **wan**ts **t**o **impr**ove **the**ir **read**ing **foc**us **an**d **spe**ed. **Fo**r **mo**re **inform**ation, **vis**it **th**e [**Intelli**reading **webs**ite.](https://intellireading.com/)
|
|
68
|
+
|
|
69
|
+
## Features
|
|
70
|
+
|
|
71
|
+
Intellireading commands can be used to:
|
|
72
|
+
- **Metaguide an EPUB file**: Metaguide an EPUB file, transforming it into a metaguided EPUB file, by transforming all XHTML files in the EPUB file into metaguided XHTML files.
|
|
73
|
+
- **Metaguide an XHTML file**: Metaguide an XHTML file, transforming it into a metaguided XHTML file.
|
|
74
|
+
- **Metaguide a directory**: Metaguide all files in a directory, transforming all EPUB, XHTML, and HTML files into metaguided files.
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
## Installation
|
|
78
|
+
Intellireading is a command line tool that can be used in Windows, Linux, and MacOS. It is written in Python and can be used as a module or as a standalone tool, as long as you have Python >3.7 installed (or Docker).
|
|
79
|
+
|
|
80
|
+
### pip
|
|
81
|
+
To install it, you can use pip:
|
|
82
|
+
```console
|
|
83
|
+
> pip install intellireading-cli
|
|
84
|
+
> intellireading --help
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### From source code
|
|
88
|
+
You can also install it from the source code:
|
|
89
|
+
```console
|
|
90
|
+
> git clone https://github.com/0x6f677548/intellireading-cli.git
|
|
91
|
+
> cd intellireading-cli
|
|
92
|
+
> pip install .
|
|
93
|
+
> intellireading --help
|
|
94
|
+
```
|
|
95
|
+
### Docker
|
|
96
|
+
Alternatively, you can use the Docker image:
|
|
97
|
+
|
|
98
|
+
#### Help command
|
|
99
|
+
```console
|
|
100
|
+
> docker pull ghcr.io/0x6f677548/intellireading-cli:latest
|
|
101
|
+
> docker run -it --rm ghcr.io/0x6f677548/intellireading-cli --help
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
#### Metaguide an EPUB file
|
|
105
|
+
##### Linux/MacOS
|
|
106
|
+
```console
|
|
107
|
+
```linux
|
|
108
|
+
> docker run -it --rm -v $(pwd)/tests:/tests ghcr.io/0x6f677548/intellireading-cli metaguide-epub --input_file '/tests/test_files/input.epub' --output_file '/tests/test_files/output.epub'
|
|
109
|
+
```
|
|
110
|
+
##### Windows
|
|
111
|
+
```powershell
|
|
112
|
+
> docker run -it --rm -v ${pwd}/tests:/tests ghcr.io/0x6f677548/intellireading-cli metaguide-epub --input_file '/tests/test_files/input.epub' --output_file '/tests/test_files/output.epub'
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
## Usage
|
|
118
|
+
All available commands and options can be seen by using the `--help` option.
|
|
119
|
+
```console
|
|
120
|
+
> intellireading --help
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
To get help on a specific command, use the `--help` option with the command name. For example, to get help on the `metaguide-epub` command, use the following command:
|
|
124
|
+
```console
|
|
125
|
+
> intellireading metaguide-epub --help
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Intellireading is based on [Click](https://github.com/pallets/click/), taking advantage of its features, such as chaining commands and options.
|
|
129
|
+
|
|
130
|
+
### Usage Examples
|
|
131
|
+
|
|
132
|
+
#### Metaguide an EPUB file
|
|
133
|
+
To metaguide an EPUB file, use the `metaguide-epub` command. The command requires the path to the EPUB file and the output file. The output file will be a metaguided epub file.
|
|
134
|
+
|
|
135
|
+
```console
|
|
136
|
+
> intellireading metaguide-epub --input_file mybook.epub --output_file mybook_metaguided.epub
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
#### Metaguide a XHTML file
|
|
140
|
+
To metaguide an XHTML file, use the `metaguide-xhtml` command. The command requires the path to the XHTML file and the output file. The output file will be a metaguided xhtml file.
|
|
141
|
+
|
|
142
|
+
```console
|
|
143
|
+
> intellireading metaguide-xhtml --input_file mybook.xhtml --output_file mybook_metaguided.xhtml
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
#### Metaguide all files in a directory
|
|
147
|
+
To metaguide all files in a directory, use the `metaguide-dir` command. The command requires the path to the directory and the output directory. The output directory will contain all metaguided files, including epub, xhtml and html files.
|
|
148
|
+
|
|
149
|
+
```console
|
|
150
|
+
> intellireading metaguide-dir --input_dir mydir --output_dir mydir_metaguided
|
|
151
|
+
```
|
|
152
|
+
|