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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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
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)))