Metadata-Version: 2.4
Name: pySvdGenerator
Version: 1.0.0
Summary: A Python module for generating SVD files
Author: Florent Valette, Philippe Thierry
License: 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
        
        APPENDIX: How to apply the Apache License to your work.
        
        To apply the Apache License to your work, attach the following boilerplate
        notice, with the fields enclosed by brackets "[]" replaced with your own
        identifying information. (Don't include the brackets!) The text should be
        enclosed in the appropriate comment syntax for the file format. We also
        recommend that a file or class name and description of purpose be included on
        the same "printed page" as the copyright notice for easier identification
        within third-party archives.
        
        Copyright [yyyy] [name of copyright owner]
        
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
        
        http://www.apache.org/licenses/LICENSE-2.0
        
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
        
Project-URL: Homepage, https://github.com/h2lab
Project-URL: Repository, https://github.com/h2lab/pySvdGenerator
Project-URL: Issues, https://github.com/h2lab/pySvdGenerator/issues
Classifier: Development Status :: 1 - Planning
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Code Generators
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: >=3.12
Description-Content-Type: text/markdown
Requires-Dist: pypdf>=5
Requires-Dist: tabula-py>=2.9
Requires-Dist: pandas>=2
Requires-Dist: ollama>=0.3
Requires-Dist: rich>=13
Provides-Extra: dev
Requires-Dist: black; extra == "dev"
Requires-Dist: flake8; extra == "dev"
Requires-Dist: flake8-docstrings; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Requires-Dist: pytest; extra == "dev"

<!--
SPDX-FileType: DOCUMENTATION
SPDX-FileCopyrightText: 2026 H2Lab Development Team
SPDX-License-Identifier: Apache-2.0
-->
# pySvdGenerator

Python module for generating SVD files.

The generator combines the two descriptions of a SoC that are publicly
available: the Linux device tree (memory map, interrupts, cores) and the
reference manual (registers and bit fields).

## Pipeline

1. **Device tree analysis** — `pySvdGenerator.dts` preprocesses and parses the
   DTSI (includes, `dt-bindings` macros, phandles, address translation);
   `pySvdGenerator.bindings` reads the peripheral descriptions from
   `Documentation/devicetree/bindings`.
2. **SVD generation** — `generate_svd()` writes a CMSIS-SVD file holding the
   CPU, the peripherals, their address blocks and their interrupts.
3. **Manual splitting** — `split_chapters()` cuts the reference manual PDF into
   one document per chapter inside a workspace.
4. **Register extraction** — `extract_registers()` reads the register memory
   maps and the bit field tables with `tabula-py`, merges the tables continued
   over several pages, separates the peripheral instances (`GPT1`, `GPT2`, ...)
   and returns a dictionary. A local `ollama` agent consolidates the result
   and is queried by default; `--no-llm` (`use_llm=False`) restricts the stage
   to the deterministic parsing.
5. **SVD enrichment** — `enrich_svd()` injects the registers and fields into
   the SVD, keeping only the registers that fall inside the address blocks
   declared by the device tree `reg` property.

Each module is documented in [doc/](doc/README.md).

## Command line

The `pysvdgen` command always needs a reference manual PDF. It supports two
mutually exclusive modes:

* **Generate a new SVD:** provide both `--kernel` and `--dtsi`; `--output` is
   required.
* **Complete an existing SVD:** provide `--svd`; `--kernel` and `--dtsi` must
   not be used. The input file is updated in place unless `--output` is given.

The DTSI argument is the device-tree name without its `.dts` or `.dtsi`
extension. For example, this generates an SVD skeleton from the `imx8mm`
device tree and enriches it with all chapters found in the manual:

```console
pysvdgen \
   --kernel /path/to/linux \
   --dtsi imx8mm \
   --pdf IMX8MDQLQRM.pdf \
   --output build/imx8mm.svd
```

Use `--vendor` to set the vendor name in a newly generated SVD, and `--verbose`
to show module logs and detailed tracebacks when a stage fails:

```console
pysvdgen -k /path/to/linux -d imx8mm -p IMX8MDQLQRM.pdf \
   -o build/imx8mm.svd --vendor NXP --verbose
```

### Selecting chapters

By default, every chapter in the reference manual is processed. `--chapter`
filters by a case-insensitive substring of the chapter title or filename and
can be repeated. The following command processes only timer-related chapters:

```console
pysvdgen -k /path/to/linux -d imx8mm -p IMX8MDQLQRM.pdf \
   -o build/imx8mm.svd --chapter Timer
```

Several filters can be provided in one run:

```console
pysvdgen -k /path/to/linux -d imx8mm -p IMX8MDQLQRM.pdf \
   -o build/imx8mm.svd -c Timer -c Watchdog
```

If no chapter matches, the command exits with status `2` and leaves the output
unchanged.

### Completing an SVD incrementally

An existing SVD can be completed chapter by chapter. Peripherals that already
contain registers are preserved on later runs. Without `--output`, the input
file is updated in place; use a different output path to keep the original:

```console
# First pass: create the SVD with the timer chapters.
pysvdgen -k /path/to/linux -d imx8mm -p IMX8MDQLQRM.pdf \
   -o build/imx8mm.svd -c Timer

# Later passes: add more chapters to the same file.
pysvdgen -s build/imx8mm.svd -p IMX8MDQLQRM.pdf -c Connectivity
pysvdgen -s build/imx8mm.svd -p IMX8MDQLQRM.pdf -c "Mass Storage"

# Keep a copy while writing the completed result elsewhere.
pysvdgen -s build/imx8mm.svd -p IMX8MDQLQRM.pdf \
   -c Ethernet -o build/imx8mm-enriched.svd
```

### Workspace and repeatable runs

Use `--workspace` to keep the intermediate chapter PDFs and extracted JSON
files. A later run with the same workspace reuses cached extraction results;
this is useful when processing a large manual or when adding chapter filters
over several runs:

```console
pysvdgen -k /path/to/linux -d imx8mm -p IMX8MDQLQRM.pdf \
   -o build/imx8mm.svd -w build/pysvdgen-work -c Timer
pysvdgen -s build/imx8mm.svd -p IMX8MDQLQRM.pdf \
   -w build/pysvdgen-work -c Connectivity
```

When `--workspace` is omitted, a temporary workspace is created and removed
after the run, including when the run fails.

### Updating one peripheral

When completing an existing SVD, use `--peripheral` to restrict the
enrichment to a named peripheral. The option is case-insensitive and can be
repeated. This is useful when a chapter describes several instances but only
one of them should be updated:

```console
pysvdgen -s build/imx8mm.svd -p IMX8MDQLQRM.pdf \
   -c Timer --peripheral GPT1
```

If the named peripheral is present in the extracted chapter but missing from
the SVD, `--allow-new` adds it using the base address and registers from the
reference manual. `--allow-new` requires at least one `--peripheral` option:

```console
pysvdgen -s build/imx8mm.svd -p IMX8MDQLQRM.pdf \
   -c Timer --peripheral GPT1 --allow-new
```

Without `--allow-new`, a missing named peripheral is reported as an unused
manual source and is not added to the SVD. Existing peripherals not named with
`--peripheral` are left unchanged.

### Ollama and deterministic extraction

Register extraction queries the Ollama server at
`http://localhost:11434` by default. Select another model with `--model` (or
the more explicit `--llm-model` alias) and another server with
`--ollama-host`:

```console
pysvdgen -k /path/to/linux -d imx8mm -p IMX8MDQLQRM.pdf \
   -o build/imx8mm.svd --model llama3.2 \
   --ollama-host http://localhost:11434
```

Use `--no-llm` when no Ollama server is available. The command then uses only
the deterministic table parsing and the extracted result can be incomplete:

```console
pysvdgen -s build/imx8mm.svd -p IMX8MDQLQRM.pdf \
   -c Timer --no-llm
```

Run `pysvdgen --help` for the complete option list:

| Option | Description |
| --- | --- |
| `-k`, `--kernel` | Linux kernel source tree; required with `--dtsi` unless `--svd` is given |
| `-d`, `--dtsi` | device-tree name without its extension; required with `--kernel` unless `--svd` is given |
| `-s`, `--svd` | existing SVD file to complete; mutually exclusive with `--kernel` and `--dtsi` |
| `-p`, `--pdf` | reference manual PDF; always required |
| `-o`, `--output` | SVD file to write; required for a new SVD, otherwise defaults to updating `--svd` in place |
| `-w`, `--workspace` | working directory to keep and reuse |
| `-c`, `--chapter` | case-insensitive substring filter for chapter titles or filenames; repeatable |
| `--peripheral` | restrict enrichment to this peripheral name; repeatable and case-insensitive |
| `--allow-new` | add the selected peripheral when it is missing from the SVD; requires `--peripheral` |
| `--model`, `--llm-model` | Ollama model used for extraction |
| `--ollama-host` | Ollama server URL |
| `--no-llm` | disable Ollama and use deterministic extraction only |
| `--vendor` | vendor name written in a newly generated SVD |
| `-v`, `--verbose` | show module logs and detailed tracebacks |

The command returns `0` on success, `1` when a pipeline stage fails, `2` when
no chapter matches the filters, and `3` for inconsistent arguments.

Peripherals missing from the device tree, peripherals missing from the manual
and registers falling outside the device tree address blocks are reported at
the end of the run.

## Programmatic use

```python
from pySvdGenerator import enrich_svd, extract_registers, generate_svd, split_chapters

svd = generate_svd("/path/to/linux", "imx8mm", "build/imx8mm.svd")
chapters = split_chapters("IMX8MDQLQRM.pdf", "build/chapters", select=["Timers"])
registers = [extract_registers(chapter) for chapter in chapters]
report = enrich_svd(svd, registers, "imx8mm.svd")
```

## Requirements

### Java

`tabula-py` reads the PDF tables through a Java program, so a JRE must be
installed and reachable:

```console
java -version          # 11 or later
sudo apt install default-jre
```

### ollama

The extraction stage queries a reachable `ollama` server by default. The
agent classifies the tables the header heuristics cannot recognise,
attributes the orphan bit field tables, splits the register names of the
peripheral instances and repairs the field names damaged by the PDF text
extraction. `OllamaUnavailableError` is raised when the server does not
answer. Use `--no-llm` to run without any server, at the price of a degraded
extraction.

Install the server, start it and pull a model:

```console
curl -fsSL https://ollama.com/install.sh | sh
ollama serve &                   # skipped when the service is already running
ollama pull qwen2.5-coder:7b     # default model
ollama pull llama3.2             # fallback model
```

Check that the server answers and knows the model:

```console
curl -s http://localhost:11434/api/tags
ollama list
```

| Item | Value |
| --- | --- |
| Default model | `qwen2.5-coder:7b`, about 5 GB of RAM |
| Fallback model | `llama3.2`, used when the requested model is not pulled |
| Default endpoint | `http://localhost:11434`, overridden by `--ollama-host` or `OLLAMA_HOST` |

The model is selected at startup: when the model asked for through `--model`
is missing on the server, the first available fallback is used and a warning
is logged; when nothing usable is pulled, the run stops with an explicit
error.
