Download closedloop/agent/codrive_langcoop_agent.py from YongshuoLiu/LANTERN: direct link, hf CLI and curl.
- Browser
- Download file 18.7 kB
-
https://huggingface.co/datasets/YongshuoLiu/LANTERN/resolve/main/closedloop/agent/codrive_langcoop_agent.py
- Command line
-
hf download hf://datasets/YongshuoLiu/LANTERN/closedloop/agent/codrive_langcoop_agent.py
-
curl -L -o codrive_langcoop_agent.py https://huggingface.co/datasets/YongshuoLiu/LANTERN/resolve/main/closedloop/agent/codrive_langcoop_agent.py
18.7 kB
| #!/usr/bin/env python3 | |
| """Single-ego LangCoop adapter for the CoDrive closed-loop benchmark.""" | |
| from __future__ import annotations | |
| import json | |
| import math | |
| import os | |
| import sys | |
| import textwrap | |
| import time | |
| import xml.etree.ElementTree as ET | |
| from collections import deque | |
| from pathlib import Path | |
| import carla | |
| import cv2 | |
| import numpy as np | |
| import yaml | |
| from leaderboard.autoagents import autonomous_agent | |
| from srunner.scenariomanager.carla_data_provider import CarlaDataProvider | |
| LANGCOOP_ROOT = Path( | |
| os.environ.get( | |
| "LANGCOOP_ROOT", | |
| "/path/to/LangCoop", | |
| ) | |
| ).resolve() | |
| if str(LANGCOOP_ROOT) not in sys.path: | |
| sys.path.insert(0, str(LANGCOOP_ROOT)) | |
| from vlmdrive.controller.vlm_controller_speed_curvature import ( # noqa: E402 | |
| VLMControllerSpeedCurvature, | |
| ) | |
| from vlmdrive.vlm.vlm_planner_speed_curvature import ( # noqa: E402 | |
| VLMPlannerSpeedCurvature, | |
| ) | |
| def get_entry_point(): | |
| return "CoDriveLangCoopAgent" | |
| def _float_attr(element, name, default=0.0): | |
| return float(element.attrib.get(name, default)) | |
| class CoDriveLangCoopAgent(autonomous_agent.AutonomousAgent): | |
| """Run the official LangCoop speed-curvature planner as one CARLA agent. | |
| LangCoop's released evaluator controls multiple ego vehicles and returns a | |
| list of controls. CoDrive uses one ego vehicle, so this adapter preserves | |
| the released planner prompts, parser, and controller while translating the | |
| route navigation target and the temporally bounded cooperative warning. | |
| """ | |
| def setup(self, path_to_conf_file, route_index=None): | |
| del path_to_conf_file, route_index | |
| self.track = autonomous_agent.Track.SENSORS | |
| self.step = -1 | |
| self.current_route_hint = None | |
| self._message_disabled = os.environ.get( | |
| "LANGCOOP_DISABLE_MESSAGES", | |
| os.environ.get("SIMLINGO_DISABLE_ROUTE_LEVEL_HINTS", "0"), | |
| ).strip().lower() in {"1", "true", "yes", "on"} | |
| self._planning_interval_s = max( | |
| 0.25, float(os.environ.get("LANGCOOP_PLANNING_INTERVAL_SECONDS", "2.0")) | |
| ) | |
| self._api_base_url = os.environ.get( | |
| "LANGCOOP_API_BASE_URL", "http://127.0.0.1:8032/v1" | |
| ) | |
| self._model_name = os.environ.get( | |
| "LANGCOOP_MODEL_NAME", "Qwen/Qwen2.5-VL-3B-Instruct-AWQ" | |
| ) | |
| self._run_dir = Path(os.environ["RUN_DIR"]).resolve() | |
| self._save_root = Path(os.environ["SAVE_PATH"]).resolve() / "codrive_langcoop" | |
| self._frame_dir = self._save_root / "rgb_front" | |
| self._frame_dir.mkdir(parents=True, exist_ok=True) | |
| self._log_path = self._run_dir / "langcoop_io.jsonl" | |
| self._log_path.unlink(missing_ok=True) | |
| agent_config = ( | |
| LANGCOOP_ROOT | |
| / "vlmdrive/agent/hypes_yaml/" | |
| "speed_curvature_CoT_concise_image_intent_2agent_qwen.yaml" | |
| ) | |
| control_config = ( | |
| LANGCOOP_ROOT / "vlmdrive/controller/hypes_yaml/speed_curvature.yaml" | |
| ) | |
| self._config = yaml.safe_load(agent_config.read_text(encoding="utf-8")) | |
| control_payload = yaml.safe_load(control_config.read_text(encoding="utf-8")) | |
| self._planner = VLMPlannerSpeedCurvature( | |
| name="api", | |
| api_model_name=self._model_name, | |
| api_base_url=self._api_base_url, | |
| api_key="dummy_key", | |
| ) | |
| self._controller = VLMControllerSpeedCurvature( | |
| control_payload["model"]["config"] | |
| ) | |
| self._history = deque(maxlen=5) | |
| self._prediction = None | |
| self._prediction_time = None | |
| self._previous_position = None | |
| self._previous_yaw = None | |
| self._route_cursor = 0 | |
| self._route_points = [] | |
| self._scenario = self._load_scenario_spec(Path(os.environ["ROUTES"])) | |
| self._last_control = carla.VehicleControl() | |
| print( | |
| "[CoDriveLangCoop] " | |
| f"model={self._model_name} api={self._api_base_url} " | |
| f"messages={'off' if self._message_disabled else 'on'} " | |
| f"planning_interval={self._planning_interval_s:.2f}s", | |
| flush=True, | |
| ) | |
| def _load_scenario_spec(route_path): | |
| root = ET.parse(route_path).getroot() | |
| scenario = root.find(".//scenario") | |
| if scenario is None: | |
| return { | |
| "name": "", | |
| "type": "", | |
| "prompt": "", | |
| "collision_point": None, | |
| } | |
| prompt_node = scenario.find("cooperative_prompt") | |
| if prompt_node is None: | |
| prompt_node = scenario.find("./parameters/parameter[@name='cooperative_prompt']") | |
| collision = scenario.find("collision_point") | |
| point = None | |
| if collision is not None: | |
| point = carla.Location( | |
| x=_float_attr(collision, "x"), | |
| y=_float_attr(collision, "y"), | |
| z=_float_attr(collision, "z"), | |
| ) | |
| return { | |
| "name": scenario.attrib.get("name", scenario.attrib.get("type", "")), | |
| "type": scenario.attrib.get("type", ""), | |
| "prompt": ( | |
| prompt_node.attrib.get("value", "") | |
| if prompt_node is not None | |
| else "" | |
| ).strip(), | |
| "collision_point": point, | |
| } | |
| def sensors(self): | |
| return [ | |
| { | |
| "type": "sensor.camera.rgb", | |
| "x": 1.3, | |
| "y": 0.0, | |
| "z": 2.3, | |
| "roll": 0.0, | |
| "pitch": 0.0, | |
| "yaw": 0.0, | |
| "width": 800, | |
| "height": 600, | |
| "fov": 100, | |
| "id": "rgb_front", | |
| }, | |
| { | |
| "type": "sensor.other.imu", | |
| "x": 0.0, | |
| "y": 0.0, | |
| "z": 0.0, | |
| "roll": 0.0, | |
| "pitch": 0.0, | |
| "yaw": 0.0, | |
| "id": "imu", | |
| }, | |
| { | |
| "type": "sensor.other.gnss", | |
| "x": 0.0, | |
| "y": 0.0, | |
| "z": 0.0, | |
| "roll": 0.0, | |
| "pitch": 0.0, | |
| "yaw": 0.0, | |
| "id": "gps", | |
| }, | |
| { | |
| "type": "sensor.speedometer", | |
| "reading_frequency": 20, | |
| "id": "speed", | |
| }, | |
| ] | |
| def _ensure_route_points(self): | |
| if self._route_points: | |
| return | |
| # Leaderboard stores the original dense route before constructing the | |
| # 50 m navigation-command plan. LangCoop needs the dense geometry for | |
| # local steering; using the command plan can place the next target | |
| # across an intersection and cause an immediate off-route turn. | |
| route = ( | |
| getattr(self, "org_dense_route_world_coord", None) | |
| or self._global_plan_world_coord | |
| or [] | |
| ) | |
| for transform, _command in route: | |
| location = transform.location if hasattr(transform, "location") else transform | |
| self._route_points.append( | |
| np.array([float(location.x), float(location.y)], dtype=np.float64) | |
| ) | |
| def _navigation_target(self, ego_transform): | |
| self._ensure_route_points() | |
| if not self._route_points: | |
| return np.array([0.0, -20.0], dtype=np.float64) | |
| position = np.array( | |
| [ego_transform.location.x, ego_transform.location.y], dtype=np.float64 | |
| ) | |
| start = max(0, self._route_cursor - 5) | |
| stop = min(len(self._route_points), self._route_cursor + 80) | |
| nearest = min( | |
| range(start, stop), | |
| key=lambda index: float(np.linalg.norm(self._route_points[index] - position)), | |
| ) | |
| self._route_cursor = max(self._route_cursor, nearest) | |
| target_index = nearest | |
| distance = 0.0 | |
| while target_index + 1 < len(self._route_points) and distance < 18.0: | |
| distance += float( | |
| np.linalg.norm( | |
| self._route_points[target_index + 1] | |
| - self._route_points[target_index] | |
| ) | |
| ) | |
| target_index += 1 | |
| delta = self._route_points[target_index] - position | |
| yaw = math.radians(float(ego_transform.rotation.yaw)) | |
| forward = np.array([math.cos(yaw), math.sin(yaw)]) | |
| right = np.array([-math.sin(yaw), math.cos(yaw)]) | |
| forward_m = float(delta @ forward) | |
| right_m = float(delta @ right) | |
| # LangCoop describes [lateral, -forward] as right/left and front/back. | |
| return np.array([right_m, -forward_m], dtype=np.float64) | |
| def _event_state(self): | |
| if not self._scenario["name"]: | |
| return {} | |
| try: | |
| from srunner.scenarios.closed_coopeval_scenarios import ( | |
| get_ablation_event_state, | |
| ) | |
| return get_ablation_event_state(self._scenario["name"]) or {} | |
| except Exception: | |
| return {} | |
| def _relative_description(ego_transform, point): | |
| if point is None: | |
| return "at the reported conflict point ahead" | |
| delta = np.array( | |
| [ | |
| point.x - ego_transform.location.x, | |
| point.y - ego_transform.location.y, | |
| ] | |
| ) | |
| yaw = math.radians(float(ego_transform.rotation.yaw)) | |
| forward = float(delta @ np.array([math.cos(yaw), math.sin(yaw)])) | |
| right = float(delta @ np.array([-math.sin(yaw), math.cos(yaw)])) | |
| lateral = "right" if right >= 0.0 else "left" | |
| longitudinal = "ahead" if forward >= 0.0 else "behind" | |
| return ( | |
| f"{abs(forward):.1f} meters {longitudinal} and " | |
| f"{abs(right):.1f} meters to the {lateral}" | |
| ) | |
| def _cooperative_message(self, ego_transform): | |
| state = self._event_state() | |
| active = ( | |
| not self._message_disabled | |
| and bool(state.get("hint_reached", False)) | |
| and not bool(state.get("hazard_cleared", False)) | |
| and bool(self._scenario["prompt"]) | |
| ) | |
| if not active: | |
| self.current_route_hint = None | |
| return "" | |
| position = self._relative_description( | |
| ego_transform, self._scenario["collision_point"] | |
| ) | |
| canonical = self._scenario["prompt"] | |
| rendered = canonical.replace("<FRONT_CAR_POS>", position) | |
| self.current_route_hint = { | |
| "name": self._scenario["name"], | |
| "text": canonical, | |
| "rendered_text": rendered, | |
| "position_description": position, | |
| } | |
| return ( | |
| "A cooperative road user reports the following safety warning: " | |
| f"{rendered}" | |
| ) | |
| def _speed(input_data): | |
| value = input_data["speed"][1] | |
| if isinstance(value, dict): | |
| if "speed" in value: | |
| return float(value["speed"]) | |
| if "move_state" in value: | |
| return float(value["move_state"].get("speed", 0.0)) | |
| return float(value) | |
| def _history_record(self, timestamp, speed, ego_transform): | |
| position = np.array( | |
| [ego_transform.location.x, ego_transform.location.y], dtype=np.float64 | |
| ) | |
| yaw = math.radians(float(ego_transform.rotation.yaw)) | |
| if self._previous_position is None: | |
| curvature = 0.0 | |
| else: | |
| distance = max(1e-6, float(np.linalg.norm(position - self._previous_position))) | |
| yaw_delta = math.atan2( | |
| math.sin(yaw - self._previous_yaw), | |
| math.cos(yaw - self._previous_yaw), | |
| ) | |
| curvature = math.degrees(yaw_delta) / distance | |
| self._previous_position = position | |
| self._previous_yaw = yaw | |
| self._history.append( | |
| { | |
| "timestamp": round(float(timestamp), 3), | |
| "speed": round(float(speed), 3), | |
| "curvature": round(float(curvature), 3), | |
| "waypoints": [0.0, 0.0], | |
| } | |
| ) | |
| def _plan(self, image_rgb, timestamp, speed, target, cooperative_message): | |
| prompts = self._config["planning"]["prompt_usage"] | |
| templates = self._config["planning"]["prompt_template"] | |
| scene, scene_prompt = self._planner.get_scene_description( | |
| image_rgb, prompts, templates | |
| ) | |
| objects, object_prompt = self._planner.get_objects_description( | |
| image_rgb, prompts, templates | |
| ) | |
| target_description = self._planner.get_target_description(target, templates) | |
| intention, intention_prompt = self._planner.get_intent_description( | |
| image_rgb, prompts, target_description, templates | |
| ) | |
| history = json.dumps({"ego_history": list(self._history)}, indent=2) | |
| prediction = self._planner._gen_individual_info( | |
| image_rgb, | |
| history, | |
| self._config, | |
| scene, | |
| objects, | |
| intention, | |
| target_description, | |
| cooperative_message, | |
| idx=0, | |
| ) | |
| if prediction is None: | |
| raise RuntimeError("LangCoop returned no parseable planning output") | |
| self._prediction = prediction | |
| self._prediction_time = float(timestamp) | |
| record = { | |
| "frame": self.step, | |
| "timestamp": float(timestamp), | |
| "speed_mps": float(speed), | |
| "target_lateral_forward_m": [float(target[0]), float(-target[1])], | |
| "cooperative_message": cooperative_message or None, | |
| "canonical_hint": ( | |
| self.current_route_hint["text"] if self.current_route_hint else None | |
| ), | |
| "prompts": { | |
| "scene": scene_prompt, | |
| "objects": object_prompt, | |
| "intent": intention_prompt, | |
| }, | |
| "intermediate": { | |
| "scene": scene, | |
| "objects": objects, | |
| "intent": intention, | |
| "target": target_description, | |
| }, | |
| "prediction": { | |
| "target_speed_mps": [ | |
| float(value) for value in prediction["target_speed"] | |
| ], | |
| "curvature_degree_per_m": [ | |
| float(value) for value in prediction["curvature"] | |
| ], | |
| "dt_seconds": float(prediction["dt"]), | |
| }, | |
| } | |
| with self._log_path.open("a", encoding="utf-8") as stream: | |
| stream.write(json.dumps(record, ensure_ascii=False) + "\n") | |
| def _fallback_control(self, speed, target): | |
| forward = max(1.0, float(-target[1])) | |
| angle = math.atan2(float(target[0]), forward) | |
| control = carla.VehicleControl() | |
| control.steer = float(np.clip(angle / 0.8, -1.0, 1.0)) | |
| control.throttle = 0.45 if speed < 5.0 else 0.15 | |
| control.brake = 0.0 | |
| return control | |
| def _prediction_control(self, timestamp, speed, target): | |
| if self._prediction is None or self._prediction_time is None: | |
| return self._fallback_control(speed, target) | |
| dt = max(0.1, float(self._prediction["dt"])) | |
| count = len(self._prediction["target_speed"]) | |
| index = min(count - 1, max(0, int((float(timestamp) - self._prediction_time) / dt))) | |
| route_info = { | |
| "speed": float(speed), | |
| "target": target, | |
| **self._prediction, | |
| } | |
| steer, throttle, brake, _meta = self._controller.run_step( | |
| route_info, buffer_idx=index | |
| ) | |
| return carla.VehicleControl( | |
| steer=float(steer), | |
| throttle=float(throttle), | |
| brake=float(bool(brake)), | |
| hand_brake=False, | |
| ) | |
| def _save_frame(self, image_bgr, speed, control, message): | |
| canvas = image_bgr.copy() | |
| lines = [ | |
| f"LangCoop | speed={speed:.2f} m/s | " | |
| f"throttle={control.throttle:.2f} brake={control.brake:.0f}", | |
| "Cooperative message: " + (message if message else "None"), | |
| ] | |
| y = 28 | |
| for line in lines: | |
| for wrapped in textwrap.wrap(line, width=95) or [""]: | |
| cv2.putText( | |
| canvas, | |
| wrapped, | |
| (12, y), | |
| cv2.FONT_HERSHEY_SIMPLEX, | |
| 0.52, | |
| (0, 0, 0), | |
| 3, | |
| cv2.LINE_AA, | |
| ) | |
| cv2.putText( | |
| canvas, | |
| wrapped, | |
| (12, y), | |
| cv2.FONT_HERSHEY_SIMPLEX, | |
| 0.52, | |
| (255, 255, 255), | |
| 1, | |
| cv2.LINE_AA, | |
| ) | |
| y += 22 | |
| cv2.imwrite(str(self._frame_dir / f"{self.step:06d}.jpg"), canvas) | |
| def run_step(self, input_data, timestamp): | |
| self.step += 1 | |
| raw = input_data["rgb_front"][1] | |
| image_bgr = raw[:, :, :3] | |
| image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) | |
| speed = self._speed(input_data) | |
| ego = CarlaDataProvider.get_hero_actor() | |
| if ego is None: | |
| return carla.VehicleControl(brake=1.0) | |
| ego_transform = ego.get_transform() | |
| target = self._navigation_target(ego_transform) | |
| message = self._cooperative_message(ego_transform) | |
| self._history_record(timestamp, speed, ego_transform) | |
| should_plan = ( | |
| self._prediction is None | |
| or self._prediction_time is None | |
| or float(timestamp) - self._prediction_time >= self._planning_interval_s | |
| ) | |
| if should_plan: | |
| started = time.monotonic() | |
| try: | |
| self._plan(image_rgb, timestamp, speed, target, message) | |
| print( | |
| f"[CoDriveLangCoop] planned frame={self.step} " | |
| f"wall_time={time.monotonic() - started:.2f}s " | |
| f"hint={bool(message)}", | |
| flush=True, | |
| ) | |
| except Exception as error: | |
| print(f"[CoDriveLangCoop] planning failed: {error}", flush=True) | |
| control = self._prediction_control(timestamp, speed, target) | |
| self._last_control = control | |
| self._save_frame( | |
| image_bgr, | |
| speed, | |
| control, | |
| self.current_route_hint["rendered_text"] | |
| if self.current_route_hint | |
| else "", | |
| ) | |
| return control | |
| def destroy(self): | |
| self._planner = None | |
| self._controller = None | |