|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | 3 | import json |
| 4 | +import logging |
4 | 5 | from pathlib import Path |
5 | 6 | from typing import TYPE_CHECKING, Any |
6 | 7 |
|
7 | 8 | if TYPE_CHECKING: |
8 | 9 | from ..models.parameter import Parameter |
9 | 10 |
|
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
10 | 13 |
|
11 | 14 | def parse_prm_file(path: Path) -> dict[str, Any]: |
12 | 15 | """Parse a PRM file into a mapping of parameter definitions. |
13 | 16 |
|
14 | 17 | Supported line formats (space-separated): |
15 | | - name subframe word bit_offset length rate [superframe] |
| 18 | + name subframe word bit_offset length rate [superframe] [KEY=VALUE ...] |
16 | 19 | Also accepts a JSON file mapping parameter names to definitions. |
17 | 20 | """ |
18 | 21 | out: dict[str, Any] = {} |
19 | | - text = path.read_text(encoding="utf-8").strip() |
20 | | - # try JSON first |
| 22 | + |
| 23 | + try: |
| 24 | + text = path.read_text(encoding="utf-8").strip() |
| 25 | + except Exception as e: |
| 26 | + logger.error(f"Failed to read PRM file {path}: {e}") |
| 27 | + raise |
| 28 | + |
| 29 | + # Try parsing as JSON first |
21 | 30 | try: |
22 | 31 | data = json.loads(text) |
23 | 32 | if isinstance(data, dict): |
24 | 33 | return data |
25 | | - except Exception: |
26 | | - pass |
| 34 | + else: |
| 35 | + logger.warning( |
| 36 | + f"PRM file {path} contains valid JSON, but the root element is not a dictionary. Falling back to text line parsing." |
| 37 | + ) |
| 38 | + except json.JSONDecodeError: |
| 39 | + pass # Not JSON, fall back to text line parsing |
27 | 40 |
|
28 | | - for line in text.splitlines(): |
| 41 | + for line_num, line in enumerate(text.splitlines(), start=1): |
29 | 42 | line = line.strip() |
30 | 43 | if not line or line.startswith("#"): |
31 | 44 | continue |
| 45 | + |
32 | 46 | parts = line.split() |
33 | | - # fallback simple formats |
34 | | - if len(parts) >= 6: |
35 | | - try: |
36 | | - name = parts[0] |
37 | | - subframe = int(parts[1]) |
38 | | - word = int(parts[2]) |
39 | | - bit_offset = int(parts[3]) |
40 | | - length = int(parts[4]) |
41 | | - rate = float(parts[5]) |
42 | | - superframe = int(parts[6]) if len(parts) > 6 else None |
43 | | - except Exception: |
44 | | - continue |
45 | | - out[name] = { |
| 47 | + if len(parts) < 6: |
| 48 | + logger.warning( |
| 49 | + f"Skipping malformed line {line_num} in {path}: insufficient fields" |
| 50 | + ) |
| 51 | + continue |
| 52 | + |
| 53 | + try: |
| 54 | + name = parts[0] |
| 55 | + subframe = int(parts[1]) |
| 56 | + word = int(parts[2]) |
| 57 | + bit_offset = int(parts[3]) |
| 58 | + length = int(parts[4]) |
| 59 | + rate = float(parts[5]) |
| 60 | + |
| 61 | + superframe = None |
| 62 | + start_idx = 6 |
| 63 | + |
| 64 | + # Check if the 7th token is a superframe integer or a keyword |
| 65 | + if len(parts) > 6 and "=" not in parts[6]: |
| 66 | + try: |
| 67 | + superframe = int(parts[6]) |
| 68 | + start_idx = 7 |
| 69 | + except ValueError: |
| 70 | + pass |
| 71 | + |
| 72 | + param_meta: dict[str, Any] = { |
46 | 73 | "subframe": subframe, |
47 | 74 | "word": word, |
48 | 75 | "bit_offset": bit_offset, |
49 | 76 | "length": length, |
50 | 77 | "rate": rate, |
51 | 78 | "superframe": superframe, |
52 | 79 | } |
| 80 | + |
| 81 | + # Parse optional trailing key-value tokens (e.g., TYPE=BNR SCALE=0.1) |
| 82 | + line_has_error = False |
| 83 | + for part in parts[start_idx:]: |
| 84 | + if "=" in part: |
| 85 | + key, val = part.split("=", 1) |
| 86 | + key = key.strip().lower() |
| 87 | + val = val.strip() |
| 88 | + |
| 89 | + if key == "type": |
| 90 | + param_meta["type"] = val |
| 91 | + elif key == "scale": |
| 92 | + try: |
| 93 | + param_meta["scale"] = float(val) |
| 94 | + except ValueError: |
| 95 | + logger.warning( |
| 96 | + f"Invalid scale value '{val}' on line {line_num} in {path}" |
| 97 | + ) |
| 98 | + line_has_error = True |
| 99 | + break |
| 100 | + elif key == "offset": |
| 101 | + try: |
| 102 | + param_meta["offset"] = float(val) |
| 103 | + except ValueError: |
| 104 | + logger.warning( |
| 105 | + f"Invalid offset value '{val}' on line {line_num} in {path}" |
| 106 | + ) |
| 107 | + line_has_error = True |
| 108 | + break |
| 109 | + |
| 110 | + if line_has_error: |
| 111 | + continue |
| 112 | + |
| 113 | + out[name] = param_meta |
| 114 | + |
| 115 | + except Exception as e: |
| 116 | + logger.warning(f"Error parsing line {line_num} in {path}: {e}") |
| 117 | + continue |
| 118 | + |
53 | 119 | return out |
54 | 120 |
|
55 | 121 |
|
|
0 commit comments