Spaces:
Running on Zero
Running on Zero
Download tests/fallback_contract_checks.py from broyang/3dai: direct link, hf CLI and curl.
- Browser
- Download file 14.9 kB
-
https://huggingface.co/spaces/broyang/3dai/resolve/main/tests/fallback_contract_checks.py
- Command line
-
hf download hf://spaces/broyang/3dai/tests/fallback_contract_checks.py
-
curl -L -o fallback_contract_checks.py https://huggingface.co/spaces/broyang/3dai/resolve/main/tests/fallback_contract_checks.py
14.9 kB
| import inspect | |
| import numpy as np | |
| from PIL import Image | |
| def synthetic_concat_views(views=3, size=32, gap=4): | |
| tiles = [np.zeros((size, gap, 4), dtype=np.uint8)] | |
| for _ in range(views): | |
| tile = np.zeros((size, size, 4), dtype=np.uint8) | |
| tile[..., :3] = 200 | |
| tile[..., 3] = 255 | |
| tiles.append(tile) | |
| tiles.append(np.zeros((size, gap, 4), dtype=np.uint8)) | |
| return Image.fromarray(np.concatenate(tiles, axis=1)) | |
| def wiring_contract(app, check, fallback_stubs): | |
| config = app.demo.get_config_file() | |
| deps = config["dependencies"] | |
| by_api = {dep["api_name"]: dep for dep in deps if dep.get("api_name")} | |
| bridge = [dep for dep in deps if "labs:3dai-" in (dep.get("js") or "")] | |
| progress_hooks = [dep for dep in deps if "labsProgressBars" in (dep.get("js") or "")] | |
| results = [ | |
| check("api_run_pro_fallback_exposed", "/run_pro_fallback" in {f"/{name}" for name in by_api}, sorted(by_api)), | |
| check("api_names_preserved", {"generate_and_extract", "extract_model", "begin_generation", "start_session", | |
| "load_example", "end_session", "materialize_export_payload", "finish_glb_export", | |
| "generate_stl_download", "enable_model_exports", "begin_glb_export", | |
| "reset_generation_outputs"} <= set(by_api), sorted(by_api)), | |
| check("bridge_is_a_preprocess_hook_on_backend_deps", | |
| len(bridge) >= 2 and all(dep["backend_fn"] and len(dep["inputs"]) == 2 for dep in bridge), | |
| [(d["api_name"], d["backend_fn"], len(d["inputs"])) for d in bridge]), | |
| check("progress_hooks_are_preprocess_hooks_on_backend_deps", | |
| len(progress_hooks) >= 6 and all(dep["backend_fn"] for dep in progress_hooks), | |
| [(d["api_name"], d["backend_fn"]) for d in progress_hooks]), | |
| check("no_js_only_dependency_in_chain", not [dep for dep in deps if dep.get("js") and not dep["backend_fn"]], | |
| [dep["id"] for dep in deps if dep.get("js") and not dep["backend_fn"]]), | |
| check("preview_and_bake_share_one_gpu_function", | |
| [name for name, _ in fallback_stubs.GPU_DECORATED] == ["gpu_task"] | |
| and fallback_stubs.GPU_DECORATED[0][1] is app.gpu_task_duration, | |
| fallback_stubs.GPU_DECORATED), | |
| check("shared_gpu_function_requests_large", | |
| [{"function": option["function"], "size": option["size"]} for option in fallback_stubs.GPU_OPTIONS] | |
| == [{"function": "gpu_task", "size": "large"}], | |
| fallback_stubs.GPU_OPTIONS), | |
| check("gpu_reservation_follows_the_mode", | |
| app.gpu_task_duration(app.GPU_PREVIEW, None, 0, 0, 0, 0, 0, 2048) == app.GPU_ALLOCATION_SECONDS | |
| and app.gpu_task_duration(app.GPU_BAKE, None, 0.95, 1024) == 12 | |
| and app.gpu_task_duration(app.GPU_BAKE, None, 0.95, 1536) == 18 | |
| and app.gpu_task_duration(app.GPU_BAKE, None, 0.95, 2048) == app.GPU_ALLOCATION_SECONDS_HIGH_TEXTURE | |
| and app.gpu_task_duration(app.GPU_BAKE, None, 0.95, 4096) == app.GPU_ALLOCATION_SECONDS_MAX_TEXTURE, | |
| [app.gpu_task_duration(app.GPU_BAKE, None, 0.95, size) for size in app.GLB_TEXTURE_SIZES]), | |
| check("only_bake_reservation_scales_with_texture_size", | |
| app.GPU_ALLOCATION_SECONDS == 18 and round(app.GPU_ALLOCATION_SECONDS * 1.5) == 27 | |
| and app.generation_gpu_duration(texture_size=512) == 18 | |
| and app.generation_gpu_duration(texture_size=1536) == 18 | |
| and app.generation_gpu_duration(texture_size=2048) == 18 | |
| and app.extraction_gpu_duration(texture_size=2048) | |
| == app.GPU_ALLOCATION_SECONDS_HIGH_TEXTURE | |
| and app.extraction_gpu_duration(texture_size=4096) | |
| == app.GPU_ALLOCATION_SECONDS_MAX_TEXTURE | |
| and app.extraction_gpu_duration(texture_size=512) == 12 | |
| and app.extraction_gpu_duration(texture_size=1024) == 12 | |
| and app.extraction_gpu_duration(texture_size=1536) == 18, | |
| (app.GPU_ALLOCATION_SECONDS, app.generation_gpu_duration(texture_size=2048), | |
| app.extraction_gpu_duration(texture_size=2048), | |
| app.extraction_gpu_duration(texture_size=4096))), | |
| check("standard_export_settings_unchanged", | |
| (app.GLB_EXPORT_SIMPLIFY, app.GLB_EXPORT_TEXTURE_SIZE) == (0.95, 1024), | |
| (app.GLB_EXPORT_SIMPLIFY, app.GLB_EXPORT_TEXTURE_SIZE)), | |
| check("extract_model_takes_state_and_settings_only", | |
| tuple(name for name in inspect.signature(app.extract_model).parameters | |
| if name != "progress") == ("state", "mesh_simplify", "texture_size"), | |
| tuple(inspect.signature(app.extract_model).parameters)), | |
| ] | |
| results.extend(generation_api_contract(app, check)) | |
| results.extend(texture_selection_contract(app, check)) | |
| results.extend(multi_image_contract(app, check)) | |
| receipt_id = next(c["id"] for c in config["components"] if c["type"] == "json" and c["props"].get("visible") is False) | |
| generation_bridge = [dep for dep in deps if dep.get("js") and receipt_id in dep["inputs"]] | |
| results.append(check("bridge_reads_signed_receipt", len(generation_bridge) >= 2, len(generation_bridge))) | |
| hidden_json = {c["id"] for c in config["components"] if c["type"] == "json" and c["props"].get("visible") is False} | |
| ack_id = sorted({dep["inputs"][0] for dep in generation_bridge if "labs:3dai-fallback" in dep["js"]}) | |
| results.append(check("bridge_result_lands_in_a_json_input", | |
| len(ack_id) == 1 and ack_id[0] in hidden_json and ack_id[0] != receipt_id, | |
| ack_id)) | |
| generations = [dep for dep in deps if str(dep.get("api_name", "")).startswith("generate_and_extract")] | |
| grant_bridges = [dep for dep in deps if "labs:3dai-grant" in (dep.get("js") or "")] | |
| refund_bridges = [dep for dep in deps if "labs:3dai-refund" in (dep.get("js") or "")] | |
| results.append(check("every_generation_flow_requests_a_grant_first", | |
| len(grant_bridges) == len(generations) >= 3 | |
| and all(set(dep["inputs"]) <= hidden_json and dep["outputs"] == [] for dep in grant_bridges), | |
| (len(grant_bridges), len(generations)))) | |
| results.append(check("every_generation_flow_can_refund_a_failed_generation", | |
| len(refund_bridges) == len(generations) | |
| and all(set(dep["inputs"]) <= hidden_json for dep in refund_bridges), | |
| len(refund_bridges))) | |
| results.append(check("bridge_js_loaded_from_module", | |
| "labs:3dai-fallback" in app.fallback_bridge and "__labs_parent" in app.fallback_bridge, | |
| app.fallback_bridge[:40])) | |
| return results | |
| def _triggered_by(dependencies, component_id, event): | |
| return [dep for dep in dependencies if (component_id, event) in [tuple(t) for t in dep.get("targets") or []]] | |
| def texture_selection_contract(app, check): | |
| config = app.demo.get_config_file() | |
| components = {component["id"]: component for component in config["components"]} | |
| selector_id = [dep for dep in config["dependencies"] | |
| if dep.get("api_name") == "generate_and_extract"][0]["inputs"][-1] | |
| selector = components[selector_id] | |
| dependencies = config["dependencies"] | |
| by_api = {dep["api_name"]: dep for dep in dependencies if dep.get("api_name")} | |
| extraction_inputs = by_api["extract_model"]["inputs"] | |
| receipt_inputs = by_api["issue_export_receipt"]["inputs"] | |
| publish_outputs = by_api["enable_model_exports"]["outputs"] | |
| hidden_id = extraction_inputs[-1] | |
| hidden = components[hidden_id] | |
| generation_dependencies = [dep for dep in dependencies | |
| if str(dep.get("api_name", "")).startswith("generate_and_extract")] | |
| single_generation = [dep for dep in generation_dependencies | |
| if components[dep["inputs"][0]]["type"] == "image"] | |
| multi_generation = [dep for dep in generation_dependencies | |
| if components[dep["inputs"][0]]["type"] == "gallery"] | |
| image_id = by_api["generate_and_extract"]["inputs"][0] | |
| regenerate_ids = [component["id"] for component in config["components"] | |
| if component["type"] == "button" and component["props"].get("value") == "Regenerate"] | |
| click_triggers = _triggered_by(dependencies, regenerate_ids[0], "click") if regenerate_ids else [] | |
| upload_triggers = _triggered_by(dependencies, image_id, "upload") | |
| return [ | |
| check("texture_size_options_are_pinned", | |
| tuple(app.GLB_TEXTURE_SIZES) == (512, 1024, 1536, 2048, 4096) | |
| and app.GLB_EXPORT_TEXTURE_SIZE == 1024, | |
| (app.GLB_TEXTURE_SIZES, app.GLB_EXPORT_TEXTURE_SIZE)), | |
| check("texture_selector_exposes_every_size", | |
| selector["type"] == "dropdown" | |
| and [choice[1] for choice in selector["props"]["choices"]] == [512, 1024, 1536, 2048, 4096] | |
| and selector["props"]["value"] == 1024, | |
| (selector["type"], selector["props"].get("choices"), selector["props"].get("value"))), | |
| check("texture_selector_feeds_generation_only", | |
| selector_id in by_api["generate_and_extract"]["inputs"] | |
| and selector_id not in extraction_inputs and selector_id not in receipt_inputs, | |
| (selector_id, extraction_inputs, receipt_inputs)), | |
| check("hidden_export_texture_size_carries_generated_state", | |
| hidden["type"] == "number" and hidden["props"].get("visible") is False | |
| and hidden_id == extraction_inputs[-1] and hidden_id in receipt_inputs | |
| and hidden_id == publish_outputs[-1] and hidden["props"].get("value") == 1024, | |
| (hidden_id, hidden["type"], hidden["props"].get("visible"), publish_outputs, receipt_inputs)), | |
| check("single_generation_chain_is_reused_by_every_trigger", | |
| len(single_generation) == 2 | |
| and len({tuple(dep["inputs"]) for dep in single_generation}) == 1 | |
| and len({tuple(dep["outputs"]) for dep in single_generation}) == 1 | |
| and len(click_triggers) == 1 and len(upload_triggers) == 1 | |
| and click_triggers[0]["inputs"] == upload_triggers[0]["inputs"] | |
| and click_triggers[0]["outputs"] == upload_triggers[0]["outputs"], | |
| ([dep.get("api_name") for dep in generation_dependencies], click_triggers, upload_triggers)), | |
| check("multi_generation_chain_shares_the_single_chain_tail", | |
| len(multi_generation) == 1 | |
| and components[multi_generation[0]["inputs"][0]]["type"] == "gallery" | |
| and tuple(multi_generation[0]["inputs"][1:]) == tuple(single_generation[0]["inputs"][1:]) | |
| and tuple(multi_generation[0]["outputs"]) == tuple(single_generation[0]["outputs"]), | |
| (multi_generation, single_generation)), | |
| ] | |
| def capacity_guard(app, image_path, check, qf): | |
| results = [] | |
| app.FALLBACK.invalidate_session("capacity-probe") | |
| base = app.FALLBACK._cache.size() | |
| entries = [] | |
| for index in range(qf.MAX_PENDING_ENTRIES - base): | |
| reserved = app.FALLBACK.defer("generate", (image_path, index), "capacity-probe") | |
| entries.append(reserved) | |
| results.append(check("capacity_reserves_up_to_the_bound", all(entries), len(entries))) | |
| results.append(check("capacity_overflow_refused", | |
| app.FALLBACK.defer("generate", (image_path, 99), "capacity-probe") is None, | |
| app.FALLBACK._cache.size())) | |
| for entry in entries: | |
| app.FALLBACK._cache.claim(entry.nonce, "generate") | |
| app.FALLBACK.invalidate_session("capacity-probe") | |
| results.append(check("cancelled_running_entries_still_hold_capacity", | |
| app.FALLBACK.defer("generate", (image_path, 98), "capacity-probe") is None, | |
| app.FALLBACK._cache.size())) | |
| for entry in entries: | |
| app.FALLBACK._cache.fail(entry.nonce, "cancelled") | |
| app.FALLBACK.invalidate_session("capacity-probe") | |
| results.append(check("capacity_released_after_executors_exit", | |
| app.FALLBACK._cache.size() == base, app.FALLBACK._cache.size())) | |
| return results | |
| def multi_image_contract(app, check): | |
| config = app.demo.get_config_file() | |
| components = {component["id"]: component for component in config["components"]} | |
| dependencies = config["dependencies"] | |
| galleries = [component for component in components.values() if component["type"] == "gallery"] | |
| buttons = [component for component in components.values() | |
| if component["type"] == "button" | |
| and component["props"].get("value") == "Generate from Multiple Images"] | |
| click_targets = _triggered_by(dependencies, buttons[0]["id"], "click") if buttons else [] | |
| views = app.split_multi_example(synthetic_concat_views()) | |
| return [ | |
| check("multi_image_gallery_is_pil", | |
| len(galleries) == 1 and galleries[0]["props"].get("type") == "pil", | |
| [(gallery["id"], gallery["props"].get("type")) for gallery in galleries]), | |
| check("multi_generate_button_starts_a_dependency", | |
| len(buttons) == 1 and len(click_targets) == 1, | |
| (len(buttons), click_targets)), | |
| check("multi_image_limits_are_pinned", | |
| (app.MULTI_IMAGE_MIN_VIEWS, app.MULTI_IMAGE_MAX_VIEWS) == (2, 6), | |
| (app.MULTI_IMAGE_MIN_VIEWS, app.MULTI_IMAGE_MAX_VIEWS)), | |
| check("multi_image_example_split_extracts_every_view", | |
| len(views) == 3 and all(view.size[0] > 0 for view in views), | |
| [(view.size) for view in views]), | |
| check("multi_image_examples_prepare_without_error", | |
| isinstance(app.prepare_multi_example(), list), type(app.prepare_multi_example()).__name__), | |
| ] | |
| def generation_api_contract(app, check): | |
| return [ | |
| check("generation_api_keeps_six_visible_args", | |
| tuple(inspect.signature(app.generate_preview_frames).parameters)[:6] == | |
| ("image", "seed", "ss_guidance_strength", "ss_sampling_steps", "slat_guidance_strength", | |
| "slat_sampling_steps"), | |
| tuple(inspect.signature(app.generate_preview_frames).parameters)), | |
| check("generation_api_appends_the_texture_size", | |
| tuple(inspect.signature(app.generate_preview_frames).parameters)[6] == "texture_size" | |
| and tuple(inspect.signature(app.generate_and_extract).parameters)[6] == "texture_size" | |
| and inspect.signature(app.generate_and_extract).parameters["texture_size"].default == 1024, | |
| tuple(inspect.signature(app.generate_and_extract).parameters)), | |
| ] | |