Spaces:
Running on Zero

abargum's picture
Update the Inter-2 Audio playground
b27aa48 verified
Raw History Blame Contribute Delete
5.61 kB
"""Shared by the Inter-2 playgrounds (the copies are kept identical; a test checks): reading the
model's answer, choosing what the schema toggle holds it to, and the generic parts of the result card.
The schema toggle holds the answer to the task's schema only when the prompt still asks for that
schema: the preset prompt, or a prompt that names every field the schema requires. Any other
prompt with the toggle on is held to valid JSON of any shape, so a prompt asking for its own fields
gets them. Any answer renders: the known layouts in each Space's inference.py, other JSON as a
field list, and text that is not JSON as text. Everything from the model is HTML-escaped.
"""
from __future__ import annotations
import ast
import html
import json
import re
from typing import Any
ANY_JSON = "Any JSON" # the grammar key for valid JSON of any shape
MAX_DEPTH = 4 # deeper JSON is shown as compact JSON text
def parse_json(text: str) -> Any | None:
"""The model's JSON answer, tolerating a code fence, surrounding prose or Python-style literals."""
text = text.strip()
fence = re.match(r"```(?:json)?\s*(.*?)\s*```", text, re.DOTALL)
if fence:
text = fence.group(1).strip()
decoder = json.JSONDecoder(strict=False) # a raw tab or newline inside a string is still the answer
# An answer that opens as JSON is all-or-nothing: a cut-off answer must not show an inner fragment.
opens_as_json = text[:1] in ("{", "[")
starts = {0: None} if opens_as_json else dict.fromkeys([*(m.start() for m in re.finditer(r"[\[{]", text)), 0])
for start in starts:
try:
value, end = decoder.raw_decode(text[start:])
if (start and not opens_as_json) or not text[start + end :].strip():
return value
except json.JSONDecodeError:
pass
for start in starts:
for end in (match.end() for match in re.finditer(r"[\]}]", text[start:])):
end += start
try:
value = ast.literal_eval(text[start:end])
json.dumps(value)
return value
except (ValueError, SyntaxError, TypeError, OverflowError, MemoryError, RecursionError):
pass
return None
def schema_target(task: str, preset_prompt: str, schema: dict, user_prompt: str, system_prompt: str) -> tuple[str, str]:
"""(grammar key, note for the result card) for a constrained request. `system_prompt` is the
one the user typed (not a default), since a default may name the task's fields itself."""
if user_prompt.strip() == preset_prompt.strip():
return task, ""
text = f"{user_prompt}\n{system_prompt}"
if all(re.search(rf"\b{re.escape(key)}\b", text) for key in schema.get("required", [])):
return task, ""
return (
ANY_JSON,
f"The prompt asks for other fields than the {task} task, so the answer was held to valid JSON only.",
)
def esc(value: Any) -> str:
return html.escape(str(value))
def badge(level: Any) -> str:
if not level or not isinstance(level, str):
return ""
style = " ih-badge-high" if level == "high" else ""
return f'<span class="ih-badge{style}">{esc(level)}</span>'
def number(value: Any) -> float | None:
"""A JSON number or numeric string as a float (booleans and other values are not numbers)."""
if isinstance(value, bool):
return None
try:
result = float(value)
except (TypeError, ValueError):
return None
return result if result == result and abs(result) != float("inf") else None
def text_of(value: Any) -> str:
"""A label as text: strings as they are, anything else as compact JSON."""
return value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)
def _scalar(value: Any) -> str:
if value is None or value == "":
return '<span class="ih-meta">–</span>'
return esc(text_of(value))
def render_value(value: Any, depth: int = 0) -> str:
"""Any JSON value as HTML: objects as captioned fields, lists of plain values on one line,
lists of objects one block each."""
if depth >= MAX_DEPTH:
return esc(json.dumps(value, ensure_ascii=False))
if isinstance(value, dict):
if not value:
return _scalar(None)
return "".join(
f'<div class="ih-field"><div class="ih-caption">{esc(key)}</div>'
f'<div class="ih-field-value">{render_value(item, depth + 1)}</div></div>'
for key, item in value.items()
)
if isinstance(value, list):
if not value:
return _scalar(None)
if all(not isinstance(item, (dict, list)) for item in value):
return esc(", ".join(text_of(item) for item in value)) or _scalar(None)
return "".join(f'<div class="ih-item">{render_value(item, depth + 1)}</div>' for item in value)
return _scalar(value)
def render_text(text: str) -> str:
"""An answer that is not JSON, paragraph by paragraph."""
paragraphs = [part.strip() for part in re.split(r"\n\s*\n", text) if part.strip()]
if not paragraphs:
return '<p class="ih-note">The model returned an empty answer.</p>'
return '<div class="ih-answer">' + "".join(f"<p>{esc(part)}</p>" for part in paragraphs) + "</div>"
def card(body: str, notes: list[str]) -> str:
notes_html = "".join(f'<p class="ih-warning">{esc(note)}</p>' for note in notes if note)
return f'<div class="ih-card">{notes_html}{body}</div>'
def message_card(text: str) -> str:
return card(f'<p class="ih-note">{esc(text)}</p>', [])