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

Render demo manifest #3151

Merged
merged 3 commits into from
Aug 30, 2023
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
100 changes: 95 additions & 5 deletions scripts/ci/build_demo_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,56 @@
from __future__ import annotations

import argparse
import html.parser
import http.server
import json
import logging
import os
import re
import shutil
import subprocess
import threading
from functools import partial
from io import BytesIO
from pathlib import Path
from typing import Any

import frontmatter
import requests
from jinja2 import Template
from PIL import Image


def measure_thumbnail(url: str) -> Any:
"""Downloads `url` and returns its width and height."""
response = requests.get(url)
response.raise_for_status()
image = Image.open(BytesIO(response.content))
return image.size


# https://stackoverflow.com/a/7778368
class HTMLTextExtractor(html.parser.HTMLParser):
def __init__(self) -> None:
super().__init__()
self.result: list[Any] = []

def handle_data(self, d: Any) -> None:
self.result.append(d)

def get_text(self) -> str:
return "".join(self.result)


def extract_text_from_html(html: str) -> str:
"""
Strips tags and unescapes entities from `html`.

This is not a sanitizer, it should not be used on untrusted input.
"""
extractor = HTMLTextExtractor()
extractor.feed(html)
return extractor.get_text()


class Example:
Expand All @@ -24,14 +65,40 @@ def __init__(
commit: str,
build_args: list[str],
):
readme_path = Path("examples/python", name, "README.md")
if readme_path.exists():
readme = frontmatter.loads(readme_path.read_text())
else:
readme = frontmatter.Post(content="")

thumbnail_url = readme.get("thumbnail")
if thumbnail_url:
width, height = measure_thumbnail(thumbnail_url)
thumbnail = {
"url": thumbnail_url,
"width": width,
"height": height,
}
else:
thumbnail = None

description_html = "".join([f"<p>{segment}</p>" for segment in description.split("\n\n")])

description = extract_text_from_html(description)
description = re.sub(r"[\n\s]+", " ", description)
description = description.strip()

self.path = os.path.join("examples/python", name, "main.py")
self.name = name
self.source_url = f"https://github.com/rerun-io/rerun/tree/{commit}/examples/python/{self.name}/main.py"
self.title = title
self.description = description
self.tags = readme.get("tags", [])
self.demo_url = f"https://demo.rerun.io/commit/{commit}/examples/{name}/"
self.rrd_url = f"https://demo.rerun.io/commit/{commit}/examples/{name}/data.rrd"
self.source_url = f"https://github.com/rerun-io/rerun/tree/{commit}/examples/python/{name}/main.py"
self.thumbnail = thumbnail
self.build_args = build_args

segments = [f"<p>{segment}</p>" for segment in description.split("\n\n")]
self.description = "".join(segments)
self.description_html = description_html

def save(self) -> None:
in_path = os.path.abspath(self.path)
Expand Down Expand Up @@ -155,6 +222,28 @@ def render_examples(examples: list[Example]) -> None:
f.write(template.render(example=example, examples=examples))


def render_manifest(examples: list[Example]) -> None:
logging.info("Rendering index")

index = []
for example in examples:
index.append(
{
"name": example.name,
"description": example.description,
"tags": example.tags,
"demo_url": example.demo_url,
"rrd_url": example.rrd_url,
"thumbnail": example.thumbnail,
}
)

index_dir = Path(BASE_PATH) / "examples"
index_dir.mkdir(parents=True, exist_ok=True)
index_path = index_dir / "manifest.json"
index_path.write_text(json.dumps(index))


def serve_files() -> None:
def serve() -> None:
logging.info("\nServing examples at http://0.0.0.0:8080/")
Expand Down Expand Up @@ -195,6 +284,7 @@ def main() -> None:

if not args.skip_examples:
shutil.rmtree(f"{BASE_PATH}/examples", ignore_errors=True)
render_manifest(examples)
save_examples_rrd(examples)

render_examples(examples)
Expand All @@ -218,7 +308,7 @@ def main() -> None:
BASE_PATH = "web_demo"
SCRIPT_PATH = os.path.dirname(os.path.relpath(__file__))
# When adding examples, add their requirements to `requirements-web-demo.txt`
EXAMPLES = {
EXAMPLES: dict[str, Any] = {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@abey79
We didn't specify this, but I assume you wanted the examples which are on demo.rerun.io, because those are the only ones which have .rrd files built on CI. If that's the case, the dna example needs a README + thumbnail - how did we make those again?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm thinking that it's maybe more future-proof to include everything in the manifest. Then, in the UI, we can pull only those example which have a RRD url specified.

As for the DNA example, I guess we just need to add a README.md with front matter in examples/python/dna/? It looks like an oversight that there isn't one already.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm thinking that it's maybe more future-proof to include everything in the manifest

That's not a difficult change to make (we fetch all the data from README files instead of hardcoding a map like this), so I'd rather only do the minimum required work here.

As for the DNA example, I guess we just need to add a README.md with front matter in examples/python/dna/?

Yes, but that requires taking a screenshot which I haven't done before, do you remember where the instructions are for that?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The script doesnt assume that the readme exists, so its safe to add it later.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taking a screenshot is ctrl-P for the command palette -> screenshot. For the upload, just upload --help. Since the screenshot feature copies to clipboard, the easiest is just upload --name example_name (the script pulls from clipboard if no input path is provided).

"arkit_scenes": {
"title": "ARKit Scenes",
"description": """
Expand Down
2 changes: 1 addition & 1 deletion scripts/ci/demo_assets/templates/example.html
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
</div>
<div class="example-description">
<div class="example-description-icon no-select">?</div>
<div class="example-description-body">{{ example.description }}</div>
<div class="example-description-body">{{ example.description_html }}</div>
</div>
<a class="icon-link no-select" href="{{ example.source_url }}" target="_blank">
<img class="icon" src="github-mark-white.svg" />
Expand Down
2 changes: 2 additions & 0 deletions scripts/ci/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@ google-cloud-storage==2.9.0
packaging==23.1
requests>=2.31,<3
tomlkit==0.11.8
python-frontmatter==1.0.0
Pillow==10.0.0