File size: 1,842 Bytes
3069ef4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# hf_patch.py - 为Hugging Face Spaces环境修补文件IO操作
import os
import sys

# 防止任何文件写入操作
class DisableFileWritingWrapper:
    """拦截文件写入操作的包装器"""
    
    def __init__(self, original_open):
        self.original_open = original_open
    
    def __call__(self, *args, **kwargs):
        file_path = str(args[0]) if args else ""
        mode = args[1] if len(args) > 1 else kwargs.get('mode', 'r')
        
        # 如果是写入模式且不是stdout/stderr,则重定向到/dev/null
        if ('w' in mode or 'a' in mode or '+' in mode) and not file_path.startswith('<'):
            try:
                if os.path.dirname(file_path) == '/app/logs':
                    print(f"拦截写入操作到: {file_path} (模式: {mode})")
                    # 在Linux环境下重定向到/dev/null
                    return self.original_open("/dev/null", mode, *args[2:], **kwargs)
            except Exception:
                pass
        
        # 其他情况使用原始的open函数
        return self.original_open(*args, **kwargs)

# 主函数
def apply_patches():
    """应用所有补丁"""
    print("正在应用Hugging Face兼容性补丁...")
    
    # 设置环境变量
    os.environ['DISABLE_FILE_LOGGING'] = '1'
    os.environ['NO_FILE_LOGGING'] = '1'
    os.environ['LOG_TO_STDOUT'] = '1'
    
    # 拦截文件写入操作
    # 注意: 这是一个全局修改,会影响所有导入本模块后的文件写入操作
    if hasattr(os, 'open'):
        original_open = os.open
        os.open = DisableFileWritingWrapper(original_open)
    
    # 确保日志目录存在
    os.makedirs('/app/logs', exist_ok=True)
    
    print("Hugging Face兼容性补丁已应用")

# 自动运行
if __name__ == "__main__":
    apply_patches()