"""Gradio Space entrypoint for the packaged HarnessLab workspace.""" import hashlib import json import os from pathlib import Path import zipfile def unpack_bundle(root: Path) -> None: bundle = root / "harnesslab_bundle.zip" manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8")) if hashlib.sha256(bundle.read_bytes()).hexdigest() != manifest["bundle_sha256"]: raise ValueError("Bundle checksum mismatch") with zipfile.ZipFile(bundle) as archive: expected = {entry["path"]: entry["sha256"] for entry in manifest["files"]} if set(archive.namelist()) != set(expected): raise ValueError("Bundle file manifest mismatch") for name in archive.namelist(): target = (root / name).resolve() if not target.is_relative_to(root.resolve()): raise ValueError("Invalid bundle member path") if hashlib.sha256(archive.read(name)).hexdigest() != expected[name]: raise ValueError("Bundle member checksum mismatch") archive.extractall(root) def main() -> None: root = Path(__file__).resolve().parent unpack_bundle(root) os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False") os.environ.setdefault("GRADIO_SSR_MODE", "False") import gradio as gr import spaces import uvicorn from space_app import app as workspace from space_app import scenario_catalog from transformers import AutoModelForCausalLM, AutoTokenizer import torch import tempfile from uuid import uuid4 model_id = "Qwen/Qwen3-4B-Instruct-2507" tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=False) model = AutoModelForCausalLM.from_pretrained( model_id, torch_dtype=torch.float16, low_cpu_mem_usage=True, trust_remote_code=False, ).eval().to("cuda") @spaces.GPU(duration=45) def run_model(case_id: str) -> dict: # GPU workers start from the image, not the CPU process's runtime files. unpack_bundle(root) from adapters.transformers_local import TransformersLocalAdapter from harness.hf_evaluation import evaluate_case adapter = TransformersLocalAdapter(model_id=model_id, model=model, tokenizer=tokenizer) path = Path(tempfile.gettempdir()) / f"harnesslab-hf-{uuid4()}.json" batch = evaluate_case(adapter, case_id, model_id, getattr(model.config, "_commit_hash", None), root, path) return {"report": batch.model_dump(mode="json")} def publish_result(result: dict) -> tuple[dict, str]: # GPU functions run in an isolated worker; update the web process here. from harness.batch import BatchReport from space_app import store_report batch = BatchReport.model_validate_json(json.dumps(result["report"])) path = Path(tempfile.gettempdir()) / f"harnesslab-hf-{uuid4()}.json" path.write_text(batch.model_dump_json(indent=2), encoding="utf-8") report_id = store_report(batch, "real_live") return {**batch.summary(), "workspace_report": f"/?report={report_id}", "failure_reason": batch.cases[0].report.evaluation.failure_reason}, str(path) def test_public_mcp() -> tuple[dict, str]: from harness.mcp_client import MCPClient with MCPClient("https://mcp.deepwiki.com/mcp") as client: server = client.initialize() tools = client.list_tools() result = client.call_tool("read_wiki_structure", {"repoName": "openai/openai-python"}) record = {"server": server, "protocol_version": client.protocol_version, "endpoint": "https://mcp.deepwiki.com/mcp", "tools": [tool.name for tool in tools], "called_tool": "read_wiki_structure", "arguments": {"repoName": "openai/openai-python"}, "call": result.model_dump(mode="json")} path = Path(tempfile.gettempdir()) / f"harnesslab-mcp-{uuid4()}.json" path.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8") return record, str(path) @spaces.GPU(duration=10) def gpu_environment_check() -> dict[str, str | float]: """Optional real CUDA check; never invoked during startup or Mock runs.""" import torch start = torch.cuda.Event(enable_timing=True) end = torch.cuda.Event(enable_timing=True) value = torch.ones(1, device="cuda") start.record() result = value * 2 end.record() torch.cuda.synchronize() return {"device": torch.cuda.get_device_name(), "check_value": float(result.item()), "kernel_time_seconds": start.elapsed_time(end) / 1000, "purpose": "GPU environment diagnostic; not a model performance benchmark"} with gr.Blocks(title="HarnessLab") as info: gr.Markdown("# HarnessLab — 실제 모델 평가\n[평가 워크스페이스 열기](/)\n\nQwen3-4B-Instruct-2507을 이 Space에서 실행합니다. API 키나 로컬 PC가 필요 없습니다. 1회 실행은 시나리오 1개이며 최대 45초의 ZeroGPU 작업을 요청합니다. 무료 쿼터를 사용합니다.") scenario = gr.Dropdown(list(scenario_catalog()), value="S01", label="평가 시나리오") execute = gr.Button("실제 모델 평가 실행 — ZeroGPU 사용", variant="primary") summary = gr.JSON(label="실제 실행 결과") artifact = gr.File(label="평가 Trace JSON 다운로드") event = execute.click(run_model, inputs=[scenario], outputs=[summary], api_name="evaluate_model", concurrency_limit=1) event.then(publish_result, inputs=[summary], outputs=[summary, artifact], api_name=False) gr.Markdown("## 외부 MCP 연동 예제 — DeepWiki\nGPU나 API 키 없이 외부 공개 MCP 서버의 도구 목록을 읽고, openai/openai-python 문서 목차를 조회합니다.") mcp_button = gr.Button("DeepWiki MCP 연결 테스트 — GPU 미사용") mcp_result = gr.JSON(label="MCP 실제 호출 결과") mcp_file = gr.File(label="MCP 호출 기록 JSON") mcp_button.click(test_public_mcp, inputs=[], outputs=[mcp_result, mcp_file], api_name="test_deepwiki_mcp", concurrency_limit=1) gr.Markdown("## 선택: GPU 환경 확인\n버튼을 누를 때만 ZeroGPU 쿼터를 사용합니다(요청 최대 10초). Mock 평가와 기록 조회에는 필요하지 않습니다.") diagnostic = gr.Button("GPU 환경 확인 — ZeroGPU 쿼터 사용") gpu_result = gr.JSON(label="환경 확인 결과 — 모델 성능 지표가 아닙니다") diagnostic.click(gpu_environment_check, inputs=[], outputs=[gpu_result], api_name="gpu_environment") info.show_error = True application = gr.mount_gradio_app(workspace, info, path="/gradio", ssr_mode=False) # Mounting bypasses Blocks.launch(), which normally sends this registration. try: from spaces.zero import startup as zero_startup except ImportError: pass else: zero_startup() uvicorn.run(application, host="0.0.0.0", port=7860, workers=1) if __name__ == "__main__": main()