Spaces:
Running on Zero
Running on Zero
File size: 11,360 Bytes
1edb5ce 4d9ddfa 1edb5ce df13472 1edb5ce df13472 1edb5ce df13472 af0fb9b df13472 af0fb9b df13472 1edb5ce df13472 4d9ddfa df13472 4d9ddfa df13472 4d9ddfa df13472 4d9ddfa df13472 4d9ddfa 3389179 df13472 4d9ddfa 1edb5ce df13472 1edb5ce df13472 1edb5ce | 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 | import ast
import hashlib
import re
import unittest
from pathlib import Path
import provenance
from i2i_contract import CONTENT_MODERATION_ENABLED, PUBLIC_ERROR_MESSAGES
ROOT = Path(__file__).resolve().parents[1]
class SpaceStaticTests(unittest.TestCase):
def test_remote_assets_are_pinned_and_candidate_count_is_stable(self):
provenance.assert_pinned_provenance()
self.assertEqual(len(provenance.CANDIDATE_ADAPTER_SPECS), 19)
self.assertEqual(set(provenance.ENABLED_ADAPTER_SPECS), set(provenance.CANDIDATE_ADAPTER_SPECS))
for spec in provenance.CANDIDATE_ADAPTER_SPECS.values():
self.assertRegex(spec.revision, r"^[0-9a-f]{40}$")
self.assertNotEqual(spec.revision, "main")
def test_content_moderation_is_explicitly_disabled(self):
self.assertIs(CONTENT_MODERATION_ENABLED, False)
app_source = (ROOT / "app.py").read_text(encoding="utf-8")
self.assertIn("content_moderation_enabled", app_source)
forbidden = ["safety_checker", "nsfw_classifier", "prompt_blocklist"]
for marker in forbidden:
self.assertNotIn(marker, app_source.lower())
def test_public_error_codes_are_exact_and_low_cardinality(self):
self.assertEqual(
set(PUBLIC_ERROR_MESSAGES),
{
"I2I_BAD_REQUEST",
"I2I_UNSUPPORTED_TYPE",
"I2I_FILE_TOO_LARGE",
"I2I_IMAGE_DECODE_FAILED",
"I2I_IMAGE_DIMENSIONS_INVALID",
"I2I_PROMPT_REQUIRED",
"I2I_PROMPT_TOO_LONG",
"I2I_LORA_NOT_ALLOWED",
"I2I_PROVIDER_BUSY",
"I2I_INFERENCE_FAILED",
"I2I_INVALID_OUTPUT",
},
)
source = (ROOT / "app.py").read_text(encoding="utf-8")
self.assertIn("return message in {", source)
self.assertNotIn('message.startswith(f"{code}:")', source)
def test_edit_endpoint_has_seven_fields_and_serial_concurrency(self):
tree = ast.parse((ROOT / "app.py").read_text(encoding="utf-8"))
function = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "edit_image")
self.assertEqual(
[argument.arg for argument in function.args.args],
[
"images_b64_json",
"prompt",
"lora_adapter",
"seed",
"randomize_seed",
"guidance_scale",
"steps",
],
)
decorator = ast.unparse(function.decorator_list[0])
self.assertIn("name='edit_image'", decorator)
self.assertIn("concurrency_limit=1", decorator)
self.assertIn("concurrency_id='i2i-pipeline'", decorator)
def test_gpu_is_internal_and_mcp_and_raw_errors_are_disabled(self):
source = (ROOT / "app.py").read_text(encoding="utf-8")
self.assertIn('@spaces.GPU(size="xlarge")', source)
self.assertNotIn("@app.mcp.tool", source)
self.assertIn("show_error=False", source)
self.assertIn("mcp_server=False", source)
self.assertNotRegex(source, r"\{\s*(?:e|exc)\s*\}")
self.assertNotIn("str(exc)", source)
self.assertNotIn("traceback", source)
self.assertIn("load_lora_weights", source)
self.assertIn("revision=spec.revision", source)
self.assertIn("set_adapters", source)
self.assertIn("unload_lora_weights", source)
self.assertIn("SingleResidentAdapterManager", source)
def test_public_runtime_has_general_default_and_19_opt_in_loras(self):
source = (ROOT / "app.py").read_text(encoding="utf-8")
self.assertIn('"edit_mode": "general-and-lora"', source)
self.assertIn('"uses_lora": True', source)
self.assertIn('"supports_general_mode": True', source)
self.assertIn('"default_edit_mode": BASE_EDIT_MODE_ID', source)
self.assertIn("allowed_edit_modes={BASE_EDIT_MODE_ID, *ENABLED_ADAPTER_SPECS}", source)
def test_homepage_is_a_hardened_full_feature_editor(self):
html = (ROOT / "index.html").read_text(encoding="utf-8")
script = (ROOT / "assets" / "app-ui.js").read_text(encoding="utf-8")
self.assertIn('src="/hy3d-assets/app-ui.js"', html)
self.assertIn('accept="image/png,image/jpeg,image/webp"', html)
self.assertIn(" multiple", html)
self.assertIn("Style / LoRA", html)
self.assertIn('id="tab-examples"', html)
self.assertIn('id="examples-scroll"', html)
self.assertNotRegex(html, r'<(?:script|link)[^>]+(?:src|href)=["\']https?://')
self.assertNotIn("googleapis", html.lower())
self.assertNotIn("jsdelivr", html.lower())
self.assertIn('const GENERAL_MODE_ID = "__base__"', script)
self.assertIn('const EXPECTED_API_VERSION = "2026-08-12.3"', script)
self.assertIn("images_b64_json: JSON.stringify(inputSnapshot)", script)
self.assertIn("lora_adapter: editMode", script)
self.assertIn('events: ["data", "status"]', script)
self.assertIn("await currentJob.wait_for_id()", script)
self.assertIn("await job.return()", script)
self.assertIn("config.uses_lora !== true", script)
self.assertIn("config.loras.length !== EXPECTED_LORA_IDS.length", script)
self.assertIn("nextLimits.input_images !== 2", script)
self.assertIn("nextLimits.min_input_images !== 1", script)
self.assertIn("nextLimits.max_input_images !== 2", script)
self.assertIn('client.predict("/load_example", { idx: index })', script)
self.assertIn("Stopped waiting for this job. The backend may still finish it.", script)
self.assertNotIn("Queued job cancelled", script)
self.assertNotIn('hideLoader("Cancelled")', script)
self.assertIn('"Anime-V2"', script)
self.assertIn('"Photo-to-Anime"', script)
self.assertIn('"General / No LoRA"', script)
lora_block = re.search(r"const EXPECTED_LORA_IDS = Object\.freeze\(\[(.*?)\]\);", script, re.DOTALL)
self.assertIsNotNone(lora_block)
ui_loras = re.findall(r'^\s*"([^"]+)",?$', lora_block.group(1), re.MULTILINE)
self.assertEqual(ui_loras, list(provenance.CANDIDATE_ADAPTER_SPECS))
suggestion_block = re.search(r"const SUGGESTIONS = Object\.freeze\(\[(.*?)\]\);", script, re.DOTALL)
self.assertIsNotNone(suggestion_block)
self.assertEqual(len(re.findall(r'^\s*\["', suggestion_block.group(1), re.MULTILINE)), 16)
suggestion_handler = re.search(r"SUGGESTIONS\.forEach\(.*?\n\}\);", script, re.DOTALL)
self.assertIsNotNone(suggestion_handler)
self.assertNotIn("loraSelect", suggestion_handler.group(0))
self.assertIn('["Upscale / Enhance", "Enhance clarity and fine detail while preserving the original composition."]', script)
self.assertNotIn("Upscale 4K", script)
self.assertNotIn("4K resolution", script)
self.assertNotIn("card.innerHTML", script)
self.assertIn("card.append(thumbnails, meta, promptText)", script)
self.assertIn('class="dot pending"', html)
self.assertIn("4 STEPS DEFAULT", html)
self.assertNotIn(".gh-btn", html)
self.assertIn(".site-btn{padding:6px 10px}", html)
self.assertLess(html.index('class="inspector"'), html.index('class="workspace"'))
self.assertIn('id="sb-status" role="status" aria-live="polite"', html)
self.assertIn('toast.setAttribute("aria-live"', script)
self.assertIn("studio.inert = true", script)
self.assertIn("function isLightboxOpen()", script)
self.assertGreaterEqual(script.count("if (isLightboxOpen()) return;"), 3)
input_strip = re.search(r"function renderInputStrip\(\) \{(.*?)\n\}", script, re.DOTALL)
self.assertIsNotNone(input_strip)
self.assertIn('const select = document.createElement("button")', input_strip.group(1))
self.assertIn('select.type = "button"', input_strip.group(1))
self.assertIn('select.className = "fs-thumb-select"', input_strip.group(1))
self.assertIn('select.setAttribute("aria-label", `Select input image ${index + 1}`)', input_strip.group(1))
self.assertIn('select.setAttribute("aria-pressed", String(index === selectedImageIndex))', input_strip.group(1))
self.assertIn("select.append(image, badge)", input_strip.group(1))
self.assertIn("thumb.append(select, remove)", input_strip.group(1))
self.assertNotIn('thumb.addEventListener("click"', input_strip.group(1))
self.assertIn(".fs-thumb-select:focus-visible", html)
def test_browser_client_is_exactly_vendored(self):
client_path = ROOT / "assets" / "gradio-client-2.3.1.js"
self.assertTrue(client_path.is_file())
digest = hashlib.sha256(client_path.read_bytes()).hexdigest()
self.assertEqual(digest, "a3d50dc5f3590c5723695abcd85e2009c42a8af08bfc9fa47a7baecc1040c0be")
def test_interactive_script_only_references_unique_existing_dom_ids(self):
html = (ROOT / "index.html").read_text(encoding="utf-8")
script = (ROOT / "assets" / "app-ui.js").read_text(encoding="utf-8")
element_ids = re.findall(r'\bid=["\']([^"\']+)["\']', html)
script_refs = set(re.findall(r'getElementById\(["\']([^"\']+)["\']\)', script))
script_created_ids = set(re.findall(r'\.id\s*=\s*["\']([^"\']+)["\']', script))
self.assertEqual(len(element_ids), len(set(element_ids)))
self.assertEqual(script_refs - set(element_ids) - script_created_ids, set())
def test_ui_assets_and_homepage_are_no_store_and_allowlisted(self):
source = (ROOT / "app.py").read_text(encoding="utf-8")
self.assertIn('"Cache-Control": "no-store, max-age=0, must-revalidate"', source)
self.assertIn('@app.get("/hy3d-assets/{asset_name}"', source)
self.assertIn('{"app-ui.js", "gradio-client-2.3.1.js"}', source)
def test_direct_python_dependencies_are_exact(self):
requirements = (ROOT / "requirements.txt").read_text(encoding="utf-8").splitlines()
packages = [line for line in requirements if line and not line.startswith("--")]
self.assertTrue(packages)
for package in packages:
self.assertRegex(package, r"^[A-Za-z0-9_.-]+==[^=<>~]+$")
self.assertEqual((ROOT / "pre-requirements.txt").read_text(encoding="utf-8").strip(), "pip==26.1.2")
def test_examples_are_fixed_non_gpu_api_assets(self):
source = (ROOT / "app.py").read_text(encoding="utf-8")
self.assertIn('@app.api(name="load_example", queue=False)', source)
self.assertIn("def load_example(idx: float) -> dict", source)
self.assertIn("parse_example_index", source)
self.assertIn("EXAMPLES_CONFIG", source)
self.assertIn("blocked_paths=[examples_path]", source)
def test_kernel_revision_is_pinned(self):
source = (ROOT / "qwenimage" / "qwen_fa3_processor.py").read_text(encoding="utf-8")
self.assertIn("from provenance import KERNEL_MODEL_REVISION", source)
self.assertIn("revision=KERNEL_MODEL_REVISION", source)
self.assertIsNone(re.search(r'get_kernel\([^)]*revision\s*=\s*["\']main["\']', source, re.DOTALL))
if __name__ == "__main__":
unittest.main()
|