stzhao commited on
Commit
490df47
·
verified ·
1 Parent(s): d136595

Create shared_vis_python_exe.py

Browse files
Files changed (1) hide show
  1. shared_vis_python_exe.py +160 -0
shared_vis_python_exe.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ from typing import Dict, Any, List, Tuple, Optional, Union
3
+ import io
4
+ from contextlib import redirect_stdout
5
+ from timeout_decorator import timeout
6
+ import base64
7
+ from PIL import Image
8
+ from vis_python_exe import PythonExecutor
9
+
10
+ class SharedRuntimeExecutor(PythonExecutor):
11
+ """
12
+ 支持变量共享的Python执行器,增强特性:
13
+ 1. 当 var_whitelist="RETAIN_ALL_VARS" 时保留所有变量
14
+ 2. 默认模式仅保留系统必要变量和白名单变量
15
+ 3. 线程安全的运行时管理
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ runtime_class=None,
21
+ get_answer_symbol: Optional[str] = None,
22
+ get_answer_expr: Optional[str] = None,
23
+ get_answer_from_stdout: bool = True,
24
+ timeout_length: int = 20,
25
+ var_whitelist: Union[List[str], str, None] = None,
26
+ ):
27
+ """
28
+ Args:
29
+ var_whitelist:
30
+ - 列表: 保留指定前缀的变量
31
+ - "RETAIN_ALL_VARS": 保留所有变量
32
+ - None: 仅保留系统变量
33
+ """
34
+ super().__init__(
35
+ runtime_class=runtime_class,
36
+ get_answer_symbol=get_answer_symbol,
37
+ get_answer_expr=get_answer_expr,
38
+ get_answer_from_stdout=get_answer_from_stdout,
39
+ timeout_length=timeout_length,
40
+ )
41
+
42
+ # 变量保留策略
43
+ self.retain_all_vars = (var_whitelist == "RETAIN_ALL_VARS")
44
+ self.var_whitelist = [] if self.retain_all_vars else (var_whitelist or [])
45
+
46
+ # 确保系统必要变量
47
+ if '_captured_figures' not in self.var_whitelist:
48
+ self.var_whitelist.append('_captured_figures')
49
+
50
+ # 线程安全运行时存储
51
+ self._runtime_pool: Dict[str, GenericRuntime] = {}
52
+ self._lock = threading.Lock()
53
+
54
+ def apply(self, code: str, messages: List[Dict], session_id: str = "default") -> Tuple[Any, str]:
55
+ """执行代码并保持会话状态"""
56
+ runtime = self._get_runtime(session_id, messages)
57
+
58
+ try:
59
+ # 执行代码
60
+ result, report = self._execute_shared(code, runtime)
61
+
62
+ # 清理变量(保留策略在此生效)
63
+ self._clean_runtime_vars(runtime)
64
+
65
+ return result, report
66
+
67
+ except Exception as e:
68
+ return None, f"Execution failed: {str(e)}"
69
+
70
+ def _get_runtime(self, session_id: str, messages: List[Dict]) -> GenericRuntime:
71
+ """线程安全地获取运行时实例"""
72
+ with self._lock:
73
+ if session_id not in self._runtime_pool:
74
+ self._runtime_pool[session_id] = self.runtime_class(messages)
75
+ return self._runtime_pool[session_id]
76
+
77
+ def _execute_shared(self, code: str, runtime: GenericRuntime) -> Tuple[Any, str]:
78
+ """使用共享运行时执行代码"""
79
+ code_lines = [line for line in code.split('\n') if line.strip()]
80
+
81
+ try:
82
+ if self.get_answer_from_stdout:
83
+ program_io = io.StringIO()
84
+ with redirect_stdout(program_io):
85
+ timeout(self.timeout_length)(runtime.exec_code)("\n".join(code_lines))
86
+ program_io.seek(0)
87
+ result = program_io.read()
88
+ elif self.answer_symbol:
89
+ timeout(self.timeout_length)(runtime.exec_code)("\n".join(code_lines))
90
+ result = runtime._global_vars.get(self.answer_symbol, "")
91
+ elif self.answer_expr:
92
+ timeout(self.timeout_length)(runtime.exec_code)("\n".join(code_lines))
93
+ result = timeout(self.timeout_length)(runtime.eval_code)(self.answer_expr)
94
+ else:
95
+ if len(code_lines) > 1:
96
+ timeout(self.timeout_length)(runtime.exec_code)("\n".join(code_lines[:-1]))
97
+ result = timeout(self.timeout_length)(runtime.eval_code)(code_lines[-1])
98
+ else:
99
+ timeout(self.timeout_length)(runtime.exec_code)("\n".join(code_lines))
100
+ result = ""
101
+
102
+ # 处理捕获的图像
103
+ captured_figures = runtime._global_vars.get("_captured_figures", [])
104
+ if captured_figures:
105
+ result = {
106
+ 'text': str(result).strip(),
107
+ 'images': captured_figures
108
+ }
109
+
110
+ return result, "Success"
111
+
112
+ except Exception as e:
113
+ return None, f"Error: {str(e)}"
114
+
115
+ def _clean_runtime_vars(self, runtime: GenericRuntime):
116
+ """实现变量保留策略"""
117
+ if self.retain_all_vars:
118
+ # 全保留模式:保留所有非系统变量
119
+ persistent_vars = {
120
+ k: self._serialize_var(v)
121
+ for k, v in runtime._global_vars.items()
122
+ if not k.startswith('_sys_') # 示例:排除真正的系统变量
123
+ }
124
+ else:
125
+ # 正常模式:按白名单保留
126
+ persistent_vars = {
127
+ k: self._serialize_var(v)
128
+ for k, v in runtime._global_vars.items()
129
+ if (
130
+ k.startswith('image_clue_') or # 保留注入的图像
131
+ any(k.startswith(p) for p in self.var_whitelist) # 用户白名单
132
+ )
133
+ }
134
+
135
+ # 重建变量空间
136
+ runtime._global_vars.clear()
137
+ runtime._global_vars.update(persistent_vars)
138
+
139
+ # 确保必要的系统变量存在
140
+ runtime._global_vars.setdefault('_captured_figures', [])
141
+
142
+ def _serialize_var(self, var_value: Any) -> Any:
143
+ """处理特殊对象的序列化"""
144
+ if isinstance(var_value, Image.Image):
145
+ # PIL图像转为base64
146
+ buf = io.BytesIO()
147
+ var_value.save(buf, format='PNG')
148
+ return base64.b64encode(buf.getvalue()).decode('utf-8')
149
+ return var_value
150
+
151
+ def cleanup_session(self, session_id: str):
152
+ """清理指定会话"""
153
+ with self._lock:
154
+ if session_id in self._runtime_pool:
155
+ del self._runtime_pool[session_id]
156
+
157
+ def cleanup_all(self):
158
+ """清理所有会话"""
159
+ with self._lock:
160
+ self._runtime_pool.clear()