|
| 1 | +from __future__ import annotations |
| 2 | + |
1 | 3 | import atexit |
| 4 | +import sys |
2 | 5 | import contextlib |
3 | 6 | import os |
4 | | -from IPython.core.display import HTML |
| 7 | +from IPython.core.display import HTML, JSON |
5 | 8 | from importlib.resources import as_file, files |
6 | 9 |
|
7 | 10 | _resource_stack = contextlib.ExitStack() |
8 | 11 | atexit.register(_resource_stack.close) |
9 | 12 |
|
10 | 13 |
|
11 | | -def display_room() -> HTML: |
12 | | - try: |
13 | | - from google.colab import secrets |
| 14 | +def display_room(url: str | None = None, token: str | None = None) -> HTML: |
| 15 | + """ |
| 16 | + Display a LiveKit room in Jupyter or Google Colab. |
| 17 | +
|
| 18 | + Args: |
| 19 | + url (str | None): The LiveKit room URL. If None, the function attempts |
| 20 | + to use the LIVEKIT_JUPYTER_URL environment variable in a local or |
| 21 | + Colab environment. |
| 22 | + token (str | None): The LiveKit join token. If None, the function |
| 23 | + attempts to use the LIVEKIT_JUPYTER_URL environment variable in a |
| 24 | + local or Colab environment. |
| 25 | +
|
| 26 | + Returns: |
| 27 | + IPython.core.display.HTML: The HTML object that embeds the LiveKit room. |
| 28 | +
|
| 29 | + Raises: |
| 30 | + ValueError: If both `url` and `token` are None and |
| 31 | + `LIVEKIT_JUPYTER_URL` is not set. |
| 32 | + """ |
| 33 | + IN_COLAB = "google.colab" in sys.modules |
| 34 | + |
| 35 | + if url is None and token is None: |
| 36 | + if IN_COLAB: |
| 37 | + from google.colab import userdata |
| 38 | + |
| 39 | + LIVEKIT_JUPYTER_URL = userdata.get("LIVEKIT_JUPYTER_URL") |
| 40 | + else: |
| 41 | + LIVEKIT_JUPYTER_URL = os.environ.get("LIVEKIT_JUPYTER_URL") |
| 42 | + |
| 43 | + if not LIVEKIT_JUPYTER_URL: |
| 44 | + raise ValueError("LIVEKIT_JUPYTER_URL must be set (or url/token must be provided).") |
| 45 | + |
| 46 | + if IN_COLAB: |
| 47 | + from google.colab import output |
14 | 48 |
|
15 | | - LIVEKIT_JUPYTER_URL = secrets.get("LIVEKIT_JUPYTER_URL") |
16 | | - except ImportError: |
17 | | - LIVEKIT_JUPYTER_URL = os.environ.get("LIVEKIT_JUPYTER_URL") |
| 49 | + def create_join_token(): |
| 50 | + return JSON({"url": url or "", "token": token or ""}) |
18 | 51 |
|
19 | | - if not LIVEKIT_JUPYTER_URL: |
20 | | - raise ValueError( |
21 | | - "LIVEKIT_JUPYTER_URL must be set via Google Colab secrets or as an environment variable." |
22 | | - ) |
| 52 | + output.register_callback("get_join_token", create_join_token) |
23 | 53 |
|
| 54 | + # Load the local HTML file that embeds the LiveKit client |
24 | 55 | index_path = files("livekit.rtc.resources") / "jupyter-html" / "index.html" |
25 | 56 | index_path = _resource_stack.enter_context(as_file(index_path)) |
26 | | - html_text = index_path.read_text() |
27 | 57 |
|
28 | | - return HTML(html_text) |
| 58 | + return HTML(index_path.read_text()) |
0 commit comments