LuffyTheFox

Untitled

Apr 7th, 2026
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.20 KB | None | 0 0
  1. import os
  2. import subprocess
  3. import sys
  4.  
  5. WORK_DIR = "/content/gguf_workspace"
  6. os.makedirs(WORK_DIR, exist_ok=True)
  7.  
  8. subprocess.check_call(
  9. [sys.executable, "-m", "pip", "install", "-q", "huggingface_hub[hf_xfer]", "hf_transfer"]
  10. )
  11.  
  12. os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
  13.  
  14. from huggingface_hub import hf_hub_download, login
  15.  
  16. try:
  17. from google.colab import userdata
  18. token = userdata.get("HF_TOKEN")
  19. except Exception:
  20. token = os.environ.get("HF_TOKEN", "").strip()
  21.  
  22. if token:
  23. login(token=token, add_to_git_credential=False)
  24.  
  25. repo = "LuffyTheFox/Qwen3.5-35B-A3B-Uncensored-FernflowerAI-GGUF"
  26. filename = "FernflowerAI.BF16.gguf"
  27.  
  28. path = hf_hub_download(
  29. repo_id=repo,
  30. filename=filename,
  31. local_dir=WORK_DIR,
  32. )
  33.  
  34. print("Downloaded:", path)
  35. print("Size GB:", round(os.path.getsize(path) / 1073741824, 2))
  36.  
  37. # ============================================================================
  38. # Unsloth UD-IQ4_XS -> JSON profile -> delete ref -> quantize YOUR Q8_0 GGUF
  39. #
  40. # Goal:
  41. # 1) Read the exact per-tensor quantization types used in:
  42. # Qwen3.5-35B-A3B-UD-IQ4_XS.gguf (Unsloth)
  43. # 2) Save them into a JSON profile (once)
  44. # 3) Delete Unsloth reference quant to save disk
  45. # 4) Quantize your finetuned GGUF (Q8_0) -> IQ4_XS using that JSON profile
  46. #
  47. # Notes:
  48. # - If your input is already quantized (Q8_0), llama-quantize needs --allow-requantize.
  49. # - This script uses regex-based --tensor-type rules (supported by llama.cpp quantizer).
  50. # - Designed for Colab/Linux.
  51. # ============================================================================
  52.  
  53. import os
  54. import sys
  55. import re
  56. import gc
  57. import json
  58. import time
  59. import subprocess
  60. import numpy as np
  61.  
  62. # ============================================================================
  63. # USER CONFIG
  64. # ============================================================================
  65.  
  66. WORK_DIR = "/content/gguf_workspace"
  67. os.makedirs(WORK_DIR, exist_ok=True)
  68.  
  69. # --- YOUR MODEL (input) ------------------------------------------------------
  70. # Put your trained model GGUF here (Q8_0 in your case):
  71. INPUT_FILE = os.path.join(WORK_DIR, "FernflowerAI.BF16.gguf")
  72.  
  73. # --- Unsloth reference quant (used only to extract profile) ------------------
  74. REF_FILE = os.path.join(WORK_DIR, "Qwen3.5-35B-A3B-UD-Q2_K_XL.gguf")
  75. REF_URL = (
  76. "https://huggingface.co/unsloth/Qwen3.5-35B-A3B-GGUF/resolve/main/Qwen3.5-35B-A3B-UD-Q2_K_XL.gguf?download=true"
  77. )
  78.  
  79. # --- iMatrix (recommended) ---------------------------------------------------
  80. IMATRIX_FILE = os.path.join(WORK_DIR, "imatrix_unsloth.gguf_file")
  81. IMATRIX_URL = (
  82. "https://huggingface.co/unsloth/Qwen3.5-35B-A3B-GGUF/resolve/main/"
  83. "imatrix_unsloth.gguf_file?download=true"
  84. )
  85.  
  86. # --- Output ------------------------------------------------------------------
  87. TARGET_BASE_TYPE = "Q4_K"
  88. OUTPUT_TAG = "UD" # marker in output filename
  89.  
  90. # --- Store the extracted quant schema in JSON --------------------------------
  91. PROFILE_JSON = os.path.join(WORK_DIR, "unsloth_ud_profile.json")
  92.  
  93. # After JSON is built, delete Unsloth reference quant GGUF to save disk
  94. DELETE_REF_AFTER_PROFILE = True
  95.  
  96. # Keep JSON compact by default (do NOT store huge name->type map)
  97. # Turn on only if you really want the full audit dump (can be big).
  98. STORE_RAW_TENSOR_MAP = False
  99.  
  100. # --- llama.cpp binaries ------------------------------------------------------
  101. LLAMA_TAG = "b8192"
  102. LLAMA_URL = (
  103. "https://github.com/ggml-org/llama.cpp/releases/download/"
  104. f"{LLAMA_TAG}/llama-{LLAMA_TAG}-bin-ubuntu-x64.tar.gz"
  105. )
  106. LLAMA_TAR = f"llama-{LLAMA_TAG}-bin-ubuntu-x64.tar.gz"
  107. LLAMA_BIN_DIR = os.path.join(WORK_DIR, "llama-bin")
  108.  
  109. # Verbosity
  110. PRINT_PROFILE_SUMMARY = True
  111. VERIFY_AFTER_QUANT = True
  112.  
  113.  
  114. # ============================================================================
  115. # UTILS
  116. # ============================================================================
  117.  
  118. def ensure_python_pkg(pkg: str):
  119. subprocess.check_call(
  120. [sys.executable, "-m", "pip", "install", "-q", pkg],
  121. stdout=subprocess.DEVNULL,
  122. stderr=subprocess.DEVNULL,
  123. )
  124.  
  125. def file_size_gb(path):
  126. return os.path.getsize(path) / (1 << 30)
  127.  
  128. def disk_free_gb(path=WORK_DIR):
  129. st = os.statvfs(path)
  130. return (st.f_bavail * st.f_frsize) / (1 << 30)
  131.  
  132. def ram_used_gb():
  133. try:
  134. with open("/proc/self/status", "r") as f:
  135. for line in f:
  136. if line.startswith("VmRSS:"):
  137. return int(line.split()[1]) / (1 << 20)
  138. except Exception:
  139. pass
  140. return -1
  141.  
  142. def safe_remove(path):
  143. try:
  144. if os.path.isfile(path):
  145. os.remove(path)
  146. except Exception:
  147. pass
  148.  
  149. def download_file(url, out_path, label, timeout=6*3600):
  150. if os.path.isfile(out_path) and os.path.getsize(out_path) > 1024:
  151. print(f"[{label}] Found: {out_path} ({file_size_gb(out_path):.2f} GB)")
  152. return out_path
  153.  
  154. print(f"[{label}] Downloading -> {out_path}")
  155. os.makedirs(os.path.dirname(out_path), exist_ok=True)
  156.  
  157. for cmd in [
  158. ["wget", "-O", out_path, "-c", "--show-progress", url],
  159. ["curl", "-L", "-o", out_path, url],
  160. ]:
  161. try:
  162. subprocess.check_call(cmd, timeout=timeout)
  163. if os.path.isfile(out_path) and os.path.getsize(out_path) > 1024:
  164. print(f"[{label}] Downloaded: {out_path} ({file_size_gb(out_path):.2f} GB)")
  165. return out_path
  166. except Exception:
  167. continue
  168.  
  169. print(f"[{label}] ERROR: download failed")
  170. return None
  171.  
  172. def get_llama_quantize():
  173. # Try existing
  174. for root, _, files in os.walk(LLAMA_BIN_DIR):
  175. if "llama-quantize" in files:
  176. p = os.path.join(root, "llama-quantize")
  177. if os.access(p, os.X_OK):
  178. print(f"[BIN] Found: {p}")
  179. return p
  180.  
  181. # Download
  182. tar_path = os.path.join(WORK_DIR, LLAMA_TAR)
  183. ok = download_file(LLAMA_URL, tar_path, "BIN", timeout=1200)
  184. if not ok:
  185. return None
  186.  
  187. os.makedirs(LLAMA_BIN_DIR, exist_ok=True)
  188.  
  189. extracted = False
  190. for strip in [True, False]:
  191. try:
  192. cmd = ["tar", "xzf", tar_path, "-C", LLAMA_BIN_DIR]
  193. if strip:
  194. cmd.append("--strip-components=1")
  195. subprocess.check_call(cmd)
  196. extracted = True
  197. break
  198. except subprocess.CalledProcessError:
  199. continue
  200.  
  201. safe_remove(tar_path)
  202.  
  203. if not extracted:
  204. print("[BIN] ERROR: extraction failed.")
  205. return None
  206.  
  207. for root, _, files in os.walk(LLAMA_BIN_DIR):
  208. if "llama-quantize" in files:
  209. p = os.path.join(root, "llama-quantize")
  210. os.chmod(p, 0o755)
  211. print(f"[BIN] Ready: {p}")
  212. return p
  213.  
  214. print("[BIN] ERROR: llama-quantize not found.")
  215. return None
  216.  
  217. def normalize_output_basename(input_path):
  218. base = os.path.splitext(os.path.basename(input_path))[0]
  219. known_suffixes = [
  220. ".Q8_0", "-Q8_0", ".F16", "-F16", ".BF16", "-BF16", ".F32", "-F32",
  221. ".Q4_0", "-Q4_0", ".Q4_K_M", "-Q4_K_M", ".Q5_K_M", "-Q5_K_M",
  222. ".IQ4_XS", "-IQ4_XS", ".IQ4_NL", "-IQ4_NL",
  223. ]
  224. for suf in known_suffixes:
  225. if base.endswith(suf):
  226. base = base[:-len(suf)]
  227. break
  228. return base
  229.  
  230. def regex_escape_literal(s: str) -> str:
  231. return re.sub(r'([.^$*+?{}\[\]\\|()])', r'\\\1', s)
  232.  
  233. def normalize_qtype(s):
  234. if s is None:
  235. return None
  236. s = str(s).strip()
  237. s = s.replace("GGML_TYPE_", "").replace("ggml_type_", "").replace("GGUF_TYPE_", "")
  238. return s.upper()
  239.  
  240. def seems_quantized_from_types(type_list):
  241. # If any tensor type starts with Q or IQ, treat as already-quantized.
  242. for t in type_list:
  243. if not t:
  244. continue
  245. u = str(t).upper()
  246. if u.startswith("Q") or u.startswith("IQ") or u.startswith("TQ") or u.startswith("KQ"):
  247. return True
  248. return False
  249.  
  250. # ============================================================================
  251. # GGUF INSPECTION
  252. # ============================================================================
  253.  
  254. def read_gguf_tensors_basic(gguf_path):
  255. """
  256. Returns list of dicts: {name, type_str, n_bytes, data_offset}
  257. """
  258. ensure_python_pkg("gguf")
  259. from gguf import GGUFReader
  260.  
  261. r = GGUFReader(gguf_path)
  262. out = []
  263. for t in r.tensors:
  264. typ = None
  265. for a in ("tensor_type", "type", "ggml_type", "data_type"):
  266. if hasattr(t, a):
  267. typ = getattr(t, a)
  268. break
  269. typ_s = normalize_qtype(typ.name if hasattr(typ, "name") else typ)
  270.  
  271. n_bytes = getattr(t, "n_bytes", None)
  272. data_offset = getattr(t, "data_offset", None)
  273.  
  274. out.append({
  275. "name": t.name,
  276. "type": typ_s,
  277. "n_bytes": int(n_bytes) if n_bytes is not None else None,
  278. "data_offset": int(data_offset) if data_offset is not None else None,
  279. })
  280.  
  281. del r
  282. gc.collect()
  283. return out
  284.  
  285. def get_tensor_names(gguf_path):
  286. return [x["name"] for x in read_gguf_tensors_basic(gguf_path)]
  287.  
  288. def get_tensor_types_map(gguf_path):
  289. items = read_gguf_tensors_basic(gguf_path)
  290. return {x["name"]: x["type"] for x in items}
  291.  
  292. # ============================================================================
  293. # PROFILE EXTRACTION (from Unsloth ref GGUF)
  294. # ============================================================================
  295.  
  296. def extract_profile_from_ref(ref_path):
  297. """
  298. Build a compact rule-set that reproduces Unsloth per-tensor types.
  299.  
  300. Output JSON structure:
  301. {
  302. "ref_file": "...",
  303. "token_embd_type": "Q8_0",
  304. "output_type": "Q6_K",
  305. "rules": [
  306. {"pattern": "^blk\\.\\d+\\.attn_q\\.weight$", "type": "Q8_0", "kind": "blk_all_layers"},
  307. {"pattern": "^blk\\.(?:0|1|2)\\.ffn_down_exps\\.weight$", "type": "IQ4_NL", "kind": "blk_subset_layers"},
  308. ...
  309. ],
  310. "stats": {...}
  311. ["tensor_types_by_name": {...}] # optional
  312. }
  313. """
  314. types = get_tensor_types_map(ref_path)
  315.  
  316. token_embd_type = types.get("token_embd.weight")
  317. output_type = types.get("output.weight")
  318.  
  319. # group block tensors by (suffix,type)->layers
  320. blk_re = re.compile(r"^blk\.(\d+)\.(.+)$")
  321. by_suffix_type_layers = {} # (suffix, type) -> set(layers)
  322. globals_map = {} # name -> type
  323. max_layer = -1
  324.  
  325. for name, typ in types.items():
  326. m = blk_re.match(name)
  327. if not m:
  328. globals_map[name] = typ
  329. continue
  330. layer = int(m.group(1))
  331. suffix = m.group(2)
  332. max_layer = max(max_layer, layer)
  333. by_suffix_type_layers.setdefault((suffix, typ), set()).add(layer)
  334.  
  335. n_layers = max_layer + 1 if max_layer >= 0 else 0
  336.  
  337. rules = []
  338.  
  339. # Global exact rules (but skip token_embd/output since we’ll pass dedicated flags)
  340. for name, typ in sorted(globals_map.items()):
  341. if name in ("token_embd.weight", "output.weight"):
  342. continue
  343. if typ is None:
  344. continue
  345. rules.append({
  346. "pattern": "^" + regex_escape_literal(name) + "$",
  347. "type": typ,
  348. "kind": "global_exact",
  349. })
  350.  
  351. # Block rules
  352. for (suffix, typ), layers in sorted(by_suffix_type_layers.items(), key=lambda x: (x[0][0], str(x[0][1]))):
  353. if typ is None:
  354. continue
  355. layers = sorted(layers)
  356. suffix_esc = regex_escape_literal(suffix)
  357.  
  358. if n_layers and len(layers) == n_layers:
  359. pat = r"^blk\.\d+\." + suffix_esc + r"$"
  360. kind = "blk_all_layers"
  361. else:
  362. alt = "|".join(str(i) for i in layers)
  363. pat = r"^blk\.(?:" + alt + r")\." + suffix_esc + r"$"
  364. kind = "blk_subset_layers"
  365.  
  366. rules.append({
  367. "pattern": pat,
  368. "type": typ,
  369. "kind": kind,
  370. })
  371.  
  372. prof = {
  373. "ref_file": os.path.basename(ref_path),
  374. "created_unix": int(time.time()),
  375. "token_embd_type": token_embd_type,
  376. "output_type": output_type,
  377. "rules": rules,
  378. "stats": {
  379. "n_tensors_total": len(types),
  380. "n_layers_detected": n_layers,
  381. "n_rules": len(rules),
  382. },
  383. }
  384.  
  385. if STORE_RAW_TENSOR_MAP:
  386. prof["tensor_types_by_name"] = types
  387.  
  388. return prof
  389.  
  390. def load_or_build_profile_json():
  391. # If profile JSON exists, use it and do NOT download ref again.
  392. if os.path.isfile(PROFILE_JSON) and os.path.getsize(PROFILE_JSON) > 100:
  393. with open(PROFILE_JSON, "r", encoding="utf-8") as f:
  394. prof = json.load(f)
  395. print(f"[PROFILE] Loaded: {PROFILE_JSON}")
  396. return prof
  397.  
  398. print("[PROFILE] JSON not found; building from Unsloth reference GGUF...")
  399.  
  400. if not os.path.isfile(REF_FILE):
  401. download_file(REF_URL, REF_FILE, "REF", timeout=6*3600)
  402.  
  403. prof = extract_profile_from_ref(REF_FILE)
  404.  
  405. with open(PROFILE_JSON, "w", encoding="utf-8") as f:
  406. json.dump(prof, f, ensure_ascii=False, indent=2)
  407.  
  408. print(f"[PROFILE] Saved: {PROFILE_JSON}")
  409.  
  410. if DELETE_REF_AFTER_PROFILE:
  411. print(f"[PROFILE] Deleting Unsloth reference quant to save disk: {REF_FILE}")
  412. safe_remove(REF_FILE)
  413.  
  414. return prof
  415.  
  416. # ============================================================================
  417. # QUANTIZE
  418. # ============================================================================
  419.  
  420. def filter_rules_to_existing_tensors(rules, tensor_names):
  421. """
  422. Keep only rules whose regex matches at least one tensor name in your input model.
  423. This reduces command size and avoids useless rules.
  424. """
  425. kept = []
  426. names = tensor_names
  427.  
  428. for r in rules:
  429. pat = r.get("pattern")
  430. typ = r.get("type")
  431. if not pat or not typ:
  432. continue
  433. try:
  434. rx = re.compile(pat)
  435. except re.error:
  436. continue
  437. if any(rx.search(n) for n in names):
  438. kept.append(r)
  439.  
  440. return kept
  441.  
  442. def quantize_with_profile(input_path, output_path, profile, imatrix_path=None):
  443. bin_path = get_llama_quantize()
  444. if not bin_path:
  445. raise RuntimeError("llama-quantize not available")
  446.  
  447. if not os.path.isfile(input_path):
  448. raise FileNotFoundError(f"Input not found: {input_path}")
  449.  
  450. # Decide if allow-requantize is needed (input already quantized)
  451. input_types_map = get_tensor_types_map(input_path)
  452. allow_requantize = seems_quantized_from_types(list(input_types_map.values()))
  453.  
  454. input_names = list(input_types_map.keys())
  455.  
  456. rules = profile.get("rules", [])
  457. rules = filter_rules_to_existing_tensors(rules, input_names)
  458.  
  459. env = os.environ.copy()
  460. bin_dir = os.path.dirname(bin_path)
  461. ld = env.get("LD_LIBRARY_PATH", "")
  462. env["LD_LIBRARY_PATH"] = f"{bin_dir}:{ld}" if ld else bin_dir
  463.  
  464. cmd = [bin_path]
  465.  
  466. if allow_requantize:
  467. cmd += ["--allow-requantize"]
  468.  
  469. if imatrix_path and os.path.isfile(imatrix_path):
  470. cmd += ["--imatrix", imatrix_path]
  471. cmd += ["--exclude-weights", "output.weight"]
  472.  
  473. # Apply dedicated types only if corresponding tensors exist in input
  474. if "token_embd.weight" in input_types_map and profile.get("token_embd_type"):
  475. cmd += ["--token-embedding-type", str(profile["token_embd_type"])]
  476. if "output.weight" in input_types_map and profile.get("output_type"):
  477. cmd += ["--output-tensor-type", str(profile["output_type"])]
  478.  
  479. for r in rules:
  480. cmd += ["--tensor-type", f"{r['pattern']}={r['type']}"]
  481.  
  482. cmd += [input_path, output_path, TARGET_BASE_TYPE]
  483.  
  484. print("\n" + "=" * 78)
  485. print("QUANTIZATION")
  486. print("=" * 78)
  487. print(f"[IN ] {input_path}")
  488. print(f"[OUT] {output_path}")
  489. print(f"[BASE] {TARGET_BASE_TYPE}")
  490. print(f"[RULES] {len(rules)} (filtered to your model)")
  491. print(f"[IMX] {imatrix_path if (imatrix_path and os.path.isfile(imatrix_path)) else 'none'}")
  492. print(f"[FLAG] allow_requantize = {allow_requantize}")
  493.  
  494. print("[CMD] (showing head)")
  495. print(" " + " \\\n ".join(cmd[:40]) + (" \\\n ... (many --tensor-type rules) ..." if len(cmd) > 40 else ""))
  496.  
  497. t0 = time.time()
  498. proc = subprocess.Popen(
  499. cmd,
  500. stdout=subprocess.PIPE,
  501. stderr=subprocess.STDOUT,
  502. text=True,
  503. env=env,
  504. bufsize=1,
  505. )
  506. for line in proc.stdout:
  507. line = line.rstrip()
  508. if line:
  509. print(" ", line)
  510. proc.wait()
  511.  
  512. if proc.returncode != 0:
  513. raise RuntimeError(f"llama-quantize failed (code={proc.returncode})")
  514.  
  515. dt = time.time() - t0
  516. out_gb = file_size_gb(output_path)
  517. print(f"[DONE] {dt/60:.1f} min | size {in_gb:.2f} GB -> {out_gb:.2f} GB")
  518.  
  519. def verify_output(output_path):
  520. print("[VERIFY] Checking output GGUF parse + quick zero-fill sample...")
  521. try:
  522. ensure_python_pkg("gguf")
  523. from gguf import GGUFReader
  524.  
  525. r = GGUFReader(output_path)
  526. tensors = list(r.tensors)
  527. print(f"[VERIFY] Tensors: {len(tensors)}")
  528.  
  529. checked = 0
  530. zeroish = 0
  531.  
  532. with open(output_path, "rb") as f:
  533. for t in tensors[:60]:
  534. n_bytes = getattr(t, "n_bytes", None)
  535. off = getattr(t, "data_offset", None)
  536. if n_bytes is None or off is None:
  537. continue
  538. n = min(4096, int(n_bytes))
  539. if n < 128:
  540. continue
  541. f.seek(int(off))
  542. raw = f.read(n)
  543. arr = np.frombuffer(raw, dtype=np.uint8)
  544. if arr.size and arr.sum() == 0:
  545. zeroish += 1
  546. checked += 1
  547.  
  548. del r
  549. gc.collect()
  550.  
  551. if zeroish:
  552. print(f"[VERIFY] WARNING: {zeroish}/{checked} sampled tensors looked zero-filled.")
  553. else:
  554. print(f"[VERIFY] OK: sampled {checked} tensors.")
  555. return True
  556. except Exception as e:
  557. print(f"[VERIFY] ERROR: {e}")
  558. return False
  559.  
  560.  
  561. # ============================================================================
  562. # MAIN
  563. # ============================================================================
  564.  
  565. def main():
  566. print("=" * 78)
  567. print("UNSLOTH UD-IQ4_XS PROFILE -> JSON -> DELETE REF -> QUANTIZE YOUR MODEL")
  568. print("=" * 78)
  569. print(f"[INFO] Work dir: {WORK_DIR}")
  570. print(f"[INFO] Input: {INPUT_FILE}")
  571. print(f"[INFO] Profile: {PROFILE_JSON}")
  572. print(f"[INFO] Target: {TARGET_BASE_TYPE}")
  573. print(f"[INFO] Disk free: {disk_free_gb():.2f} GB | RAM used: {ram_used_gb():.2f} GB")
  574.  
  575. if not os.path.isfile(INPUT_FILE):
  576. sys.exit(f"[ERROR] Your input GGUF not found: {INPUT_FILE}")
  577.  
  578. # iMatrix is small enough to keep; download if missing
  579. download_file(IMATRIX_URL, IMATRIX_FILE, "IMATRIX", timeout=1800)
  580.  
  581. # Build/load JSON profile (this step deletes REF_FILE if it had to download it)
  582. profile = load_or_build_profile_json()
  583.  
  584. if PRINT_PROFILE_SUMMARY:
  585. print("[PROFILE] Summary:")
  586. print(json.dumps(profile.get("stats", {}), indent=2, ensure_ascii=False))
  587. print(f"[PROFILE] token_embd_type: {profile.get('token_embd_type')}")
  588. print(f"[PROFILE] output_type: {profile.get('output_type')}")
  589. print(f"[PROFILE] rules_total: {len(profile.get('rules', []))}")
  590.  
  591. base = normalize_output_basename(INPUT_FILE)
  592. output_path = os.path.join(WORK_DIR, f"{base}-{OUTPUT_TAG}-{TARGET_BASE_TYPE}.gguf")
  593.  
  594. quantize_with_profile(INPUT_FILE, output_path, profile, IMATRIX_FILE)
  595.  
  596. if VERIFY_AFTER_QUANT:
  597. print("\n" + "=" * 78)
  598. verify_output(output_path)
  599.  
  600. print("\n" + "=" * 78)
  601. print("COMPLETE")
  602. print("=" * 78)
  603. print(f"[OUT] {output_path}")
  604. print(f"[OUT] Size: {file_size_gb(output_path):.2f} GB")
  605. print(f"[SYS] Free disk: {disk_free_gb():.2f} GB")
  606.  
  607. print("\n[FS]")
  608. for fn in sorted(os.listdir(WORK_DIR)):
  609. fp = os.path.join(WORK_DIR, fn)
  610. if os.path.isfile(fp):
  611. try:
  612. print(f" {fn} ({file_size_gb(fp):.2f} GB)")
  613. except Exception:
  614. print(f" {fn}")
  615.  
  616. if __name__ == "__main__":
  617. main()
Advertisement
Add Comment
Please, Sign In to add comment