sycommon-python-lib 0.1.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.

Potentially problematic release.


This version of sycommon-python-lib might be problematic. Click here for more details.

sycommon/__init__.py ADDED
File without changes
@@ -0,0 +1,73 @@
1
+ import yaml
2
+
3
+
4
+ class SingletonMeta(type):
5
+ _instances = {}
6
+
7
+ def __call__(cls, *args, **kwargs):
8
+ if cls not in cls._instances:
9
+ cls._instances[cls] = super().__call__(*args, **kwargs)
10
+ return cls._instances[cls]
11
+
12
+
13
+ class Config(metaclass=SingletonMeta):
14
+ def __init__(self, config_file='app.yaml'):
15
+ with open(config_file, 'r') as f:
16
+ self.config = yaml.safe_load(f)
17
+ self.MaxBytes = self.config.get('MaxBytes', 209715200)
18
+ self.Timeout = self.config.get('Timeout', 300000)
19
+ self.OCR = self.config.get('OCR', None)
20
+ self.INVOICE_OCR = self.config.get('INVOICE_OCR', None)
21
+ self.UnstructuredAPI = self.config.get('UnstructuredAPI', None)
22
+ self.MaxRetries = self.config.get('MaxRetries', 3)
23
+ self.llm_configs = []
24
+ self.embedding_configs = []
25
+ self.reranker_configs = []
26
+ self._process_config()
27
+
28
+ def get_llm_config(self, model_name):
29
+ for llm in self.llm_configs:
30
+ if llm.get('model') == model_name:
31
+ return llm
32
+ raise ValueError(f"No configuration found for model: {model_name}")
33
+
34
+ def get_embedding_config(self, model_name):
35
+ for llm in self.embedding_configs:
36
+ if llm.get('model') == model_name:
37
+ return llm
38
+ raise ValueError(f"No configuration found for model: {model_name}")
39
+
40
+ def get_reranker_config(self, model_name):
41
+ for llm in self.reranker_configs:
42
+ if llm.get('model') == model_name:
43
+ return llm
44
+ raise ValueError(f"No configuration found for model: {model_name}")
45
+
46
+ def _process_config(self):
47
+ llm_config_list = self.config.get('LLMConfig', [])
48
+ for llm_config in llm_config_list:
49
+ try:
50
+ # 延迟导入 LLMConfigModel
51
+ from sycommon.config.LLMConfig import LLMConfig
52
+ validated_config = LLMConfig(**llm_config)
53
+ self.llm_configs.append(validated_config.model_dump())
54
+ except ValueError as e:
55
+ print(f"Invalid LLM configuration: {e}")
56
+
57
+ embedding_config_list = self.config.get('EmbeddingConfig', [])
58
+ for embedding_config in embedding_config_list:
59
+ try:
60
+ from sycommon.config.EmbeddingConfig import EmbeddingConfig
61
+ validated_config = EmbeddingConfig(**embedding_config)
62
+ self.embedding_configs.append(validated_config.model_dump())
63
+ except ValueError as e:
64
+ print(f"Invalid LLM configuration: {e}")
65
+
66
+ reranker_config_list = self.config.get('RerankerConfig', [])
67
+ for reranker_config in reranker_config_list:
68
+ try:
69
+ from sycommon.config.RerankerConfig import RerankerConfig
70
+ validated_config = RerankerConfig(**reranker_config)
71
+ self.reranker_configs.append(validated_config.model_dump())
72
+ except ValueError as e:
73
+ print(f"Invalid LLM configuration: {e}")
@@ -0,0 +1,34 @@
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class HikariConfig(BaseModel):
5
+ minimum_idle: int
6
+ maximum_pool_size: int
7
+ idle_timeout: int
8
+
9
+
10
+ class DatabaseConfig(BaseModel):
11
+ url: str
12
+ username: str
13
+ password: str
14
+ driver_class_name: str
15
+ time_between_eviction_runs_millis: int
16
+ min_evictable_idle_time_millis: int
17
+ validation_query: str
18
+ test_while_idle: bool
19
+ test_on_borrow: bool
20
+ test_on_return: bool
21
+ hikari: HikariConfig
22
+
23
+
24
+ def convert_key_to_snake_case(key):
25
+ import re
26
+ # 处理驼峰命名转换为下划线命名
27
+ key = re.sub(r'(?<!^)(?=[A-Z])', '_', key).lower()
28
+ return key.replace('-', '_')
29
+
30
+
31
+ def convert_dict_keys(d):
32
+ if isinstance(d, dict):
33
+ return {convert_key_to_snake_case(k): convert_dict_keys(v) for k, v in d.items()}
34
+ return d
@@ -0,0 +1,16 @@
1
+
2
+ from pydantic import BaseModel
3
+
4
+
5
+ class EmbeddingConfig(BaseModel):
6
+ model: str
7
+ provider: str
8
+ baseUrl: str
9
+ maxTokens: int
10
+ dimension: int
11
+
12
+ @classmethod
13
+ def from_config(cls, model_name: str):
14
+ from sycommon.config.Config import Config
15
+ llm_config = Config().get_embedding_config(model_name)
16
+ return cls(**llm_config)
@@ -0,0 +1,16 @@
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class LLMConfig(BaseModel):
5
+ model: str
6
+ provider: str
7
+ baseUrl: str
8
+ maxTokens: int
9
+ vision: bool
10
+ callFunction: bool
11
+
12
+ @classmethod
13
+ def from_config(cls, model_name: str):
14
+ from sycommon.config.Config import Config
15
+ llm_config = Config().get_llm_config(model_name)
16
+ return cls(**llm_config)
@@ -0,0 +1,13 @@
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class RerankerConfig(BaseModel):
5
+ model: str
6
+ provider: str
7
+ baseUrl: str
8
+
9
+ @classmethod
10
+ def from_config(cls, model_name: str):
11
+ from sycommon.config.Config import Config
12
+ llm_config = Config().get_reranker_config(model_name)
13
+ return cls(**llm_config)
File without changes
@@ -0,0 +1,79 @@
1
+ from sqlalchemy import create_engine, text
2
+
3
+ from sycommon.config.Config import SingletonMeta
4
+ from sycommon.config.DatabaseConfig import DatabaseConfig, convert_dict_keys
5
+ from sycommon.logging.kafka_log import SYLogger
6
+ from sycommon.synacos.nacos_service import NacosService
7
+
8
+
9
+ class DatabaseService(metaclass=SingletonMeta):
10
+ _engine = None
11
+
12
+ @staticmethod
13
+ def setup_database(config: dict, shareConfigKey: str):
14
+ common = NacosService(config).share_configs.get(shareConfigKey, {})
15
+ if common and common.get('spring', {}).get('datasource', None):
16
+ databaseConfig = common.get('spring', {}).get('datasource', None)
17
+ converted_dict = convert_dict_keys(databaseConfig)
18
+ db_config = DatabaseConfig.model_validate(converted_dict)
19
+ DatabaseService._engine = DatabaseConnector(db_config).engine
20
+
21
+ @staticmethod
22
+ def engine():
23
+ return DatabaseService._engine
24
+
25
+
26
+ class DatabaseConnector(metaclass=SingletonMeta):
27
+ def __init__(self, db_config: DatabaseConfig):
28
+ # 从 DatabaseConfig 中提取数据库连接信息
29
+ self.db_user = db_config.username
30
+ self.db_password = db_config.password
31
+ # 提取 URL 中的主机、端口和数据库名
32
+ url_parts = db_config.url.split('//')[1].split('/')
33
+ host_port = url_parts[0].split(':')
34
+ self.db_host = host_port[0]
35
+ self.db_port = host_port[1]
36
+ self.db_name = url_parts[1].split('?')[0]
37
+
38
+ # 提取 URL 中的参数
39
+ params_str = url_parts[1].split('?')[1] if len(
40
+ url_parts[1].split('?')) > 1 else ''
41
+ params = {}
42
+ for param in params_str.split('&'):
43
+ if param:
44
+ key, value = param.split('=')
45
+ params[key] = value
46
+
47
+ # 在params中去掉指定的参数
48
+ for key in ['useUnicode', 'characterEncoding', 'serverTimezone', 'zeroDateTimeBehavior']:
49
+ if key in params:
50
+ del params[key]
51
+
52
+ # 构建数据库连接 URL
53
+ self.db_url = f'mysql+mysqlconnector://{self.db_user}:{self.db_password}@{self.db_host}:{self.db_port}/{self.db_name}'
54
+
55
+ SYLogger.info(f"Database URL: {self.db_url}")
56
+
57
+ # 优化连接池配置
58
+ self.engine = create_engine(
59
+ self.db_url,
60
+ connect_args=params,
61
+ pool_size=10, # 连接池大小
62
+ max_overflow=20, # 最大溢出连接数
63
+ pool_timeout=30, # 连接超时时间(秒)
64
+ pool_recycle=3600, # 连接回收时间(秒)
65
+ pool_pre_ping=True # 每次获取连接前检查连接是否有效
66
+ )
67
+
68
+ # 测试
69
+ if not self.test_connection():
70
+ raise Exception("Database connection test failed")
71
+
72
+ def test_connection(self):
73
+ try:
74
+ with self.engine.connect() as connection:
75
+ connection.execute(text("SELECT 1"))
76
+ return True
77
+ except Exception as e:
78
+ SYLogger.error(f"Database connection test failed: {e}")
79
+ return False
File without changes
@@ -0,0 +1,17 @@
1
+ from fastapi import FastAPI, APIRouter
2
+
3
+
4
+ def setup_health_handler(app: FastAPI):
5
+ health_router = APIRouter()
6
+
7
+ @health_router.get("/actuator/health")
8
+ async def health_check():
9
+ """返回应用的健康状态"""
10
+ return {
11
+ "status": "UP",
12
+ "groups": ["liveness", "readiness"]
13
+ }
14
+
15
+ app.include_router(health_router)
16
+
17
+ return app
@@ -0,0 +1,13 @@
1
+ from fastapi import FastAPI, APIRouter
2
+
3
+
4
+ def setup_ping_handler(app: FastAPI):
5
+ ping_router = APIRouter()
6
+
7
+ @ping_router.get("/ping")
8
+ async def ping():
9
+ return {"status": "alive"}
10
+
11
+ app.include_router(ping_router)
12
+
13
+ return app
File without changes