from pathlib import Path
from uuid import uuid4
from io import BytesIO
from base64 import b64encode
from html import escape
from PIL import Image
from nbinlineai.browser_receipt import MediaClip
from nbinlineai.tools import (setup_share, start_share, capture_screen, stop_share,
start_camera, capture_camera, stop_source, start_recording,
record_microphone, start_microphone, operation_status, release_media)
kit = Path.cwd() / f'presenter-kit-{uuid4().hex[:10]}'
kit.mkdir()
def done(receipt, label):
print(label, receipt.status, receipt.operation_id)
if receipt.status != 'completed':
raise RuntimeError(f'{label} has not completed. Return after the browser finishes: {receipt.error}')
return receipt.result
def image_data(image):
assert isinstance(image, Image.Image)
stream = BytesIO()
image.save(stream, format='PNG')
return stream.getvalue()
def data_uri(raw, mime):
return f'data:{mime};base64,{b64encode(raw).decode("ascii")}'Application: make a portable presenter kit
Application: make a portable presenter kit
This notebook builds a real, self-contained HTML presentation from a camera photo, a short camera video with audio, a separate microphone narration, a screen still, a short screen recording, and notes you type. Open the saved HTML locally to present or share it. Media bytes are embedded, so keep the final HTML private if the captures are private. It can be large. Capture requires nbinlineai JupyterLab, a live Python kernel, browser support, and your choices in the browser permission and Share controls. A model connection is needed only for the optional staged AI route near the end; it may incur charges.
Run cells in order and check each later inspection after its media row finishes. A call cell returns immediately; capture calls may show visible browser permission prompts, which you decide whether to grant. No cell blocks while you decide. save_to=None keeps capture bytes in memory. The notebook writes Python copies to a unique local folder without assuming that Path.cwd() is Jupyter’s server root. If you choose saved browser files instead, supply an explicit server-root mapping before opening their paths from Python.
Published nbinlineai 0.1.18 includes these media APIs, which shipped in 0.1.16. Install or upgrade nbinlineai in the JupyterLab server environment. Restart JupyterLab, reload the browser, then restart the selected Python kernel and rerun imports. Use your notebook’s selected image-capable connection for image questions.
Write the presentation before capturing
Edit these concrete placeholders for your topic. The kit uses typed narration and speaker notes. It does not transcribe microphone audio or understand video frames automatically. The camera and screen videos are evidence, not model inputs.
title = 'How our prototype works'
audience = 'Product team'
opening_note = 'Explain the problem and the one result we want the audience to remember.'
photo_note = 'Introduce the presenter and the physical setup shown in the photo.'
camera_note = 'Explain what happens in the short camera demonstration.'
narration_text = 'Typed narration: replace this with the words you recorded on the microphone.'
screen_note = 'Point out the key control in the still and explain the screen walkthrough.'
closing_note = 'State the next step and the question you want the audience to consider.'
notes = {'opening': opening_note, 'photo': photo_note, 'camera': camera_note,
'narration': narration_text, 'screen': screen_note, 'closing': closing_note}Photo and short camera video with sound
Use a safe camera scene and grant camera and microphone permission if you choose. Starting with audio=True gives this source both tracks. Capture the still first. Record a few seconds from this same source, then stop it. A short memory recording must fit the browser’s 60-second and 16 MiB limits; this example uses six seconds.
camera_start = start_camera(audio=True)
camera_startBrowserReceipt(operation_id=None, status='running')
camera_source = done(camera_start, 'camera with audio')['source_id']
print('Camera source ID:', camera_source)camera with audio completed VKh6_GmciLRZsSuLY2xNQcDuZcd_9Er5
Camera source ID: [private device detail]
photo_capture = capture_camera(source_id=camera_source, save_to=None, max_size=1280)
photo_captureBrowserReceipt(operation_id=None, status='running')
photo = done(photo_capture, 'presenter photo')
assert isinstance(photo, Image.Image)
photo_ref = {'media_id': photo_capture.media['media_id']}
print('Photo:', photo.size, photo_capture.media['mime_type'])
display(photo)presenter photo completed 1SsiByXPAk7o_wym_TNGxV1o2fSe9UaW
Photo: (1000, 600) image/png
camera_video_capture = start_recording(camera_source, save_to=None, duration=6)
camera_video_captureBrowserReceipt(operation_id=None, status='running')
camera_video = done(camera_video_capture, 'camera video')
assert isinstance(camera_video, MediaClip)
assert camera_video.mime_type.startswith('video/')
print('Camera clip:', camera_video.mime_type, len(camera_video.data), 'bytes')camera video completed crej8nT7HMCzF6-7cV1wWKMfBIZs4tTu
Camera clip: video/webm;codecs=vp9,opus 49698 bytes
camera_stop = stop_source(camera_source)
camera_stopBrowserReceipt(operation_id=None, status='running')
print(done(camera_stop, 'camera source cleanup'))camera source cleanup completed __PEOms6GSq4W1qwpbqMbiSkLAiFI4mY
{'source_id': '[opaque hardware reference]', 'stopped': True}
Separate microphone narration
Record a separate six-second voice note. Speak the typed narration_text or revise it afterward to match what you actually said. This operation opens and closes its own microphone source.
narration_capture = record_microphone(save_to=None, duration=6)
narration_captureBrowserReceipt(operation_id=None, status='running')
narration = done(narration_capture, 'microphone narration')
assert isinstance(narration, MediaClip)
assert narration.mime_type.startswith('audio/')
print('Narration:', narration.mime_type, len(narration.data), 'bytes')microphone narration completed KfBf1zBJ-YYgM4D9xrsoHbugZzz3lquL
Narration: audio/webm;codecs=opus 1641 bytes
Screen still and short screen recording
Keep unrelated windows out of view. setup_share reports availability; start_share prepares a visible Share button. Click it and choose the intended tab or screen. A model or Python call cannot silently select a display. The screen recording uses video from the selected share. Browser support varies; if sharing is unavailable, this full kit cannot be built here.
screen_capture = capture_screen(source_id=screen_source, save_to=None, max_size=1280)
screen_captureBrowserReceipt(operation_id=None, status='running')
screen_image = done(screen_capture, 'screen still')
assert isinstance(screen_image, Image.Image)
print('Screen still:', screen_image.size)
display(screen_image)screen still completed kYCiHazFNDgIOJNixqMuVNSs4axyjNu-
Screen still: (1000, 600)
screen_video_capture = start_recording(screen_source, save_to=None, duration=6)
screen_video_captureBrowserReceipt(operation_id=None, status='running')
screen_video = done(screen_video_capture, 'screen video')
assert isinstance(screen_video, MediaClip)
assert screen_video.mime_type.startswith('video/')
print('Screen clip:', screen_video.mime_type, len(screen_video.data), 'bytes')screen video completed 0NO2l2gVKZpPFSKIrHacFi3gRv_bgjgu
Screen clip: video/webm;codecs=vp9 48155 bytes
Build and open the real deck
The next code saves asset copies with browser-supported media extensions plus a single portable HTML file. HTML escaping keeps typed notes as text. The HTML uses built-in image, video and audio controls. Browser codec support varies, so open the final file in a browser that can play the captured MIME types. Keep the asset copies for editing; the HTML itself embeds all media.
SLIDE_KEYS = ('opening', 'photo', 'camera', 'narration', 'screen_still', 'screen_video', 'closing')
def clip_extension(clip):
mime = clip.mime_type.split(';', 1)[0]
extensions = {'video/webm': '.webm', 'video/mp4': '.mp4',
'audio/webm': '.webm', 'audio/mp4': '.m4a', 'audio/ogg': '.ogg'}
if mime not in extensions:
raise ValueError(f'No portable file extension for the recorded MIME type: {mime}')
return extensions[mime]
def build_presenter_deck(target, *, title, audience, notes, photo, camera_video,
narration, screen_image, screen_video,
slide_text=None, speaker_notes=None):
target.mkdir(exist_ok=True)
photo_bytes = image_data(photo)
screen_bytes = image_data(screen_image)
assert all(isinstance(c, MediaClip) and c.data for c in (camera_video, narration, screen_video))
(target / 'photo.png').write_bytes(photo_bytes)
(target / 'screen.png').write_bytes(screen_bytes)
(target / f'camera-video{clip_extension(camera_video)}').write_bytes(camera_video.data)
(target / f'narration{clip_extension(narration)}').write_bytes(narration.data)
(target / f'screen-video{clip_extension(screen_video)}').write_bytes(screen_video.data)
default_lines = [notes['opening'], notes['photo'], notes['camera'], notes['narration'],
notes['screen'], notes['screen'], notes['closing']]
slide_text = default_lines if slide_text is None else slide_text
speaker_notes = default_lines if speaker_notes is None else speaker_notes
if len(slide_text) != len(SLIDE_KEYS) or len(speaker_notes) != len(SLIDE_KEYS):
raise ValueError('The deck needs exactly seven slide captions and seven speaker notes')
safe = lambda value: escape(str(value), quote=True)
def slide(index, heading, media):
caption = f'<p class="lede">{safe(slide_text[index])}</p>'
note = f'<aside><strong>Speaker note</strong><p>{safe(speaker_notes[index])}</p></aside>'
return f'<section class="slide"><h2>{safe(heading)}</h2>{caption}{media}{note}</section>'
slides = [slide(0, 'Opening', '<p>For '+safe(audience)+'</p>')]
slides.append(slide(1, 'Presenter and setup', f'<img src="{data_uri(photo_bytes,"image/png")}" alt="Presenter photo">'))
slides.append(slide(2, 'Camera demonstration', f'<video controls playsinline src="{data_uri(camera_video.data,camera_video.mime_type)}"></video>'))
slides.append(slide(3, 'Narration', f'<audio controls src="{data_uri(narration.data,narration.mime_type)}"></audio>'))
slides.append(slide(4, 'Screen still', f'<img src="{data_uri(screen_bytes,"image/png")}" alt="Shared screen still">'))
slides.append(slide(5, 'Screen walkthrough', f'<video controls playsinline src="{data_uri(screen_video.data,screen_video.mime_type)}"></video>'))
slides.append(slide(6, 'Next step', ''))
css = """<style>html{font:20px system-ui;background:#14243a;color:#f8fafc}body{margin:0}header{padding:1rem 2rem;background:#0b1627}main{max-width:1100px;margin:auto}.slide{min-height:80vh;padding:2rem;margin:2rem 0;background:#203650;border-radius:1rem;box-sizing:border-box}.slide img,.slide video{max-width:100%;max-height:55vh;display:block;margin:auto}.slide audio{width:100%}.lede{font-size:2rem}aside{font-size:.8rem;border-top:1px solid #8da7c5;margin-top:2rem;padding-top:1rem}h1,h2{line-height:1.2}@media print{html{background:white;color:black}.slide{break-after:page;border:1px solid #777;min-height:90vh;background:white}}</style>"""
html = '<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>'+safe(title)+'</title>'+css+'<header><h1>'+safe(title)+'</h1><p>For '+safe(audience)+'</p></header><main>'+''.join(slides)+'</main></html>'
path = target / 'presentation.html'
path.write_text(html, encoding='utf-8')
return pathdeck_path = build_presenter_deck(kit, title=title, audience=audience, notes=notes,
photo=photo, camera_video=camera_video, narration=narration,
screen_image=screen_image, screen_video=screen_video)
print('Portable presentation:', deck_path, 'size:', deck_path.stat().st_size, 'bytes')
print('Open that HTML file locally to review all seven slides and media controls.')Portable presentation: [temporary local path] size: 221394 bytes
Open that HTML file locally to review all seven slides and media controls.
Optional staged AI route to a second kit
The optional AI route is a separate, complete capture route. Run the setup, content, and presenter-build-function cells, then run this route instead of the direct capture cells and presenter-direct-build if you want the model to request sources. The model only starts sources and reports IDs; Python makes the actual captures so their bytes arrive as Pillow images and MediaClip values. It does not see or hear raw clips.
All IDs below must come from your current run. An AI tool call does not create a Python variable. Keep this notebook and kernel open, and do not restart it between source start, status, and Python handoff. These source-control questions declare four unique tools, below the 20-reference limit. The deck-writing question later adds one more.
If you change tool menus, turn off Tools on an earlier declaration cell.
Run the AI questions in stages. Request a source, use operation_status on that exact operation ID, then copy the returned source ID into Python.
Do not substitute a recording operation ID for a source ID. Run each status question only after the browser control finishes. If its target snapshot is still active, run it again later.
The saved worked run used a generated canvas and silent generated audio for the direct capture route. It then ran seven AI questions for source control and model-authored deck text. The three input() handoffs and alternate AI-capture deck remain unrun interactive exercises. Close the notebook to end any AI-started sources. The saved run does not establish physical camera, microphone, or screen-permission behavior.
Call &start_camera with audio=True and facing="user" after I choose a safe scene. Give only the returned camera-start operation ID and state. Ask me to handle the browser permission prompt. Do not claim a source ID yet.
Operation ID: 3TFRPWA7e38yCCaRcqiEqo_up3f6ppjS — waiting_for_user. Please handle the browser permission prompt.
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
| Tool | Result state | Submitted arguments | Observed result |
|---|---|---|---|
start_camera |
receipt accepted | {“audio”:true,“facing”:“user”} | {“operation_id”:“3TFRPWA7e38yCCaRcqiEqo_up3f6ppjS”,“status”:“waiting_for_user”} |
Call &operation_status with the exact camera-start operation ID from the preceding answer. Report the lookup state and target snapshot state. Give the camera source ID only if the target completed and its result has source_id; otherwise stop here.
Lookup state: completed. Target snapshot state: completed. Camera source ID: [private device detail].
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
| Tool | Result state | Submitted arguments | Observed result |
|---|---|---|---|
operation_status |
completed | {“operation_id”:“3TFRPWA7e38yCCaRcqiEqo_up3f6ppjS”} | {“operation_id”:“3TFRPWA7e38yCCaRcqiEqo_up3f6ppjS”,“status”:“completed”,“result”:{“source_id”:“[opaque hardware reference]”,“kind”:“camera”,“audio”:true,“video”:true,“device_id”:“[opaque hardware reference]”,“width”:1000,“height”:600}} |
ai_camera_source = input('Paste the completed camera SOURCE ID from the AI status answer: ').strip()
assert ai_camera_source, 'Use the source ID, not the operation ID.'
ai_photo_receipt = capture_camera(source_id=ai_camera_source, save_to=None, max_size=1280)ai_photo = done(ai_photo_receipt, 'AI-route camera still')
assert isinstance(ai_photo, Image.Image)
ai_camera_video_receipt = start_recording(ai_camera_source, save_to=None, duration=6)ai_camera_video = done(ai_camera_video_receipt, 'AI-route camera video')
assert isinstance(ai_camera_video, MediaClip) and ai_camera_video.mime_type.startswith('video/')
ai_camera_stop = stop_source(ai_camera_source)print(done(ai_camera_stop, 'AI-route camera cleanup'))Call &start_microphone once after I choose to grant microphone access. Give only the microphone-start operation ID and current state; do not claim the source is ready.
Microphone-start operation ID: QKINhmsJW51f3nyJm-8nrifIOi_v6a2q — waiting_for_user.
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
| Tool | Result state | Submitted arguments | Observed result |
|---|---|---|---|
start_microphone |
receipt accepted | {} | {“operation_id”:“QKINhmsJW51f3nyJm-8nrifIOi_v6a2q”,“status”:“waiting_for_user”} |
Call &operation_status with the exact microphone-start operation ID from the preceding answer. Give the actual target state and its microphone source ID only if completed. Keep that source open for Python.
Microphone target state: completed. Source ID: [private device detail]. Keep it open for Python.
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
| Tool | Result state | Submitted arguments | Observed result |
|---|---|---|---|
operation_status |
completed | {“operation_id”:“QKINhmsJW51f3nyJm-8nrifIOi_v6a2q”} | {“operation_id”:“QKINhmsJW51f3nyJm-8nrifIOi_v6a2q”,“status”:“completed”,“result”:{“source_id”:“[opaque hardware reference]”,“kind”:“microphone”,“audio”:true,“video”:false,“device_id”:“[opaque hardware reference]”}} |
ai_microphone_source = input('Paste the completed microphone SOURCE ID from the AI status answer: ').strip()
assert ai_microphone_source, 'Use the source ID, not the operation ID.'
ai_narration_receipt = start_recording(ai_microphone_source, save_to=None, duration=6)ai_narration = done(ai_narration_receipt, 'AI-route narration')
assert isinstance(ai_narration, MediaClip) and ai_narration.mime_type.startswith('audio/')
ai_microphone_stop = stop_source(ai_microphone_source)print(done(ai_microphone_stop, 'AI-route microphone cleanup'))Share-start operation ID: Yt27hnOT-38VFf6ANjBlYcQpsBuCDvfl — waiting_for_user. Please click the visible Share button and select a safe tab.
Share target state: completed. Screen source ID: [private device detail]. Keep the share open for Python.
ai_screen_source = input('Paste the completed screen SOURCE ID from the AI status answer: ').strip()
assert ai_screen_source, 'Use the source ID, not the operation ID.'
ai_screen_receipt = capture_screen(source_id=ai_screen_source, save_to=None, max_size=1280)ai_screen_image = done(ai_screen_receipt, 'AI-route screen still')
assert isinstance(ai_screen_image, Image.Image)
ai_screen_video_receipt = start_recording(ai_screen_source, save_to=None, duration=6)ai_screen_video = done(ai_screen_video_receipt, 'AI-route screen video')
assert isinstance(ai_screen_video, MediaClip) and ai_screen_video.mime_type.startswith('video/')
ai_share_stop = stop_share(ai_screen_source)ai_kit = Path.cwd() / f'presenter-kit-ai-{uuid4().hex[:10]}'
ai_deck_path = build_presenter_deck(ai_kit, title=title, audience=audience, notes=notes,
photo=ai_photo, camera_video=ai_camera_video, narration=ai_narration,
screen_image=ai_screen_image, screen_video=ai_screen_video)
print('AI-route portable presentation:', ai_deck_path)Optional model-authored second deck
After either capture route has produced real Image and MediaClip values, a live model can write the seven slide captions and seven speaker notes through one bounded Python tool. This call creates a second self-contained HTML deck using the already captured photo, camera video with sound, narration, screen still, and screen video. It cannot transcribe audio or inspect video. The typed title and notes below give it honest source material.
Run the setup cell after the direct deck, skipping the optional staged AI capture section if you do not need it. If you completed that AI capture route, change asset_route to "ai" before running the setup. Run only one route’s setup at a time. The tool takes two strings of exactly seven nonempty lines. Slide order: opening, photo, camera, narration, screen still, screen walkthrough, closing. It treats each as text and HTML-escapes it.
asset_route = 'direct' # Set to 'ai' after completing the staged AI capture route above.
if asset_route == 'direct':
selected_assets = (photo, camera_video, narration, screen_image, screen_video)
elif asset_route == 'ai':
selected_assets = (ai_photo, ai_camera_video, ai_narration, ai_screen_image, ai_screen_video)
else:
raise ValueError('asset_route must be direct or ai')
model_deck_folder = Path.cwd() / f'presenter-kit-model-{uuid4().hex[:10]}'
def create_presenter_deck_from_text(slide_text: str, speaker_notes: str) -> str:
"""Write a second HTML deck from seven captions and seven notes, using captured media."""
def seven_lines(value, field, limit):
lines = [line.strip() for line in value.splitlines()]
if len(lines) != 7 or any(not line or len(line) > limit for line in lines):
raise ValueError(f'{field} needs exactly seven nonempty lines of at most {limit} characters')
return lines
captions = seven_lines(slide_text, 'slide_text', 250)
note_lines = seven_lines(speaker_notes, 'speaker_notes', 500)
saved = build_presenter_deck(model_deck_folder, title=title, audience=audience,
notes=notes, photo=selected_assets[0], camera_video=selected_assets[1],
narration=selected_assets[2], screen_image=selected_assets[3],
screen_video=selected_assets[4], slide_text=captions, speaker_notes=note_lines)
return str(saved)Available for the next AI question:
- &
create_presenter_deck_from_text: Write a second portable HTML deck from seven slide-caption lines and seven speaker-note lines, using the captured media in this kernel.
Keep this ordinary Markdown cell’s Tools control on for the following question. The current notebook offers at most five distinct tools across both conversations.
Use the live typed $title and $notes as your source. Draft exactly seven short, nonempty, single-line slide captions and exactly seven single-line speaker notes in this order: opening, presenter photo, camera video, microphone narration, screen still, screen walkthrough, closing. Do not claim to have transcribed or watched the clips. Call create_presenter_deck_from_text exactly once with the captions joined by newline characters in slide_text and the notes joined by newline characters in speaker_notes. Report the actual saved HTML path returned by the tool; if the call fails, report its error and do not claim a deck exists.
Saved HTML deck: [temporary local path]
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
| Tool | Result state | Submitted arguments | Observed result |
|---|---|---|---|
create_presenter_deck_from_text |
completed | {“slide_text”:“How our prototype works: the problem and the takeaway\nMeet the presenter and the physical setup\nA short camera demonstration\nHear the separate microphone narration\nThe screen still: find the key control\nFollow the screen walkthrough\nNext step and an open question”,“speaker_notes”:"Explain the problem and the one result the product team should remember.\nIntroduce the presenter and describe the physical setup shown in the photo.\nExplain what happens in the camera demonstration; do not assume the clip describes itself.\nPlay the microphone recording and replace the typed narration placeholder with accurate words if needed.\nPoint out the key control in the screen still an | ‘[local path]’ |
model_deck_path = model_deck_folder / 'presentation.html'
assert model_deck_path.is_file(), 'Run the model tool question successfully before checking.'
saved_html = model_deck_path.read_text(encoding='utf-8')
assert saved_html.count('data:image/png;base64,') == 2
assert saved_html.count('data:video/') == 2
assert saved_html.count('data:audio/') == 1
print('Model-authored deck exists:', model_deck_path)
print('Seven slides and embedded media:', saved_html.count('class="slide"'), model_deck_path.stat().st_size, 'bytes')Model-authored deck exists: [temporary local path]
Seven slides and embedded media: 7 221231 bytes
Release only managed media created by the route you ran, after its HTML has been written and reviewed. The Python bytes and exported presentations, including the optional model-authored deck, remain. If you used both routes, release both sets. A memory result can expire, in which case a release may fail harmlessly; do not delete unrelated media.
used_receipts = []
if 'deck_path' in globals():
used_receipts += [photo_capture, camera_video_capture, narration_capture, screen_capture, screen_video_capture]
if 'ai_deck_path' in globals():
used_receipts += [ai_photo_receipt, ai_camera_video_receipt, ai_narration_receipt,
ai_screen_receipt, ai_screen_video_receipt]
release_receipts = [release_media(r.media['media_id']) for r in used_receipts if isinstance(r.media, dict) and r.media.get('media_id')]
print('Requested releases:', len(release_receipts))Requested releases: 5
for receipt in release_receipts:
print('Release state:', receipt.status, receipt.error)
print('Decks kept:', [str(p) for p in (globals().get('deck_path'), globals().get('ai_deck_path'), globals().get('model_deck_path')) if p and p.is_file()])Release state: completed None
Release state: completed None
Release state: completed None
Release state: completed None
Release state: completed None
Decks kept: ['[temporary local path]', '[temporary local path]']