File size: 2,337 Bytes
cdf42c7
 
 
 
 
 
 
 
 
 
43fe6c7
 
cdf42c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
932e635
 
 
 
 
 
 
cdf42c7
 
932e635
cdf42c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43fe6c7
 
cdf42c7
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import random

import fastapi
import gradio as gr
import uvicorn

from viser_proxy_manager import ViserProxyManager


def main() -> None:
    app = fastapi.FastAPI()
    viser_manager = ViserProxyManager(app)

    # Create a Gradio interface with title, iframe, and buttons
    with gr.Blocks(title="Viser Viewer") as demo:
        # Add a title and description
        gr.Markdown("# 🌐 Viser Interactive Viewer")

        # Add the iframe with a border
        add_sphere_btn = gr.Button("Add Random Sphere")
        iframe_html = gr.HTML("")

        @demo.load(outputs=[iframe_html])
        def start_server(request: gr.Request):
            assert request.session_hash is not None
            viser_manager.start_server(request.session_hash)

            # Use the request's base URL if available
            host = request.headers["host"]

            # Determine protocol (use HTTPS for HuggingFace Spaces or other secure environments)
            protocol = (
                "https"
                if request.headers.get("x-forwarded-proto") == "https"
                else "http"
            )

            return f"""
            <div style="border: 2px solid #ccc; padding: 10px;">
                <iframe src="{protocol}://{host}/viser/{request.session_hash}/" width="100%" height="500px" frameborder="0"></iframe>
            </div>
            """

        @add_sphere_btn.click
        def add_random_sphere(request: gr.Request):
            assert request.session_hash is not None
            server = viser_manager.get_server(request.session_hash)

            # Add icosphere with random properties
            server.scene.add_icosphere(
                name=f"sphere_{random.randint(1, 10000)}",
                position=(
                    random.uniform(-1, 1),
                    random.uniform(-1, 1),
                    random.uniform(-1, 1),
                ),
                radius=random.uniform(0.05, 0.2),
                color=(random.random(), random.random(), random.random()),
            )

        @demo.unload
        def stop(request: gr.Request):
            assert request.session_hash is not None
            viser_manager.stop_server(request.session_hash)

    gr.mount_gradio_app(app, demo, "/")
    uvicorn.run(app, host="0.0.0.0", port=7860)


if __name__ == "__main__":
    main()