Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add debugging information #31

Merged
merged 9 commits into from
May 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions .github/workflows/CI.yaml
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
# This file is autogenerated by maturin v1.5.1
# To update, run
#
# maturin generate-ci github
# maturin generate-ci github
#
name: CI

on:
push:
branches:
- main
- master
- '*'
tags:
- '*'
pull_request:
Expand Down Expand Up @@ -45,7 +44,7 @@ jobs:
uses: PyO3/maturin-action@v1
with:
target: ${{ matrix.platform.target }}
args: --release --out dist --find-interpreter
args: --release --out dist --find-interpreter
sccache: 'true'
manylinux: auto
- name: Upload wheels
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 8 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,20 @@ path = "src/rust/lib.rs"
crate-type = ["cdylib"]

[dependencies]
log = "0.4.21"
pyo3 = "0.21.2"
resvg = { version = "0.41.0", features = ["raster-images","text"] }
svgtypes = "0.15.0"


[profile.release.package."*"]
opt-level = 3
codegen-units = 1
opt-level ='z'
strip = true

[profile.release]
panic = "abort"
codegen-units = 1
lto = "fat"
opt-level = 3
opt-level ='z'
strip = true
37 changes: 37 additions & 0 deletions docs/debugging.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
Debugging
=========

While `resvg-py`_ is a very thin wrapper around the `resvg`_ project there might be bugs in *resvg-py* (or *resvg*).

In order to debug the issue you have to enable logging in `resvg-py`_

How to log in `resvg-py`_?

When you call `resvg-py`_'s function in your code you can pass `log_information=True` to print debug information to the stdout

For example:

.. code-block:: python

import resvg_py
import base64

svg_string = """
<svg width="300" height="130" xmlns="http://www.w3.org/2000/svg">
  <rect width="200" height="100" x="10" y="10" rx="20" ry="20" fill="blue" />
</svg>
"""

# a large list of bytes
png_bytes: list[bytes] = resvg_py.svg_to_bytes(
svg_string=svg_string,
log_information = True ## <----------- CHECK THIS LINE
)
base64_utf8_str = base64.b64encode(bytes(png_bytes)).decode("utf-8")
print(f"data:image/png;base64,{base64_utf8_str}")




.. _resvg-py: https://github.com/baseplate-admin/resvg-py
.. _resvg: https://docs.rs/resvg/latest/resvg/
1 change: 1 addition & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Safe bindings for `resvg <https://github.com/RazrFalcon/resvg>`_
installation
usage
resvg
debugging
contributing

Indices and tables
Expand Down
2 changes: 1 addition & 1 deletion docs/resvg.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ Resvg Module

.. autofunction:: svg_to_bytes

.. autofuncton:: version
.. autofunction:: version
59 changes: 58 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ package-mode = false
[tool.poetry.dependencies]
python = "^3.12"


[tool.poetry.group.dev.dependencies]
pytest = "^8.1.1"
poethepoet = "^0.26.1"

[tool.poetry.group.docs.dependencies]
sphinx = "^7.2.6"
Expand Down Expand Up @@ -38,3 +40,8 @@ Documentation = "https://resvg-py.readthedocs.io/"

[tool.maturin]
features = ["pyo3/extension-module"]

[tool.poe.tasks]
test = "pytest . -rP"
"build:release" = "maturin build --release"
"dev" = "maturin build"
23 changes: 13 additions & 10 deletions resvg_py.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,22 @@ from typing import Literal
def svg_to_bytes(
svg_string: str | None = None,
svg_path: str | None = None,
background: str | None = None,
skip_system_fonts: bool | None = False,
log_information: bool = False,
width: int | None = None,
height: int | None = None,
zoom: int | None = None,
dpi: int | None = 0,
resources_dir: str | None = None,
languages: list[str] | None = None,
font_size: int | None = None,
font_family: str | None = None,
serif_family: str | None = None,
sans_serif_family: str | None = None,
cursive_family: str | None = None,
fantasy_family: str | None = None,
monospace_family: str | None = None,
languages: list[str] | None = [],
font_size: int | None = 16,
font_family: str | None = Literal["Times New Roman"],
serif_family: str | None = Literal["Times New Roman"],
sans_serif_family: str | None = Literal["Arial"],
cursive_family: str | None = Literal["Comic Sans MS"],
fantasy_family: str | None = ["Impact"],
monospace_family: str | None = Literal["Courier New"],
font_files: list[str] | None = None,
font_dirs: list[str] | None = None,
shape_rendering: Literal[
Expand All @@ -25,8 +30,6 @@ def svg_to_bytes(
image_rendering: Literal["optimize_quality", "optimize_speed"] = Literal[
"optimize_quality"
],
background: str | None = None,
skip_system_fonts: bool | None = None,
) -> list[bytes]:
"""
:param svg_str: A string containing valid svg.
Expand Down
44 changes: 42 additions & 2 deletions src/rust/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ fn load_fonts(options: &mut Opts, fontdb: &mut resvg::usvg::fontdb::Database) {
if let Some(font_files) = &options.font_files {
for path in font_files {
if let Err(e) = fontdb.load_font_file(path) {
println!("Failed to load '{}' cause {}.", path.to_string(), e);
log::warn!("Failed to load '{}' cause {}.", path.to_string(), e);
}
}
}
Expand Down Expand Up @@ -144,6 +144,8 @@ fn svg_to_bytes(
height: Option<u32>,
zoom: Option<u32>,
dpi: Option<u32>,
// Log informations
log_information: Option<bool>,
// Resource Directory
resources_dir: Option<String>,
// Fonts
Expand All @@ -166,6 +168,12 @@ fn svg_to_bytes(
// Skip System Fonts
skip_system_fonts: Option<bool>,
) -> PyResult<Vec<u8>> {
if log_information.unwrap_or(false) {
if let Ok(()) = log::set_logger(&LOGGER) {
log::set_max_level(log::LevelFilter::Warn);
}
}

let mut _svg_string = String::new();

if let Some(svg_string) = svg_string {
Expand Down Expand Up @@ -254,7 +262,7 @@ fn svg_to_bytes(
let usvg_options = resvg::usvg::Options {
resources_dir: _resources_dir,
dpi: dpi.unwrap_or(0) as f32,
font_family: font_family.unwrap_or_else(|| "Times New Roman".to_string()),
font_family: font_family.unwrap_or("Times New Roman".to_owned()),
font_size: font_size.unwrap_or(16) as f32,
languages: languages.unwrap_or(vec![]),
shape_rendering: _shape_rendering,
Expand Down Expand Up @@ -293,3 +301,35 @@ fn resvg_py(_py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(version, m)?)?;
Ok(())
}

/// A simple stderr logger.
static LOGGER: SimpleLogger = SimpleLogger;
struct SimpleLogger;
impl log::Log for SimpleLogger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
metadata.level() <= log::LevelFilter::Warn
}

fn log(&self, record: &log::Record) {
if self.enabled(record.metadata()) {
let target = if !record.target().is_empty() {
record.target()
} else {
record.module_path().unwrap_or_default()
};

let line = record.line().unwrap_or(0);
let args = record.args();

match record.level() {
log::Level::Error => println!("Error (in {}:{}): {}", target, line, args),
log::Level::Warn => println!("Warning (in {}:{}): {}", target, line, args),
log::Level::Info => println!("Info (in {}:{}): {}", target, line, args),
log::Level::Debug => println!("Debug (in {}:{}): {}", target, line, args),
log::Level::Trace => println!("Trace (in {}:{}): {}", target, line, args),
}
}
}

fn flush(&self) {}
}
Loading