File size: 12,122 Bytes
13b5f12 57e078a 881204c 13b5f12 881204c 13b5f12 881204c 3e8f00a 8237e23 881204c 57e078a 881204c 57e078a 881204c 13b5f12 9579e1a 13b5f12 9579e1a 13b5f12 881204c 13b5f12 881204c 13b5f12 881204c 13b5f12 9579e1a 881204c 13b5f12 881204c 57e078a 881204c 57e078a 881204c 57e078a 13b5f12 881204c 13b5f12 881204c 13b5f12 881204c 57e078a 881204c 57e078a 881204c 57e078a 881204c 57e078a 881204c 13b5f12 57e078a 5891bca e5b68d1 5891bca 881204c 5891bca 3e8f00a 881204c 8237e23 13b5f12 8237e23 13b5f12 | 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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | """Deterministic post-processing for bucket HTML artifacts."""
from __future__ import annotations
import base64
import json
import posixpath
import re
import tempfile
from pathlib import Path
from typing import Any
from huggingface_hub import HfApi
from huggingface_hub.errors import RemoteEntryNotFoundError
from fast_agent import AgentAuth
from .artifact_contract import validate_stage_manifest
from .app_jobs import ResearchJob
MARKER = "__BIRCH_SYSTEM_CSS__"
STYLE_RE = re.compile(
r"<style\b(?=[^>]*\bdata-birch-system\b)[^>]*>.*?</style>",
re.I | re.S,
)
STYLE_CONTENT_RE = re.compile(
r"<style\b(?=[^>]*\bdata-birch-system\b)[^>]*>(?P<css>.*?)</style>",
re.I | re.S,
)
MARKER_STYLE_RE = re.compile(
rf"<style\b[^>]*>\s*{re.escape(MARKER)}\s*</style>",
re.I | re.S,
)
PAGE_RE = re.compile(
r'<main\b[^>]*\bclass=["\'][^"\']*\bpage\b[^"\']*["\']',
re.I,
)
MAIN_CLASS_RE = re.compile(r'(<main\b[^>]*\bclass=["\'])([^"\']*)', re.I)
MAIN_RE = re.compile(r"<main\b", re.I)
ASSET_REF_RE = re.compile(
r"""(?:src|href)=["'](?P<value>[^"'#?]+)(?:[?#][^"']*)?["']""",
re.I,
)
LOCAL_ASSET_SRC_RE = re.compile(
r"""(?P<prefix>\bsrc\s*=\s*)(?P<quote>["'])(?P<value>assets/[^"'#?]+)(?P=quote)""",
re.I,
)
MAX_PRESENTATION_BYTES = 25 * 1024 * 1024
SAFE_ASSET_MEDIA_TYPES = {
".avif": "image/avif",
".csv": "text/csv",
".gif": "image/gif",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".json": "application/json",
".png": "image/png",
".svg": "image/svg+xml",
".webp": "image/webp",
}
def finalize_bucket_html(
job: ResearchJob,
auth: AgentAuth | None,
home: Path,
*,
api: HfApi | None = None,
required: bool = False,
) -> tuple[str, str] | None:
"""Finalize a Birch draft without requiring Hugging Face Jobs."""
if auth is None or not auth.token:
if required:
raise RuntimeError("Caller authentication is required to publish HTML")
return None
api = api or HfApi()
username = api.whoami(token=auth.token)["name"]
bucket_id = f"{username}/research-agent"
attempt = max(1, job.birch_finalize_attempts)
attempt_root = f"scratch/presentation/attempts/{attempt}"
attempt_path = f"{job.artifact_id}/{attempt_root}/report.html"
legacy_draft_path = f"{job.artifact_id}/scratch/report.html"
output_path = f"{job.artifact_id}/output/report.html"
draft_paths = (
(attempt_path, legacy_draft_path, output_path)
if hasattr(api, "list_bucket_tree")
else (legacy_draft_path, output_path)
)
with tempfile.TemporaryDirectory() as directory:
local_root = Path(directory)
local = local_root / "report.html"
source_path = _download_first(
api,
bucket_id,
draft_paths,
local,
auth.token,
)
if source_path is None:
if required:
raise FileNotFoundError(
f"Birch draft was not staged at {attempt_path}"
)
return None
html = local.read_text()
assets: list[tuple[bytes, str]] = []
embedded_assets: dict[str, tuple[str, bytes]] = {}
if source_path == attempt_path:
assets, embedded_assets = _load_presentation_assets(
api,
bucket_id,
job.artifact_id,
attempt_root,
html,
local_root,
auth.token,
)
html = _embed_presentation_assets(html, embedded_assets)
css = _birch_css_path(home).read_text()
if MARKER in html:
finalized = _ensure_page_shell(_inject_birch_css(html, css))
elif source_path == output_path:
_validate_html(html)
return _artifact_urls(username, job.artifact_id)
elif _has_trusted_birch_css(html, css):
finalized = _ensure_page_shell(html)
else:
if required:
raise ValueError(
"Birch draft has neither a stylesheet placeholder nor the "
"exact trusted stylesheet"
)
return None
_validate_html(finalized)
api.batch_bucket_files(
bucket_id,
add=[(finalized.encode(), output_path), *assets],
token=auth.token,
)
job.add_event(
"Finalized Birch HTML with the bundled stylesheet",
kind="artifact",
)
return _artifact_urls(username, job.artifact_id)
def _load_presentation_assets(
api: Any,
bucket_id: str,
workspace: str,
attempt_root: str,
html: str,
local_root: Path,
token: str,
) -> tuple[list[tuple[bytes, str]], dict[str, tuple[str, bytes]]]:
manifest_remote = f"{workspace}/{attempt_root}/manifest.json"
manifest_local = local_root / "manifest.json"
api.download_bucket_files(
bucket_id,
[(manifest_remote, manifest_local)],
raise_on_missing_files=True,
token=token,
)
manifest = json.loads(manifest_local.read_text())
paths = validate_stage_manifest(
manifest,
stage="presentation",
allowed_prefixes=(f"{attempt_root}/",),
)
report_path = f"{attempt_root}/report.html"
if manifest.get("entrypoint") != report_path or report_path not in paths:
raise ValueError("Presentation manifest must declare its report entrypoint")
asset_prefix = f"{attempt_root}/assets/"
asset_paths = tuple(path for path in paths if path.startswith(asset_prefix))
declared_refs = {
posixpath.relpath(path, attempt_root): path for path in asset_paths
}
referenced = _relative_asset_references(html)
undeclared = sorted(referenced - declared_refs.keys())
if undeclared:
raise ValueError(
"HTML references assets not declared by the presentation manifest: "
+ ", ".join(undeclared)
)
uploads: list[tuple[bytes, str]] = []
embeds: dict[str, tuple[str, bytes]] = {}
total = 0
for index, path in enumerate(asset_paths):
suffix = _path_suffix(path)
media_type = SAFE_ASSET_MEDIA_TYPES.get(suffix)
if media_type is None:
raise ValueError(f"Unsupported presentation asset type: {path}")
local = local_root / f"asset-{index}{suffix}"
api.download_bucket_files(
bucket_id,
[(f"{workspace}/{path}", local)],
raise_on_missing_files=True,
token=token,
)
payload = local.read_bytes()
total += len(payload)
if not payload:
raise ValueError(f"Presentation asset is empty: {path}")
if total > MAX_PRESENTATION_BYTES:
raise ValueError(
f"Presentation assets exceed {MAX_PRESENTATION_BYTES} bytes"
)
relative = posixpath.relpath(path, asset_prefix)
uploads.append((payload, f"{workspace}/output/assets/{relative}"))
embeds[f"assets/{relative}"] = (media_type, payload)
return uploads, embeds
def _path_suffix(path: str) -> str:
"""Return a normalized lowercase suffix for a POSIX artifact path."""
return Path(path).suffix.lower()
def _relative_asset_references(html: str) -> set[str]:
references: set[str] = set()
for match in ASSET_REF_RE.finditer(html):
value = match.group("value").strip()
if (
not value
or value.startswith(("/", "http://", "https://", "hf://", "data:"))
):
continue
normalized = posixpath.normpath(value)
if normalized.startswith("../"):
raise ValueError(f"HTML asset reference escapes output/: {value}")
if normalized.startswith("assets/"):
references.add(normalized)
return references
def _embed_presentation_assets(
html: str,
assets: dict[str, tuple[str, bytes]],
) -> str:
"""Embed declared local image sources while retaining published asset files."""
def replace(match: re.Match[str]) -> str:
value = posixpath.normpath(match.group("value"))
asset = assets.get(value)
if asset is None:
return match.group(0)
media_type, payload = asset
if not media_type.startswith("image/"):
return match.group(0)
encoded = base64.b64encode(payload).decode("ascii")
return (
f"{match.group('prefix')}{match.group('quote')}"
f"data:{media_type};base64,{encoded}{match.group('quote')}"
)
return LOCAL_ASSET_SRC_RE.sub(replace, html)
def read_bucket_markdown(
job: ResearchJob,
auth: AgentAuth | None,
*,
api: HfApi | None = None,
) -> str:
"""Read an available Markdown report with the caller's token."""
if auth is None or not auth.token:
raise RuntimeError("Caller authentication is required to read the report")
api = api or HfApi()
username = api.whoami(token=auth.token)["name"]
bucket_id = f"{username}/research-agent"
report_path = f"{job.artifact_id}/output/report.md"
with tempfile.TemporaryDirectory() as directory:
local = Path(directory) / "report.md"
api.download_bucket_files(
bucket_id,
[(report_path, local)],
raise_on_missing_files=True,
token=auth.token,
)
return local.read_text()
def _inject_birch_css(html: str, css: str) -> str:
"""Normalize a marker-only style element and inject trusted Birch CSS."""
replacement = f"<style data-birch-system>{css.strip()}</style>"
if MARKER_STYLE_RE.search(html):
return MARKER_STYLE_RE.sub(replacement, html, count=1)
return html.replace(MARKER, css.strip())
def _has_trusted_birch_css(html: str, css: str) -> bool:
match = STYLE_CONTENT_RE.search(html)
return match is not None and match.group("css").strip() == css.strip()
def _ensure_page_shell(html: str) -> str:
"""Add Birch's required `.page` class to the first main element."""
if PAGE_RE.search(html):
return html
if MAIN_CLASS_RE.search(html):
return MAIN_CLASS_RE.sub(r"\1page \2", html, count=1)
if MAIN_RE.search(html):
return MAIN_RE.sub('<main class="page"', html, count=1)
return html
def _download_first(
api: Any,
bucket_id: str,
remote_paths: tuple[str, ...],
local_path: Path,
token: str,
) -> str | None:
for remote_path in remote_paths:
try:
api.download_bucket_files(
bucket_id,
[(remote_path, local_path)],
raise_on_missing_files=True,
token=token,
)
return remote_path
except RemoteEntryNotFoundError:
continue
return None
def _birch_css_path(home: Path) -> Path:
candidates = (
home / "skills" / "birch-html" / "assets" / "birch-system.css",
home.parent
/ "deploy"
/ "research-tool-one"
/ "skills"
/ "birch-html"
/ "assets"
/ "birch-system.css",
)
for path in candidates:
if path.exists():
return path
raise FileNotFoundError("Bundled Birch stylesheet is missing")
def _validate_html(html: str) -> None:
if MARKER in html:
raise ValueError("Birch CSS placeholder remains")
if not html.lstrip().lower().startswith("<!doctype html>"):
raise ValueError("HTML artifact has no doctype")
if not STYLE_RE.search(html):
raise ValueError("HTML artifact has no embedded Birch stylesheet")
if not PAGE_RE.search(html):
raise ValueError("HTML artifact has no Birch page shell")
if "</html>" not in html.lower():
raise ValueError("HTML artifact is incomplete")
def _artifact_urls(username: str, job_id: str) -> tuple[str, str]:
path = f"{job_id}/output/report.html"
return (
f"hf://buckets/{username}/research-agent/{path}",
f"https://huggingface.co/buckets/{username}/research-agent/tree/{path}",
)
|