SuperModelingFactory 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. ExcelMaster/ExcelFormatTool.py +487 -0
  2. ExcelMaster/ExcelMaster.py +917 -0
  3. ExcelMaster/Template.py +525 -0
  4. ExcelMaster/Utility.py +233 -0
  5. ExcelMaster/__init__.py +3 -0
  6. Modeling_Tool/Core/Binning_Tool.py +1608 -0
  7. Modeling_Tool/Core/Binning_Tool.pyi +48 -0
  8. Modeling_Tool/Core/Check_DuckDB_Compatibility.py +835 -0
  9. Modeling_Tool/Core/Json_Data_Converter.py +621 -0
  10. Modeling_Tool/Core/Model_Registry_Tool.py +199 -0
  11. Modeling_Tool/Core/ODPS_Tool.py +284 -0
  12. Modeling_Tool/Core/Slope_Tool.py +356 -0
  13. Modeling_Tool/Core/Slope_Tool.pyi +31 -0
  14. Modeling_Tool/Core/XOR_Encryptor.py +207 -0
  15. Modeling_Tool/Core/XOR_Encryptor.pyi +26 -0
  16. Modeling_Tool/Core/__init__.py +99 -0
  17. Modeling_Tool/Core/kDataFrame.py +228 -0
  18. Modeling_Tool/Core/kDataFrame.pyi +43 -0
  19. Modeling_Tool/Core/sample_weight_utils.py +77 -0
  20. Modeling_Tool/Core/utils.py +2672 -0
  21. Modeling_Tool/Eval/Evaluation_Tool.py +1452 -0
  22. Modeling_Tool/Eval/Evaluation_Tool.pyi +47 -0
  23. Modeling_Tool/Eval/Model_Eval_Tool.py +2548 -0
  24. Modeling_Tool/Eval/Model_Eval_Tool.pyi +37 -0
  25. Modeling_Tool/Eval/__init__.py +54 -0
  26. Modeling_Tool/Eval/evaluate_model.py +2008 -0
  27. Modeling_Tool/Eval/evaluate_model.pyi +50 -0
  28. Modeling_Tool/Eval/weighted_eval_utils.py +326 -0
  29. Modeling_Tool/Explainability/Coalition_Structure.py +305 -0
  30. Modeling_Tool/Explainability/Model_Explainer.py +743 -0
  31. Modeling_Tool/Explainability/__init__.py +24 -0
  32. Modeling_Tool/Feature/Distribution_Tool.py +509 -0
  33. Modeling_Tool/Feature/Distribution_Tool.pyi +42 -0
  34. Modeling_Tool/Feature/Feature_Insights.py +762 -0
  35. Modeling_Tool/Feature/Feature_Insights.pyi +33 -0
  36. Modeling_Tool/Feature/PSI_Tool.py +1195 -0
  37. Modeling_Tool/Feature/PSI_Tool.pyi +29 -0
  38. Modeling_Tool/Feature/WOE_Engine_Feature_Patch.py +355 -0
  39. Modeling_Tool/Feature/__init__.py +40 -0
  40. Modeling_Tool/Model/Backward_Tool.py +778 -0
  41. Modeling_Tool/Model/Backward_Tool.pyi +45 -0
  42. Modeling_Tool/Model/GBM_Search_Tool.py +251 -0
  43. Modeling_Tool/Model/GBM_Tool.py +1610 -0
  44. Modeling_Tool/Model/GBM_Tool.pyi +90 -0
  45. Modeling_Tool/Model/LRM_Tool.py +1198 -0
  46. Modeling_Tool/Model/LRM_Tool.pyi +47 -0
  47. Modeling_Tool/Model/__init__.py +61 -0
  48. Modeling_Tool/Sample/Distribution_Adaptation.py +131 -0
  49. Modeling_Tool/Sample/Distribution_Adaptation.pyi +30 -0
  50. Modeling_Tool/Sample/Reject_Infer.py +413 -0
  51. Modeling_Tool/Sample/Reject_Infer.pyi +43 -0
  52. Modeling_Tool/Sample/Sample_Split.py +520 -0
  53. Modeling_Tool/Sample/Sample_Split.pyi +43 -0
  54. Modeling_Tool/Sample/__init__.py +31 -0
  55. Modeling_Tool/UAT/UAT_Consistency_Checker.py +1180 -0
  56. Modeling_Tool/UAT/__init__.py +19 -0
  57. Modeling_Tool/WOE/WOE_Adapter.py +204 -0
  58. Modeling_Tool/WOE/WOE_Adapter.pyi +21 -0
  59. Modeling_Tool/WOE/WOE_Master.py +491 -0
  60. Modeling_Tool/WOE/WOE_Master.pyi +40 -0
  61. Modeling_Tool/WOE/WOE_Monotone_Binner.py +3324 -0
  62. Modeling_Tool/WOE/WOE_Monotone_Binner.pyi +71 -0
  63. Modeling_Tool/WOE/WOE_Plot_Tool.py +919 -0
  64. Modeling_Tool/WOE/WOE_Plot_Tool.pyi +46 -0
  65. Modeling_Tool/WOE/WOE_Report_Builder.py +214 -0
  66. Modeling_Tool/WOE/WOE_Report_Builder.pyi +24 -0
  67. Modeling_Tool/WOE/WOE_Tool.py +1094 -0
  68. Modeling_Tool/WOE/WOE_Tool.pyi +41 -0
  69. Modeling_Tool/WOE/__init__.py +86 -0
  70. Modeling_Tool/WOE/plot_woe_tool.py +290 -0
  71. Modeling_Tool/WOE/plot_woe_tool.pyi +25 -0
  72. Modeling_Tool/__init__.py +176 -0
  73. Report/Report_Tool.py +380 -0
  74. Report/__init__.py +3 -0
  75. supermodelingfactory-0.2.0.dist-info/METADATA +268 -0
  76. supermodelingfactory-0.2.0.dist-info/RECORD +79 -0
  77. supermodelingfactory-0.2.0.dist-info/WHEEL +5 -0
  78. supermodelingfactory-0.2.0.dist-info/licenses/LICENSE +102 -0
  79. supermodelingfactory-0.2.0.dist-info/top_level.txt +3 -0
@@ -0,0 +1,356 @@
1
+ import logging
2
+ import numpy as np
3
+ import pandas as pd
4
+ # Available only in newer pandas versions. Older Airflow images should skip it.
5
+ try:
6
+ pd.set_option('future.no_silent_downcasting', True)
7
+ except (KeyError, ValueError):
8
+ pass
9
+ pd.options.mode.chained_assignment = None # default='warn'
10
+ logging.basicConfig(level=logging.INFO, format="%(message)s")
11
+
12
+
13
+ def calculate_slope_sklearn(data, column):
14
+ """
15
+ 使用SKlearn的LinearRegression计算数据列的斜率。
16
+
17
+ 基于最小二乘法,通过LinearRegression模型拟合数据点,
18
+ 返回线性回归的斜率系数。
19
+
20
+ Parameters
21
+ ----------
22
+ data : pandas.DataFrame
23
+ 包含数据的DataFrame
24
+ column : str
25
+ 数据列名
26
+
27
+ Returns
28
+ -------
29
+ float
30
+ 线性回归的斜率值
31
+
32
+ Examples
33
+ --------
34
+ >>> df = pd.DataFrame({'values': [1, 2, 3, 4, 5]})
35
+ >>> calculate_slope_sklearn(df, 'values')
36
+ 1.0
37
+ """
38
+
39
+ from sklearn.linear_model import LinearRegression
40
+
41
+ series = data[column]
42
+ # 确保数据是NumPy数组格式
43
+ y = np.array(series).reshape(-1, 1)
44
+
45
+ # 创建x轴(索引)
46
+ x = np.arange(len(series)).reshape(-1, 1)
47
+
48
+ # 创建并拟合线性回归模型
49
+ model = LinearRegression()
50
+ model.fit(x, y)
51
+
52
+ # 获取斜率
53
+ slope = model.coef_[0][0]
54
+
55
+ return slope
56
+
57
+
58
+ def calculate_slope_scipy(data, column):
59
+ """
60
+ 使用SciPy的linregress函数计算数据列的斜率。
61
+
62
+ 基于最小二乘法,通过scipy.stats.linregress函数拟合数据点,
63
+ 返回斜率及更多统计信息。
64
+
65
+ Parameters
66
+ ----------
67
+ data : pandas.DataFrame
68
+ 包含数据的DataFrame
69
+ column : str
70
+ 数据列名
71
+
72
+ Returns
73
+ -------
74
+ tuple
75
+ (slope, r_value, p_value, std_err) 元组,包含:
76
+ - slope: 斜率值
77
+ - r_value: 相关系数
78
+ - p_value: p值
79
+ - std_err: 标准误差
80
+
81
+ Examples
82
+ --------
83
+ >>> df = pd.DataFrame({'values': [1, 2, 3, 4, 5]})
84
+ >>> slope, r, p, se = calculate_slope_scipy(df, 'values')
85
+ >>> print(f"斜率: {slope}, 相关系数: {r}")
86
+ 斜率: 1.0, 相关系数: 1.0
87
+ """
88
+
89
+ from scipy import stats
90
+
91
+ series = data[column]
92
+ # 确保数据是NumPy数组格式
93
+ y = np.array(series)
94
+
95
+ # 创建x轴(索引)
96
+ x = np.arange(len(y))
97
+
98
+ # 执行线性回归
99
+ slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
100
+
101
+ return slope, r_value, p_value, std_err
102
+
103
+
104
+ def calculate_slope_numpy(data, column):
105
+ """
106
+ 使用NumPy的polyfit函数计算数据列的斜率。
107
+
108
+ 使用numpy.polyfit函数进行一阶多项式拟合,
109
+ 返回线性回归的斜率。
110
+
111
+ Parameters
112
+ ----------
113
+ data : pandas.DataFrame
114
+ 包含数据的DataFrame
115
+ column : str
116
+ 数据列名
117
+
118
+ Returns
119
+ -------
120
+ float
121
+ 线性回归的斜率值
122
+
123
+ Examples
124
+ --------
125
+ >>> df = pd.DataFrame({'values': [1, 2, 3, 4, 5]})
126
+ >>> calculate_slope_numpy(df, 'values')
127
+ 1.0
128
+ """
129
+
130
+ import numpy as np
131
+
132
+ series = data[column]
133
+ # 确保数据是NumPy数组格式
134
+ y = np.array(series)
135
+
136
+ # 创建x轴(索引)
137
+ x = np.arange(len(y))
138
+
139
+ # 使用一次多项式拟合(线性回归),返回斜率和截距
140
+ slope, intercept = np.polyfit(x, y, 1)
141
+
142
+ return slope
143
+
144
+
145
+ def calculate_slope_manual(data, column):
146
+ """
147
+ 手动使用最小二乘法计算数据列的斜率。
148
+
149
+ 通过手动实现最小二乘法公式,计算线性回归的斜率:
150
+ slope = Σ((x - x_mean) * (y - y_mean)) / Σ((x - x_mean)²)
151
+
152
+ Parameters
153
+ ----------
154
+ data : pandas.DataFrame
155
+ 包含数据的DataFrame
156
+ column : str
157
+ 数据列名
158
+
159
+ Returns
160
+ -------
161
+ float
162
+ 线性回归的斜率值
163
+
164
+ Examples
165
+ --------
166
+ >>> df = pd.DataFrame({'values': [1, 2, 3, 4, 5]})
167
+ >>> calculate_slope_manual(df, 'values')
168
+ 1.0
169
+ """
170
+
171
+ series = data[column]
172
+
173
+ # 确保数据是NumPy数组格式
174
+ y = np.array(series)
175
+
176
+ # 创建x轴(索引)
177
+ x = np.arange(len(y))
178
+
179
+ # 计算x和y的平均值
180
+ x_mean = np.mean(x)
181
+ y_mean = np.mean(y)
182
+
183
+ # 计算斜率和截距
184
+ numerator = np.sum((x - x_mean) * (y - y_mean))
185
+ denominator = np.sum((x - x_mean) ** 2)
186
+
187
+ slope = numerator / denominator
188
+
189
+ return slope
190
+
191
+
192
+ class SlopeCalculator:
193
+ """
194
+ 斜率计算器。
195
+
196
+ 提供多种方法计算数据列的线性回归斜率,支持:
197
+ - sklearn LinearRegression
198
+ - scipy.stats.linregress
199
+ - numpy.polyfit
200
+ - 手动最小二乘法
201
+
202
+ Parameters
203
+ ----------
204
+ data : pandas.DataFrame
205
+ 包含数据的DataFrame
206
+ column : str
207
+ 数据列名
208
+
209
+ Attributes
210
+ ----------
211
+ data : pandas.DataFrame
212
+ 输入数据
213
+ column : str
214
+ 列名
215
+ y : numpy.ndarray
216
+ 转换后的数据数组
217
+ x : numpy.ndarray
218
+ x轴数组(索引)
219
+
220
+ Examples
221
+ --------
222
+ >>> df = pd.DataFrame({'values': [1, 2, 3, 4, 5]})
223
+ >>> calc = SlopeCalculator(df, 'values')
224
+ >>> calc.calculate_sklearn()
225
+ 1.0
226
+ >>> calc.calculate_scipy()
227
+ (1.0, 1.0, 9.999999999999996e-08, 0.0)
228
+ """
229
+
230
+ def __init__(self, data, column):
231
+ """
232
+ 初始化斜率计算器。
233
+
234
+ Parameters
235
+ ----------
236
+ data : pandas.DataFrame
237
+ 包含数据的DataFrame
238
+ column : str
239
+ 数据列名
240
+ """
241
+ self.data = data
242
+ self.column = column
243
+ self.series = data[column]
244
+ self.y = np.array(self.series)
245
+ self.x = np.arange(len(self.series))
246
+
247
+ def calculate_sklearn(self):
248
+ """
249
+ 使用sklearn LinearRegression计算斜率。
250
+
251
+ Returns
252
+ -------
253
+ float
254
+ 线性回归的斜率值
255
+ """
256
+ return calculate_slope_sklearn(self.data, self.column)
257
+
258
+ def calculate_scipy(self):
259
+ """
260
+ 使用scipy.stats.linregress计算斜率。
261
+
262
+ Returns
263
+ -------
264
+ tuple
265
+ (slope, r_value, p_value, std_err) 元组
266
+ """
267
+ return calculate_slope_scipy(self.data, self.column)
268
+
269
+ def calculate_numpy(self):
270
+ """
271
+ 使用numpy.polyfit计算斜率。
272
+
273
+ Returns
274
+ -------
275
+ float
276
+ 线性回归的斜率值
277
+ """
278
+ return calculate_slope_numpy(self.data, self.column)
279
+
280
+ def calculate_manual(self):
281
+ """
282
+ 使用手动最小二乘法计算斜率。
283
+
284
+ Returns
285
+ -------
286
+ float
287
+ 线性回归的斜率值
288
+ """
289
+ return calculate_slope_manual(self.data, self.column)
290
+
291
+ def calculate_all(self):
292
+ """
293
+ 使用所有方法计算斜率。
294
+
295
+ Returns
296
+ -------
297
+ dict
298
+ 包含各种方法计算结果的字典
299
+ """
300
+ results = {}
301
+
302
+ # sklearn方法
303
+ results['sklearn'] = self.calculate_sklearn()
304
+
305
+ # scipy方法
306
+ scipy_result = self.calculate_scipy()
307
+ results['scipy_slope'] = scipy_result[0]
308
+ results['scipy_r_value'] = scipy_result[1]
309
+ results['scipy_p_value'] = scipy_result[2]
310
+ results['scipy_std_err'] = scipy_result[3]
311
+
312
+ # numpy方法
313
+ results['numpy'] = self.calculate_numpy()
314
+
315
+ # 手动方法
316
+ results['manual'] = self.calculate_manual()
317
+
318
+ return results
319
+
320
+ @staticmethod
321
+ def calculate(data, column, method='sklearn'):
322
+ """
323
+ 静态方法:使用指定方法计算斜率。
324
+
325
+ Parameters
326
+ ----------
327
+ data : pandas.DataFrame
328
+ 包含数据的DataFrame
329
+ column : str
330
+ 数据列名
331
+ method : str, default 'sklearn'
332
+ 计算方法,候选值:'sklearn', 'scipy', 'numpy', 'manual'
333
+
334
+ Returns
335
+ -------
336
+ float or tuple
337
+ 斜率值(scipy返回元组,其他返回浮点数)
338
+
339
+ Examples
340
+ --------
341
+ >>> df = pd.DataFrame({'values': [1, 2, 3, 4, 5]})
342
+ >>> SlopeCalculator.calculate(df, 'values', method='numpy')
343
+ 1.0
344
+ """
345
+ calc = SlopeCalculator(data, column)
346
+
347
+ if method == 'sklearn':
348
+ return calc.calculate_sklearn()
349
+ elif method == 'scipy':
350
+ return calc.calculate_scipy()
351
+ elif method == 'numpy':
352
+ return calc.calculate_numpy()
353
+ elif method == 'manual':
354
+ return calc.calculate_manual()
355
+ else:
356
+ raise ValueError(f"不支持的方法: {method}。请选择: 'sklearn', 'scipy', 'numpy', 'manual'")
@@ -0,0 +1,31 @@
1
+ # =============================================================================
2
+ # Modeling_Tool.Core.Slope_Tool
3
+ # -----------------------------------------------------------------------------
4
+ # Copyright (c) 2026 Kyle Sun <github.com/Kyle-J-Sun>. All rights reserved.
5
+ # SuperModelingFactory — Licensed under the Business Source License 1.1.
6
+ #
7
+ # This stub describes the public API of a closed-source module compiled to a
8
+ # native extension (.so / .pyd). The original source is not distributed.
9
+ # Production / commercial use requires a separate commercial license.
10
+ #
11
+ # FINGERPRINT: SMF-SLOPETOOL-fb45b118
12
+ # (Unique trace marker. Do not remove or alter — used for plagiarism
13
+ # detection across the public internet.)
14
+ # =============================================================================
15
+
16
+ import logging
17
+ import numpy as np
18
+ import pandas as pd
19
+ def calculate_slope_sklearn(data, column): ...
20
+ def calculate_slope_scipy(data, column): ...
21
+ def calculate_slope_numpy(data, column): ...
22
+ def calculate_slope_manual(data, column): ...
23
+
24
+ class SlopeCalculator:
25
+ def __init__(self, data, column): ...
26
+ def calculate_sklearn(self): ...
27
+ def calculate_scipy(self): ...
28
+ def calculate_numpy(self): ...
29
+ def calculate_manual(self): ...
30
+ def calculate_all(self): ...
31
+ def calculate(data, column, method = 'sklearn'): ...
@@ -0,0 +1,207 @@
1
+ import base64
2
+ import random
3
+ import pandas as pd
4
+ import numpy as np
5
+
6
+ class TextEncryptor:
7
+ """
8
+ 基于XOR算法的文本加密解密工具类。
9
+
10
+ 该类提供文本加密和解密功能,支持单个字符串以及整个Pandas DataFrame的加解密操作。
11
+ 加密后的数据使用Base64 URL安全编码,便于存储和传输。
12
+
13
+ Attributes:
14
+ key (str): 加密解密使用的密钥。如果为None,则使用空字符串作为密钥。
15
+ suffix (str): DataFrame列名加密后的后缀,默认为'_encrypted'。
16
+
17
+ Example:
18
+ >>> encryptor = TextEncryptor(key="my_secret_key")
19
+ >>> encrypted = encryptor.encrypt("Hello World")
20
+ >>> decrypted = encryptor.decrypt(encrypted)
21
+ >>> print(decrypted) # 输出: Hello World
22
+ """
23
+
24
+ def __init__(self, key=None, suffix='_encrypted'):
25
+ """
26
+ 初始化加密器实例。
27
+
28
+ Parameters:
29
+ key (str, optional): 加密解密使用的密钥。如果为None,则使用空字符串作为密钥。
30
+ 注意:使用空密钥加密后的数据将不具有保密性。
31
+ suffix (str, optional): 当对DataFrame进行加密时,列名添加的后缀。
32
+ 默认为'_encrypted'。解密时会移除此后缀。
33
+ """
34
+ self.key = key
35
+ self.suffix = suffix
36
+
37
+ def encrypt(self, text):
38
+ """
39
+ 对输入的文本进行加密。
40
+
41
+ 使用XOR算法将明文与密钥进行异或操作,然后通过Base64 URL安全编码输出。
42
+ 加密结果包含原始文本长度信息(前2个字节),用于解密时的验证。
43
+
44
+ Parameters:
45
+ text (str): 需要加密的明文字符串。
46
+
47
+ Returns:
48
+ str: 加密后的字符串,使用Base64 URL安全编码。
49
+
50
+ Raises:
51
+ AttributeError: 如果key属性为None(self.key为None时,实际使用空字符串)。
52
+
53
+ Example:
54
+ >>> encryptor = TextEncryptor(key="secret")
55
+ >>> encrypted = encryptor.encrypt("Hello")
56
+ >>> print(encrypted) # 输出类似: aAAAAS垂涎==
57
+ """
58
+ # Text to bytes
59
+ text_bytes = text.encode('utf-8')
60
+
61
+ # Expand byte length
62
+ key_bytes = (self.key * (len(text_bytes) // len(self.key) + 1)).encode('utf-8')
63
+ key_bytes = key_bytes[:len(text_bytes)]
64
+
65
+ # XOR encryption
66
+ encrypted_bytes = bytes([text_bytes[i] ^ key_bytes[i] for i in range(len(text_bytes))])
67
+
68
+ # Add 2 more bytes for verification
69
+ length_byte = len(text).to_bytes(2, 'big')
70
+
71
+ # combine
72
+ result_bytes = length_byte + encrypted_bytes
73
+ return base64.urlsafe_b64encode(result_bytes).decode('utf-8')
74
+
75
+ def decrypt(self, encrypted_text):
76
+ """
77
+ 对加密后的文本进行解密。
78
+
79
+ 首先使用Base64解码,然后提取长度信息(前2字节),接着使用XOR算法与密钥进行异或操作恢复明文。
80
+ 解密后会验证恢复文本的长度是否与存储的长度信息匹配,以确保数据完整性。
81
+
82
+ Parameters:
83
+ encrypted_text (str): 经过encrypt方法加密的Base64编码字符串。
84
+
85
+ Returns:
86
+ str: 解密后的原始明文字符串。
87
+
88
+ Raises:
89
+ ValueError: 如果解密失败,可能原因包括:
90
+ - Base64解码失败(输入不是有效的Base64字符串)
91
+ - 长度验证失败(数据被篡改或使用了不同的密钥)
92
+ - 其他解码错误
93
+
94
+ Example:
95
+ >>> encryptor = TextEncryptor(key="secret")
96
+ >>> encrypted = encryptor.encrypt("Hello")
97
+ >>> decrypted = encryptor.decrypt(encrypted)
98
+ >>> print(decrypted) # 输出: Hello
99
+ """
100
+ try:
101
+ # b64 decryption
102
+ decoded_bytes = base64.urlsafe_b64decode(encrypted_text.encode('utf-8'))
103
+
104
+ # extract length info
105
+ text_length = int.from_bytes(decoded_bytes[:2], 'big')
106
+
107
+ # extract encryption info
108
+ encrypted_bytes = decoded_bytes[2:]
109
+
110
+ # regenerate key
111
+ key_bytes = (self.key * (len(encrypted_bytes) // len(self.key) + 1)).encode('utf-8')
112
+ key_bytes = key_bytes[:len(encrypted_bytes)]
113
+
114
+ # XOR Decrypt
115
+ decrypted_bytes = bytes([encrypted_bytes[i] ^ key_bytes[i] for i in range(len(encrypted_bytes))])
116
+
117
+ # Check Length
118
+ if len(decrypted_bytes) != text_length:
119
+ raise ValueError("Text Length Does Not Match!")
120
+
121
+ return decrypted_bytes.decode('utf-8')
122
+ except:
123
+ raise ValueError("Decrypt Failed! Data Might be Destroyed or Incorrect Key!")
124
+
125
+ def encrypt_dataframe(self, data):
126
+ """
127
+ 对整个Pandas DataFrame进行加密。
128
+
129
+ 将DataFrame中的所有列值转换为字符串格式后进行加密,同时为列名添加指定的后缀。
130
+ 该方法返回一个全新的DataFrame,原始数据不会被修改。
131
+
132
+ Parameters:
133
+ data (pandas.DataFrame): 需要加密的Pandas DataFrame对象。
134
+ 所有列的值都会被转换为字符串格式进行加密。
135
+
136
+ Returns:
137
+ pandas.DataFrame: 加密后的新DataFrame,具有以下特点:
138
+ - 所有列值都经过加密,使用Base64编码
139
+ - 所有列名都添加了初始化时指定的后缀(默认为'_encrypted')
140
+ - 返回的是副本,原始DataFrame保持不变
141
+
142
+ Raises:
143
+ AttributeError: 如果key属性为None导致加密失败。
144
+
145
+ Note:
146
+ - 加密后的DataFrame无法直接用于数据分析,必须先解密
147
+ - 建议在加密前备份原始DataFrame的列名对应关系
148
+
149
+ Example:
150
+ >>> import pandas as pd
151
+ >>> df = pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [25, 30]})
152
+ >>> encryptor = TextEncryptor(key="secret")
153
+ >>> encrypted_df = encryptor.encrypt_dataframe(df)
154
+ >>> print(encrypted_df.columns.tolist()) # 输出: ['name_encrypted', 'age_encrypted']
155
+ """
156
+ res = data.copy()
157
+ collist = data.columns.tolist()
158
+ for col in collist:
159
+ ## Encryption
160
+ res[col] = res[col].astype(str)
161
+ res[col] = res[col].apply(lambda x: self.encrypt(x))
162
+ res.columns = [x + self.suffix for x in res.columns]
163
+ return res
164
+
165
+ def decrypt_dataframe(self, data):
166
+ """
167
+ 对加密后的Pandas DataFrame进行解密。
168
+
169
+ 遍历DataFrame中的所有列,对每个列值进行解密,同时移除列名中的加密后缀。
170
+ 该方法返回一个全新的DataFrame,原始数据不会被修改。
171
+
172
+ Parameters:
173
+ data (pandas.DataFrame): 需要解密的Pandas DataFrame对象。
174
+ 应该是由encrypt_dataframe方法加密产生的DataFrame。
175
+
176
+ Returns:
177
+ pandas.DataFrame: 解密后的新DataFrame,具有以下特点:
178
+ - 所有列值都经过解密,恢复为原始字符串格式
179
+ - 所有列名都移除了初始化时指定的后缀(默认为'_encrypted')
180
+ - 返回的是副本,原始DataFrame保持不变
181
+
182
+ Raises:
183
+ ValueError: 如果解密失败,可能原因包括:
184
+ - 列值不是有效的加密字符串
185
+ - 使用了错误的密钥进行解密
186
+ - 数据在传输或存储过程中被损坏
187
+ UnicodeDecodeError: 如果解密后的字节无法正确解码为UTF-8字符串。
188
+
189
+ Note:
190
+ - 加密和解密必须使用相同的密钥
191
+ - 如果DataFrame包含非加密的列,解密操作可能会失败
192
+
193
+ Example:
194
+ >>> import pandas as pd
195
+ >>> df = pd.DataFrame({'name_encrypted': ['aGVsbG8=', 'd29ybGQ='],
196
+ ... 'age_encrypted': ['c2F2ZWQ=', 'dGVzdA==']})
197
+ >>> encryptor = TextEncryptor(key="secret")
198
+ >>> decrypted_df = encryptor.decrypt_dataframe(df)
199
+ >>> print(decrypted_df.columns.tolist()) # 输出: ['name', 'age']
200
+ """
201
+ res = data.copy()
202
+ collist = data.columns.tolist()
203
+ for col in collist:
204
+ ## Encryption
205
+ res[col] = res[col].apply(lambda x: self.decrypt(x))
206
+ res.columns = [x.replace(self.suffix, "") for x in res.columns]
207
+ return res
@@ -0,0 +1,26 @@
1
+ # =============================================================================
2
+ # Modeling_Tool.Core.XOR_Encryptor
3
+ # -----------------------------------------------------------------------------
4
+ # Copyright (c) 2026 Kyle Sun <github.com/Kyle-J-Sun>. All rights reserved.
5
+ # SuperModelingFactory — Licensed under the Business Source License 1.1.
6
+ #
7
+ # This stub describes the public API of a closed-source module compiled to a
8
+ # native extension (.so / .pyd). The original source is not distributed.
9
+ # Production / commercial use requires a separate commercial license.
10
+ #
11
+ # FINGERPRINT: SMF-XORENCRYPTOR-2acb2941
12
+ # (Unique trace marker. Do not remove or alter — used for plagiarism
13
+ # detection across the public internet.)
14
+ # =============================================================================
15
+
16
+ import base64
17
+ import random
18
+ import pandas as pd
19
+ import numpy as np
20
+
21
+ class TextEncryptor:
22
+ def __init__(self, key = None, suffix = '_encrypted'): ...
23
+ def encrypt(self, text): ...
24
+ def decrypt(self, encrypted_text): ...
25
+ def encrypt_dataframe(self, data): ...
26
+ def decrypt_dataframe(self, data): ...