lasvsim-openapi 0.1.11__tar.gz

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 (25) hide show
  1. lasvsim-openapi-0.1.11/PKG-INFO +172 -0
  2. lasvsim-openapi-0.1.11/README.md +149 -0
  3. lasvsim-openapi-0.1.11/lasvsim_openapi/__init__.py +2 -0
  4. lasvsim-openapi-0.1.11/lasvsim_openapi/client.py +66 -0
  5. lasvsim-openapi-0.1.11/lasvsim_openapi/http_client.py +170 -0
  6. lasvsim-openapi-0.1.11/lasvsim_openapi/process_task.py +89 -0
  7. lasvsim-openapi-0.1.11/lasvsim_openapi/process_task_model.py +107 -0
  8. lasvsim-openapi-0.1.11/lasvsim_openapi/qxmap.py +980 -0
  9. lasvsim-openapi-0.1.11/lasvsim_openapi/qxmap_model.py +3 -0
  10. lasvsim-openapi-0.1.11/lasvsim_openapi/request_model.py +3 -0
  11. lasvsim-openapi-0.1.11/lasvsim_openapi/resources.py +74 -0
  12. lasvsim-openapi-0.1.11/lasvsim_openapi/response_model.py +4 -0
  13. lasvsim-openapi-0.1.11/lasvsim_openapi/sim_record.py +147 -0
  14. lasvsim-openapi-0.1.11/lasvsim_openapi/sim_record_model.py +513 -0
  15. lasvsim-openapi-0.1.11/lasvsim_openapi/simulator.py +897 -0
  16. lasvsim-openapi-0.1.11/lasvsim_openapi/simulator_model.py +1940 -0
  17. lasvsim-openapi-0.1.11/lasvsim_openapi/train_task.py +37 -0
  18. lasvsim-openapi-0.1.11/lasvsim_openapi/train_task_model.py +39 -0
  19. lasvsim-openapi-0.1.11/lasvsim_openapi.egg-info/PKG-INFO +172 -0
  20. lasvsim-openapi-0.1.11/lasvsim_openapi.egg-info/SOURCES.txt +23 -0
  21. lasvsim-openapi-0.1.11/lasvsim_openapi.egg-info/dependency_links.txt +1 -0
  22. lasvsim-openapi-0.1.11/lasvsim_openapi.egg-info/requires.txt +1 -0
  23. lasvsim-openapi-0.1.11/lasvsim_openapi.egg-info/top_level.txt +1 -0
  24. lasvsim-openapi-0.1.11/setup.cfg +4 -0
  25. lasvsim-openapi-0.1.11/setup.py +48 -0
@@ -0,0 +1,172 @@
1
+ Metadata-Version: 2.1
2
+ Name: lasvsim-openapi
3
+ Version: 0.1.11
4
+ Summary: Lasvsim OpenAPI SDK for Python - A client library for accessing Lasvsim's simulation platform
5
+ Home-page: https://github.com/rl-lasvsim/openapi-sdk-python
6
+ Author: Zhihong Luo
7
+ Author-email: luozhihong@risenlighten.com
8
+ Project-URL: Source, https://github.com/rl-lasvsim/openapi-sdk-python
9
+ Project-URL: Bug Reports, https://github.com/rl-lasvsim/openapi-sdk-python/issues
10
+ Keywords: Qianxing,Lasvsim,自动驾驶,OpenAPI,Simulation,Autonomous Driving
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.7
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.0
21
+ Description-Content-Type: text/markdown
22
+ Requires-Dist: requests>=2.25.0
23
+
24
+ # Lasvsim OpenAPI SDK for Python
25
+
26
+ 千行仿真平台(Lasvsim)的 Python SDK。提供了一种简单直观的方式来控制和获取自动驾驶场景的仿真。
27
+
28
+ ## 安装
29
+
30
+ 您可以直接从PyPI安装该软件包:
31
+
32
+ ```bash
33
+ pip install lasvsim-openapi
34
+ ```
35
+
36
+ ## 快速开始
37
+
38
+ 以下是 SDK 使用的简单示例:
39
+
40
+ ```python
41
+ import os
42
+
43
+ from lasvsim_openapi.client import Client
44
+ from lasvsim_openapi.http_client import HttpConfig
45
+ from lasvsim_openapi.simulator import SimulatorConfig
46
+
47
+ # 接口地址
48
+ endpoint = os.getenv("QX_ENDPOINT") # 线上环境地址: https://qianxing-api.risenlighten.com
49
+ # 授权token
50
+ token = os.getenv("QX_TOKEN") # 登录仿真平台后访问https://qianxing.risenlighten.com/#/usecenter/personalCenter, 点击最下面按钮复制token
51
+
52
+ # 登录仿真平台, 选择想要进行联合仿真的任务及剧本
53
+ task_id = 0 # 替换为你的任务ID
54
+ record_id = 0 # 替换为你的剧本ID
55
+
56
+ # 1. 初始化客户端
57
+ cli = Client(HttpConfig(
58
+ endpoint=endpoint, # 接口地址
59
+ token=token, # 授权token
60
+ ))
61
+
62
+ # 2. 拷贝剧本, 返回的结构中new_record_id字段就是新创建的剧本ID
63
+ # 仿真结束后可到该剧本下查看结果详情
64
+ new_record = cli.process_task.copy_record(task_id, record_id)
65
+ print("拷贝剧本成功")
66
+
67
+ # 3. 通过拷贝的场景Id、Version和SimRecordId初始化仿真器
68
+ simulator = cli.init_simulator_from_config({
69
+ "scen_id": new_record.scen_id,
70
+ "scen_ver": new_record.scen_ver,
71
+ "sim_record_id": new_record.sim_record_id,
72
+ })
73
+ print("初始化仿真器成功")
74
+
75
+ try:
76
+ # 获取测试车辆列表
77
+ test_vehicle_list = simulator.get_test_vehicle_id_list()
78
+ print("测试车辆ID列表:", test_vehicle_list)
79
+
80
+ # 使测试车辆环形行驶
81
+ for i in range(50):
82
+ # 设置方向盘转角10度, 纵向加速度0.05
83
+ ste_wheel = 10.0
84
+ lon_acc = 0.05
85
+ # 设置车辆的控制信息
86
+ simulator.set_vehicle_control_info(test_vehicle_list.list[0], ste_wheel, lon_acc)
87
+
88
+ # 执行仿真器步骤
89
+ step_res = simulator.step()
90
+ print(f"第 {i} 步结果: {step_res}")
91
+
92
+ # 可在此处继续调用其他接口, 查看联合仿真文档: https://www.risenlighten.com/#/union
93
+
94
+ # 仿真结束后, 到千行仿真平台对应的taskId/recordId下查看联合仿真结果详情
95
+ print(f"https://qianxing.risenlighten.com/#/configuration/circleTask?id={task_id}")
96
+
97
+ # 如想直接查看本次联合仿真的回放视频, 可访问下面网址:
98
+ print(f"https://qianxing.risenlighten.com/#/sampleRoad/cartest/?id={task_id}&record_id={new_record.new_record_id}&sim_record_id={new_record.sim_record_id}")
99
+
100
+ finally:
101
+ # 停止仿真器, 释放服务器资源
102
+ simulator.stop()
103
+ ```
104
+
105
+ ## 可用API
106
+
107
+ ### 仿真器API
108
+
109
+ #### 仿真控制
110
+ - `init_simulator_from_config(sim_config)`: 从配置初始化仿真器
111
+ - `init_simulator_from_sim(simulation_id, addr)`: 从现有仿真初始化仿真器
112
+ - `step()`: 仿真前进一步
113
+ - `stop()`: 停止仿真
114
+ - `reset(reset_traffic_flow)`: 重置仿真器到初始状态,可选择是否重置交通流
115
+
116
+ #### 车辆API
117
+ - `get_vehicle_id_list()`: 获取所有车辆ID
118
+ - `get_test_vehicle_id_list()`: 获取测试车辆ID
119
+ - `get_vehicle_base_info(id_list)`: 获取车辆基本信息
120
+ - `get_vehicle_position(id_list)`: 获取车辆位置
121
+ - `get_vehicle_moving_info(id_list)`: 获取车辆运动信息
122
+ - `get_vehicle_control_info(id_list)`: 获取车辆控制参数
123
+ - `get_vehicle_perception_info(vehicle_id)`: 获取车辆感知信息
124
+ - `get_vehicle_reference_lines(vehicle_id)`: 获取可用参考线
125
+ - `get_vehicle_planning_info(vehicle_id)`: 获取车辆规划信息
126
+ - `get_vehicle_navigation_info(vehicle_id)`: 获取车辆导航信息
127
+ - `get_vehicle_collision_status(vehicle_id)`: 检查车辆碰撞状态
128
+ - `get_vehicle_target_speed(vehicle_id)`: 获取车辆目标速度
129
+ - `set_vehicle_position(vehicle_id, point, phi)`: 设置车辆位置和航向角
130
+ - `set_vehicle_control_info(vehicle_id, ste_wheel, lon_acc)`: 设置车辆控制参数
131
+ - `set_vehicle_planning_info(vehicle_id, planning_path)`: 设置车辆规划路径
132
+ - `set_vehicle_moving_info(vehicle_id, u, v, w, u_acc, v_acc, w_acc)`: 设置车辆运动参数
133
+ - `set_vehicle_base_info(vehicle_id, base_info)`: 设置车辆基本信息
134
+
135
+ #### 交通流API
136
+ - `get_traffic_flow_info()`: 获取交通流信息
137
+ - `get_traffic_flow_vehicle_info(vehicle_id)`: 获取交通流车辆信息
138
+ - `get_traffic_flow_vehicle_list()`: 获取交通流车辆列表
139
+ - `get_traffic_flow_vehicle_position(vehicle_id)`: 获取交通流车辆位置
140
+ - `get_traffic_flow_vehicle_moving_info(vehicle_id)`: 获取交通流车辆运动信息
141
+ - `get_traffic_flow_vehicle_control_info(vehicle_id)`: 获取交通流车辆控制信息
142
+
143
+ #### 场景API
144
+ - `get_scene_info()`: 获取场景信息
145
+ - `get_scene_objects()`: 获取场景物体列表
146
+ - `get_scene_object_info(object_id)`: 获取场景物体信息
147
+ - `get_scene_object_position(object_id)`: 获取场景物体位置
148
+ - `get_scene_object_moving_info(object_id)`: 获取场景物体运动信息
149
+ - `get_scene_object_control_info(object_id)`: 获取场景物体控制信息
150
+
151
+ #### 路网API
152
+ - `get_lane_info(lane_id)`: 获取车道信息
153
+ - `get_lane_list()`: 获取车道列表
154
+ - `get_lane_center_line(lane_id)`: 获取车道中心线
155
+ - `get_lane_boundary(lane_id)`: 获取车道边界
156
+ - `get_lane_width(lane_id)`: 获取车道宽度
157
+ - `get_lane_speed_limit(lane_id)`: 获取车道限速
158
+ - `get_lane_type(lane_id)`: 获取车道类型
159
+ - `get_lane_direction(lane_id)`: 获取车道方向
160
+ - `get_lane_predecessor(lane_id)`: 获取前序车道
161
+ - `get_lane_successor(lane_id)`: 获取后继车道
162
+
163
+ #### 路口API
164
+ - `get_junction_info(junction_id)`: 获取路口信息
165
+ - `get_junction_list()`: 获取路口列表
166
+ - `get_junction_center_point(junction_id)`: 获取路口中心点
167
+ - `get_junction_boundary(junction_id)`: 获取路口边界
168
+ - `get_junction_type(junction_id)`: 获取路口类型
169
+ - `get_junction_direction(junction_id)`: 获取路口方向
170
+ - `get_junction_predecessor(junction_id)`: 获取前序路口
171
+ - `get_junction_successor(junction_id)`: 获取后继路口
172
+ - `get_movement_list(junction_id)`: 获取移动列表
@@ -0,0 +1,149 @@
1
+ # Lasvsim OpenAPI SDK for Python
2
+
3
+ 千行仿真平台(Lasvsim)的 Python SDK。提供了一种简单直观的方式来控制和获取自动驾驶场景的仿真。
4
+
5
+ ## 安装
6
+
7
+ 您可以直接从PyPI安装该软件包:
8
+
9
+ ```bash
10
+ pip install lasvsim-openapi
11
+ ```
12
+
13
+ ## 快速开始
14
+
15
+ 以下是 SDK 使用的简单示例:
16
+
17
+ ```python
18
+ import os
19
+
20
+ from lasvsim_openapi.client import Client
21
+ from lasvsim_openapi.http_client import HttpConfig
22
+ from lasvsim_openapi.simulator import SimulatorConfig
23
+
24
+ # 接口地址
25
+ endpoint = os.getenv("QX_ENDPOINT") # 线上环境地址: https://qianxing-api.risenlighten.com
26
+ # 授权token
27
+ token = os.getenv("QX_TOKEN") # 登录仿真平台后访问https://qianxing.risenlighten.com/#/usecenter/personalCenter, 点击最下面按钮复制token
28
+
29
+ # 登录仿真平台, 选择想要进行联合仿真的任务及剧本
30
+ task_id = 0 # 替换为你的任务ID
31
+ record_id = 0 # 替换为你的剧本ID
32
+
33
+ # 1. 初始化客户端
34
+ cli = Client(HttpConfig(
35
+ endpoint=endpoint, # 接口地址
36
+ token=token, # 授权token
37
+ ))
38
+
39
+ # 2. 拷贝剧本, 返回的结构中new_record_id字段就是新创建的剧本ID
40
+ # 仿真结束后可到该剧本下查看结果详情
41
+ new_record = cli.process_task.copy_record(task_id, record_id)
42
+ print("拷贝剧本成功")
43
+
44
+ # 3. 通过拷贝的场景Id、Version和SimRecordId初始化仿真器
45
+ simulator = cli.init_simulator_from_config({
46
+ "scen_id": new_record.scen_id,
47
+ "scen_ver": new_record.scen_ver,
48
+ "sim_record_id": new_record.sim_record_id,
49
+ })
50
+ print("初始化仿真器成功")
51
+
52
+ try:
53
+ # 获取测试车辆列表
54
+ test_vehicle_list = simulator.get_test_vehicle_id_list()
55
+ print("测试车辆ID列表:", test_vehicle_list)
56
+
57
+ # 使测试车辆环形行驶
58
+ for i in range(50):
59
+ # 设置方向盘转角10度, 纵向加速度0.05
60
+ ste_wheel = 10.0
61
+ lon_acc = 0.05
62
+ # 设置车辆的控制信息
63
+ simulator.set_vehicle_control_info(test_vehicle_list.list[0], ste_wheel, lon_acc)
64
+
65
+ # 执行仿真器步骤
66
+ step_res = simulator.step()
67
+ print(f"第 {i} 步结果: {step_res}")
68
+
69
+ # 可在此处继续调用其他接口, 查看联合仿真文档: https://www.risenlighten.com/#/union
70
+
71
+ # 仿真结束后, 到千行仿真平台对应的taskId/recordId下查看联合仿真结果详情
72
+ print(f"https://qianxing.risenlighten.com/#/configuration/circleTask?id={task_id}")
73
+
74
+ # 如想直接查看本次联合仿真的回放视频, 可访问下面网址:
75
+ print(f"https://qianxing.risenlighten.com/#/sampleRoad/cartest/?id={task_id}&record_id={new_record.new_record_id}&sim_record_id={new_record.sim_record_id}")
76
+
77
+ finally:
78
+ # 停止仿真器, 释放服务器资源
79
+ simulator.stop()
80
+ ```
81
+
82
+ ## 可用API
83
+
84
+ ### 仿真器API
85
+
86
+ #### 仿真控制
87
+ - `init_simulator_from_config(sim_config)`: 从配置初始化仿真器
88
+ - `init_simulator_from_sim(simulation_id, addr)`: 从现有仿真初始化仿真器
89
+ - `step()`: 仿真前进一步
90
+ - `stop()`: 停止仿真
91
+ - `reset(reset_traffic_flow)`: 重置仿真器到初始状态,可选择是否重置交通流
92
+
93
+ #### 车辆API
94
+ - `get_vehicle_id_list()`: 获取所有车辆ID
95
+ - `get_test_vehicle_id_list()`: 获取测试车辆ID
96
+ - `get_vehicle_base_info(id_list)`: 获取车辆基本信息
97
+ - `get_vehicle_position(id_list)`: 获取车辆位置
98
+ - `get_vehicle_moving_info(id_list)`: 获取车辆运动信息
99
+ - `get_vehicle_control_info(id_list)`: 获取车辆控制参数
100
+ - `get_vehicle_perception_info(vehicle_id)`: 获取车辆感知信息
101
+ - `get_vehicle_reference_lines(vehicle_id)`: 获取可用参考线
102
+ - `get_vehicle_planning_info(vehicle_id)`: 获取车辆规划信息
103
+ - `get_vehicle_navigation_info(vehicle_id)`: 获取车辆导航信息
104
+ - `get_vehicle_collision_status(vehicle_id)`: 检查车辆碰撞状态
105
+ - `get_vehicle_target_speed(vehicle_id)`: 获取车辆目标速度
106
+ - `set_vehicle_position(vehicle_id, point, phi)`: 设置车辆位置和航向角
107
+ - `set_vehicle_control_info(vehicle_id, ste_wheel, lon_acc)`: 设置车辆控制参数
108
+ - `set_vehicle_planning_info(vehicle_id, planning_path)`: 设置车辆规划路径
109
+ - `set_vehicle_moving_info(vehicle_id, u, v, w, u_acc, v_acc, w_acc)`: 设置车辆运动参数
110
+ - `set_vehicle_base_info(vehicle_id, base_info)`: 设置车辆基本信息
111
+
112
+ #### 交通流API
113
+ - `get_traffic_flow_info()`: 获取交通流信息
114
+ - `get_traffic_flow_vehicle_info(vehicle_id)`: 获取交通流车辆信息
115
+ - `get_traffic_flow_vehicle_list()`: 获取交通流车辆列表
116
+ - `get_traffic_flow_vehicle_position(vehicle_id)`: 获取交通流车辆位置
117
+ - `get_traffic_flow_vehicle_moving_info(vehicle_id)`: 获取交通流车辆运动信息
118
+ - `get_traffic_flow_vehicle_control_info(vehicle_id)`: 获取交通流车辆控制信息
119
+
120
+ #### 场景API
121
+ - `get_scene_info()`: 获取场景信息
122
+ - `get_scene_objects()`: 获取场景物体列表
123
+ - `get_scene_object_info(object_id)`: 获取场景物体信息
124
+ - `get_scene_object_position(object_id)`: 获取场景物体位置
125
+ - `get_scene_object_moving_info(object_id)`: 获取场景物体运动信息
126
+ - `get_scene_object_control_info(object_id)`: 获取场景物体控制信息
127
+
128
+ #### 路网API
129
+ - `get_lane_info(lane_id)`: 获取车道信息
130
+ - `get_lane_list()`: 获取车道列表
131
+ - `get_lane_center_line(lane_id)`: 获取车道中心线
132
+ - `get_lane_boundary(lane_id)`: 获取车道边界
133
+ - `get_lane_width(lane_id)`: 获取车道宽度
134
+ - `get_lane_speed_limit(lane_id)`: 获取车道限速
135
+ - `get_lane_type(lane_id)`: 获取车道类型
136
+ - `get_lane_direction(lane_id)`: 获取车道方向
137
+ - `get_lane_predecessor(lane_id)`: 获取前序车道
138
+ - `get_lane_successor(lane_id)`: 获取后继车道
139
+
140
+ #### 路口API
141
+ - `get_junction_info(junction_id)`: 获取路口信息
142
+ - `get_junction_list()`: 获取路口列表
143
+ - `get_junction_center_point(junction_id)`: 获取路口中心点
144
+ - `get_junction_boundary(junction_id)`: 获取路口边界
145
+ - `get_junction_type(junction_id)`: 获取路口类型
146
+ - `get_junction_direction(junction_id)`: 获取路口方向
147
+ - `get_junction_predecessor(junction_id)`: 获取前序路口
148
+ - `get_junction_successor(junction_id)`: 获取后继路口
149
+ - `get_movement_list(junction_id)`: 获取移动列表
@@ -0,0 +1,2 @@
1
+
2
+ __version__ = '0.1.3'
@@ -0,0 +1,66 @@
1
+ """
2
+ Client module for the lasvsim API.
3
+ """
4
+ from typing import Optional
5
+
6
+ from lasvsim_openapi.http_client import HttpConfig, HttpClient
7
+ from lasvsim_openapi.train_task import TrainTask
8
+ from lasvsim_openapi.resources import Resources
9
+ from lasvsim_openapi.process_task import ProcessTask
10
+ from lasvsim_openapi.simulator import Simulator, SimulatorConfig
11
+ from lasvsim_openapi.sim_record import SimRecord
12
+
13
+
14
+ class Client:
15
+ """Main client for the API."""
16
+ config: HttpConfig = None
17
+ http_client: HttpClient = None
18
+ train_task: TrainTask = None
19
+ resources: Resources = None
20
+ process_task: ProcessTask = None
21
+ simulator: Simulator = None
22
+ sim_record: SimRecord = None
23
+
24
+ def __init__(self, config: HttpConfig):
25
+ """Initialize a new API client.
26
+
27
+ Args:
28
+ config: HTTP configuration for the client
29
+ """
30
+ self.config = config
31
+ self.http_client = HttpClient(config)
32
+ self.init_common_client()
33
+
34
+ def init_common_client(self):
35
+ """Initialize the common client components."""
36
+ self.train_task = TrainTask(self.http_client)
37
+ self.resources = Resources(self.http_client)
38
+ self.process_task = ProcessTask(self.http_client)
39
+ self.sim_record = SimRecord(self.http_client)
40
+
41
+ def init_simulator_from_config(self, sim_config: SimulatorConfig) -> Simulator:
42
+ """Initialize a simulator from the given configuration.
43
+
44
+ Args:
45
+ sim_config: Configuration for the simulator
46
+
47
+ Returns:
48
+ A new simulator instance
49
+ """
50
+ simulator = Simulator(self.http_client)
51
+ simulator.init_from_config(sim_config)
52
+ return simulator
53
+
54
+ def init_simulator_from_sim(self, sim_id: str, addr: str) -> Simulator:
55
+ """Initialize a simulator from existing simulation.
56
+
57
+ Args:
58
+ sim_id: ID of the existing simulation
59
+ addr: Address of the simulation
60
+
61
+ Returns:
62
+ A new simulator instance
63
+ """
64
+ simulator = Simulator(self.http_client)
65
+ simulator.init_from_sim(sim_id, addr)
66
+ return simulator
@@ -0,0 +1,170 @@
1
+ """
2
+ HTTP client module for the lasvsim API.
3
+ """
4
+ from typing import Any, Dict, Callable, Optional, Type, TypeVar,Tuple
5
+ import requests
6
+
7
+
8
+ class ErrorReason:
9
+ """Error reason constants."""
10
+ CALL_GRPC_ERR = "CALL_GRPC_ERR"
11
+ PARAM_UNAVAILABLE = "PARAM_UNVAILABLE" # Keep original typo for compatibility
12
+ NOT_EXIST = "NOT_EXIST"
13
+ GET_HEADER_ERR = "GET_HEADER_ERR"
14
+
15
+
16
+ class APIError(Exception):
17
+ """Error returned by the API."""
18
+ status_code: int = 0
19
+ message: Any = None
20
+ url: str = ""
21
+ reason: str = ""
22
+
23
+ def __init__(self, status_code: int, message: Any, url: str, reason: str = ""):
24
+ super().__init__(f"APIError {url} {status_code}: {message}")
25
+ self.status_code = status_code
26
+ self.message = message
27
+ self.url = url
28
+ self.reason = reason
29
+
30
+ @staticmethod
31
+ def is_api_error(err: Exception) -> Tuple[Optional['APIError'], bool]:
32
+ """Check if an error is an APIError.
33
+
34
+ Args:
35
+ err: The error to check
36
+
37
+ Returns:
38
+ A tuple of (APIError instance if it is an APIError, boolean indicating if it is an APIError)
39
+ """
40
+ if isinstance(err, APIError):
41
+ return err, True
42
+ return None, False
43
+
44
+ @staticmethod
45
+ def match_error_reason(err: Exception, err_str: str) -> bool:
46
+ """Check if an error matches a specific error reason.
47
+
48
+ Args:
49
+ err: The error to check
50
+ err_str: The error reason to match against
51
+
52
+ Returns:
53
+ True if the error matches the reason, False otherwise
54
+ """
55
+ if isinstance(err, APIError):
56
+ return err.reason == err_str
57
+ return False
58
+
59
+
60
+ class HttpConfig:
61
+ """Configuration for the HTTP client."""
62
+ token: str = ""
63
+ endpoint: str = ""
64
+
65
+ def __init__(self, token: str = "", endpoint: str = ""):
66
+ """Initialize HTTP configuration.
67
+
68
+ Args:
69
+ token: Authentication token
70
+ endpoint: API endpoint URL
71
+ """
72
+ self.token = token
73
+ self.endpoint = endpoint
74
+
75
+
76
+ T = TypeVar('T')
77
+
78
+ class HttpClient():
79
+ """HTTP client for the API."""
80
+ config: HttpConfig = None
81
+ headers: Dict[str, str] = {}
82
+
83
+ def __init__(self, config: HttpConfig, headers: Dict[str, str] = None):
84
+ """Initialize HTTP client.
85
+
86
+ Args:
87
+ config: Client configuration
88
+ headers: Optional custom headers
89
+ """
90
+ self.config = config
91
+ self.headers = headers or {}
92
+ self.headers["Authorization"] = f"Bearer {config.token}"
93
+
94
+ def clone(self) -> 'HttpClient':
95
+ """Create a clone of this client.
96
+
97
+ Returns:
98
+ A new HttpClient instance with the same configuration
99
+ """
100
+
101
+ return HttpClient(self.config, dict(self.headers))
102
+
103
+ def _handle_response(self, response: requests.Response, out_type: Optional[Type[T]] = None) -> Optional[T]:
104
+ if response.status_code != 200:
105
+ try:
106
+ error_data = response.json()
107
+ reason = error_data.get('reason') if isinstance(error_data, dict) else None
108
+ raise APIError(
109
+ status_code=response.status_code,
110
+ message=error_data,
111
+ url=f"{response.request.method},{response.url}",
112
+ reason=reason
113
+ )
114
+ except ValueError:
115
+ raise APIError(
116
+ status_code=response.status_code,
117
+ message=response.text,
118
+ url=f"{response.request.method},{response.url}"
119
+ )
120
+
121
+ if out_type is None:
122
+ return None
123
+
124
+ try:
125
+ response_data = response.json()
126
+ return out_type.from_dict(response_data)
127
+ except ValueError:
128
+ raise APIError("Invalid JSON response")
129
+
130
+ def get(self, path: str, params: Dict[str, str] = None, out_type: Optional[Type[T]] = None) -> T:
131
+ """Send GET request.
132
+
133
+ Args:
134
+ path: API endpoint path
135
+ params: Query parameters
136
+ out: Type to parse response into
137
+
138
+ Returns:
139
+ Response data parsed into specified type
140
+
141
+ Raises:
142
+ APIError: If the request fails
143
+ """
144
+ response = requests.get(
145
+ self.config.endpoint + path,
146
+ params=params,
147
+ headers=self.headers
148
+ )
149
+ return self._handle_response(response, out_type)
150
+
151
+ def post(self, path: str, data: Any = None, out_type: Optional[Type[T]] = None) -> T:
152
+ """Send POST request.
153
+
154
+ Args:
155
+ path: API endpoint path
156
+ data: Request data
157
+ out: Type to parse response into
158
+
159
+ Returns:
160
+ Response data parsed into specified type
161
+
162
+ Raises:
163
+ APIError: If the request fails
164
+ """
165
+ response = requests.post(
166
+ self.config.endpoint + path,
167
+ json=data,
168
+ headers=self.headers
169
+ )
170
+ return self._handle_response(response, out_type)
@@ -0,0 +1,89 @@
1
+ """
2
+ Process task module for the lasvsim API.
3
+ """
4
+ from typing import Optional
5
+
6
+ from lasvsim_openapi.http_client import HttpClient
7
+ from lasvsim_openapi.process_task_model import (
8
+ CopyRecordReq,
9
+ CopyRecordRes,
10
+ GetRecordScenarioReq,
11
+ GetRecordScenarioRes,
12
+ GetTaskRecordIdsReq,
13
+ GetTaskRecordIdsRes,
14
+ )
15
+
16
+
17
+ class ProcessTask:
18
+ """Process task client for the API."""
19
+ http_client: HttpClient = None
20
+
21
+ def __init__(self, http_client: HttpClient):
22
+ """Initialize process task client.
23
+
24
+ Args:
25
+ http_client: HTTP client instance
26
+ """
27
+ self.http_client = http_client.clone()
28
+
29
+ def copy_record(self, task_id: int, record_id: int) -> CopyRecordRes:
30
+ """Copy a record.
31
+
32
+ Args:
33
+ task_id: Task ID
34
+ record_id: Record ID
35
+
36
+ Returns:
37
+ Copy record response
38
+
39
+ Raises:
40
+ APIError: If the request fails
41
+ """
42
+ req = CopyRecordReq(task_id=task_id, record_id=record_id)
43
+
44
+ return self.http_client.post(
45
+ "/openapi/process_task/v2/record/copy",
46
+ {"task_id": req.task_id, "record_id": req.record_id},
47
+ CopyRecordRes
48
+ )
49
+
50
+ def get_record_scenario(self, task_id: int, record_id: int) -> GetRecordScenarioRes:
51
+ """Get record scenario.
52
+
53
+ Args:
54
+ task_id: Task ID
55
+ record_id: Record ID
56
+
57
+ Returns:
58
+ Get record scenario response
59
+
60
+ Raises:
61
+ APIError: If the request fails
62
+ """
63
+ req = GetRecordScenarioReq(task_id=task_id, record_id=record_id)
64
+
65
+ return self.http_client.post(
66
+ "/openapi/process_task/v2/record/scenario/get",
67
+ {"task_id": req.task_id, "record_id": req.record_id},
68
+ GetRecordScenarioRes
69
+ )
70
+
71
+ def get_task_record_ids(self, task_id: int) -> GetTaskRecordIdsRes:
72
+ """Get task record IDs.
73
+
74
+ Args:
75
+ task_id: Task ID
76
+
77
+ Returns:
78
+ Get task record IDs response
79
+
80
+ Raises:
81
+ APIError: If the request fails
82
+ """
83
+ req = GetTaskRecordIdsReq(task_id=task_id)
84
+
85
+ return self.http_client.post(
86
+ "/openapi/process_task/v2/record/id_list",
87
+ {"task_id": req.task_id},
88
+ GetTaskRecordIdsRes
89
+ )