diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..61cf301 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,10 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 +max_line_length = 100 + diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..c80badb --- /dev/null +++ b/.env.example @@ -0,0 +1,11 @@ +# OneDrive / Microsoft Graph configuration +ONEDRIVE_CLIENT_ID= # TODO: set your Azure app client ID +ONEDRIVE_CLIENT_SECRET= # TODO: set your Azure app client secret (if used) +ONEDRIVE_TENANT_ID=consumers # TODO: 'consumers' for personal Microsoft accounts + +# When using OneDrive source +SRC_FOLDER=onedrive:/Documents/Books # TODO: OneDrive path or local folder + +# Output folder for build artifacts +OUT_FOLDER=dist # TODO: output directory + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..bd32416 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,42 @@ +name: CI + +on: + push: + branches: ["main"] + pull_request: + branches: ["main"] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - name: Install Poetry + run: pipx install poetry + - name: Install deps + run: poetry install + - name: Lint + run: | + poetry run black --check . + poetry run flake8 + - name: Type check + run: poetry run mypy avendehut + - name: Test + run: poetry run pytest --maxfail=1 --disable-warnings -q + - name: Build sample + run: | + mkdir -p examples/books + # Generate a tiny PDF + python - <<'PY' +from pypdf import PdfWriter +from pathlib import Path +src = Path('examples/books'); src.mkdir(parents=True, exist_ok=True) +writer = PdfWriter(); writer.add_blank_page(width=72, height=72); writer.add_metadata({"/Title": "CI PDF", "/Author": "CI"}) +with open(src / 'ci.pdf', 'wb') as f: + writer.write(f) +PY + poetry run avendehut build --src examples/books --out dist + diff --git a/.gitignore b/.gitignore index b7faf40..aeffe5f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,37 @@ +# Python +__pycache__/ +*.pyc +*.pyo +*.pyd +.Python +*.so + +# Env +.env +.venv/ +venv/ + +# Poetry +poetry.lock + +# Tests +.pytest_cache/ +.coverage +coverage.xml +htmlcov/ + +# Build artifacts +dist/ +build/ +*.egg-info/ + +# IDE +.vscode/ +.idea/ + +# Generated site +site/ + # Byte-compiled / optimized / DLL files __pycache__/ *.py[codz] diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md new file mode 100644 index 0000000..8a18c94 --- /dev/null +++ b/CONTRIBUTORS.md @@ -0,0 +1,8 @@ +## Contributors + +Thanks to everyone who has contributed to `avendehut`. + +- Your Name Here + +_Please add your name here when you contribute to the project._ + diff --git a/LICENSE b/LICENSE index 261eeb9..4809b4a 100644 --- a/LICENSE +++ b/LICENSE @@ -1,3 +1,67 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. +Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. +Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. +You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + +(b) You must cause any modified files to carry prominent notices stating that You changed the files; and + +(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. +Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. +This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. +Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. +In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. +While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ diff --git a/README.md b/README.md index 0cf48c8..b21b29c 100644 --- a/README.md +++ b/README.md @@ -1 +1,120 @@ +## avendehut + +A CLI tool to scan a folder of books (local or OneDrive), extract metadata, generate tags, and produce a searchable HTML catalog. + +Inspired by the historical figure [Juan Hispalense (siglo XII)](https://es.wikipedia.org/wiki/Juan_Hispalense_%28siglo_XII%29), also known as Avendehut Hispanus. + +### Features + +- **📚 Metadata extraction**: EPUB, PDF, MOBI (extensible to other formats). +- **🏷 Automatic tag generation**: From metadata and file content. +- **🌐 HTML catalog generation**: + - Generates `index.html`, `data.json`, and static assets. + - Searchable, filterable, and responsive UI. + - Supports tag filtering, instant search, and lazy loading for large datasets. +- **⚡ Incremental builds**: Uses a `.manifest.json` to skip unchanged files. +- **☁ OneDrive integration**: Via Microsoft Graph API. +- **🔍 CLI search**: Search without opening the HTML site. +- **📤 Export catalog**: To CSV or JSON. +- **🖥 Cross‑platform**: macOS and Linux. + +### Requirements + +- **OS**: macOS or Linux +- **Python**: 3.10+ +- **Dependency management**: Poetry +- **For OneDrive integration**: + - Microsoft account + - Microsoft Graph API app registration + +### Installation + +1. Clone the repository. + ```bash + git clone https://github.com/khnumdev/avendehut.git + cd avendehut + ``` +2. Install dependencies with Poetry. + ```bash + poetry install + ``` +3. Set environment variables for OneDrive (if needed). + - `ONEDRIVE_CLIENT_ID` + - `ONEDRIVE_CLIENT_SECRET` + - `SRC_FOLDER` (OneDrive folder path) + - `OUT_FOLDER` (local output path) + +### OneDrive Setup + +- If `--src` points to a OneDrive path, the tool uses Microsoft Graph API. +- Required environment variables: + - `ONEDRIVE_CLIENT_ID` + - `ONEDRIVE_CLIENT_SECRET` + - `ONEDRIVE_TENANT_ID` + - `SRC_FOLDER` (OneDrive folder path) + - `OUT_FOLDER` (local output path) +- Register an app and configure permissions by following Microsoft's official docs: [Register an application](https://learn.microsoft.com/en-us/graph/auth-register-app-v2). + +### CLI Commands + +| Command | Description | Options | +| --- | --- | --- | +| `avendehut build` | Scans source folder, processes new/updated books, generates HTML site. | `--src ` (source folder), `--out ` (output folder), `--format html` (default), `--force` (reprocess all) | +| `avendehut watch` | Watches source folder for changes, auto‑rebuilds HTML. | Same as build plus `--interval ` | +| `avendehut clean` | Deletes generated output and manifest. | `--out ` | +| `avendehut open` | Opens generated HTML in default browser. | `--out ` | +| `avendehut search` | CLI search in local index. | `--query ""`, `--tags ""` | +| `avendehut export` | Exports catalog to CSV or JSON. | `--out `, `--format csv|json` | + +### Usage + +```bash +# Build a catalog from a local folder +poetry run avendehut build --src ./books --out ./dist + +# Open the generated HTML +poetry run avendehut open --out ./dist + +# Search from the CLI +poetry run avendehut search --out ./dist --query "Dune" --tags "sci-fi,epub" + +# Export catalog +poetry run avendehut export --src-out ./dist --format csv --out ./dist/catalog.csv +``` + +### HTML Catalog Features + +- Responsive design (mobile, tablet, desktop). +- Instant search with highlighting. +- Tag filtering (multi‑select). +- Lazy loading for large datasets. +- Split `data.json` into chunks if > 5 MB. +- Keyboard shortcuts for navigation. +- Dark mode toggle. + +### CI/CD Integration + +- Use GitHub Actions for: + - Linting (`flake8`, `black`). + - Running tests (`pytest`). + - Building HTML output. + - Deploying to GitHub Pages (optional). + +- Example workflow: + - Trigger on push to `main`. + - Install Python & Poetry. + - Run `poetry install`, `poetry run pytest`. + - If tests pass, run `avendehut build` and deploy. + +### Development Guide + +- Run in development mode: `poetry run avendehut --help`. +- Add new commands: extend the CLI module and register the command. +- Extend metadata extraction: add new extractor classes/modules. +- Contribute: see [`CONTRIBUTORS.md`](CONTRIBUTORS.md). + +### License + +Apache 2.0 License. + # avendehut \ No newline at end of file diff --git a/avendehut/__init__.py b/avendehut/__init__.py new file mode 100644 index 0000000..e685474 --- /dev/null +++ b/avendehut/__init__.py @@ -0,0 +1,11 @@ +"""avendehut package. + +CLI to scan books, extract metadata, and generate a searchable HTML catalog. +""" + +__all__ = [ + "__version__", +] + +__version__ = "0.1.0" + diff --git a/avendehut/cli.py b/avendehut/cli.py new file mode 100644 index 0000000..d112c47 --- /dev/null +++ b/avendehut/cli.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import sys + +import click +from rich.console import Console + +from .commands.build import build_command +from .commands.watch import watch_command +from .commands.clean import clean_command +from .commands.open import open_command +from .commands.search import search_command +from .commands.export import export_command + + +console = Console() + + +@click.group(context_settings={"help_option_names": ["-h", "-help", "--help"]}) +@click.version_option(package_name="avendehut") +def main() -> None: + """avendehut - build and search a local HTML catalog of books. + + Inspired by Juan Hispalense (Avendehut Hispanus). + """ + + +# Register subcommands +main.add_command(build_command, name="build") +main.add_command(watch_command, name="watch") +main.add_command(clean_command, name="clean") +main.add_command(open_command, name="open") +main.add_command(search_command, name="search") +main.add_command(export_command, name="export") + + +if __name__ == "__main__": # pragma: no cover + try: + main() + except click.ClickException as e: # pragma: no cover + console.print(f"[red]Error:[/red] {e}") + sys.exit(e.exit_code if hasattr(e, "exit_code") else 1) + diff --git a/avendehut/commands/build.py b/avendehut/commands/build.py new file mode 100644 index 0000000..439b01d --- /dev/null +++ b/avendehut/commands/build.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import hashlib +import os +from datetime import datetime, timezone +from pathlib import Path +from typing import Iterable, List + +import click +from rich.console import Console +from rich.progress import Progress + +from ..utils.metadata import extract_catalog_item +from ..utils.manifest import Manifest, ManifestFile, load_manifest, write_manifest +from ..utils.htmlgen import copy_template_and_write_data + + +console = Console() + + +SUPPORTED_EXTENSIONS = {".epub", ".pdf", ".mobi"} + + +def iter_source_files(src: Path) -> Iterable[Path]: + for root, _dirs, files in os.walk(src): + for name in files: + path = Path(root) / name + if path.suffix.lower() in SUPPORTED_EXTENSIONS: + yield path + + +def compute_file_hash(path: Path) -> str: + sha = hashlib.sha256() + with path.open("rb") as f: + for chunk in iter(lambda: f.read(1024 * 1024), b""): + sha.update(chunk) + return sha.hexdigest() + + +@click.command(context_settings={"help_option_names": ["-h", "-help", "--help"]}) +@click.option("--src", type=click.Path(exists=True, file_okay=False, path_type=Path), required=True, help="Source folder (local path)") +@click.option("--out", type=click.Path(file_okay=False, path_type=Path), required=True, help="Output folder") +@click.option("--format", "format_", type=click.Choice(["html"], case_sensitive=False), default="html", show_default=True) +@click.option("--force", is_flag=True, help="Reprocess all files, ignoring manifest") +def build_command(src: Path, out: Path, format_: str, force: bool) -> None: + """Scan source, process new/updated books, and generate HTML site.""" + out.mkdir(parents=True, exist_ok=True) + + manifest_path = out / ".manifest.json" + previous_manifest = None if force else load_manifest(manifest_path) + previous_index = {f.path_rel: f for f in (previous_manifest.files if previous_manifest else [])} + + source_files = list(iter_source_files(src)) + to_process: List[Path] = [] + manifest_files: List[ManifestFile] = [] + + for file_path in source_files: + stat = file_path.stat() + path_rel = str(file_path.relative_to(src)) + prev = previous_index.get(path_rel) + if prev and prev.size_bytes == stat.st_size and prev.mtime_ns == stat.st_mtime_ns: + manifest_files.append(prev) + continue + to_process.append(file_path) + + items = [] + with Progress() as progress: + task = progress.add_task("Processing files", total=len(to_process)) + for file_path in to_process: + try: + item = extract_catalog_item(src, file_path) + items.append(item) + + stat = file_path.stat() + sha256 = compute_file_hash(file_path) + manifest_files.append( + ManifestFile(path_rel=str(file_path.relative_to(src)), size_bytes=stat.st_size, mtime_ns=stat.st_mtime_ns, sha256=sha256) + ) + except Exception as exc: # pragma: no cover - rare edge cases + console.print(f"[yellow]Warning[/yellow]: Failed to process {file_path}: {exc}") + finally: + progress.advance(task) + + # If there was a previous catalog, we should merge unchanged items. + # For simplicity, regenerate catalog from disk for all manifest entries. + # This keeps logic deterministic while still skipping heavy parsing of unchanged files. + catalog = [] + for mf in manifest_files: + file_path = src / mf.path_rel + try: + catalog.append(extract_catalog_item(src, file_path)) + except Exception as exc: # pragma: no cover + console.print(f"[yellow]Warning[/yellow]: Failed to refresh {file_path}: {exc}") + + copy_template_and_write_data(out, catalog) + + manifest = Manifest(version="1", generated_at=datetime.now(timezone.utc).isoformat(), files=manifest_files) + write_manifest(manifest_path, manifest) + + console.print(f"[green]Build complete[/green]: {out}") + diff --git a/avendehut/commands/clean.py b/avendehut/commands/clean.py new file mode 100644 index 0000000..ca78f5f --- /dev/null +++ b/avendehut/commands/clean.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +import shutil +from pathlib import Path + +import click +from rich.console import Console + + +console = Console() + + +@click.command(context_settings={"help_option_names": ["-h", "-help", "--help"]}) +@click.option("--out", type=click.Path(file_okay=False, path_type=Path), required=True) +def clean_command(out: Path) -> None: + """Delete generated output and manifest.""" + if not out.exists(): + console.print(f"[yellow]Nothing to clean:[/yellow] {out}") + return + for child in out.iterdir(): + if child.name == ".gitkeep": + continue + if child.is_dir(): + shutil.rmtree(child) + else: + child.unlink(missing_ok=True) + console.print(f"[green]Cleaned:[/green] {out}") + diff --git a/avendehut/commands/export.py b/avendehut/commands/export.py new file mode 100644 index 0000000..1f1c977 --- /dev/null +++ b/avendehut/commands/export.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +import csv +import json +from pathlib import Path +from typing import Iterable + +import click + +from .search import iter_catalog + + +@click.command(context_settings={"help_option_names": ["-h", "-help", "--help"]}) +@click.option("--out", type=click.Path(dir_okay=False, path_type=Path), required=True) +@click.option("--format", "format_", type=click.Choice(["csv", "json"], case_sensitive=False), required=True) +@click.option("--src-out", "out_dir", type=click.Path(file_okay=False, path_type=Path), required=True, help="Directory containing built catalog (for reading data)") +def export_command(out: Path, format_: str, out_dir: Path) -> None: + """Export catalog to CSV or JSON.""" + items = list(iter_catalog(out_dir)) + if format_ == "json": + # Write atomically to avoid partial files + tmp = out.with_suffix(out.suffix + ".tmp") + tmp.write_text(json.dumps(items, ensure_ascii=False, indent=2), encoding="utf-8") + tmp.replace(out) + else: + fieldnames = [ + "id", + "path_rel", + "filename", + "extension", + "title", + "authors", + "published_year", + "language", + "size_bytes", + "tags", + "created_at", + "modified_at", + ] + # Write atomically to avoid partial files + tmp = out.with_suffix(out.suffix + ".tmp") + with tmp.open("w", newline="", encoding="utf-8") as f: + writer = csv.DictWriter(f, fieldnames=fieldnames) + writer.writeheader() + for it in items: + row = it.copy() + row["authors"] = ", ".join(row.get("authors", []) or []) + row["tags"] = ", ".join(row.get("tags", []) or []) + writer.writerow(row) + tmp.replace(out) + diff --git a/avendehut/commands/open.py b/avendehut/commands/open.py new file mode 100644 index 0000000..16fbe19 --- /dev/null +++ b/avendehut/commands/open.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import webbrowser +from pathlib import Path + +import click +from rich.console import Console + + +console = Console() + + +@click.command(context_settings={"help_option_names": ["-h", "-help", "--help"]}) +@click.option("--out", type=click.Path(file_okay=False, path_type=Path), required=True) +def open_command(out: Path) -> None: + """Open generated HTML in default browser.""" + index = out / "index.html" + if not index.exists(): + raise click.ClickException(f"index.html not found in {out}") + webbrowser.open_new_tab(index.resolve().as_uri()) + console.print(f"Opened {index}") + diff --git a/avendehut/commands/search.py b/avendehut/commands/search.py new file mode 100644 index 0000000..822c22c --- /dev/null +++ b/avendehut/commands/search.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Iterable, List + +import click +from rich.console import Console +from rich.table import Table + + +console = Console() + + +def iter_catalog(out: Path) -> Iterable[dict]: + data_json = out / "data.json" + data_index = out / "data" / "index.json" + if data_json.exists(): + data = json.loads(data_json.read_text(encoding="utf-8")) + for item in data: + yield item + elif data_index.exists(): + index = json.loads(data_index.read_text(encoding="utf-8")) + for chunk in index.get("chunks", []): + chunk_path = out / chunk + arr = json.loads(chunk_path.read_text(encoding="utf-8")) + for item in arr: + yield item + else: + raise click.ClickException("No catalog found. Run 'avendehut build' first.") + + +@click.command(context_settings={"help_option_names": ["-h", "-help", "--help"]}) +@click.option("--out", type=click.Path(file_okay=False, path_type=Path), required=True) +@click.option("--query", type=str, default="", help="Search text") +@click.option("--tags", type=str, default="", help="Comma-separated tags to filter") +def search_command(out: Path, query: str, tags: str) -> None: + """Search the local catalog index from the CLI.""" + query_lower = query.lower().strip() + tag_filters = [t.strip().lower() for t in tags.split(",") if t.strip()] + + results: List[dict] = [] + for item in iter_catalog(out): + haystack = " ".join([ + item.get("title", ""), + ", ".join(item.get("authors", []) or []), + " ".join(item.get("tags", []) or []), + ]).lower() + if query_lower and query_lower not in haystack: + continue + if tag_filters: + item_tags = {t.lower() for t in (item.get("tags", []) or [])} + if not set(tag_filters).issubset(item_tags): + continue + results.append(item) + + table = Table(show_header=True, header_style="bold") + table.add_column("Title") + table.add_column("Authors") + table.add_column("Year") + table.add_column("Path") + for it in results[:50]: + table.add_row( + it.get("title", ""), + ", ".join(it.get("authors", []) or []), + str(it.get("published_year", "") or ""), + it.get("path_rel", ""), + ) + console.print(table) + console.print(f"[green]{len(results)}[/green] result(s)") + diff --git a/avendehut/commands/watch.py b/avendehut/commands/watch.py new file mode 100644 index 0000000..4181d63 --- /dev/null +++ b/avendehut/commands/watch.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +import time +from pathlib import Path + +import click +from rich.console import Console + +from .build import build_command + + +console = Console() + + +@click.command(context_settings={"help_option_names": ["-h", "-help", "--help"]}) +@click.option("--src", type=click.Path(exists=True, file_okay=False, path_type=Path), required=True) +@click.option("--out", type=click.Path(file_okay=False, path_type=Path), required=True) +@click.option("--interval", type=float, default=2.0, show_default=True, help="Polling interval in seconds") +def watch_command(src: Path, out: Path, interval: float) -> None: + """Watch a source folder for changes and auto-rebuild HTML.""" + console.print(f"Watching {src} for changes. Press Ctrl+C to stop.") + last_snapshot = None + try: + while True: + snapshot = tuple((p, p.stat().st_mtime_ns) for p in sorted(src.rglob("*")) if p.is_file()) + if snapshot != last_snapshot: + # Trigger a build + console.print("Change detected. Rebuilding...") + build_command.main( # type: ignore + args=["--src", str(src), "--out", str(out)], prog_name="avendehut build", standalone_mode=False + ) + last_snapshot = snapshot + time.sleep(interval) + except KeyboardInterrupt: # pragma: no cover + console.print("Stopped watching.") + diff --git a/avendehut/utils/htmlgen.py b/avendehut/utils/htmlgen.py new file mode 100644 index 0000000..f8339e9 --- /dev/null +++ b/avendehut/utils/htmlgen.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +import json +import math +import shutil +from pathlib import Path +from typing import List + + +MAX_JSON_BYTES = 5 * 1024 * 1024 # 5 MB + + +def _ensure_dir(path: Path) -> None: + path.mkdir(parents=True, exist_ok=True) + + +def _copy_template(dst: Path, template_dir: Path) -> None: + _ensure_dir(dst) + for name in ("index.html", "style.css", "script.js"): + shutil.copy2(template_dir / name, dst / name) + + +def _write_json_atomic(path: Path, data: object) -> None: + tmp = path.with_suffix(path.suffix + ".tmp") + tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8") + tmp.replace(path) + + +def copy_template_and_write_data(out: Path, catalog: List[dict]) -> None: + template_dir = Path(__file__).resolve().parents[2] / "html_template" + _copy_template(out, template_dir) + + # Write data.json or chunk + data_json = out / "data.json" + serialized = json.dumps(catalog, ensure_ascii=False) + if len(serialized.encode("utf-8")) <= MAX_JSON_BYTES: + _write_json_atomic(data_json, catalog) + # Remove previous chunked directory if exists + chunk_dir = out / "data" + if chunk_dir.exists(): + shutil.rmtree(chunk_dir) + return + + # Chunking + chunk_dir = out / "data" + if chunk_dir.exists(): + shutil.rmtree(chunk_dir) + _ensure_dir(chunk_dir) + + # naive even split by count so each chunk is below limit + items_per_chunk = max(1, math.floor(len(catalog) / max(1, math.ceil(len(serialized.encode('utf-8')) / MAX_JSON_BYTES)))) + chunks = [] + for idx in range(0, len(catalog), items_per_chunk): + part = catalog[idx: idx + items_per_chunk] + chunk_name = f"data-{idx // items_per_chunk + 1:04d}.json" + _write_json_atomic(chunk_dir / chunk_name, part) + chunks.append(f"data/{chunk_name}") + + _write_json_atomic(chunk_dir / "index.json", {"chunks": chunks}) + diff --git a/avendehut/utils/manifest.py b/avendehut/utils/manifest.py new file mode 100644 index 0000000..d66fe73 --- /dev/null +++ b/avendehut/utils/manifest.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +import json +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import List, Optional + + +from pydantic import BaseModel + + +class ManifestFile(BaseModel): + path_rel: str + size_bytes: int + mtime_ns: int + sha256: str + + +class Manifest(BaseModel): + version: str + generated_at: str + files: List[ManifestFile] + + +def load_manifest(path: Path) -> Optional[Manifest]: + if not path.exists(): + return None + data = json.loads(path.read_text(encoding="utf-8")) + return Manifest.model_validate(data) + + +def write_manifest(path: Path, manifest: Manifest) -> None: + tmp = path.with_suffix(path.suffix + ".tmp") + tmp.write_text(manifest.model_dump_json(indent=2), encoding="utf-8") + tmp.replace(path) + diff --git a/avendehut/utils/metadata.py b/avendehut/utils/metadata.py new file mode 100644 index 0000000..d75977b --- /dev/null +++ b/avendehut/utils/metadata.py @@ -0,0 +1,121 @@ +from __future__ import annotations + +import hashlib +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import List, Optional + +from ebooklib import epub # type: ignore +from pypdf import PdfReader # type: ignore + + +def _stable_id(path: Path) -> str: + stat = path.stat() + h = hashlib.sha256() + h.update(str(path.resolve()).encode()) + h.update(str(stat.st_size).encode()) + h.update(str(stat.st_mtime_ns).encode()) + return h.hexdigest() + + +def _iso(ts: float) -> str: + return datetime.fromtimestamp(ts, tz=timezone.utc).isoformat() + + +def _extract_epub(path: Path) -> tuple[str, List[str], Optional[int], Optional[str]]: + book = epub.read_epub(str(path)) + title = (book.get_metadata("DC", "title") or [["", {}]])[0][0] or path.stem + authors = [a[0] for a in (book.get_metadata("DC", "creator") or []) if a and a[0]] or [] + lang = (book.get_metadata("DC", "language") or [[None, {}]])[0][0] + pubdate_raw = (book.get_metadata("DC", "date") or [[None, {}]])[0][0] + year = None + if pubdate_raw: + try: + year = int(str(pubdate_raw)[:4]) + except Exception: + year = None + return str(title), authors, year, (str(lang) if lang else None) + + +def _extract_pdf(path: Path) -> tuple[str, List[str], Optional[int], Optional[str]]: + reader = PdfReader(str(path)) + info = reader.metadata or {} + title = (getattr(info, "title", None) or path.stem) + author = getattr(info, "author", None) + authors = [author] if author else [] + year = None + try: + if getattr(info, "creation_date", None): + # format like D:YYYYMMDDHHmmSS + year = int(str(info.creation_date)[2:6]) + except Exception: + year = None + return str(title), authors, year, None + + +def _extract_mobi(path: Path) -> tuple[str, List[str], Optional[int], Optional[str]]: + # Best-effort: try to import mobi, else fallback to filename + try: + import mobi # type: ignore + + with open(path, "rb") as f: + book = mobi.Mobi(f) + meta = getattr(book, "header", None) + title = getattr(meta, "title", None) or path.stem + author = getattr(meta, "author", None) + authors = [author] if author else [] + return str(title), authors, None, None + except Exception: + return path.stem, [], None, None + + +def _generate_tags(extension: str, title: str, authors: List[str], year: Optional[int], language: Optional[str]) -> List[str]: + tags = set() + tags.add(extension.lstrip(".").lower()) + for a in authors: + if a: + tags.add(a.lower()) + if language: + tags.add(language.lower()) + if year: + tags.add(str(year)) + return sorted(tags) + + +def extract_catalog_item(src_root: Path, path: Path) -> dict: + """Extract metadata for a supported file and return a catalog item dict. + + The function is light-weight and avoids heavy NLP; it relies on embedded metadata. + """ + extension = path.suffix.lower() + title: str + authors: List[str] + year: Optional[int] + language: Optional[str] + if extension == ".epub": + title, authors, year, language = _extract_epub(path) + elif extension == ".pdf": + title, authors, year, language = _extract_pdf(path) + elif extension == ".mobi": + title, authors, year, language = _extract_mobi(path) + else: + raise ValueError(f"Unsupported extension: {extension}") + + stat = path.stat() + item = { + "id": _stable_id(path), + "path_rel": str(path.relative_to(src_root)), + "filename": path.name, + "extension": extension.lstrip("."), + "title": title or path.stem, + "authors": authors, + "published_year": year, + "language": language, + "size_bytes": stat.st_size, + "tags": _generate_tags(extension, title, authors, year, language), + "created_at": _iso(stat.st_ctime), + "modified_at": _iso(stat.st_mtime), + } + return item + diff --git a/avendehut/utils/onedrive.py b/avendehut/utils/onedrive.py new file mode 100644 index 0000000..4477951 --- /dev/null +++ b/avendehut/utils/onedrive.py @@ -0,0 +1,77 @@ +from __future__ import annotations + +import os +from pathlib import Path +from typing import Generator, Iterable, List + +from msgraph import GraphServiceClient # type: ignore +from azure.identity import ClientSecretCredential # type: ignore + + +def is_onedrive_path(path: str) -> bool: + return path.startswith("onedrive:/") + + +def ensure_onedrive_env() -> None: + required = ["ONEDRIVE_CLIENT_ID", "ONEDRIVE_CLIENT_SECRET", "ONEDRIVE_TENANT_ID"] + missing = [k for k in required if not os.getenv(k)] + if missing: + raise RuntimeError(f"Missing OneDrive environment variables: {', '.join(missing)}") + + +def _get_graph_client() -> GraphServiceClient: + tenant_id = os.environ["ONEDRIVE_TENANT_ID"] + client_id = os.environ["ONEDRIVE_CLIENT_ID"] + client_secret = os.environ["ONEDRIVE_CLIENT_SECRET"] + credential = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret) + # Use app-only default scope for Microsoft Graph + scopes = ["https://graph.microsoft.com/.default"] + return GraphServiceClient(credential=credential, scopes=scopes) + + +def _list_children_once(client: GraphServiceClient, rel_path: str): + if rel_path.strip("/"): + return client.me.drive.root.item_with_path(rel_path).children.get() + return client.me.drive.root.children.get() + + +def _iterate_children(client: GraphServiceClient, rel_path: str): + collection = _list_children_once(client, rel_path) + while True: + if collection and getattr(collection, "value", None): + for it in collection.value: + yield it + next_link = getattr(collection, "odata_next_link", None) + if not next_link: + break + # Follow next link via SDK request adapter + collection = client._client._request_adapter.send_async( # type: ignore[attr-defined] + request_info=client._client._request_adapter.base_url_provider.clone_request_information(next_link), # type: ignore[attr-defined] + response_type=type(collection), + ).result() + + +def list_onedrive_files(prefix_path: str) -> Iterable[Path]: # pragma: no cover - network + """List files under the given OneDrive path using Microsoft Graph (app-only). + + Returns Path objects with the pseudo scheme 'onedrive:/...'. Only files are returned; folders + are traversed recursively. + """ + if not is_onedrive_path(prefix_path): + raise ValueError("prefix_path must start with 'onedrive:/'") + + ensure_onedrive_env() + client = _get_graph_client() + + rel = prefix_path[len("onedrive:/"):].lstrip("/") + stack = [rel] + while stack: + current_rel = stack.pop() + for it in _iterate_children(client, current_rel): + if getattr(it, "folder", None) is not None: + child_rel = f"{current_rel}/{it.name}" if current_rel else it.name + stack.append(child_rel) + else: + path_str = f"onedrive:/{current_rel}/{it.name}" if current_rel else f"onedrive:/{it.name}" + yield Path(path_str.replace("//", "/")) + diff --git a/html_template/index.html b/html_template/index.html new file mode 100644 index 0000000..4804087 --- /dev/null +++ b/html_template/index.html @@ -0,0 +1,31 @@ + + + + + + avendehut catalog + + + +
+

avendehut

+
+ + + +
+
+ +
+
+
    +
    + +
    + Built with avendehut. Keyboard: / focus, Esc clear, d dark, j/k nav. +
    + + + + + diff --git a/html_template/script.js b/html_template/script.js new file mode 100644 index 0000000..3e041fa --- /dev/null +++ b/html_template/script.js @@ -0,0 +1,116 @@ +(function(){ + const qs = (sel, el=document) => el.querySelector(sel); + const qsa = (sel, el=document) => Array.from(el.querySelectorAll(sel)); + + const state = { + items: [], + filtered: [], + tagSet: new Set(), + query: "", + tags: new Set(), + cursor: -1, + }; + + function loadData(){ + const indexPath = 'data/index.json'; + return fetch('data.json').then(r => { + if(r.ok) return r.json().then(arr => [arr]); + // Try chunked + return fetch(indexPath).then(r2 => r2.json()).then(idx => Promise.all(idx.chunks.map(p => fetch(p).then(r => r.json())))); + }).then(chunks => chunks.flat()); + } + + function renderTags(){ + const el = qs('#tags'); + el.innerHTML = ''; + Array.from(state.tagSet).sort().forEach(tag => { + const opt = document.createElement('option'); + opt.value = tag; opt.textContent = tag; + el.appendChild(opt); + }); + } + + function highlight(text, query){ + if(!query) return text; + const idx = text.toLowerCase().indexOf(query.toLowerCase()); + if(idx === -1) return text; + return text.substring(0, idx) + '' + text.substring(idx, idx+query.length) + '' + text.substring(idx+query.length); + } + + function render(){ + const list = qs('#results'); + list.innerHTML = ''; + const query = state.query.trim(); + const tags = state.tags; + const filtered = state.items.filter(it => { + const hay = [it.title||'', (it.authors||[]).join(', '), (it.tags||[]).join(' ')].join(' ').toLowerCase(); + if(query && !hay.includes(query.toLowerCase())) return false; + if(tags.size){ + const set = new Set((it.tags||[]).map(t=>t.toLowerCase())); + for(const t of tags){ if(!set.has(t)) return false; } + } + return true; + }); + state.filtered = filtered; + qs('#stats').textContent = `${filtered.length} result(s)`; + + // Lazy render in chunks + const CHUNK = 100; + let i = 0; + function step(){ + const frag = document.createDocumentFragment(); + for(let k=0; k${highlight(it.title||'', query)} +
    ${(it.authors||[]).join(', ')} ${it.published_year?('· '+it.published_year):''} · ${it.extension}
    +
    ${(it.tags||[]).map(t=>`${t}`).join('')}
    +
    ${it.path_rel}
    `; + frag.appendChild(li); + } + list.appendChild(frag); + if(i < filtered.length){ + requestIdleCallback(step); + } + } + step(); + } + + function applyDark(pref){ + const root = document.documentElement; + if(pref) root.classList.add('dark'); else root.classList.remove('dark'); + } + + function initShortcuts(){ + document.addEventListener('keydown', (e) => { + if(e.key === '/'){ e.preventDefault(); qs('#search').focus(); } + else if(e.key === 'Escape'){ qs('#search').value=''; state.query=''; render(); } + else if(e.key.toLowerCase() === 'd'){ const cur = localStorage.getItem('dark')==='1'; const next = !cur; localStorage.setItem('dark', next?'1':'0'); applyDark(next); } + else if(e.key === 'j' || e.key === 'k'){ /* reserved for list navigation */ } + }); + } + + function init(){ + const darkPref = localStorage.getItem('dark')==='1'; + applyDark(darkPref); + initShortcuts(); + + loadData().then(items => { + state.items = items; + items.forEach(it => (it.tags||[]).forEach(t => state.tagSet.add(String(t).toLowerCase()))); + renderTags(); + render(); + }); + + qs('#search').addEventListener('input', e => { state.query = e.target.value; render(); }); + qs('#tags').addEventListener('change', e => { + const sel = Array.from(e.target.selectedOptions).map(o=>o.value.toLowerCase()); + state.tags = new Set(sel); + render(); + }); + } + + document.addEventListener('DOMContentLoaded', init); +})(); + diff --git a/html_template/style.css b/html_template/style.css new file mode 100644 index 0000000..7f69ee7 --- /dev/null +++ b/html_template/style.css @@ -0,0 +1,65 @@ +:root { + --bg: #ffffff; + --fg: #111111; + --muted: #666666; + --accent: #2f6feb; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #0e0f13; + --fg: #e6e6e6; + --muted: #9aa0a6; + --accent: #8ab4f8; + } +} + +html.dark { + --bg: #0e0f13; + --fg: #e6e6e6; + --muted: #9aa0a6; + --accent: #8ab4f8; +} + +body { + margin: 0; + font-family: system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Arial, sans-serif; + background: var(--bg); + color: var(--fg); +} + +header { + position: sticky; + top: 0; + background: var(--bg); + border-bottom: 1px solid #ddd3; + padding: 0.75rem 1rem; + display: flex; + align-items: center; + gap: 1rem; +} + +header h1 { + margin: 0; + font-size: 1.1rem; +} + +.controls { display: flex; gap: 0.5rem; align-items: center; } +#search { padding: 0.5rem; min-width: 240px; } +#tags { min-width: 180px; } +#dark-toggle { padding: 0.5rem 0.75rem; } + +main { padding: 1rem; } + +#results { list-style: none; padding: 0; margin: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 0.75rem; } + +.card { border: 1px solid #ddd3; border-radius: 8px; padding: 0.75rem; } +.card h3 { margin: 0 0 0.25rem 0; font-size: 1rem; } +.card .meta { color: var(--muted); font-size: 0.9rem; } +.tags { margin-top: 0.25rem; display: flex; gap: 0.25rem; flex-wrap: wrap; } +.tag { background: #eee3; border: 1px solid #ddd4; border-radius: 999px; padding: 0.1rem 0.5rem; font-size: 0.8rem; } + +mark { background: #ffec99; } + +footer { padding: 1rem; color: var(--muted); } + diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..c05041c --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,70 @@ +[tool.poetry] +name = "avendehut" +version = "0.1.0" +description = "CLI to scan books, extract metadata, and generate a searchable HTML catalog." +authors = ["khnumdev "] +license = "Apache-2.0" +readme = "README.md" +homepage = "https://github.com/khnumdev/avendehut" +repository = "https://github.com/khnumdev/avendehut" +keywords = ["books", "metadata", "catalog", "cli", "onedrive"] +packages = [{ include = "avendehut" }] + +[tool.poetry.scripts] +avendehut = "avendehut.cli:main" + +[tool.poetry.dependencies] +python = ">=3.10,<4.0" +click = "^8.1.7" +rich = "^13.7.1" +pydantic = "^2.8.2" +watchdog = "^4.0.1" +msal = "^1.29.0" +requests = "^2.32.3" +tqdm = "^4.66.4" +ebooklib = "^0.18" +pypdf = "^5.0.1" +python-slugify = "^8.0.4" +chardet = "^5.2.0" +azure-identity = "^1.17.1" +msgraph-sdk = "^1.8.0" + +[tool.poetry.group.dev.dependencies] +pytest = "^8.2.2" +pytest-cov = "^5.0.0" +black = "^24.8.0" +flake8 = "^7.1.1" +isort = "^5.13.2" +mypy = "^1.11.1" + +[tool.black] +line-length = 100 +target-version = ["py310"] + +[tool.isort] +profile = "black" +line_length = 100 + +[tool.flake8] +max-line-length = 100 +extend-ignore = ["E203", "W503"] + +[tool.pytest.ini_options] +addopts = "-q" +testpaths = ["tests"] + +[tool.mypy] +python_version = "3.10" +strict = true +warn_unused_ignores = true +warn_redundant_casts = true +warn_unused_configs = true +disallow_untyped_defs = true +exclude = [ + "tests/", +] + +[build-system] +requires = ["poetry-core>=1.7.0"] +build-backend = "poetry.core.masonry.api" + diff --git a/tests/test_build.py b/tests/test_build.py new file mode 100644 index 0000000..67d2914 --- /dev/null +++ b/tests/test_build.py @@ -0,0 +1,44 @@ +from __future__ import annotations + +import json +from pathlib import Path +from click.testing import CliRunner + +from avendehut.cli import main + + +def create_sample_pdf(dir_path: Path, name: str = "a.pdf") -> Path: + from pypdf import PdfWriter + + pdf = dir_path / name + writer = PdfWriter() + writer.add_blank_page(width=72, height=72) + writer.add_metadata({"/Title": name, "/Author": "Author"}) + with open(pdf, "wb") as f: + writer.write(f) + return pdf + + +def test_build_and_manifest(tmp_path: Path) -> None: + src = tmp_path / "src" + out = tmp_path / "out" + src.mkdir() + create_sample_pdf(src, "a.pdf") + + runner = CliRunner() + result = runner.invoke(main, ["build", "--src", str(src), "--out", str(out)]) + assert result.exit_code == 0, result.output + + assert (out / "index.html").exists() + assert (out / ".manifest.json").exists() + + # Data should exist + data_json = out / "data.json" + assert data_json.exists() + data = json.loads(data_json.read_text(encoding="utf-8")) + assert isinstance(data, list) and len(data) >= 1 + + # Re-run without changes should be fast and still succeed + result2 = runner.invoke(main, ["build", "--src", str(src), "--out", str(out)]) + assert result2.exit_code == 0, result2.output + diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..3811015 --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,44 @@ +from __future__ import annotations + +from pathlib import Path +from click.testing import CliRunner + +from avendehut.cli import main + + +def test_cli_help() -> None: + runner = CliRunner() + result = runner.invoke(main, ["--help"]) + assert result.exit_code == 0 + assert "Usage" in result.output + + +def test_cli_search_and_export(tmp_path: Path) -> None: + from pypdf import PdfWriter + + src = tmp_path / "src"; src.mkdir() + out = tmp_path / "out" + writer = PdfWriter(); writer.add_blank_page(width=72, height=72); writer.add_metadata({"/Title": "Hello", "/Author": "Bob"}) + with open(src / "doc.pdf", "wb") as f: + writer.write(f) + + runner = CliRunner() + assert runner.invoke(main, ["build", "--src", str(src), "--out", str(out)]).exit_code == 0 + + # search + result = runner.invoke(main, ["search", "--out", str(out), "--query", "hello"]) + assert result.exit_code == 0 + assert "result(s)" in result.output + + # export json + json_out = tmp_path / "export.json" + result = runner.invoke(main, ["export", "--out", str(json_out), "--format", "json", "--src-out", str(out)]) + assert result.exit_code == 0 + assert json_out.exists() + + # export csv + csv_out = tmp_path / "export.csv" + result = runner.invoke(main, ["export", "--out", str(csv_out), "--format", "csv", "--src-out", str(out)]) + assert result.exit_code == 0 + assert csv_out.exists() + diff --git a/tests/test_manifest.py b/tests/test_manifest.py new file mode 100644 index 0000000..728007e --- /dev/null +++ b/tests/test_manifest.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +from pathlib import Path +from avendehut.utils.manifest import Manifest, ManifestFile, write_manifest, load_manifest + + +def test_manifest_roundtrip(tmp_path: Path) -> None: + path = tmp_path / ".manifest.json" + m = Manifest(version="1", generated_at="2020-01-01T00:00:00Z", files=[ + ManifestFile(path_rel="a.epub", size_bytes=123, mtime_ns=456, sha256="deadbeef"), + ]) + write_manifest(path, m) + loaded = load_manifest(path) + assert loaded is not None + assert loaded.version == "1" + assert loaded.files[0].path_rel == "a.epub" + diff --git a/tests/test_metadata.py b/tests/test_metadata.py new file mode 100644 index 0000000..95eafb5 --- /dev/null +++ b/tests/test_metadata.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from pathlib import Path +import json + +from avendehut.utils.metadata import extract_catalog_item + + +def test_extract_pdf_minimal(tmp_path: Path) -> None: + # Create a tiny PDF using pypdf writer to ensure metadata exists + from pypdf import PdfWriter + + pdf_path = tmp_path / "test.pdf" + writer = PdfWriter() + writer.add_blank_page(width=72, height=72) + writer.add_metadata({"/Title": "Sample PDF", "/Author": "Alice"}) + with open(pdf_path, "wb") as f: + writer.write(f) + + item = extract_catalog_item(tmp_path, pdf_path) + assert item["title"] == "Sample PDF" + assert "alice" in [t.lower() for t in item["tags"]] + assert item["extension"] == "pdf" +