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

feat(convert/html): inline CSS and JS with convert --one_file --offline #505

Merged
merged 22 commits into from
Jan 3, 2025
Merged
Show file tree
Hide file tree
Changes from 6 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
4 changes: 2 additions & 2 deletions docs/source/_static/template.html
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
{%- for presentation_config in presentation_configs -%}
{% set outer_loop = loop %}
{%- for slide_config in presentation_config.slides -%}
{%- if data_uri -%}
{%- if one_file -%}
{% set file = file_to_data_uri(slide_config.file) %}
{%- else -%}
{% set file = assets_dir / slide_config.file.name %}
Expand Down Expand Up @@ -315,7 +315,7 @@
hideCursorTime: {{ hide_cursor_time }}
});

{% if data_uri %}
{% if one_file %}
// Fix found by @t-fritsch on GitHub
// see: https://github.com/hakimel/reveal.js/discussions/3362#discussioncomment-6651475.
function fixBase64VideoBackground(event) {
Expand Down
2 changes: 1 addition & 1 deletion docs/source/faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ Questions related to `manim-slides convert [SCENES]... output.html`.

### I moved my `.html` file and it stopped working

If you did not specify `-cdata_uri=true` when converting,
If you did not specify `--one-file` when converting,
then Manim Slides generated a folder containing all
the video files, in the same folder as the HTML
output. As the path to video files is a relative path,
Expand Down
7 changes: 4 additions & 3 deletions docs/source/reference/sharing.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,10 @@ and it there to preserve the original aspect ratio (16:9).

### Sharing ONE HTML file

If you set the `data_uri` option to `true` (with `-cdata_uri=true`),
all animations will be data URI encoded, making the HTML a self-contained
presentation file that can be shared on its own.
If you set the `--one_file` flag, all animations will be data URI encoded,
Rapsssito marked this conversation as resolved.
Show resolved Hide resolved
making the HTML a self-contained presentation file that can be shared
on its own. If you also set the `--offline` flag, the JS and CSS files will
be included in the HTML file as well.

### Over the internet

Expand Down
78 changes: 59 additions & 19 deletions manim_slides/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import shutil
import subprocess
import tempfile
import warnings
import webbrowser
from base64 import b64encode
from collections import deque
Expand Down Expand Up @@ -290,7 +291,7 @@ class RevealTheme(str, StrEnum):

class RevealJS(Converter):
# Export option:
data_uri: bool = False
one_file: bool = False
offline: bool = Field(
False, description="Download remote assets for offline presentation."
)
Expand Down Expand Up @@ -404,11 +405,10 @@ def convert_to(self, dest: Path) -> None: # noqa: C901
)
full_assets_dir = dirname / assets_dir

if not self.data_uri or self.offline:
if not self.one_file or self.offline:
logger.debug(f"Assets will be saved to: {full_assets_dir}")
full_assets_dir.mkdir(parents=True, exist_ok=True)

if not self.data_uri:
if not self.one_file:
num_presentation_configs = len(self.presentation_configs)

if num_presentation_configs > 1:
Expand All @@ -427,6 +427,7 @@ def prefix(i: int) -> str:
def prefix(i: int) -> str:
return ""

full_assets_dir.mkdir(parents=True, exist_ok=True)
for i, presentation_config in enumerate(self.presentation_configs):
presentation_config.copy_to(
full_assets_dir, include_reversed=False, prefix=prefix(i)
Expand All @@ -453,28 +454,50 @@ def prefix(i: int) -> str:
get_duration_ms=get_duration_ms,
has_notes=has_notes,
env=os.environ,
prefix=prefix if not self.data_uri else None,
prefix=prefix if not self.one_file else None,
**options,
)

if self.offline:
soup = BeautifulSoup(content, "html.parser")
session = requests.Session()

for tag, inner in [("link", "href"), ("script", "src")]:
for item in soup.find_all(tag):
if item.has_attr(inner) and (link := item[inner]).startswith(
"http"
):
asset_name = link.rsplit("/", 1)[1]
asset = session.get(link)
# If not offline, write the content to the file
if not self.offline:
f.write(content)
return

# If offline, download remote assets and store them in the assets folder
soup = BeautifulSoup(content, "html.parser")
session = requests.Session()

for tag, inner in [("link", "href"), ("script", "src")]:
for item in soup.find_all(tag):
if item.has_attr(inner) and (link := item[inner]).startswith(
"http"
):
asset_name = link.rsplit("/", 1)[1]
asset = session.get(link)
if self.one_file:
# If it is a CSS file, inline it
if tag == "link" and "stylesheet" in item["rel"]:
item.decompose()
style = soup.new_tag("style")
style.string = asset.text
soup.head.append(style)
# If it is a JS file, inline it
elif tag == "script":
item.decompose()
script = soup.new_tag("script")
script.string = asset.text
soup.head.append(script)
else:
raise ValueError(
f"Unable to inline {tag} asset: {link}"
)
else:
full_assets_dir.mkdir(parents=True, exist_ok=True)
with open(full_assets_dir / asset_name, "wb") as asset_file:
asset_file.write(asset.content)

item[inner] = str(assets_dir / asset_name)

content = str(soup)

content = str(soup)
f.write(content)


Expand Down Expand Up @@ -707,6 +730,11 @@ def callback(ctx: Context, param: Parameter, value: bool) -> None:
help="Use the template given by FILE instead of default one. "
"To echo the default template, use '--show-template'.",
)
@click.option(
"--one-file",
is_flag=True,
help="Save all assets in a single HTML file.",
Rapsssito marked this conversation as resolved.
Show resolved Hide resolved
)
@click.option(
"--offline",
is_flag=True,
Expand All @@ -725,6 +753,7 @@ def convert(
config_options: dict[str, str],
template: Optional[Path],
offline: bool,
one_file: bool,
) -> None:
"""Convert SCENE(s) into a given format and writes the result in DEST."""
presentation_configs = get_scenes_presentation_config(scenes, folder)
Expand All @@ -742,6 +771,17 @@ def convert(
else:
cls = Converter.from_string(to)

# Change data_uri to one_file and print a warning
if "data_uri" in config_options:
warnings.simplefilter("default")
Rapsssito marked this conversation as resolved.
Show resolved Hide resolved
warnings.warn(
"The 'data_uri' configuration option is deprecated. "
"Use 'one_file' instead.",
DeprecationWarning,
stacklevel=2,
)
config_options["one_file"] = config_options.pop("data_uri")
Rapsssito marked this conversation as resolved.
Show resolved Hide resolved

if (
offline
and issubclass(cls, (RevealJS, HtmlZip))
Expand Down
10 changes: 5 additions & 5 deletions manim_slides/ipython/ipython_magic.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def construct(self):
in a cell and evaluate it. Then, a typical Jupyter notebook cell for Manim Slides
could look as follows::

%%manim_slides -v WARNING --progress_bar None MySlide --manim-slides controls=true data_uri=true
%%manim_slides -v WARNING --progress_bar None MySlide --manim-slides controls=true one_file
Rapsssito marked this conversation as resolved.
Show resolved Hide resolved

class MySlide(Slide):
def construct(self):
Expand Down Expand Up @@ -223,16 +223,16 @@ def construct(self):
kwargs = dict(arg.split("=", 1) for arg in manim_slides_args)

if embed: # Embedding implies data-uri
kwargs["data_uri"] = "true"
kwargs["one_file"] = "true"

# TODO: FIXME
# Seems like files are blocked so date-uri is the only working option...
if kwargs.get("data_uri", "false").lower().strip() == "false":
if kwargs.get("one_file", "false").lower().strip() == "false":
logger.warning(
"data_uri option is currently automatically enabled, "
"one_file option is currently automatically enabled, "
"because using local video files does not seem to work properly."
)
kwargs["data_uri"] = "true"
kwargs["one_file"] = "true"

presentation_configs = get_scenes_presentation_config(
[clsname], Path("./slides")
Expand Down
4 changes: 2 additions & 2 deletions manim_slides/templates/revealjs.html
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
{% for presentation_config in presentation_configs -%}
{% set outer_loop = loop %}
{%- for slide_config in presentation_config.slides -%}
{%- if data_uri -%}
{%- if one_file -%}
{% set file = file_to_data_uri(slide_config.file) %}
{%- else -%}
{% set file = assets_dir / (prefix(outer_loop.index0) + slide_config.file.name) %}
Expand Down Expand Up @@ -317,7 +317,7 @@
hideCursorTime: {{ hide_cursor_time }}
});

{% if data_uri -%}
{% if one_file -%}
// Fix found by @t-fritsch on GitHub
// see: https://github.com/hakimel/reveal.js/discussions/3362#discussioncomment-6651475.
function fixBase64VideoBackground(event) {
Expand Down
45 changes: 45 additions & 0 deletions tests/test_convert.py
Rapsssito marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from pathlib import Path

import pytest
import requests
from bs4 import BeautifulSoup
from pydantic import ValidationError

from manim_slides.config import PresentationConfig
Expand Down Expand Up @@ -174,6 +176,49 @@ def test_revealjs_offline_converter(
]:
assert (assets_dir / file).exists()

def test_revealjs_offline_inlining(
self,
tmp_path: Path,
presentation_config: PresentationConfig,
monkeypatch: pytest.MonkeyPatch,
) -> None:
# Mock requests.Session.get to return a fake response
class MockResponse:
def __init__(self, content: bytes, text: str, status_code: int) -> None:
self.content = content
self.text = text
self.status_code = status_code

# Apply the monkeypatch
monkeypatch.setattr(
requests.Session,
"get",
lambda: MockResponse(
b"body { background-color: #9a3241; }",
"body { background-color: #9a3241; }",
200,
),
)

out_file = tmp_path / "slides.html"
RevealJS(
presentation_configs=[presentation_config], offline="true", one_file="true"
).convert_to(out_file)
assert out_file.exists()

with open(out_file, encoding="utf-8") as file:
content = file.read()

soup = BeautifulSoup(content, "html.parser")

# Check if CSS is inlined
styles = soup.find_all("style")
assert any("background-color: #9a3241;" in style.string for style in styles)

# Check if JS is inlined
scripts = soup.find_all("script")
assert any("background-color: #9a3241;" in script.string for script in scripts)

Rapsssito marked this conversation as resolved.
Show resolved Hide resolved
def test_htmlzip_converter(
self, tmp_path: Path, presentation_config: PresentationConfig
) -> None:
Expand Down