| 1 | import argparse |
| 2 | import json |
| 3 | import logging |
| 4 | from pprint import pprint |
| 5 | from typing import Any |
| 6 | from con_duct._formatter import SummaryFormatter |
| 7 | from con_duct.json_utils import is_jsonl_file, load_info_file, load_usage_file |
| 8 | |
| 9 | lgr = logging.getLogger(__name__) |
| 10 | |
| 11 | |
| 12 | def get_field_conversion_mapping() -> dict[str, str]: |
| 13 | """ |
| 14 | Map field names to SummaryFormatter conversion types. |
| 15 | """ |
| 16 | return { |
| 17 | "average_pcpu": "P", |
| 18 | "average_pmem": "P", |
| 19 | "average_rss": "S", |
| 20 | "average_vsz": "S", |
| 21 | "peak_pcpu": "P", |
| 22 | "peak_pmem": "P", |
| 23 | "memory_total": "S", |
| 24 | "peak_rss": "S", |
| 25 | "peak_vsz": "S", |
| 26 | "wall_clock_time": "T", |
| 27 | "start_time": "D", |
| 28 | "end_time": "D", |
| 29 | } |
| 30 | |
| 31 | |
| 32 | def _apply_conversion( |
| 33 | key: str, value: Any, field_mapping: dict[str, str], formatter: SummaryFormatter |
| 34 | ) -> Any: |
| 35 | """ |
| 36 | Apply SummaryFormatter conversion to a value based on field name. |
| 37 | """ |
| 38 | if not isinstance(value, (int, float)): |
| 39 | return value |
| 40 | |
| 41 | conversion = field_mapping.get(key.lower()) |
| 42 | if conversion: |
| 43 | return formatter.convert_field(str(value), conversion) |
| 44 | |
| 45 | return value |
| 46 | |
| 47 | |
| 48 | def humanize_data(data: Any, formatter: SummaryFormatter) -> Any: |
| 49 | """ |
| 50 | Recursively humanize numeric values using SummaryFormatter conversions. |
| 51 | """ |
| 52 | field_mapping = get_field_conversion_mapping() |
| 53 | |
| 54 | if isinstance(data, dict): |
| 55 | return { |
| 56 | key: humanize_data( |
| 57 | _apply_conversion(key, value, field_mapping, formatter), formatter |
| 58 | ) |
| 59 | for key, value in data.items() |
| 60 | } |
| 61 | elif isinstance(data, list): |
| 62 | return [humanize_data(item, formatter) for item in data] |
| 63 | else: |
| 64 | return data |
| 65 | |
| 66 | |
| 67 | def pprint_json(args: argparse.Namespace) -> int: |
| 68 | """ |
| 69 | Prints the contents of a JSON file using pprint. |
| 70 | |
| 71 | Handles both standard JSON files and JSON Lines (usage.jsonl) files. |
| 72 | """ |
| 73 | try: |
| 74 | if is_jsonl_file(args.file_path): |
| 75 | data: Any = load_usage_file(args.file_path) |
| 76 | else: |
| 77 | data = load_info_file(args.file_path) |
| 78 | |
| 79 | if args.humanize: |
| 80 | formatter = SummaryFormatter() |
| 81 | data = humanize_data(data, formatter) |
| 82 | |
| 83 | pprint(data) |
| 84 | |
| 85 | except FileNotFoundError: |
| 86 | lgr.error("File not found: %s", args.file_path) |
| 87 | return 1 |
| 88 | except json.JSONDecodeError as e: |
| 89 | lgr.error("Error decoding JSON: %s", e) |
| 90 | return 1 |
| 91 | |
| 92 | return 0 |