Skip to content
Open
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
82 changes: 73 additions & 9 deletions packages/api/annotation_studio/gradio.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
import json
import logging
import os
import secrets
import tempfile
import zipfile
from collections import OrderedDict
from collections.abc import Callable, Iterator
from pathlib import Path
from typing import Any, Protocol
Expand Down Expand Up @@ -108,6 +110,11 @@ def validate_refold(self, options: dict) -> dict: ...
#design-card-notice { padding: 4px 12px; margin: 0; font-size: 12px; opacity: 0.8; }
"""

# A public host serves many short-lived browser tabs; cap the per-tab result registry so it
# cannot grow without bound. Evicting a client releases its tracked sessions.
MAX_TRACKED_CLIENTS = 64


HOST_BRIDGE = """
const configure = () => {
const frame = element.querySelector('iframe');
Expand Down Expand Up @@ -141,21 +148,45 @@ def validate_refold(self, options: dict) -> dict: ...
}"""


def identity_headers(request: gr.Request | None) -> dict[str, str]:
"""Forward the proxy-authenticated user to Studio for in-process hand-off calls.

In identity mode Studio rejects requests without the configured header, and sessions are
owned by that user. The Gradio request came through the same trusted proxy, so its header
is as trustworthy as the browser's own Studio requests and keeps results openable in the iframe.
"""
from annotation_studio import main as studio_main

header = studio_main.IDENTITY_HEADER
if not header or request is None:
return {}
value = request.headers.get(header)
return {header: value} if value else {}


class StudioHandoff:
"""Use Studio's versioned HTTP contract without sharing document internals."""

def __init__(self, studio: FastAPI, editor_path: str = "/"):
self.editor_path = editor_path
self.transport = httpx.ASGITransport(app=studio)

async def open(self, name: str, cif: str) -> tuple[str, str]:
async with httpx.AsyncClient(transport=self.transport, base_url="http://studio") as client:
async def open(self, name: str, cif: str, headers: dict[str, str] | None = None) -> tuple[str, str]:
async with httpx.AsyncClient(transport=self.transport, base_url="http://studio", headers=headers) as client:
response = await client.post("/api/v1/sessions", files={"file": (name, cif.encode())})
response.raise_for_status()
session = response.json()
session_id = session["session_id"]
return session_id, self.frame(session_id)

async def close(self, session_ids: list[str], headers: dict[str, str] | None = None) -> None:
"""Release hand-off sessions; Studio's bounded store would otherwise evict live user sessions."""
async with httpx.AsyncClient(transport=self.transport, base_url="http://studio", headers=headers) as client:
for session_id in session_ids:
response = await client.delete(f"/api/v1/sessions/{quote(session_id, safe='')}")
if response.status_code not in (204, 404):
response.raise_for_status()

def frame(self, session_id: str | None = None, *, example: str | None = None, card: bool = False) -> str:
"""The editor's frame. With `card` (design-card mode), Studio draws the card in its sidebar and the frame takes
the window's height, as the page does."""
Expand All @@ -173,11 +204,13 @@ def frame(self, session_id: str | None = None, *, example: str | None = None, ca
'allow="clipboard-write; fullscreen; webgpu"></iframe>'
)

async def export(self, session_id: str, warning_checks: frozenset[str]) -> dict:
async def export(
self, session_id: str, warning_checks: frozenset[str], headers: dict[str, str] | None = None
) -> dict:
if not session_id:
raise gr.Error("Open a structure in Studio first")
session_id = quote(session_id, safe="")
async with httpx.AsyncClient(transport=self.transport, base_url="http://studio") as client:
async with httpx.AsyncClient(transport=self.transport, base_url="http://studio", headers=headers) as client:
response = await client.post(f"/api/v1/sessions/{session_id}/export")
response.raise_for_status()
snapshot = response.json()
Expand Down Expand Up @@ -536,6 +569,9 @@ def create_demo(
refold_models=refold_models,
refold_limits=refold_limits,
)
# Result sessions each browser tab created, released when that tab generates again or when
# the bounded registry evicts the tab.
results_by_client: OrderedDict[str, list[str]] = OrderedDict()
with gr.Blocks(delete_cache=(3600, 3600)) as demo:
gr.Markdown(f"# {provider.title}")
session = gr.Textbox(visible=False)
Expand Down Expand Up @@ -588,11 +624,15 @@ def check_input(snapshot: dict, options: dict) -> None:
async def run_cifs(cif: str, options: dict) -> list[str]:
return await _run_cifs(generate_fn, cif, options)

async def generate_cif(cif: str, options: dict) -> dict:
async def generate_cif(cif: str, options: dict, request: gr.Request = None) -> dict:
"""Generate from an annotated CIF through the same Studio validation and model path."""
validated = provider.validate(options or {})
session_id, _ = await handoff.open("input.cif", cif)
snapshot = await handoff.export(session_id, provider.warning_checks)
headers = identity_headers(request)
session_id, _ = await handoff.open("input.cif", cif, headers)
try:
snapshot = await handoff.export(session_id, provider.warning_checks, headers)
finally:
await handoff.close([session_id], headers)
check_input(snapshot, validated)