wei-data-shu 0.4.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.
@@ -0,0 +1,297 @@
1
+ # !/usr/bin/python
2
+ # -*- coding:utf-8 -*-
3
+ """
4
+ ████─█──█─████─███─█──█─███─███
5
+ █──█─█──█─█──█─█───██─█──█──█──
6
+ ████─████─█──█─███─█─██──█──███
7
+ █────█──█─█──█─█───█──█──█──█──
8
+ █────█──█─████─███─█──█─███─███
9
+ ╔╗╔╗╔╗╔═══╗╔══╗╔╗──╔══╗╔══╗╔══╗╔═══╗╔══╗
10
+ ║║║║║║║╔══╝╚╗╔╝║║──╚╗╔╝║╔╗║║╔╗║╚═╗─║╚╗╔╝
11
+ ║║║║║║║╚══╗─║║─║║───║║─║╚╝║║║║║─╔╝╔╝─║║─
12
+ ║║║║║║║╔══╝─║║─║║───║║─║╔╗║║║║║╔╝╔╝──║║─
13
+ ║╚╝╚╝║║╚══╗╔╝╚╗║╚═╗╔╝╚╗║║║║║╚╝║║─╚═╗╔╝╚╗
14
+ ╚═╝╚═╝╚═══╝╚══╝╚══╝╚══╝╚╝╚╝╚══╝╚═══╝╚══╝
15
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
16
+
17
+ 佛祖保佑 永不宕机 永无BUG
18
+
19
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
20
+ @project:home
21
+ @author:Phoenix,weiliaozi
22
+ @file:pywork
23
+ @ide:PyCharm
24
+ @date:2023/12/3
25
+ @time:17:33
26
+ @month:十二月
27
+ @email:thisluckyboy@126.com
28
+ """
29
+ import mysql.connector
30
+ from collections import deque
31
+ # import openpyxl
32
+ # import pandas as pd
33
+ from .timingTool import fn_timer
34
+ from typing import List, Optional, Union, Any
35
+ # import pymysql
36
+
37
+ # class Database:
38
+ # def __init__(self, host: str, port: int, user: str, password: str, db: str, charset: str = 'utf8'):
39
+ # """
40
+ # Database class for managing MySQL connections and operations.
41
+ # """
42
+ # self.connection_state = False
43
+ # self.connection = None
44
+ # self.host = host
45
+ # self.port = port
46
+ # self.user = user
47
+ # self.password = password
48
+ # self.db = db
49
+ # self.charset = charset
50
+
51
+ # def _connect(self) -> None:
52
+ # """
53
+ # Establish a connection to the database if not already connected.
54
+ # """
55
+ # if not self.connection_state:
56
+ # try:
57
+ # self.connection = pymysql.connect(
58
+ # host=self.host,
59
+ # port=self.port,
60
+ # user=self.user,
61
+ # password=self.password,
62
+ # db=self.db,
63
+ # charset=self.charset,
64
+ # cursorclass=pymysql.cursors.DictCursor
65
+ # )
66
+ # self.connection_state = True
67
+ # except Exception as e:
68
+ # raise ConnectionError(f"Database connection failed: {e}")
69
+
70
+ # def _close(self) -> None:
71
+ # """
72
+ # Close the database connection if open.
73
+ # """
74
+ # if self.connection_state and self.connection:
75
+ # try:
76
+ # self.connection.close()
77
+ # self.connection_state = False
78
+ # except Exception as e:
79
+ # raise RuntimeError(f"Error closing the connection: {e}")
80
+
81
+ # def _execute(
82
+ # self,
83
+ # sql: str,
84
+ # params: Optional[Union[List[tuple], tuple]] = None,
85
+ # fetch_all: bool = True,
86
+ # as_df: bool = False,
87
+ # procedure: bool = False
88
+ # ) -> Optional[Union[List[dict], pd.DataFrame]]:
89
+ # """
90
+ # Execute a SQL query or stored procedure.
91
+ # """
92
+ # self._connect() # Ensure connection is open
93
+ # try:
94
+ # with self.connection.cursor() as cursor:
95
+ # if procedure:
96
+ # cursor.callproc(sql, params)
97
+ # elif params:
98
+ # cursor.executemany(sql, params) if isinstance(params, list) else cursor.execute(sql, params)
99
+ # else:
100
+ # cursor.execute(sql)
101
+
102
+ # if fetch_all:
103
+ # results = cursor.fetchall()
104
+ # return pd.DataFrame(results) if as_df else results
105
+
106
+ # self.connection.commit()
107
+ # except Exception as e:
108
+ # self.connection.rollback()
109
+ # raise RuntimeError(f"Error executing query: {e}")
110
+ # finally:
111
+ # self._close()
112
+
113
+ # def fetch_all(self, sql: str) -> List[dict]:
114
+ # """
115
+ # Fetch all results from a query.
116
+ # """
117
+ # return self._execute(sql, fetch_all=True, as_df=False)
118
+
119
+ # def fetch_as_df(self, sql: str) -> pd.DataFrame:
120
+ # """
121
+ # Fetch results as a pandas DataFrame.
122
+ # """
123
+ # return self._execute(sql, fetch_all=True, as_df=True)
124
+
125
+ # def execute_write(self, sql: str, params: Optional[Union[List[tuple], tuple]] = None) -> None:
126
+ # """
127
+ # Execute a write (INSERT, UPDATE, DELETE) operation.
128
+ # """
129
+ # self._execute(sql, params=params, fetch_all=False)
130
+
131
+ # def execute_many(self, sql: str, params: List[tuple]) -> None:
132
+ # """
133
+ # Execute many write operations (batch insert/update/delete).
134
+ # """
135
+ # self._execute(sql, params=params, fetch_all=False)
136
+
137
+ # def call_procedure(self, procedure_name: str, params: Optional[tuple] = None) -> None:
138
+ # """
139
+ # Call a stored procedure.
140
+ # """
141
+ # self._execute(procedure_name, params=params, fetch_all=False, procedure=True)
142
+
143
+ # def __call__(
144
+ # self,
145
+ # sql: str,
146
+ # params: Optional[Union[List[tuple], tuple]] = None,
147
+ # operation_mode: str = "r",
148
+ # as_df: bool = False
149
+ # ) -> Optional[Union[List[dict], pd.DataFrame, None]]:
150
+ # """
151
+ # A unified method for executing different types of operations.
152
+
153
+ # Modes:
154
+ # - 'r': Read query, fetch results.
155
+ # - 'w': Write operation.
156
+ # - 'm': Write many (batch operations).
157
+ # - 'p': Call a stored procedure.
158
+ # """
159
+ # if operation_mode == "r":
160
+ # return self.fetch_as_df(sql) if as_df else self.fetch_all(sql)
161
+ # elif operation_mode == "w":
162
+ # self.execute_write(sql, params=params)
163
+ # elif operation_mode == "m":
164
+ # if not isinstance(params, list):
165
+ # raise ValueError("For batch operations, 'params' must be a list of tuples.")
166
+ # self.execute_many(sql, params=params)
167
+ # elif operation_mode == "p":
168
+ # self.call_procedure(sql, params=params)
169
+ # else:
170
+ # raise ValueError(f"Invalid operation mode: {operation_mode}")
171
+
172
+ # Example Usage:
173
+ # db = Database(host='localhost', port=3306, user='root', password='password', db='testdb')
174
+ # db('SELECT * FROM users', operation_mode='r')
175
+ # db('INSERT INTO users (name, age) VALUES (%s, %s)', params=[('Alice', 30), ('Bob', 25)], operation_mode='m')
176
+
177
+ class MySQLDatabase:
178
+ def __init__(self, config):
179
+ self.config = config
180
+ self.connection = None
181
+ self.connect()
182
+
183
+ def connect(self):
184
+ try:
185
+ self.connection = mysql.connector.connect(**self.config)
186
+ print("Connected to MySQL database")
187
+ except mysql.connector.Error as err:
188
+ print(f"Error: {err}")
189
+
190
+ def close(self):
191
+ if self.connection:
192
+ self.connection.close()
193
+ print("MySQL connection closed")
194
+
195
+ def execute_query(self, query, params=None):
196
+ cursor = self.connection.cursor()
197
+ try:
198
+ if params:
199
+ if isinstance(params, list):
200
+ cursor.executemany(query, params)
201
+ else:
202
+ cursor.execute(query, params)
203
+ else:
204
+ cursor.execute(query)
205
+ self.connection.commit()
206
+ print("Query executed successfully")
207
+ except mysql.connector.Error as err:
208
+ print(f"Error: {err}")
209
+ finally:
210
+ cursor.close()
211
+
212
+ def execute_many(self, query, params_list):
213
+ cursor = self.connection.cursor()
214
+ try:
215
+ cursor.executemany(query, params_list)
216
+ self.connection.commit()
217
+ print("Batch query executed successfully")
218
+ except mysql.connector.Error as err:
219
+ print(f"Error: {err}")
220
+ finally:
221
+ cursor.close()
222
+
223
+ def fetch_query(self, query, params=None,dictionary=False):
224
+ cursor = self.connection.cursor(dictionary=dictionary)
225
+ try:
226
+ if params:
227
+ cursor.execute(query, params)
228
+ else:
229
+ cursor.execute(query)
230
+ result = cursor.fetchall()
231
+ return result
232
+ except mysql.connector.Error as err:
233
+ print(f"Error: {err}")
234
+ finally:
235
+ cursor.close()
236
+
237
+ def call_procedure(self, proc_name, params=None):
238
+ """
239
+ 调用存储过程的方法
240
+ :param proc_name: 存储过程名称
241
+ :param params: 存储过程参数,可以是单个值或元组
242
+ :return: 如果存储过程有返回结果则返回结果集,否则返回None
243
+ """
244
+ cursor = self.connection.cursor(dictionary=True)
245
+ try:
246
+ if params:
247
+ cursor.callproc(proc_name, params if isinstance(params, (list, tuple)) else (params,))
248
+ else:
249
+ cursor.callproc(proc_name)
250
+
251
+ # 获取存储过程的所有结果集
252
+ results = []
253
+ for result in cursor.stored_results():
254
+ results.extend(result.fetchall())
255
+
256
+ self.connection.commit()
257
+ return results if results else None
258
+
259
+ except mysql.connector.Error as err:
260
+ print(f"存储过程调用错误: {err}")
261
+ self.connection.rollback()
262
+ return None
263
+ finally:
264
+ cursor.close()
265
+
266
+ def run_ai_chatbot(self, chat_history_size=5, system_msg="System: You are a helpful AI assistant."):
267
+ try:
268
+ from mysql.ai.genai import MyLLM
269
+ except Exception as e:
270
+ print(f"AI模块加载失败: {e}")
271
+ return
272
+ my_llm = MyLLM(self.connection)
273
+ chat_history = deque(maxlen=chat_history_size)
274
+ while True:
275
+ user_input = input("\nUser: ")
276
+ if user_input.lower() in ("exit", "quit"):
277
+ break
278
+ history = [system_msg] + list(chat_history) + [f"User: {user_input}"]
279
+ prompt = "\n".join(history)
280
+ try:
281
+ response = my_llm.invoke(prompt)
282
+ except Exception as err:
283
+ print(f"AI调用错误: {err}")
284
+ continue
285
+ print(f"Bot: {response}")
286
+ chat_history.append(f"User: {user_input}")
287
+ chat_history.append(f"Bot: {response}")
288
+
289
+ # from wei_office_simptool import SQLManager
290
+ # cfg = {
291
+ # 'user': 'root',
292
+ # 'password': '你的密码',
293
+ # 'host': '127.0.0.1',
294
+ # 'database': 'mlcorpus'
295
+ # }
296
+ # db = SQLManager.MySQLDatabase(cfg)
297
+ # db.run_ai_chatbot(chat_history_size=5, system_msg="System: You are a helpful AI assistant.")
@@ -0,0 +1,101 @@
1
+ """Public package exports for `wei-data-shu`."""
2
+
3
+ from importlib import import_module
4
+ from importlib.metadata import PackageNotFoundError, version
5
+
6
+ try:
7
+ __version__ = version("wei-data-shu")
8
+ except PackageNotFoundError:
9
+ __version__ = "0+unknown"
10
+
11
+ __all__ = [
12
+ "SQLManager",
13
+ "baseColor",
14
+ "chartsManager",
15
+ "excelManager",
16
+ "fileManager",
17
+ "mailManager",
18
+ "ollamaManager",
19
+ "stringManager",
20
+ "textManager",
21
+ "timingTool",
22
+ "database",
23
+ "excel",
24
+ "mail",
25
+ "text",
26
+ "MySQLDatabase",
27
+ "mav_colors",
28
+ "TrendPredictor",
29
+ "MultipleTrendPredictor",
30
+ "TextAnalysis",
31
+ "create_workbook",
32
+ "ExcelManager",
33
+ "ExcelHandler",
34
+ "OpenExcel",
35
+ "ExcelOperation",
36
+ "quick_excel",
37
+ "read_excel_quick",
38
+ "FileManagement",
39
+ "DailyEmailReport",
40
+ "ChatBot",
41
+ "StringBaba",
42
+ "DateFormat",
43
+ "decrypt",
44
+ "eFormat",
45
+ "textCombing",
46
+ "fn_timer",
47
+ "__version__",
48
+ ]
49
+
50
+ _EXPORTS = {
51
+ "SQLManager": ("wei_data_shu.SQLManager", None),
52
+ "baseColor": ("wei_data_shu.baseColor", None),
53
+ "chartsManager": ("wei_data_shu.chartsManager", None),
54
+ "excelManager": ("wei_data_shu.excelManager", None),
55
+ "fileManager": ("wei_data_shu.fileManager", None),
56
+ "mailManager": ("wei_data_shu.mailManager", None),
57
+ "ollamaManager": ("wei_data_shu.ollamaManager", None),
58
+ "stringManager": ("wei_data_shu.stringManager", None),
59
+ "textManager": ("wei_data_shu.textManager", None),
60
+ "timingTool": ("wei_data_shu.timingTool", None),
61
+ "database": ("wei_data_shu.database", None),
62
+ "excel": ("wei_data_shu.excel", None),
63
+ "mail": ("wei_data_shu.mail", None),
64
+ "text": ("wei_data_shu.text", None),
65
+ "MySQLDatabase": ("wei_data_shu.database", "MySQLDatabase"),
66
+ "mav_colors": ("wei_data_shu.baseColor", "mav_colors"),
67
+ "TrendPredictor": ("wei_data_shu.text.forecast", "TrendPredictor"),
68
+ "MultipleTrendPredictor": ("wei_data_shu.text.forecast", "MultipleTrendPredictor"),
69
+ "TextAnalysis": ("wei_data_shu.text.analysis", "TextAnalysis"),
70
+ "create_workbook": ("wei_data_shu.excel", "create_workbook"),
71
+ "ExcelManager": ("wei_data_shu.excel", "ExcelManager"),
72
+ "ExcelHandler": ("wei_data_shu.excel", "ExcelHandler"),
73
+ "OpenExcel": ("wei_data_shu.excel", "OpenExcel"),
74
+ "ExcelOperation": ("wei_data_shu.excel", "ExcelOperation"),
75
+ "quick_excel": ("wei_data_shu.excel", "quick_excel"),
76
+ "read_excel_quick": ("wei_data_shu.excel", "read_excel_quick"),
77
+ "FileManagement": ("wei_data_shu.fileManager", "FileManagement"),
78
+ "DailyEmailReport": ("wei_data_shu.mail", "DailyEmailReport"),
79
+ "ChatBot": ("wei_data_shu.ollamaManager", "ChatBot"),
80
+ "StringBaba": ("wei_data_shu.text", "StringBaba"),
81
+ "DateFormat": ("wei_data_shu.text", "DateFormat"),
82
+ "decrypt": ("wei_data_shu.text", "decrypt"),
83
+ "eFormat": ("wei_data_shu.text", "eFormat"),
84
+ "textCombing": ("wei_data_shu.text", "textCombing"),
85
+ "fn_timer": ("wei_data_shu.timingTool", "fn_timer"),
86
+ }
87
+
88
+
89
+ def __getattr__(name: str):
90
+ target = _EXPORTS.get(name)
91
+ if target is None:
92
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
93
+ module_name, attr_name = target
94
+ module = import_module(module_name)
95
+ if attr_name is None:
96
+ return module
97
+ return getattr(module, attr_name)
98
+
99
+
100
+ def __dir__():
101
+ return sorted(set(globals().keys()) | set(__all__))
@@ -0,0 +1,41 @@
1
+ mav_colors = [
2
+ '#60ACFC', # 靛蓝
3
+ '#32D3EB', # 天蓝
4
+ '#5BC49F', # 薄荷绿
5
+ '#FEB64D', # 橙黄
6
+ '#FF7C7C', # 桃红
7
+ '#9287E7', # 淡紫
8
+ '#FFDD55', # 浅黄
9
+ '#FFAA85', # 浅橙
10
+ '#A8E6CF', # 浅绿
11
+ '#DCE775', # 柠檬黄
12
+ '#FF8A65', # 珊瑚橙
13
+ '#9575CD', # 紫罗兰
14
+ '#81C784', # 草绿色
15
+ '#4DD0E1', # 青蓝
16
+ '#BA68C8', # 浅紫
17
+ '#7986CB', # 灰蓝
18
+ '#4FC3F7', # 宝石蓝
19
+ '#F06292', # 樱花粉
20
+ '#AED581', # 青柠绿
21
+ '#FFD54F', # 金黄
22
+ '#FFAB91', # 桃橙
23
+ '#FBC02D', # 金黄
24
+ '#8D6E63', # 栗色
25
+ '#BDBDBD', # 灰色
26
+ '#FFCDD2', # 淡粉
27
+ '#C5E1A5', # 浅绿
28
+ '#80DEEA', # 浅青
29
+ '#CE93D8', # 薰衣草紫
30
+ '#F48FB1', # 粉红
31
+ '#B39DDB', # 丁香紫
32
+ '#FF7043', # 鲑鱼橙
33
+ '#D4E157', # 柠檬绿
34
+ '#FFEB3B', # 向日葵黄
35
+ '#9575CD', # 淡紫
36
+ '#7986CB', # 薰衣草蓝
37
+ '#E57373', # 玫瑰红
38
+ '#FFF176', # 浅黄
39
+ '#FFB74D', # 杏橙
40
+ '#A1887F' # 浅褐
41
+ ]
@@ -0,0 +1,53 @@
1
+ """Compatibility layer for legacy `chartsManager` imports.
2
+
3
+ Deprecated:
4
+ - wei_data_shu.chartsManager.TrendPredictor -> wei_data_shu.text.forecast.TrendPredictor
5
+ - wei_data_shu.chartsManager.MultipleTrendPredictor -> wei_data_shu.text.forecast.MultipleTrendPredictor
6
+ - wei_data_shu.chartsManager.TextAnalysis -> wei_data_shu.text.analysis.TextAnalysis
7
+ """
8
+
9
+ import warnings
10
+
11
+ from .text.analysis import TextAnalysis as _TextAnalysis
12
+ from .text.forecast import MultipleTrendPredictor as _MultipleTrendPredictor
13
+ from .text.forecast import TrendPredictor as _TrendPredictor
14
+
15
+ warnings.warn(
16
+ "`wei_data_shu.chartsManager` 已弃用,将在后续版本移除。"
17
+ "请改用 `wei_data_shu.text.analysis` 或 `wei_data_shu.text.forecast`.",
18
+ FutureWarning,
19
+ stacklevel=2,
20
+ )
21
+
22
+
23
+ class TrendPredictor(_TrendPredictor):
24
+ def __init__(self, *args, **kwargs):
25
+ warnings.warn(
26
+ "`chartsManager.TrendPredictor` 已弃用,请改用 `wei_data_shu.text.forecast.TrendPredictor`.",
27
+ FutureWarning,
28
+ stacklevel=2,
29
+ )
30
+ super().__init__(*args, **kwargs)
31
+
32
+
33
+ class MultipleTrendPredictor(_MultipleTrendPredictor):
34
+ def __init__(self, *args, **kwargs):
35
+ warnings.warn(
36
+ "`chartsManager.MultipleTrendPredictor` 已弃用,请改用 `wei_data_shu.text.forecast.MultipleTrendPredictor`.",
37
+ FutureWarning,
38
+ stacklevel=2,
39
+ )
40
+ super().__init__(*args, **kwargs)
41
+
42
+
43
+ class TextAnalysis(_TextAnalysis):
44
+ def __init__(self, *args, **kwargs):
45
+ warnings.warn(
46
+ "`chartsManager.TextAnalysis` 已弃用,请改用 `wei_data_shu.text.analysis.TextAnalysis`.",
47
+ FutureWarning,
48
+ stacklevel=2,
49
+ )
50
+ super().__init__(*args, **kwargs)
51
+
52
+
53
+ __all__ = ["TrendPredictor", "MultipleTrendPredictor", "TextAnalysis"]
@@ -0,0 +1,5 @@
1
+ """Database domain exports."""
2
+
3
+ from ..SQLManager import MySQLDatabase
4
+
5
+ __all__ = ["MySQLDatabase"]
@@ -0,0 +1,2 @@
1
+ from .fileManager import FileManagement
2
+ from .excelManager import ExcelHandler, OpenExcel, ExcelOperation, eExcel
@@ -0,0 +1,13 @@
1
+ """Excel domain exports."""
2
+
3
+ from ..excelManager import ExcelHandler, ExcelManager, ExcelOperation, OpenExcel, create_workbook, quick_excel, read_excel_quick
4
+
5
+ __all__ = [
6
+ "create_workbook",
7
+ "ExcelManager",
8
+ "ExcelHandler",
9
+ "OpenExcel",
10
+ "ExcelOperation",
11
+ "quick_excel",
12
+ "read_excel_quick",
13
+ ]