File size: 4,928 Bytes
8d72f2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Chạy SAU trace_vendor_usage.py, cùng thư mục (vẫn trên Kaggle hoặc máy bất kỳ có
final_project/ đầy đủ + vendor_files_used.json). Không cần torch/GPU.

    !python prune_vendor.py

Việc này làm 3 thứ:
1. Đọc vendor_files_used.json (danh sách file diffusers thực sự được import khi chạy
   qua mọi nhánh chính của app -- base model, Turbo LoRA, Transparent PNG, ...).
2. Copy đúng những file đó, CỘNG THÊM mọi __init__.py trên đường dẫn cha của chúng
   (bắt buộc để Python còn nhận diện được đó là package -- kể cả khi __init__.py đó
   chỉ toàn "_LazyModule" wiring chứ không có gì được app dùng trực tiếp), cộng thêm
   vài file "luôn cần" (py.typed, dependency_versions_table.py -- được
   dependency_versions_check.py đọc bằng importlib chứ không phải `import` thường nên
   không lọt vào sys.modules trace).
3. Ghi ra final_project_trimmed/ với cùng cấu trúc app.py/requirements.txt/README.md/
   vendor/group_offloading_no_try_finally_leak.patch, rồi nén thành .zip.

QUAN TRỌNG: sau khi chạy xong, bạn PHẢI test lại `python app.py` (hoặc ít nhất
`trace_vendor_usage.py`) trỏ vào bản trimmed này trước khi xoá bản gốc -- nếu trace ở
bước 1 chưa chọc đủ mọi nhánh (ví dụ bạn chưa test "Edit an image" hay QWEN_COMPILE=1),
bản trimmed sẽ thiếu file và crash ImportError đúng lúc bạn bấm nhánh đó. An toàn nhất:
giữ lại bản gốc cho tới khi bản trimmed chạy ổn qua hết các mode bạn thực sự dùng.
"""
import json
import shutil
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parent
VENDOR_SRC = PROJECT_ROOT / "vendor" / "diffusers" / "src"
MANIFEST = PROJECT_ROOT / "vendor_files_used.json"
OUT_ROOT = PROJECT_ROOT.parent / "final_project_trimmed"
OUT_VENDOR_SRC = OUT_ROOT / "vendor" / "diffusers" / "src"

# Always kept regardless of the trace, because they're read in ways that don't show up
# as a normal `import` (dependency_versions_check.py opens dependency_versions_table.py
# via its own module lookup, not a plain `import`), or they carry no code but matter for
# packaging correctness (py.typed marks the package as typed for type checkers).
ALWAYS_KEEP = {
    "diffusers/py.typed",
    "diffusers/dependency_versions_table.py",
    "diffusers/dependency_versions_check.py",
}


def main() -> None:
    if not MANIFEST.is_file():
        raise SystemExit(
            f"{MANIFEST} not found -- run trace_vendor_usage.py on Kaggle first and "
            f"copy vendor_files_used.json next to this script."
        )
    used = set(json.loads(MANIFEST.read_text(encoding="utf-8")))
    used |= ALWAYS_KEEP

    # Every __init__.py on the path down to each used file must survive too, even if it
    # never showed up by name in the trace on its own -- Python needs it present just to
    # resolve `diffusers.foo.bar` as a package at all before the lazy import machinery
    # inside it even runs.
    init_files = set()
    for rel in used:
        parts = Path(rel).parts
        for i in range(1, len(parts)):
            init_files.add(str(Path(*parts[:i]) / "__init__.py"))
    used |= init_files

    if OUT_ROOT.exists():
        shutil.rmtree(OUT_ROOT)
    OUT_VENDOR_SRC.mkdir(parents=True)

    copied, missing = 0, []
    for rel in sorted(used):
        src = VENDOR_SRC / rel
        if not src.is_file():
            missing.append(rel)
            continue
        dst = OUT_VENDOR_SRC / rel
        dst.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(src, dst)
        copied += 1

    if missing:
        print(f"[prune] WARNING: {len(missing)} files in the manifest don't exist under "
              f"{VENDOR_SRC} (renamed/moved?): {missing[:10]}{'...' if len(missing) > 10 else ''}")

    # Non-diffusers project files, copied as-is.
    for name in ["app.py", "requirements.txt", "README.md"]:
        shutil.copy2(PROJECT_ROOT / name, OUT_ROOT / name)
    (OUT_ROOT / "vendor").mkdir(exist_ok=True)
    shutil.copy2(
        PROJECT_ROOT / "vendor" / "group_offloading_no_try_finally_leak.patch",
        OUT_ROOT / "vendor" / "group_offloading_no_try_finally_leak.patch",
    )

    def dir_size(p: Path) -> int:
        return sum(f.stat().st_size for f in p.rglob("*") if f.is_file())

    before = dir_size(VENDOR_SRC)
    after = dir_size(OUT_VENDOR_SRC)
    print(f"[prune] kept {copied} diffusers files "
          f"({sum(1 for f in VENDOR_SRC.rglob('*.py'))} -> {sum(1 for f in OUT_VENDOR_SRC.rglob('*.py'))} .py files)")
    print(f"[prune] vendor/diffusers size: {before/1e6:.1f} MB -> {after/1e6:.1f} MB")

    zip_path = shutil.make_archive(str(OUT_ROOT), "zip", root_dir=OUT_ROOT.parent, base_dir=OUT_ROOT.name)
    print(f"[prune] wrote {zip_path}")


if __name__ == "__main__":
    main()