sleepyconvert 2.3.2__tar.gz → 2.4.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.
Files changed (42) hide show
  1. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/PKG-INFO +32 -5
  2. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/README.md +30 -3
  3. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/pyproject.toml +2 -2
  4. sleepyconvert-2.4.0/sleepyconvert/api.py +87 -0
  5. sleepyconvert-2.4.0/sleepyconvert/core/about.py +58 -0
  6. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/core/config.py +7 -5
  7. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/main.py +10 -4
  8. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/__init__.py +14 -0
  9. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/doc_shared.py +68 -28
  10. sleepyconvert-2.4.0/sleepyconvert/utils/epub_html.py +21 -0
  11. sleepyconvert-2.4.0/sleepyconvert/utils/epub_md.py +21 -0
  12. sleepyconvert-2.4.0/sleepyconvert/utils/epub_pdf.py +21 -0
  13. sleepyconvert-2.4.0/sleepyconvert/utils/epub_shared.py +848 -0
  14. sleepyconvert-2.4.0/sleepyconvert/utils/epub_txt.py +21 -0
  15. sleepyconvert-2.4.0/sleepyconvert/utils/html_txt.py +21 -0
  16. sleepyconvert-2.4.0/sleepyconvert/utils/md_txt.py +21 -0
  17. sleepyconvert-2.4.0/sleepyconvert/utils/pdf_render.py +452 -0
  18. sleepyconvert-2.4.0/sleepyconvert/utils/pdf_txt.py +21 -0
  19. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/LICENSE +0 -0
  20. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/__init__.py +0 -0
  21. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/cli/__init__.py +0 -0
  22. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/cli/command_logic.py +0 -0
  23. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/core/__init__.py +0 -0
  24. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/core/logging.py +0 -0
  25. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/core/sleepy_params.py +0 -0
  26. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/core/version.py +0 -0
  27. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/csv_json.py +0 -0
  28. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/csv_parquet.py +0 -0
  29. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/csv_pkl.py +0 -0
  30. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/csv_xlsx.py +0 -0
  31. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/data_shared.py +0 -0
  32. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/html_md.py +0 -0
  33. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/html_pdf.py +0 -0
  34. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/image_shared.py +0 -0
  35. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/json_parquet.py +0 -0
  36. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/json_pkl.py +0 -0
  37. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/json_xlsx.py +0 -0
  38. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/md_pdf.py +0 -0
  39. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/parquet_pkl.py +0 -0
  40. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/parquet_xlsx.py +0 -0
  41. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/pkl_xlsx.py +0 -0
  42. {sleepyconvert-2.3.2 → sleepyconvert-2.4.0}/sleepyconvert/utils/png_jpg.py +0 -0
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sleepyconvert
3
- Version: 2.3.2
3
+ Version: 2.4.0
4
4
  Summary: Convert data files, images, and documents between formats from a single terse CLI.
5
5
  License-Expression: GPL-3.0-or-later
6
6
  License-File: LICENSE
7
- Keywords: pandas,data,documents,images,converter,cli
7
+ Keywords: pandas,data,documents,epub,images,converter,cli
8
8
  Author: Isaac Yep
9
9
  Author-email: anthonybenchyep@gmail.com
10
10
  Requires-Python: >=3.11
@@ -62,7 +62,7 @@ Description-Content-Type: text/markdown
62
62
  uv tool install sleepyconvert # or: pipx install sleepyconvert
63
63
  ```
64
64
 
65
- > `-v` / `--version` prints the version and best-effort checks PyPI for a newer release — it works even when placed alongside the paths.
65
+ > `-v` / `--version` prints the version and best-effort checks PyPI for a newer release — it works even when placed alongside the paths. Run `sleepyconvert about` for the project's PyPI + GitHub links.
66
66
 
67
67
  ## Configure
68
68
 
@@ -81,7 +81,7 @@ convert_output_archive_dir: null # a dir → also save a dated copy of every o
81
81
  | --- | --- |
82
82
  | **Data** | `csv`, `parquet`, `json`, `pkl`, `xlsx` |
83
83
  | **Images** | `png`, `jpg`, `jpeg` |
84
- | **Documents** | `html`, `pdf`, `md` |
84
+ | **Documents** | `html`, `pdf`, `md`, `txt`, `epub` |
85
85
 
86
86
  Any pair **within the same category** is valid (in either direction); cross-category conversions are rejected.
87
87
 
@@ -107,13 +107,18 @@ $ sleepyconvert photo.png photo.jpg
107
107
  Created /Users/dingus/pics/photo.jpg
108
108
  ```
109
109
 
110
- **Documents** — convert between markup and PDF:
110
+ **Documents** — convert between markup, text, PDF and EPUB:
111
111
 
112
112
  ```console
113
113
  $ sleepyconvert notes.md notes.pdf
114
114
  Created /Users/dingus/docs/notes.pdf
115
+
116
+ $ sleepyconvert notes.md notes.epub
117
+ Created /Users/dingus/docs/notes.epub
115
118
  ```
116
119
 
120
+ EPUB output is e-reader ready: chapters split at top-level headings, a table of contents, and local images embedded. See [EPUB conversions](docs/epub.md).
121
+
117
122
  With `convert_output_archive_dir` set, each conversion also writes a dated archive copy:
118
123
 
119
124
  ```console
@@ -130,6 +135,26 @@ Error: Input and output extensions must belong to the same type group.
130
135
  Use `convert --help` to see the supported categories.
131
136
  ```
132
137
 
138
+ **About** — print the version and the project's public PyPI + GitHub links:
139
+
140
+ ```console
141
+ $ sleepyconvert about
142
+ sleepyconvert 2.3.1
143
+ PyPI: https://pypi.org/project/sleepyconvert/
144
+ GitHub: https://github.com/anthonybench/convert
145
+ ```
146
+
147
+ ## Library use
148
+
149
+ The `sleepyconvert.api` module converts without touching `~/sleepyconfig`, archiving, or printing — suitable for services and containers:
150
+
151
+ ```python
152
+ from sleepyconvert.api import canConvert, convertFile
153
+
154
+ if canConvert("md", "epub"):
155
+ convertFile("notes.md", "notes.epub") # raises ValueError / FileNotFoundError
156
+ ```
157
+
133
158
  ## Development
134
159
 
135
160
  ```sh
@@ -144,5 +169,7 @@ uv run pytest # or ./tools/test.sh
144
169
  - [Project outline](docs/OUTLINE.md) — repository layout
145
170
  - [Test drive](docs/test_drive.md) — setup, testing, and CLI usage
146
171
  - [Adding a conversion](docs/new_command.md) — how to add a new format pair
172
+ - [EPUB conversions](docs/epub.md) — how document formats convert to and from EPUB
173
+ - [Library API](docs/api.md) — calling sleepyconvert from Python
147
174
  - [Publishing](docs/publish.md) — release to PyPI
148
175
 
@@ -18,7 +18,7 @@
18
18
  uv tool install sleepyconvert # or: pipx install sleepyconvert
19
19
  ```
20
20
 
21
- > `-v` / `--version` prints the version and best-effort checks PyPI for a newer release — it works even when placed alongside the paths.
21
+ > `-v` / `--version` prints the version and best-effort checks PyPI for a newer release — it works even when placed alongside the paths. Run `sleepyconvert about` for the project's PyPI + GitHub links.
22
22
 
23
23
  ## Configure
24
24
 
@@ -37,7 +37,7 @@ convert_output_archive_dir: null # a dir → also save a dated copy of every o
37
37
  | --- | --- |
38
38
  | **Data** | `csv`, `parquet`, `json`, `pkl`, `xlsx` |
39
39
  | **Images** | `png`, `jpg`, `jpeg` |
40
- | **Documents** | `html`, `pdf`, `md` |
40
+ | **Documents** | `html`, `pdf`, `md`, `txt`, `epub` |
41
41
 
42
42
  Any pair **within the same category** is valid (in either direction); cross-category conversions are rejected.
43
43
 
@@ -63,13 +63,18 @@ $ sleepyconvert photo.png photo.jpg
63
63
  Created /Users/dingus/pics/photo.jpg
64
64
  ```
65
65
 
66
- **Documents** — convert between markup and PDF:
66
+ **Documents** — convert between markup, text, PDF and EPUB:
67
67
 
68
68
  ```console
69
69
  $ sleepyconvert notes.md notes.pdf
70
70
  Created /Users/dingus/docs/notes.pdf
71
+
72
+ $ sleepyconvert notes.md notes.epub
73
+ Created /Users/dingus/docs/notes.epub
71
74
  ```
72
75
 
76
+ EPUB output is e-reader ready: chapters split at top-level headings, a table of contents, and local images embedded. See [EPUB conversions](docs/epub.md).
77
+
73
78
  With `convert_output_archive_dir` set, each conversion also writes a dated archive copy:
74
79
 
75
80
  ```console
@@ -86,6 +91,26 @@ Error: Input and output extensions must belong to the same type group.
86
91
  Use `convert --help` to see the supported categories.
87
92
  ```
88
93
 
94
+ **About** — print the version and the project's public PyPI + GitHub links:
95
+
96
+ ```console
97
+ $ sleepyconvert about
98
+ sleepyconvert 2.3.1
99
+ PyPI: https://pypi.org/project/sleepyconvert/
100
+ GitHub: https://github.com/anthonybench/convert
101
+ ```
102
+
103
+ ## Library use
104
+
105
+ The `sleepyconvert.api` module converts without touching `~/sleepyconfig`, archiving, or printing — suitable for services and containers:
106
+
107
+ ```python
108
+ from sleepyconvert.api import canConvert, convertFile
109
+
110
+ if canConvert("md", "epub"):
111
+ convertFile("notes.md", "notes.epub") # raises ValueError / FileNotFoundError
112
+ ```
113
+
89
114
  ## Development
90
115
 
91
116
  ```sh
@@ -100,4 +125,6 @@ uv run pytest # or ./tools/test.sh
100
125
  - [Project outline](docs/OUTLINE.md) — repository layout
101
126
  - [Test drive](docs/test_drive.md) — setup, testing, and CLI usage
102
127
  - [Adding a conversion](docs/new_command.md) — how to add a new format pair
128
+ - [EPUB conversions](docs/epub.md) — how document formats convert to and from EPUB
129
+ - [Library API](docs/api.md) — calling sleepyconvert from Python
103
130
  - [Publishing](docs/publish.md) — release to PyPI
@@ -4,13 +4,13 @@ build-backend = "poetry.core.masonry.api"
4
4
 
5
5
  [project]
6
6
  name = "sleepyconvert"
7
- version = "2.3.2"
7
+ version = "2.4.0"
8
8
  description = "Convert data files, images, and documents between formats from a single terse CLI."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
11
11
  license = "GPL-3.0-or-later"
12
12
  license-files = ["LICENSE"]
13
- keywords = ["pandas", "data", "documents", "images", "converter", "cli"]
13
+ keywords = ["pandas", "data", "documents", "epub", "images", "converter", "cli"]
14
14
  authors = [{ name = "Isaac Yep", email = "anthonybenchyep@gmail.com" }]
15
15
  classifiers = [
16
16
  "Development Status :: 5 - Production/Stable",
@@ -0,0 +1,87 @@
1
+ """Programmatic API for using sleepyconvert as a library.
2
+
3
+ Unlike the CLI, these functions never read or write the shared sleepy config
4
+ (``~/sleepyconfig/params.yml``), never archive outputs and never print, which
5
+ makes them safe to call from services and containers:
6
+
7
+ ```python
8
+ from sleepyconvert.api import convertFile
9
+
10
+ convertFile("notes.md", "notes.epub")
11
+ ```
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from pathlib import Path
17
+
18
+ from sleepyconvert.core.config import SUPPORTED_EXTENSIONS
19
+ from sleepyconvert.utils import getConversionHandler
20
+
21
+ __all__ = ["canConvert", "convertFile", "SUPPORTED_EXTENSIONS"]
22
+
23
+
24
+ def _extensionCategory(extension: str) -> str | None:
25
+ """Return the category of a lowercase, dot-less extension.
26
+
27
+ Parameters:
28
+ extension: The extension, e.g. ``md``.
29
+
30
+ Returns:
31
+ The category name, or ``None`` when unsupported.
32
+ """
33
+
34
+ for category_name, extensions in SUPPORTED_EXTENSIONS.items():
35
+ if extension in extensions:
36
+ return category_name
37
+ return None
38
+
39
+
40
+ def canConvert(input_extension: str, output_extension: str) -> bool:
41
+ """Report whether a conversion between two extensions is supported.
42
+
43
+ Parameters:
44
+ input_extension: The source extension, with or without a leading dot.
45
+ output_extension: The destination extension, with or without a leading dot.
46
+
47
+ Returns:
48
+ ``True`` when both extensions share a category and differ.
49
+ """
50
+
51
+ source = input_extension.lower().lstrip(".")
52
+ target = output_extension.lower().lstrip(".")
53
+ category = _extensionCategory(source)
54
+ return category is not None and source != target and category == _extensionCategory(target)
55
+
56
+
57
+ def convertFile(input_path: Path | str, output_path: Path | str) -> Path:
58
+ """Convert a file, inferring the conversion from both paths' extensions.
59
+
60
+ Parameters:
61
+ input_path: The existing source file.
62
+ output_path: The destination file; parent directories are created.
63
+
64
+ Returns:
65
+ The resolved output path.
66
+
67
+ Raises:
68
+ FileNotFoundError: When the input file does not exist.
69
+ ValueError: When the extension pair is not a supported conversion.
70
+ """
71
+
72
+ source = Path(input_path).expanduser().resolve()
73
+ target = Path(output_path).expanduser().resolve()
74
+ source_extension = source.suffix.lower().lstrip(".")
75
+ target_extension = target.suffix.lower().lstrip(".")
76
+
77
+ if not canConvert(source_extension, target_extension):
78
+ raise ValueError(f"Unsupported conversion: .{source_extension} -> .{target_extension}")
79
+ if not source.is_file():
80
+ raise FileNotFoundError(f"Input file does not exist: {source}")
81
+
82
+ handler = getConversionHandler(
83
+ input_extension=source_extension, output_extension=target_extension
84
+ )
85
+ target.parent.mkdir(parents=True, exist_ok=True)
86
+ handler(source, target)
87
+ return target
@@ -0,0 +1,58 @@
1
+ """Public project links for the ``about`` pseudo-command.
2
+
3
+ sleepyconvert is a single-command CLI, so ``about`` is handled by a pre-scan in
4
+ the entrypoint (like ``--version``) rather than a Typer subcommand. The GitHub
5
+ URL is read from the installed package metadata (i.e. the ``[project.urls]``
6
+ entries) with a hardcoded fallback for running uninstalled from source; the PyPI
7
+ URL is derived from the distribution name.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from importlib.metadata import PackageNotFoundError, metadata
13
+
14
+ from sleepyconvert.core.version import DIST_NAME, getVersion
15
+
16
+ _GITHUB_FALLBACK = "https://github.com/anthonybench/convert"
17
+
18
+
19
+ def pypiUrl() -> str:
20
+ """Return the public PyPI project URL."""
21
+
22
+ return f"https://pypi.org/project/{DIST_NAME}/"
23
+
24
+
25
+ def githubUrl() -> str:
26
+ """Return the public GitHub URL from package metadata, or a fallback."""
27
+
28
+ try:
29
+ entries = metadata(DIST_NAME).get_all("Project-URL") or []
30
+ except PackageNotFoundError:
31
+ return _GITHUB_FALLBACK
32
+
33
+ labelled: dict[str, str] = {}
34
+ for entry in entries: # each entry looks like "Source, https://github.com/…"
35
+ label, _, url = entry.partition(",")
36
+ labelled[label.strip().lower()] = url.strip()
37
+
38
+ for key in ("source", "homepage", "repository"):
39
+ if "github.com" in labelled.get(key, ""):
40
+ return labelled[key]
41
+ for url in labelled.values():
42
+ if "github.com" in url:
43
+ return url
44
+ return _GITHUB_FALLBACK
45
+
46
+
47
+ def wantsAbout(args) -> bool:
48
+ """Return whether the first argument is the ``about`` pseudo-command."""
49
+
50
+ return bool(args) and args[0] == "about"
51
+
52
+
53
+ def printAbout() -> None:
54
+ """Print the project's version and public PyPI + GitHub links."""
55
+
56
+ print(f"{DIST_NAME} {getVersion()}")
57
+ print(f"PyPI: {pypiUrl()}")
58
+ print(f"GitHub: {githubUrl()}")
@@ -8,6 +8,12 @@ import os
8
8
 
9
9
  from sleepyconvert.core.sleepy_params import loadSleepyParams, requireParam
10
10
 
11
+ SUPPORTED_EXTENSIONS: dict[str, tuple[str, ...]] = {
12
+ "data": ("csv", "parquet", "json", "pkl", "xlsx"),
13
+ "img": ("png", "jpg", "jpeg"),
14
+ "doc": ("html", "pdf", "md", "txt", "epub"),
15
+ }
16
+
11
17
 
12
18
  @dataclass(frozen=True)
13
19
  class AppConfig:
@@ -53,11 +59,7 @@ def loadAppConfig() -> AppConfig:
53
59
  The populated application configuration.
54
60
  """
55
61
 
56
- supported_extensions = {
57
- "data": ("csv", "parquet", "json", "pkl", "xlsx"),
58
- "img": ("png", "jpg", "jpeg"),
59
- "doc": ("html", "pdf", "md"),
60
- }
62
+ supported_extensions = dict(SUPPORTED_EXTENSIONS)
61
63
  log_level = os.getenv("CONVERT_LOG_LEVEL", "INFO").upper()
62
64
 
63
65
  params = loadSleepyParams()
@@ -7,13 +7,14 @@ import sys
7
7
  import typer
8
8
 
9
9
  from sleepyconvert.cli.command_logic import runConversion
10
+ from sleepyconvert.core.about import printAbout, wantsAbout
10
11
  from sleepyconvert.core.version import printVersion, wantsVersion
11
12
 
12
13
  app = typer.Typer(
13
14
  add_completion=False,
14
15
  help=(
15
16
  "Convert files between supported formats by passing an input and output path. "
16
- "Pass -v/--version to print the version."
17
+ "Pass -v/--version to print the version, or `about` for project links."
17
18
  ),
18
19
  )
19
20
 
@@ -28,13 +29,18 @@ def main(input_path: str, output_path: str) -> None:
28
29
  def run() -> None:
29
30
  """Run the Typer application.
30
31
 
31
- ``-v``/``--version`` is honored before Typer parses, so it works even when it
32
- appears alongside the paths; the conversion is skipped.
32
+ ``-v``/``--version`` and the ``about`` pseudo-command are honored before Typer
33
+ parses (sleepyconvert is a single-command CLI, so they can't be real
34
+ subcommands); when present, the conversion is skipped.
33
35
  """
34
36
 
35
- if wantsVersion(sys.argv[1:]):
37
+ args = sys.argv[1:]
38
+ if wantsVersion(args):
36
39
  printVersion()
37
40
  return
41
+ if wantsAbout(args):
42
+ printAbout()
43
+ return
38
44
  app()
39
45
 
40
46
 
@@ -9,14 +9,21 @@ from sleepyconvert.utils.csv_json import convertCsvJson
9
9
  from sleepyconvert.utils.csv_parquet import convertCsvParquet
10
10
  from sleepyconvert.utils.csv_pkl import convertCsvPkl
11
11
  from sleepyconvert.utils.csv_xlsx import convertCsvXlsx
12
+ from sleepyconvert.utils.epub_html import convertEpubHtml
13
+ from sleepyconvert.utils.epub_md import convertEpubMd
14
+ from sleepyconvert.utils.epub_pdf import convertEpubPdf
15
+ from sleepyconvert.utils.epub_txt import convertEpubTxt
12
16
  from sleepyconvert.utils.html_md import convertHtmlMd
13
17
  from sleepyconvert.utils.html_pdf import convertHtmlPdf
18
+ from sleepyconvert.utils.html_txt import convertHtmlTxt
14
19
  from sleepyconvert.utils.json_parquet import convertJsonParquet
15
20
  from sleepyconvert.utils.json_pkl import convertJsonPkl
16
21
  from sleepyconvert.utils.json_xlsx import convertJsonXlsx
17
22
  from sleepyconvert.utils.md_pdf import convertMdPdf
23
+ from sleepyconvert.utils.md_txt import convertMdTxt
18
24
  from sleepyconvert.utils.parquet_pkl import convertParquetPkl
19
25
  from sleepyconvert.utils.parquet_xlsx import convertParquetXlsx
26
+ from sleepyconvert.utils.pdf_txt import convertPdfTxt
20
27
  from sleepyconvert.utils.pkl_xlsx import convertPklXlsx
21
28
  from sleepyconvert.utils.png_jpg import convertPngJpg
22
29
 
@@ -39,6 +46,13 @@ _HANDLERS: dict[frozenset[str], ConversionHandler] = {
39
46
  frozenset({"html", "md"}): convertHtmlMd,
40
47
  frozenset({"html", "pdf"}): convertHtmlPdf,
41
48
  frozenset({"md", "pdf"}): convertMdPdf,
49
+ frozenset({"epub", "html"}): convertEpubHtml,
50
+ frozenset({"epub", "md"}): convertEpubMd,
51
+ frozenset({"epub", "pdf"}): convertEpubPdf,
52
+ frozenset({"epub", "txt"}): convertEpubTxt,
53
+ frozenset({"html", "txt"}): convertHtmlTxt,
54
+ frozenset({"md", "txt"}): convertMdTxt,
55
+ frozenset({"pdf", "txt"}): convertPdfTxt,
42
56
  }
43
57
 
44
58
 
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import re
5
6
  from html import escape
6
7
  from pathlib import Path
7
8
 
@@ -9,8 +10,12 @@ from bs4 import BeautifulSoup
9
10
  from markdown import markdown
10
11
  from markdownify import markdownify
11
12
  from pypdf import PdfReader
12
- from reportlab.lib.pagesizes import letter
13
- from reportlab.pdfgen.canvas import Canvas
13
+
14
+ from sleepyconvert.utils.pdf_render import writePdfFromHtml
15
+
16
+ MARKDOWN_INDENT = 4
17
+ _LIST_MARKER = re.compile(r"^( *)(?:[-*+]|\d+[.)])\s")
18
+ _FENCE = re.compile(r"^( *)(```|~~~)")
14
19
 
15
20
 
16
21
  def convertHtmlMd(input_path: Path, output_path: Path) -> None:
@@ -51,9 +56,9 @@ def convertHtmlPdf(input_path: Path, output_path: Path) -> None:
51
56
 
52
57
  match (input_path.suffix.lower(), output_path.suffix.lower()):
53
58
  case (".html", ".pdf"):
54
- html_content = input_path.read_text(encoding="utf-8")
55
- plain_text = extractTextFromHtml(html_content=html_content)
56
- writePdfFromText(output_path=output_path, text_content=plain_text)
59
+ writePdfFromHtml(
60
+ output_path=output_path, html_content=input_path.read_text(encoding="utf-8")
61
+ )
57
62
  case (".pdf", ".html"):
58
63
  plain_text = extractTextFromPdf(input_path=input_path)
59
64
  output_path.write_text(renderHtmlFromText(text_content=plain_text), encoding="utf-8")
@@ -76,10 +81,9 @@ def convertMdPdf(input_path: Path, output_path: Path) -> None:
76
81
 
77
82
  match (input_path.suffix.lower(), output_path.suffix.lower()):
78
83
  case (".md", ".pdf"):
79
- markdown_content = input_path.read_text(encoding="utf-8")
80
- html_content = markdown(markdown_content)
81
- plain_text = extractTextFromHtml(html_content=html_content)
82
- writePdfFromText(output_path=output_path, text_content=plain_text)
84
+ markdown_content = normalizeListIndent(input_path.read_text(encoding="utf-8"))
85
+ html_content = markdown(markdown_content, extensions=["extra", "sane_lists"])
86
+ writePdfFromHtml(output_path=output_path, html_content=html_content)
83
87
  case (".pdf", ".md"):
84
88
  plain_text = extractTextFromPdf(input_path=input_path)
85
89
  output_path.write_text(plain_text, encoding="utf-8")
@@ -132,28 +136,64 @@ def renderHtmlFromText(text_content: str) -> str:
132
136
  return f"<html><body><pre>{escaped_text}</pre></body></html>"
133
137
 
134
138
 
135
- def writePdfFromText(output_path: Path, text_content: str) -> None:
136
- """Write plain text content into a basic PDF file.
139
+ def normalizeListIndent(markdown_content: str) -> str:
140
+ """Rescale nested list indentation to the 4 spaces Python-Markdown expects.
141
+
142
+ Editors and formatters such as prettier nest lists with 2 or 3 spaces, which
143
+ Python-Markdown flattens into a single level. Indentation inside list blocks is
144
+ rescaled; lines outside lists are left untouched.
137
145
 
138
146
  Parameters:
139
- output_path: The destination PDF file path.
140
- text_content: The text content to render into the PDF.
147
+ markdown_content: The Markdown source.
141
148
 
142
149
  Returns:
143
- None.
150
+ The Markdown source with list nesting indented by 4 spaces per level.
144
151
  """
145
152
 
146
- pdf_canvas = Canvas(str(output_path), pagesize=letter)
147
- page_width, page_height = letter
148
- x_position = 72
149
- y_position = page_height - 72
150
- line_height = 16
151
-
152
- for line in text_content.splitlines() or [""]:
153
- if y_position <= 72:
154
- pdf_canvas.showPage()
155
- y_position = page_height - 72
156
- pdf_canvas.drawString(x_position, y_position, line[:110])
157
- y_position -= line_height
158
-
159
- pdf_canvas.save()
153
+ lines = markdown_content.splitlines()
154
+ indents = [
155
+ len(match.group(1))
156
+ for line in lines
157
+ if (match := _LIST_MARKER.match(line)) and match.group(1)
158
+ ]
159
+ unit = min(indents, default=MARKDOWN_INDENT)
160
+ if unit >= MARKDOWN_INDENT:
161
+ return markdown_content
162
+
163
+ def rescale(indent: int) -> int:
164
+ """Map an indent measured in ``unit`` steps onto 4-space steps.
165
+
166
+ Parameters:
167
+ indent: The original number of leading spaces.
168
+
169
+ Returns:
170
+ The rescaled number of leading spaces.
171
+ """
172
+
173
+ return indent // unit * MARKDOWN_INDENT + indent % unit
174
+
175
+ result: list[str] = []
176
+ in_list = False
177
+ fence_shift: int | None = None
178
+ for line in lines:
179
+ indent = len(line) - len(line.lstrip(" "))
180
+ fence = _FENCE.match(line)
181
+ if fence_shift is not None:
182
+ result.append(" " * fence_shift + line if line.strip() else line)
183
+ if fence:
184
+ fence_shift = None
185
+ continue
186
+ if _LIST_MARKER.match(line) and indent == 0:
187
+ in_list = True
188
+ elif line.strip() and indent == 0:
189
+ in_list = False
190
+ if not in_list or not line.strip():
191
+ if fence:
192
+ fence_shift = 0
193
+ result.append(line)
194
+ continue
195
+ shift = rescale(indent) - indent
196
+ if fence:
197
+ fence_shift = shift
198
+ result.append(" " * shift + line)
199
+ return "\n".join(result) + ("\n" if markdown_content.endswith("\n") else "")
@@ -0,0 +1,21 @@
1
+ """EPUB and HTML conversion logic."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from sleepyconvert.utils.epub_shared import convertViaHtmlDocument
8
+
9
+
10
+ def convertEpubHtml(input_path: Path, output_path: Path) -> None:
11
+ """Convert between EPUB and HTML document files.
12
+
13
+ Parameters:
14
+ input_path: The source file path.
15
+ output_path: The destination file path.
16
+
17
+ Returns:
18
+ None.
19
+ """
20
+
21
+ convertViaHtmlDocument(input_path=input_path, output_path=output_path)
@@ -0,0 +1,21 @@
1
+ """EPUB and Markdown conversion logic."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from sleepyconvert.utils.epub_shared import convertViaHtmlDocument
8
+
9
+
10
+ def convertEpubMd(input_path: Path, output_path: Path) -> None:
11
+ """Convert between EPUB and Markdown document files.
12
+
13
+ Parameters:
14
+ input_path: The source file path.
15
+ output_path: The destination file path.
16
+
17
+ Returns:
18
+ None.
19
+ """
20
+
21
+ convertViaHtmlDocument(input_path=input_path, output_path=output_path)
@@ -0,0 +1,21 @@
1
+ """EPUB and PDF conversion logic."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from sleepyconvert.utils.epub_shared import convertViaHtmlDocument
8
+
9
+
10
+ def convertEpubPdf(input_path: Path, output_path: Path) -> None:
11
+ """Convert between EPUB and PDF document files.
12
+
13
+ Parameters:
14
+ input_path: The source file path.
15
+ output_path: The destination file path.
16
+
17
+ Returns:
18
+ None.
19
+ """
20
+
21
+ convertViaHtmlDocument(input_path=input_path, output_path=output_path)