File size: 2,152 Bytes
5221c8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Patch chumpy 0.70 for Python 3.11 and NumPy 2.x.

Run this after:

    pip install --no-build-isolation chumpy==0.70

The script intentionally avoids importing chumpy, because the unpatched package
can fail during import on modern Python/NumPy versions.
"""

from __future__ import annotations

import importlib.util
from pathlib import Path


GETARGSPEC_OLD = "inspect.getargspec("
GETARGSPEC_NEW = "inspect.getfullargspec("

NUMPY_IMPORT_OLD = (
    "from numpy import bool, int, float, complex, object, unicode, str, nan, inf"
)
NUMPY_IMPORT_NEW = """from numpy import bool, nan, inf
import builtins as _builtins

int = _builtins.int
float = _builtins.float
complex = _builtins.complex
object = _builtins.object
unicode = _builtins.str
str = _builtins.str"""


def find_chumpy_dir() -> Path:
    spec = importlib.util.find_spec("chumpy")
    if spec is None:
        raise SystemExit(
            "chumpy is not installed. Run: "
            "pip install --no-build-isolation chumpy==0.70"
        )
    if spec.submodule_search_locations:
        return Path(next(iter(spec.submodule_search_locations)))
    if spec.origin:
        return Path(spec.origin).parent
    raise SystemExit("Could not locate the installed chumpy package.")


def patch_file(path: Path, replacements: list[tuple[str, str]]) -> bool:
    text = path.read_text(encoding="utf-8")
    updated = text
    for old, new in replacements:
        updated = updated.replace(old, new)
    if updated == text:
        return False
    path.write_text(updated, encoding="utf-8")
    return True


def main() -> None:
    chumpy_dir = find_chumpy_dir()

    changed = []
    ch_py = chumpy_dir / "ch.py"
    init_py = chumpy_dir / "__init__.py"

    if patch_file(ch_py, [(GETARGSPEC_OLD, GETARGSPEC_NEW)]):
        changed.append(str(ch_py))

    if patch_file(init_py, [(NUMPY_IMPORT_OLD, NUMPY_IMPORT_NEW)]):
        changed.append(str(init_py))

    if changed:
        print("Patched chumpy files:")
        for path in changed:
            print(f"  {path}")
    else:
        print("chumpy is already patched.")


if __name__ == "__main__":
    main()