from pathlib import Path, PurePosixPath
from tempfile import mkdtemp
from hashlib import sha256
from urllib.request import urlopen
from PIL import Image, ImageDraw
from nbinlineai.tools import extract_frames, crop_image, annotate_image, operation_status, release_media
root_text = input('Absolute Jupyter server root (the folder served by JupyterLab): ').strip()
root_choice = Path(root_text).expanduser()
if not root_choice.is_absolute():
raise ValueError('Enter an absolute Jupyter server-root folder; do not use the kernel working directory as a guess.')
server_root = root_choice.resolve(strict=True)
if not server_root.is_dir() or not Path.cwd().resolve().is_relative_to(server_root):
raise ValueError('The server root must be an existing folder containing this kernel working directory.')
def server_ref(path):
"""Make a server-root-relative path for an owned file or save destination."""
target = Path(path).resolve()
return target.relative_to(server_root).as_posix()
def server_file(reference):
"""Map a server-returned relative path to the configured local root."""
if not isinstance(reference, str) or not reference or '\\' in reference:
raise ValueError('Expected a server-root-relative media path.')
relative = PurePosixPath(reference)
if relative.is_absolute() or relative.as_posix() != reference or reference == '.' or '..' in relative.parts:
raise ValueError('Media path must be a clean server-root-relative path.')
candidate = server_root / reference
if not candidate.resolve().is_relative_to(server_root):
raise ValueError('Media path escapes the configured server root.')
return candidate
clip_name = 'owned-notebook-tab-2087303b97be.webm'
clip_sha256 = '2087303b97be4ba56da4d95d19d1106f6c0ddb5d9030e3f74f5c47e84bc4d63a'
clip_size = 72134
clip_url = 'https://raw.githubusercontent.com/rahuldave/nbinlineai/main/examples/media/owned-notebook-tab-2087303b97be.webm'
local_clips = [Path.cwd() / 'media' / clip_name, server_root / 'examples' / 'media' / clip_name, server_root / 'media' / clip_name]
local_clip = next((candidate for candidate in local_clips if candidate.is_file()), None)
if local_clip is not None:
if local_clip.stat().st_size != clip_size:
raise ValueError(f'Companion clip has the wrong size: {local_clip}')
clip_bytes = local_clip.read_bytes()
else:
try:
with urlopen(clip_url, timeout=10) as response:
clip_bytes = response.read(clip_size + 1)
except OSError as error:
raise RuntimeError(f'Download {clip_url} and put it in media/{clip_name} beside this notebook.') from error
if len(clip_bytes) != clip_size or sha256(clip_bytes).hexdigest() != clip_sha256:
raise ValueError('Companion clip size or SHA-256 differs from the published recording.')
work = Path(mkdtemp(prefix='nbinlineai-transform-', dir=Path.cwd()))
image_path = work / 'source.png'
video_path = work / clip_name
image = Image.new('RGB', (64, 64), 'white')
ImageDraw.Draw(image).rectangle((4, 4, 20, 20), fill='red')
image.save(image_path, format='PNG')
video_path.write_bytes(clip_bytes)
image_ref = {'path': server_ref(image_path), 'sha256': sha256(image_path.read_bytes()).hexdigest()}
video_ref = {'path': server_ref(video_path), 'sha256': clip_sha256}
print('Exact created PNG and recorded notebook-tab clip:', image_ref, video_ref)
from IPython.display import display, HTML
from base64 import b64encode
from html import escape
video_uri = 'data:video/webm;base64,' + b64encode(clip_bytes).decode('ascii')
display(HTML(f'<video controls preload="metadata" width="320" src="{escape(video_uri, quote=True)}"></video>'))Exact created PNG and recorded notebook-tab clip: {'path': 'nbinlineai-transform-v5x45ohi/source.png', 'sha256': '634c6cc561e039ccc2073df913453ea426885c9d9e964a246f04251642236a50'} {'path': 'nbinlineai-transform-v5x45ohi/owned-notebook-tab-2087303b97be.webm', 'sha256': '2087303b97be4ba56da4d95d19d1106f6c0ddb5d9030e3f74f5c47e84bc4d63a'}