File size: 4,144 Bytes
27caffe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
110
111
112
113
114
115
116
117
"""
Python 3.13 Compatibility Patch
Fixes pkgutil.ImpImporter issues for AI/ML packages
"""

import sys
import pkgutil
import importlib
import importlib.util
import warnings
from typing import Any, Optional, Union


class ImpImporter:
    """
    Compatibility shim for pkgutil.ImpImporter removed in Python 3.12+
    This fixes issues with packages that still try to use the old imp module
    """
    
    def __init__(self, path: Optional[str] = None):
        self.path = path
    
    def find_module(self, fullname: str, path=None):
        """Find module using modern importlib instead of deprecated imp"""
        try:
            if isinstance(path, list) and path:
                package = path[0] if path else None
            else:
                package = None
            spec = importlib.util.find_spec(fullname, package)
            if spec is not None:
                return self
        except (ImportError, ValueError, AttributeError):
            pass
        return None
    
    def load_module(self, fullname: str):
        """Load module using modern importlib"""
        try:
            spec = importlib.util.find_spec(fullname)
            if spec is not None:
                module = importlib.util.module_from_spec(spec)
                sys.modules[fullname] = module
                if spec.loader:
                    spec.loader.exec_module(module)
                return module
        except Exception as e:
            warnings.warn(f"Failed to load module {fullname}: {e}")
        raise ImportError(f"No module named '{fullname}'")


def apply_python313_patches():
    """Apply all necessary patches for Python 3.13 compatibility"""
    
    # Patch 1: Add missing pkgutil.ImpImporter
    if not hasattr(pkgutil, 'ImpImporter'):
        # Dynamically add the attribute
        setattr(pkgutil, 'ImpImporter', ImpImporter)
        print("✓ Applied pkgutil.ImpImporter compatibility patch")
    
    # Patch 2: Fix pkg_resources for newer setuptools
    try:
        import pkg_resources
        # Monkey patch any problematic pkg_resources functionality
        if not hasattr(pkg_resources, '_initialize_master_working_set'):
            def _initialize_master_working_set():
                """Dummy implementation for missing function"""
                pass
            pkg_resources._initialize_master_working_set = _initialize_master_working_set
            print("✓ Applied pkg_resources compatibility patch")
    except ImportError:
        print("! pkg_resources not available - installing alternative")
    
    # Patch 3: Fix distutils issues
    try:
        # Check if distutils is available
        import setuptools._distutils
        if 'distutils' not in sys.modules:
            sys.modules['distutils'] = setuptools._distutils
            print("✓ Applied distutils compatibility patch")
    except ImportError:
        print("! distutils patches not needed")
    
    # Patch 4: Fix collections.abc imports
    try:
        import collections
        from collections.abc import Iterable, Mapping, MutableMapping
        if not hasattr(collections, 'Iterable'):
            setattr(collections, 'Iterable', Iterable)
            setattr(collections, 'Mapping', Mapping)
            setattr(collections, 'MutableMapping', MutableMapping)
            print("✓ Applied collections.abc compatibility patch")
    except (ImportError, AttributeError):
        pass
    
    # Patch 5: numpy compatibility
    try:
        import numpy as np
        # Fix numpy version issues by adding fallback attributes
        if not hasattr(np, 'bool'):
            setattr(np, 'bool', bool)
        if not hasattr(np, 'int'):
            setattr(np, 'int', int)
        if not hasattr(np, 'float'):
            setattr(np, 'float', float)
        if not hasattr(np, 'complex'):
            setattr(np, 'complex', complex)
        print("✓ Applied numpy compatibility patch")
    except ImportError:
        print("! numpy not available for patching")
    
    print("✓ All Python 3.13 compatibility patches applied successfully")


if __name__ == "__main__":
    apply_python313_patches()