first commit

This commit is contained in:
2026-02-08 14:42:58 +08:00
commit 20e1deae21
8197 changed files with 2264639 additions and 0 deletions

163
sdk/python/README.md Normal file
View File

@@ -0,0 +1,163 @@
# 智能算法展示平台Python SDK
本SDK提供了与智能算法展示平台API交互的Python客户端支持算法调用、仿真数据生成等功能。
## 安装
### 从源码安装
```bash
cd sdk/python
pip install -e .
```
### 从PyPI安装
```bash
pip install algorithm-showcase-sdk
```
## 使用示例
### 1. 初始化客户端
```python
from algorithm_showcase import AlgorithmShowcaseClient
# 初始化客户端
client = AlgorithmShowcaseClient(
base_url="http://localhost:8000/api/v1", # API基础URL
api_key="your-api-key" # 可选API密钥
)
```
### 2. 获取算法列表
```python
# 获取所有算法
algorithms = client.get_algorithms()
# 获取特定类型的算法
algorithms = client.get_algorithms(algorithm_type="computer_vision")
# 打印算法信息
for algo in algorithms:
print(f"算法ID: {algo.id}")
print(f"算法名称: {algo.name}")
print(f"算法描述: {algo.description}")
print(f"算法类型: {algo.type}")
print("---")
```
### 3. 获取算法详情
```python
# 获取算法详情
algorithm = client.get_algorithm(algorithm_id="algorithm-123456")
print(f"算法ID: {algorithm.id}")
print(f"算法名称: {algorithm.name}")
print(f"算法描述: {algorithm.description}")
print(f"算法类型: {algorithm.type}")
print("版本信息:")
for version in algorithm.versions:
print(f" - 版本: {version.version} (默认: {version.is_default})")
print(f" URL: {version.url}")
print(f" 参数: {version.params}")
```
### 4. 调用算法
```python
# 准备输入数据
input_data = {
"text": "这是一段测试文本"
}
# 准备算法参数
params = {
"confidence_threshold": 0.5,
"model_name": "resnet50"
}
# 调用算法
result = client.call_algorithm(
algorithm_id="algorithm-123456",
version_id="version-123456",
input_data=input_data,
params=params
)
print(f"调用ID: {result.id}")
print(f"状态: {result.status}")
print(f"响应时间: {result.response_time} 秒")
print(f"输出数据: {result.output_data}")
```
### 5. 获取调用结果
```python
# 获取调用结果
result = client.get_call_result(call_id="call-123456")
print(f"调用ID: {result.id}")
print(f"状态: {result.status}")
print(f"响应时间: {result.response_time} 秒")
print(f"输出数据: {result.output_data}")
```
### 6. 生成仿真输入数据
```python
# 生成文本数据
text_data = client.generate_simulation_data(
prompt="生成一段关于人工智能的新闻文本",
data_type="text"
)
print(f"生成的文本: {text_data['data']}")
# 生成结构化数据
structured_data = client.generate_simulation_data(
prompt="生成一个包含姓名、年龄、职业的用户信息",
data_type="structured"
)
print(f"生成的结构化数据: {structured_data['data']}")
```
## API文档
### 核心方法
- `get_algorithms(algorithm_type=None)`: 获取算法列表
- `get_algorithm(algorithm_id)`: 获取算法详情
- `get_algorithm_versions(algorithm_id)`: 获取算法版本列表
- `call_algorithm(algorithm_id, version_id, input_data, params=None)`: 调用算法
- `get_call_result(call_id)`: 获取调用结果
- `generate_simulation_data(prompt, data_type="text")`: 生成仿真输入数据
### 数据模型
- `Algorithm`: 算法信息
- `AlgorithmVersion`: 算法版本信息
- `AlgorithmCallRequest`: 算法调用请求
- `AlgorithmCallResult`: 算法调用结果
## 错误处理
SDK会捕获API请求中的错误并抛出异常。建议在使用时添加异常处理
```python
try:
result = client.call_algorithm(...)
except Exception as e:
print(f"调用失败: {e}")
```
## 版本兼容性
- Python 3.7+
- requests 2.31.0+
## 许可证
MIT License

View File

@@ -0,0 +1,14 @@
"""智能算法展示平台Python SDK"""
__version__ = "1.0.0"
from .client import AlgorithmShowcaseClient
from .models import Algorithm, AlgorithmVersion, AlgorithmCallRequest, AlgorithmCallResult
__all__ = [
"AlgorithmShowcaseClient",
"Algorithm",
"AlgorithmVersion",
"AlgorithmCallRequest",
"AlgorithmCallResult"
]

View File

@@ -0,0 +1,276 @@
"""智能算法展示平台客户端"""
import requests
import json
from typing import List, Optional, Dict, Any
from .models import Algorithm, AlgorithmVersion, AlgorithmCallRequest, AlgorithmCallResult
class AlgorithmShowcaseClient:
"""智能算法展示平台客户端类"""
def __init__(self, base_url: str = "http://localhost:8000/api/v1", api_key: Optional[str] = None):
"""初始化客户端
Args:
base_url: API基础URL
api_key: API密钥
"""
self.base_url = base_url.rstrip("/")
self.api_key = api_key
self.session = requests.Session()
# 设置默认请求头
self.session.headers.update({
"Content-Type": "application/json"
})
# 如果提供了API密钥设置认证头
if self.api_key:
self.session.headers.update({
"Authorization": f"Bearer {self.api_key}"
})
def _request(self, method: str, endpoint: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""发送请求
Args:
method: 请求方法
endpoint: 端点
data: 请求数据
Returns:
响应数据
"""
url = f"{self.base_url}/{endpoint}"
try:
if method == "GET":
response = self.session.get(url, params=data)
elif method == "POST":
response = self.session.post(url, json=data)
elif method == "PUT":
response = self.session.put(url, json=data)
elif method == "DELETE":
response = self.session.delete(url, json=data)
else:
raise ValueError(f"Unsupported method: {method}")
# 检查响应状态
response.raise_for_status()
# 返回响应数据
return response.json()
except requests.RequestException as e:
raise Exception(f"API request failed: {e}")
def get_algorithms(self, algorithm_type: Optional[str] = None) -> List[Algorithm]:
"""获取算法列表
Args:
algorithm_type: 算法类型
Returns:
算法列表
"""
params = {}
if algorithm_type:
params["type"] = algorithm_type
response = self._request("GET", "algorithms", params)
algorithms = []
for algo_data in response.get("algorithms", []):
algorithm = Algorithm(**algo_data)
algorithms.append(algorithm)
return algorithms
def get_algorithm(self, algorithm_id: str) -> Algorithm:
"""获取算法详情
Args:
algorithm_id: 算法ID
Returns:
算法详情
"""
response = self._request("GET", f"algorithms/{algorithm_id}")
return Algorithm(**response)
def get_algorithm_versions(self, algorithm_id: str) -> List[AlgorithmVersion]:
"""获取算法版本列表
Args:
algorithm_id: 算法ID
Returns:
版本列表
"""
response = self._request("GET", f"algorithms/{algorithm_id}/versions")
versions = []
for version_data in response:
version = AlgorithmVersion(**version_data)
versions.append(version)
return versions
def call_algorithm(self, algorithm_id: str, version_id: str, input_data: Dict[str, Any], params: Optional[Dict[str, Any]] = None) -> AlgorithmCallResult:
"""调用算法
Args:
algorithm_id: 算法ID
version_id: 版本ID
input_data: 输入数据
params: 算法参数
Returns:
调用结果
"""
request_data = AlgorithmCallRequest(
algorithm_id=algorithm_id,
version_id=version_id,
input_data=input_data,
params=params or {}
)
response = self._request("POST", "algorithms/call", request_data.dict())
return AlgorithmCallResult(**response)
def get_call_result(self, call_id: str) -> AlgorithmCallResult:
"""获取调用结果
Args:
call_id: 调用ID
Returns:
调用结果
"""
response = self._request("GET", f"algorithms/calls/{call_id}")
return AlgorithmCallResult(**response)
def generate_simulation_data(self, prompt: str, data_type: str = "text") -> Dict[str, Any]:
"""生成仿真输入数据
Args:
prompt: 描述
data_type: 数据类型
Returns:
生成的数据
"""
response = self._request("POST", "openai/generate-data", {
"prompt": prompt,
"data_type": data_type
})
return response
def get_call_history(self, algorithm_id: Optional[str] = None, status: Optional[str] = None,
start_date: Optional[str] = None, end_date: Optional[str] = None) -> List[AlgorithmCallResult]:
"""获取调用历史
Args:
algorithm_id: 算法ID
status: 调用状态
start_date: 开始日期
end_date: 结束日期
Returns:
调用历史列表
"""
params = {}
if algorithm_id:
params["algorithm_id"] = algorithm_id
if status:
params["status"] = status
if start_date:
params["start_date"] = start_date
if end_date:
params["end_date"] = end_date
response = self._request("GET", "history/user-calls", params)
history = []
for call_data in response.get("history", []):
call_result = AlgorithmCallResult(**call_data)
history.append(call_result)
return history
def get_call_statistics(self, algorithm_id: Optional[str] = None) -> Dict[str, Any]:
"""获取调用统计
Args:
algorithm_id: 算法ID
Returns:
统计信息
"""
params = {}
if algorithm_id:
params["algorithm_id"] = algorithm_id
response = self._request("GET", "history/statistics", params)
return response
def export_history(self, algorithm_id: Optional[str] = None, start_date: Optional[str] = None,
end_date: Optional[str] = None, format_type: str = "json") -> Dict[str, Any]:
"""导出历史记录
Args:
algorithm_id: 算法ID
start_date: 开始日期
end_date: 结束日期
format_type: 导出格式
Returns:
导出结果
"""
params = {
"format_type": format_type
}
if algorithm_id:
params["algorithm_id"] = algorithm_id
if start_date:
params["start_date"] = start_date
if end_date:
params["end_date"] = end_date
response = self._request("GET", "history/export", params)
return response
def get_algorithm_performance(self, algorithm_id: str, days: int = 7) -> Dict[str, Any]:
"""获取算法性能指标
Args:
algorithm_id: 算法ID
days: 统计天数
Returns:
性能指标
"""
response = self._request("GET", f"monitoring/performance/algorithm/{algorithm_id}", {"days": days})
return response
def get_system_health(self) -> Dict[str, Any]:
"""获取系统健康状况
Returns:
系统健康状况
"""
response = self._request("GET", "monitoring/health")
return response
def check_permission(self, algorithm_id: str, permission_type: str = "execute") -> bool:
"""检查权限
Args:
algorithm_id: 算法ID
permission_type: 权限类型
Returns:
是否有权限
"""
response = self._request("POST", "permissions/check", {
"algorithm_id": algorithm_id,
"permission_type": permission_type
})
return response.get("has_permission", False)

View File

@@ -0,0 +1,58 @@
"""智能算法展示平台数据模型"""
from typing import List, Optional, Dict, Any
from dataclasses import dataclass
@dataclass
class AlgorithmVersion:
"""算法版本"""
id: str
algorithm_id: str
version: str
url: str
params: Dict[str, Any]
input_schema: Dict[str, Any]
output_schema: Dict[str, Any]
is_default: bool
created_at: str
updated_at: str
@dataclass
class Algorithm:
"""算法"""
id: str
name: str
description: str
type: str
status: str
versions: List[AlgorithmVersion]
created_at: str
updated_at: str
@dataclass
class AlgorithmCallRequest:
"""算法调用请求"""
algorithm_id: str
version_id: str
input_data: Dict[str, Any]
params: Dict[str, Any]
@dataclass
class AlgorithmCallResult:
"""算法调用结果"""
id: str
user_id: str
algorithm_id: str
version_id: str
input_data: Dict[str, Any]
params: Dict[str, Any]
output_data: Dict[str, Any]
status: str
response_time: float
error_message: Optional[str]
created_at: str
updated_at: str

27
sdk/python/setup.py Normal file
View File

@@ -0,0 +1,27 @@
"""智能算法展示平台Python SDK安装配置"""
from setuptools import setup, find_packages
with open("README.md", "r", encoding="utf-8") as f:
long_description = f.read()
setup(
name="algorithm-showcase-sdk",
version="1.0.0",
description="智能算法展示平台Python SDK",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/algorithm-showcase/sdk",
author="Algorithm Showcase Team",
author_email="team@algorithm-showcase.com",
packages=find_packages(),
install_requires=[
"requests>=2.31.0"
],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires=">=3.7",
)