Spaces:
Sleeping
Sleeping
Download main.py from codemichaeld/new03: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/spaces/codemichaeld/new03/resolve/main/main.py
- Command line
-
hf download hf://spaces/codemichaeld/new03/main.py
-
curl -L -o main.py https://huggingface.co/spaces/codemichaeld/new03/resolve/main/main.py
15.2 kB
| import os | |
| import re | |
| import sys | |
| import json | |
| import tempfile | |
| import traceback | |
| import shutil | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| if HERE not in sys.path: | |
| sys.path.insert(0, HERE) | |
| if os.path.isdir(os.path.join(HERE, "comfy")) and os.path.isfile( | |
| os.path.join(HERE, "comfy", "quant_ops.py") | |
| ): | |
| sys.stderr.write(f"[main] using Space-root comfy at {os.path.join(HERE, 'comfy')}\n") | |
| else: | |
| sys.stderr.write(f"[main] no Space-root comfy/quant_ops.py found at {HERE}\n") | |
| sys.stderr.flush() | |
| if "COMFY_ALLOW_VENDORED" not in os.environ: | |
| os.environ["COMFY_ALLOW_VENDORED"] = "1" | |
| os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "0") | |
| os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") | |
| def _dump_convert_to_quant_layout(): | |
| try: | |
| import convert_to_quant | |
| import pkgutil as _pkgutil | |
| import os as _os | |
| _pkg_dir = _os.path.dirname(convert_to_quant.__file__) | |
| _mods = sorted(m.name for m in _pkgutil.iter_modules([_pkg_dir])) | |
| sys.stderr.write(f"[main] convert_to_quant at {_pkg_dir}\n") | |
| sys.stderr.write(f"[main] submodules: {_mods}\n") | |
| cv_dir = _os.path.join(_pkg_dir, "converters") | |
| if _os.path.isdir(cv_dir): | |
| _cv = sorted(m.name for m in _pkgutil.iter_modules([cv_dir])) | |
| sys.stderr.write(f"[main] convert_to_quant.converters: {_cv}\n") | |
| sys.stderr.flush() | |
| except Exception as _e: | |
| sys.stderr.write(f"[main] convert_to_quant listing failed: {type(_e).__name__}: {_e}\n") | |
| sys.stderr.flush() | |
| try: | |
| import comfy.quant_ops as _cq | |
| sys.stderr.write(f"[main] comfy.quant_ops resolved to {getattr(_cq, '__file__', None)}\n") | |
| _names = sorted(n for n in dir(_cq) if not n.startswith("_")) | |
| sys.stderr.write(f"[main] has AsymW4A8Int8Layout: {'AsymW4A8Int8Layout' in _names}\n") | |
| sys.stderr.flush() | |
| except Exception as _e: | |
| sys.stderr.write(f"[main] comfy.quant_ops import FAILED: {type(_e).__name__}: {_e}\n") | |
| sys.stderr.flush() | |
| _dump_convert_to_quant_layout() | |
| def _patch_gradio_client(): | |
| import gradio_client.utils as gu | |
| patched_any = False | |
| orig_get_type = getattr(gu, "get_type", None) | |
| if orig_get_type is not None and not getattr(orig_get_type, "_w4a8_patched", False): | |
| def safe_get_type(schema): | |
| if not isinstance(schema, dict): | |
| return "any" | |
| return orig_get_type(schema) | |
| safe_get_type._w4a8_patched = True | |
| gu.get_type = safe_get_type | |
| patched_any = True | |
| orig_jstp = getattr(gu, "_json_schema_to_python_type", None) | |
| if orig_jstp is not None and not getattr(orig_jstp, "_w4a8_patched", False): | |
| def safe_jstp(schema, defs=None): | |
| if not isinstance(schema, dict): | |
| return "any" | |
| return orig_jstp(schema, defs) | |
| safe_jstp._w4a8_patched = True | |
| gu._json_schema_to_python_type = safe_jstp | |
| patched_any = True | |
| orig_public = getattr(gu, "json_schema_to_python_type", None) | |
| if orig_public is not None and not getattr(orig_public, "_w4a8_patched", False): | |
| def safe_public(schema, defs=None): | |
| if not isinstance(schema, dict): | |
| return "any" | |
| try: | |
| return orig_public(schema, defs) | |
| except TypeError: | |
| return "any" | |
| safe_public._w4a8_patched = True | |
| gu.json_schema_to_python_type = safe_public | |
| patched_any = True | |
| return patched_any | |
| def _patch_starlette_templates(): | |
| try: | |
| import inspect | |
| from starlette.templating import Jinja2Templates | |
| except Exception as e: | |
| return f"import failed: {type(e).__name__}: {e}" | |
| orig = getattr(Jinja2Templates, "TemplateResponse", None) | |
| if orig is None: | |
| return "no TemplateResponse attr" | |
| if getattr(orig, "_w4a8_patched", False): | |
| return "already patched" | |
| try: | |
| params = list(inspect.signature(orig).parameters) | |
| except Exception: | |
| params = [] | |
| new_style = len(params) >= 3 and params[1] == "request" and params[2] == "name" | |
| if not new_style: | |
| return "old-style signature, no patch needed" | |
| def compat(self, *args, **kwargs): | |
| if args and isinstance(args[0], str): | |
| name = args[0] | |
| context = args[1] if len(args) > 1 else kwargs.pop("context", None) | |
| if not isinstance(context, dict): | |
| context = {} | |
| request = context.get("request") | |
| if request is None: | |
| from starlette.requests import Request | |
| scope = { | |
| "type": "http", | |
| "method": "GET", | |
| "path": "/", | |
| "headers": [], | |
| "query_string": b"", | |
| } | |
| request = Request(scope) | |
| return orig(self, request, name, context, *args[2:], **kwargs) | |
| return orig(self, *args, **kwargs) | |
| compat._w4a8_patched = True | |
| Jinja2Templates.TemplateResponse = compat | |
| return "patched" | |
| try: | |
| _ok1 = _patch_gradio_client() | |
| sys.stderr.write(f"[main] gradio_client patch applied={_ok1}\n") | |
| except Exception as _e: | |
| sys.stderr.write(f"[main] gradio_client patch FAILED: {type(_e).__name__}: {_e}\n") | |
| try: | |
| _ok2 = _patch_starlette_templates() | |
| sys.stderr.write(f"[main] starlette template patch: {_ok2}\n") | |
| except Exception as _e: | |
| sys.stderr.write(f"[main] starlette template patch FAILED: {type(_e).__name__}: {_e}\n") | |
| sys.stderr.flush() | |
| try: | |
| from install_w4a8 import install as _install_w4a8 | |
| _install_w4a8(verbose=True) | |
| except Exception as _e: | |
| print("[main] w4a8 install step failed:", _e) | |
| import gradio as gr | |
| import torch | |
| CONVERTERS = {} | |
| WARNINGS = [] | |
| def _try_register(name, module_path, func_name): | |
| try: | |
| mod = __import__(module_path, fromlist=[func_name]) | |
| except Exception as e: | |
| WARNINGS.append(f"{name}: import failed ({type(e).__name__}: {e})") | |
| return | |
| fn = getattr(mod, func_name, None) | |
| if fn is None: | |
| WARNINGS.append(f"{name}: {module_path}.{func_name} missing") | |
| return | |
| CONVERTERS[name] = (module_path, func_name, fn) | |
| def _scan_for_converters(): | |
| import importlib | |
| import pkgutil | |
| try: | |
| import convert_to_quant | |
| except Exception as e: | |
| WARNINGS.append(f"convert_to_quant: import failed ({type(e).__name__}: {e})") | |
| return | |
| pkg_dir = os.path.dirname(os.path.abspath(convert_to_quant.__file__)) | |
| top_modules = [m.name for m in pkgutil.iter_modules([pkg_dir])] | |
| candidate_paths = [f"convert_to_quant.{n}" for n in top_modules] | |
| cv_dir = os.path.join(pkg_dir, "converters") | |
| if os.path.isdir(cv_dir): | |
| for m in pkgutil.iter_modules([cv_dir]): | |
| candidate_paths.append(f"convert_to_quant.converters.{m.name}") | |
| candidate_paths.append("convert_to_quant.converters") | |
| seen_canonical = set() | |
| scan_log = [] | |
| for mod_path in candidate_paths: | |
| try: | |
| mod = importlib.import_module(mod_path) | |
| except Exception: | |
| continue | |
| for attr_name in dir(mod): | |
| if not attr_name.startswith("convert_to_"): | |
| continue | |
| attr = getattr(mod, attr_name, None) | |
| if not callable(attr): | |
| continue | |
| canonical = attr_name[len("convert_to_"):] | |
| if canonical in seen_canonical: | |
| continue | |
| seen_canonical.add(canonical) | |
| CONVERTERS[canonical] = (mod_path, attr_name, attr) | |
| scan_log.append(f"{canonical} <- {mod_path}.{attr_name}") | |
| for line in scan_log: | |
| sys.stderr.write(f"[main] registered converter {line}\n") | |
| sys.stderr.flush() | |
| def _discover(): | |
| try: | |
| from convert_to_quant.w4a8 import convert_to_w4a8, w4a8_available | |
| if w4a8_available(): | |
| CONVERTERS["w4a8"] = ("convert_to_quant.w4a8", "convert_to_w4a8", convert_to_w4a8) | |
| else: | |
| from convert_to_quant.w4a8 import w4a8_last_error | |
| WARNINGS.append(f"w4a8: unavailable ({w4a8_last_error()})") | |
| except Exception as e: | |
| WARNINGS.append(f"w4a8: import failed ({type(e).__name__}: {e})") | |
| _scan_for_converters() | |
| _discover() | |
| _HF_URL_RE = re.compile(r"^(?:https?://)?(?:www\.)?huggingface\.co/(.+)$", re.IGNORECASE) | |
| _REVISION_MARKERS = ("tree", "blob", "resolve", "raw") | |
| def _parse_hf_reference(hf_repo, hf_filename): | |
| """Return (repo_id, subfolder, filename) from any user input. | |
| Accepts: | |
| - "user/repo" (with filename supplied separately) | |
| - "https://huggingface.co/user/repo" | |
| - "https://huggingface.co/user/repo/tree/main/subfolder" | |
| - "https://huggingface.co/user/repo/tree/main/subfolder/file.safetensors" | |
| - "https://huggingface.co/user/repo/blob/main/subfolder/file.safetensors" | |
| - "https://huggingface.co/user/repo/resolve/main/subfolder/file.safetensors" | |
| - same as above but with subfolder supplied via the filename textbox | |
| """ | |
| repo = (hf_repo or "").strip().rstrip("/") | |
| fname = (hf_filename or "").strip().strip("/") | |
| m = _HF_URL_RE.match(repo) | |
| if m: | |
| repo = m.group(1) | |
| parts = [p for p in repo.split("/") if p] | |
| if len(parts) < 2: | |
| raise ValueError( | |
| f"HF repo must be 'user/repo' or a huggingface.co URL; got {hf_repo!r}" | |
| ) | |
| repo_id = f"{parts[0]}/{parts[1]}" | |
| rest = parts[2:] | |
| if rest and rest[0] in _REVISION_MARKERS: | |
| rest = rest[2:] if len(rest) > 1 else [] | |
| subfolder = "" | |
| file_from_url = "" | |
| if rest: | |
| last = rest[-1] | |
| if last.endswith(".safetensors") or last.endswith(".sft"): | |
| file_from_url = last | |
| subfolder = "/".join(rest[:-1]) | |
| else: | |
| subfolder = "/".join(rest) | |
| if fname: | |
| if "/" in fname: | |
| bits = [b for b in fname.split("/") if b] | |
| file_from_url = bits[-1] | |
| if not subfolder: | |
| subfolder = "/".join(bits[:-1]) | |
| else: | |
| file_from_url = fname | |
| if not file_from_url: | |
| raise ValueError( | |
| "No filename given. Put the .safetensors filename in the 'HF filename' box, " | |
| "or paste a huggingface.co URL ending in the file." | |
| ) | |
| return repo_id, subfolder, file_from_url | |
| def _resolve_input_file(uploaded_file, hf_repo, hf_filename, hf_token): | |
| if uploaded_file: | |
| return uploaded_file, None | |
| if hf_repo: | |
| repo_id, subfolder, filename = _parse_hf_reference(hf_repo, hf_filename) | |
| sys.stderr.write( | |
| f"[main] HF resolve: repo_id={repo_id!r} subfolder={subfolder!r} filename={filename!r}\n" | |
| ) | |
| sys.stderr.flush() | |
| from huggingface_hub import hf_hub_download | |
| path = hf_hub_download( | |
| repo_id=repo_id, | |
| filename=filename, | |
| subfolder=subfolder or None, | |
| token=(hf_token.strip() if isinstance(hf_token, str) and hf_token.strip() else None), | |
| ) | |
| return path, None | |
| raise ValueError("Provide either an uploaded file or HF repo + filename") | |
| def _call_converter(kind, entry, src_path, dst_path, **kw): | |
| _, _, fn = entry | |
| try: | |
| fn(input_file=src_path, output_file=dst_path, **kw) | |
| return | |
| except TypeError: | |
| pass | |
| fn(src_path, dst_path, **kw) | |
| def convert( | |
| uploaded_file, | |
| hf_repo, | |
| hf_filename, | |
| hf_token, | |
| conversion_type, | |
| progress=gr.Progress(), | |
| ): | |
| if conversion_type not in CONVERTERS: | |
| return None, f"Conversion type '{conversion_type}' unavailable. Available: {list(CONVERTERS)}" | |
| workdir = tempfile.mkdtemp(prefix="qc_") | |
| try: | |
| progress(0.02, desc="Resolving input") | |
| src_path, _ = _resolve_input_file(uploaded_file, hf_repo, hf_filename, hf_token) | |
| base = os.path.splitext(os.path.basename(src_path))[0] | |
| dst_path = os.path.join(workdir, f"{base}_{conversion_type}.safetensors") | |
| entry = CONVERTERS[conversion_type] | |
| def cb(i, total, key): | |
| try: | |
| progress(0.05 + 0.9 * (i / max(total, 1)), desc=f"{conversion_type}: {i}/{total} {key}") | |
| except Exception: | |
| pass | |
| progress(0.05, desc=f"Running {conversion_type}") | |
| kwargs = {} | |
| try: | |
| import inspect | |
| sig = inspect.signature(entry[2]) | |
| if "progress_cb" in sig.parameters: | |
| kwargs["progress_cb"] = cb | |
| if "device" in sig.parameters: | |
| kwargs["device"] = "cuda" if torch.cuda.is_available() else "cpu" | |
| if "low_memory" in sig.parameters: | |
| kwargs["low_memory"] = True | |
| except Exception: | |
| pass | |
| _call_converter(conversion_type, entry, src_path, dst_path, **kwargs) | |
| if not os.path.exists(dst_path): | |
| return None, f"Converter did not produce {dst_path}" | |
| progress(0.98, desc="Finalizing") | |
| final_dir = tempfile.mkdtemp(prefix="qc_out_") | |
| final_path = os.path.join(final_dir, os.path.basename(dst_path)) | |
| shutil.move(dst_path, final_path) | |
| size_mb = os.path.getsize(final_path) / (1024 * 1024) | |
| status = f"OK {conversion_type}: {os.path.basename(final_path)} ({size_mb:.1f} MB)" | |
| if WARNINGS: | |
| status += "\n" + "\n".join(WARNINGS) | |
| return final_path, status | |
| except Exception as e: | |
| traceback.print_exc() | |
| return None, f"FAILED: {type(e).__name__}: {e}" | |
| with gr.Blocks(title="Quant Converter") as demo: | |
| gr.Markdown("# Quant Converter") | |
| gr.Markdown( | |
| "CPU-safe safetensors quantizer. Available types: " | |
| + (", ".join(sorted(CONVERTERS)) if CONVERTERS else "none detected") | |
| ) | |
| if WARNINGS: | |
| gr.Markdown("Warnings:\n- " + "\n- ".join(WARNINGS)) | |
| with gr.Row(): | |
| with gr.Column(): | |
| uploaded_file = gr.File(label="Upload safetensors", file_types=[".safetensors"]) | |
| hf_repo = gr.Textbox( | |
| label="Or HF repo id / URL", | |
| placeholder="Comfy-Org/Wan_2.2_ComfyUI_Repackaged or https://huggingface.co/Comfy-Org/Wan_2.2_ComfyUI_Repackaged/tree/main/split_files/diffusion_models", | |
| ) | |
| hf_filename = gr.Textbox( | |
| label="HF filename", | |
| placeholder="wan2.2_fun_vace_low_noise_14B_fp8_scaled.safetensors", | |
| ) | |
| hf_token = gr.Textbox(label="HF token (optional)", type="password") | |
| conversion_type = gr.Dropdown( | |
| choices=sorted(CONVERTERS.keys()), | |
| value=("w4a8" if "w4a8" in CONVERTERS else (sorted(CONVERTERS.keys())[0] if CONVERTERS else None)), | |
| label="Conversion type", | |
| ) | |
| run_btn = gr.Button("Convert", variant="primary") | |
| with gr.Column(): | |
| out_file = gr.File(label="Output") | |
| status = gr.Textbox(label="Status", lines=8) | |
| run_btn.click( | |
| fn=convert, | |
| inputs=[uploaded_file, hf_repo, hf_filename, hf_token, conversion_type], | |
| outputs=[out_file, status], | |
| show_progress=True, | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860))) |