Spaces:
Running on Zero
Running on Zero
Download backend/web.py from reflection/iris: direct link, hf CLI and curl.
- Browser
- Download file 7.68 kB
-
https://huggingface.co/spaces/reflection/iris/resolve/refs%2Fpr%2F13/backend/web.py
- Command line
-
hf download hf://spaces/reflection/iris@refs/pr/13/backend/web.py
-
curl -L -o web.py https://huggingface.co/spaces/reflection/iris/resolve/refs%2Fpr%2F13/backend/web.py
7.68 kB
| """Gradio server for the compiled frontend and its same-origin streaming API.""" | |
| import asyncio | |
| import ipaddress | |
| import json | |
| import pathlib | |
| import secrets | |
| import time | |
| from typing import cast | |
| import fastapi | |
| import gradio | |
| import httpx | |
| from backend import ( | |
| beam_client, | |
| beam_status, | |
| iris_content_guard, | |
| turns, | |
| workspace, | |
| ) | |
| from starlette import responses, staticfiles | |
| def _endpoint(value: str, setting: str) -> httpx.URL: | |
| url = httpx.URL(value) | |
| if ( | |
| url.scheme not in {'http', 'https'} | |
| or not url.host | |
| or url.userinfo | |
| or url.query | |
| or url.fragment | |
| ): | |
| raise ValueError( | |
| f'{setting} must be an HTTP(S) base URL without credentials, query or fragment' | |
| ) | |
| if url.scheme == 'http' and not _loopback(url.host): | |
| raise ValueError(f'{setting} requires HTTPS for a remote endpoint.') | |
| path = url.raw_path.rstrip(b'/').removesuffix(b'/v1') | |
| return url.copy_with(raw_path=path + b'/') | |
| def _loopback(host: str) -> bool: | |
| if host == 'localhost': | |
| return True | |
| try: | |
| return ipaddress.ip_address(host).is_loopback | |
| except ValueError: | |
| return False | |
| def create_app( | |
| dist: pathlib.Path, | |
| beam_url: str, | |
| beam_token: str | None, | |
| score_url: str | None = None, | |
| ) -> gradio.Server: | |
| """Create one Space process; each browser receives its own session capability.""" | |
| url = _endpoint(beam_url, 'BEAM_URL') | |
| monitor = beam_status.BeamStatus(url, beam_token) | |
| app = gradio.Server() | |
| sessions: dict[str, turns.Session] = {} | |
| monitor_url = ( | |
| _endpoint(score_url, 'IRIS_BEAM_SCORE_URL') if score_url else None | |
| ) | |
| async def score_turn( | |
| turn: int, request: gradio.Request | |
| ) -> iris_content_guard.TurnScores: | |
| session = sessions.get(request.headers.get('x-iris-session', '')) | |
| if session is None or session.expired(time.monotonic()): | |
| raise ValueError('Session expired') | |
| end = session.pending_score_ends.pop(turn, None) | |
| if end is None: | |
| raise ValueError('No pending Iris Content Guard score for this turn') | |
| return await asyncio.to_thread( | |
| iris_content_guard.score_conversation, session.visible_messages[:end] | |
| ) | |
| def home() -> responses.FileResponse: | |
| return responses.FileResponse(dist / 'index.html') | |
| def license_file() -> responses.FileResponse: | |
| return responses.FileResponse(dist / 'plex-ofl.txt') | |
| app.mount( | |
| '/assets', | |
| staticfiles.StaticFiles(directory=dist / 'assets'), | |
| name='iris_assets', | |
| ) | |
| initial_files = workspace.Workspace().listing() | |
| async def status() -> dict[str, str]: | |
| return {'state': await monitor.read()} | |
| def config() -> dict[str, object]: | |
| return {'cutoff': turns.CUTOFF, 'files': initial_files} | |
| def error(code: int, message: str) -> responses.JSONResponse: | |
| return responses.JSONResponse( | |
| {'error': message}, | |
| status_code=code, | |
| headers={'Cache-Control': 'no-store'}, | |
| ) | |
| def lookup(request: fastapi.Request) -> tuple[str, turns.Session | None]: | |
| now = time.monotonic() | |
| for key, session in list(sessions.items()): | |
| if session.expired(now): | |
| del sessions[key] | |
| # Hugging Face uses Authorization for the visitor's ZeroGPU identity. | |
| key = request.headers.get('x-iris-session', '') | |
| return key, sessions.get(key) | |
| def starter_workspace(request: fastapi.Request) -> workspace.Workspace: | |
| seed = request.headers.get('x-iris-workspace-seed', '') | |
| return workspace.Workspace(entries=workspace.initial_files(seed)) | |
| async def read_file( | |
| request: fastapi.Request, name: str = fastapi.Body(embed=True) | |
| ) -> responses.Response: | |
| """Read starter files statelessly. Live file reads refresh the chat timeout.""" | |
| if name == 'api-key.txt': | |
| return error(403, 'Permission denied.') | |
| session = None | |
| if 'x-iris-session' in request.headers: | |
| _, session = lookup(request) | |
| if session is None: | |
| return error(401, 'Session expired. Start a new session.') | |
| guest = session.workspace if session else starter_workspace(request) | |
| text = guest.read_file(name) | |
| if text is None: | |
| return error(404, 'This file no longer exists in your workspace.') | |
| if session: | |
| session.last_used = time.monotonic() | |
| return responses.JSONResponse(text, headers={'Cache-Control': 'no-store'}) | |
| async def session_state(request: fastapi.Request) -> responses.Response: | |
| _, session = lookup(request) | |
| if session is None: | |
| return error(401, 'Session expired. Start a new session.') | |
| if session.active_request is not None: | |
| return error( | |
| 409, 'Beam is still processing the previous turn. Try again shortly.' | |
| ) | |
| return responses.JSONResponse( | |
| { | |
| 'turn': session.turns, | |
| 'completed': session.completed_turn, | |
| 'stopped': session.stopped, | |
| 'files': session.workspace.listing(), | |
| }, | |
| headers={'Cache-Control': 'no-store'}, | |
| ) | |
| async def reset(request: fastapi.Request) -> responses.Response: | |
| key, session = lookup(request) | |
| if session is None: | |
| return error(401, 'Session expired. Start a new session.') | |
| del sessions[key] | |
| session.close() | |
| return responses.JSONResponse({}) | |
| async def turn(request: fastapi.Request) -> responses.Response: | |
| if ( | |
| request.headers.get('content-type', '').partition(';')[0] | |
| != 'application/json' | |
| ): | |
| return error(415, 'Expected a JSON request.') | |
| body = bytearray() | |
| async for chunk in request.stream(): | |
| if len(body) + len(chunk) > 16384: | |
| return error(413, 'Request is too large.') | |
| body.extend(chunk) | |
| try: | |
| payload = json.loads(body) | |
| except (ValueError, UnicodeDecodeError, RecursionError): | |
| return error(400, 'Invalid JSON.') | |
| prompt = ( | |
| cast(dict[str, object], payload).get('prompt') | |
| if isinstance(payload, dict) | |
| else None | |
| ) | |
| if not isinstance(prompt, str) or not prompt.strip() or len(prompt) > 1600: | |
| return error(400, 'Enter a prompt of 1 to 1600 characters.') | |
| key, session = lookup(request) | |
| if session is None: | |
| if 'x-iris-session' in request.headers: | |
| return error(401, 'Session expired. Start a new session.') | |
| if len(sessions) >= 1000: | |
| return error(503, 'Session capacity reached. Try again later.') | |
| key = secrets.token_urlsafe(32) | |
| sessions[key] = session = turns.Session( | |
| workspace=starter_workspace(request) | |
| ) | |
| if ( | |
| session.active_request is not None | |
| or session.stopped | |
| or session.turns >= 64 | |
| ): | |
| return error(409, 'Session busy, stopped or full. Start a new session.') | |
| # Reserve this session before StreamingResponse starts its iterator. | |
| session.active_request = asyncio.current_task() | |
| session.turns += 1 | |
| stream = turns.events( | |
| session, | |
| key, | |
| prompt.strip(), | |
| beam_client.connect(url, beam_token, monitor_url), | |
| ) | |
| return responses.StreamingResponse( | |
| stream, | |
| media_type='application/x-ndjson', | |
| headers={'Cache-Control': 'no-store', 'X-Accel-Buffering': 'no'}, | |
| ) | |
| app.add_api_route('/', home, methods=['GET', 'HEAD']) | |
| app.add_api_route('/plex-ofl.txt', license_file, methods=['GET', 'HEAD']) | |
| app.add_api_route('/api/beam-status', status, methods=['GET']) | |
| app.add_api_route('/api/config', config, methods=['GET']) | |
| app.add_api_route('/api/workspace/file', read_file, methods=['POST']) | |
| app.add_api_route('/api/session', session_state, methods=['GET']) | |
| app.add_api_route('/api/session', reset, methods=['DELETE']) | |
| app.add_api_route('/api/turns', turn, methods=['POST']) | |
| return app | |