File size: 11,841 Bytes
5e4510c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
"""
Utilities for exporting evolution traces to various formats
"""

import json
import logging
import time
from pathlib import Path
from typing import Any, Dict, List, Optional, Union

logger = logging.getLogger(__name__)


def export_traces_jsonl(
    traces: List[Any], output_path: Union[str, Path], compress: bool = False
) -> None:
    """
    Export traces to JSONL format (one JSON object per line)

    Args:
        traces: List of trace objects with to_dict() method
        output_path: Path to save the JSONL file
        compress: Whether to compress the output with gzip
    """
    output_path = Path(output_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)

    if compress:
        import gzip

        if not output_path.suffix == ".gz":
            output_path = output_path.with_suffix(output_path.suffix + ".gz")
        open_func = gzip.open
        mode = "wt"
    else:
        open_func = open
        mode = "w"

    with open_func(output_path, mode) as f:
        for trace in traces:
            trace_dict = trace.to_dict() if hasattr(trace, "to_dict") else trace
            json.dump(trace_dict, f)
            f.write("\n")

    logger.info(f"Exported {len(traces)} traces to {output_path}")


def export_traces_json(
    traces: List[Any], output_path: Union[str, Path], metadata: Optional[Dict[str, Any]] = None
) -> None:
    """
    Export traces to JSON format with metadata

    Args:
        traces: List of trace objects with to_dict() method
        output_path: Path to save the JSON file
        metadata: Optional metadata to include in the output
    """
    output_path = Path(output_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)

    # Convert traces to dictionaries
    trace_dicts = []
    for trace in traces:
        if hasattr(trace, "to_dict"):
            trace_dicts.append(trace.to_dict())
        else:
            trace_dicts.append(trace)

    # Build output structure
    output_data = {"metadata": metadata or {}, "traces": trace_dicts}

    # Add default metadata
    output_data["metadata"].setdefault("total_traces", len(trace_dicts))
    output_data["metadata"].setdefault("exported_at", time.time())

    with open(output_path, "w") as f:
        json.dump(output_data, f, indent=2)

    logger.info(f"Exported {len(traces)} traces to {output_path}")


def export_traces_hdf5(
    traces: List[Any], output_path: Union[str, Path], metadata: Optional[Dict[str, Any]] = None
) -> None:
    """
    Export traces to HDF5 format

    Args:
        traces: List of trace objects with to_dict() method
        output_path: Path to save the HDF5 file
        metadata: Optional metadata to include in the output
    """
    try:
        import h5py
        import numpy as np
    except ImportError:
        logger.error("h5py is required for HDF5 export. Install with: pip install h5py")
        raise ImportError("h5py not installed")

    output_path = Path(output_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)

    with h5py.File(output_path, "w") as f:
        # Create groups
        traces_group = f.create_group("traces")
        meta_group = f.create_group("metadata")

        # Add metadata
        if metadata:
            for key, value in metadata.items():
                if isinstance(value, (str, int, float, bool)):
                    meta_group.attrs[key] = value
                else:
                    meta_group.attrs[key] = json.dumps(value)

        meta_group.attrs["total_traces"] = len(traces)
        meta_group.attrs["exported_at"] = time.time()

        # Add traces
        for i, trace in enumerate(traces):
            trace_dict = trace.to_dict() if hasattr(trace, "to_dict") else trace
            trace_group = traces_group.create_group(f"trace_{i:06d}")

            for key, value in trace_dict.items():
                if value is None:
                    continue

                if isinstance(value, dict):
                    # Store dictionaries as JSON strings in attributes
                    trace_group.attrs[key] = json.dumps(value)
                elif isinstance(value, list):
                    # Convert lists to numpy arrays if possible
                    try:
                        arr = np.array(value)
                        trace_group.create_dataset(key, data=arr)
                    except (ValueError, TypeError):
                        # Fall back to JSON for complex lists
                        trace_group.attrs[key] = json.dumps(value)
                elif isinstance(value, str):
                    # Store strings as attributes
                    trace_group.attrs[key] = value
                elif isinstance(value, (int, float, bool)):
                    # Store scalars as attributes
                    trace_group.attrs[key] = value
                else:
                    # Store other types as JSON
                    trace_group.attrs[key] = json.dumps(value)

    logger.info(f"Exported {len(traces)} traces to {output_path}")


def append_trace_jsonl(trace: Any, output_path: Union[str, Path], compress: bool = False) -> None:
    """
    Append a single trace to a JSONL file

    Args:
        trace: Trace object with to_dict() method
        output_path: Path to the JSONL file
        compress: Whether the file is compressed with gzip
    """
    output_path = Path(output_path)

    if compress:
        import gzip

        if not output_path.suffix == ".gz":
            output_path = output_path.with_suffix(output_path.suffix + ".gz")
        open_func = gzip.open
        mode = "at"
    else:
        open_func = open
        mode = "a"

    trace_dict = trace.to_dict() if hasattr(trace, "to_dict") else trace

    with open_func(output_path, mode) as f:
        json.dump(trace_dict, f)
        f.write("\n")


def load_traces_jsonl(input_path: Union[str, Path], compress: bool = False) -> List[Dict[str, Any]]:
    """
    Load traces from a JSONL file

    Args:
        input_path: Path to the JSONL file
        compress: Whether the file is compressed with gzip

    Returns:
        List of trace dictionaries
    """
    input_path = Path(input_path)

    if compress or input_path.suffix == ".gz":
        import gzip

        open_func = gzip.open
        mode = "rt"
    else:
        open_func = open
        mode = "r"

    traces = []
    with open_func(input_path, mode) as f:
        for line in f:
            if line.strip():
                traces.append(json.loads(line))

    return traces


def load_traces_json(input_path: Union[str, Path]) -> tuple[List[Dict[str, Any]], Dict[str, Any]]:
    """
    Load traces from a JSON file

    Args:
        input_path: Path to the JSON file

    Returns:
        Tuple of (traces list, metadata dict)
    """
    with open(input_path, "r") as f:
        data = json.load(f)

    traces = data.get("traces", [])
    metadata = data.get("metadata", {})

    return traces, metadata


def load_traces_hdf5(input_path: Union[str, Path]) -> tuple[List[Dict[str, Any]], Dict[str, Any]]:
    """
    Load traces from an HDF5 file

    Args:
        input_path: Path to the HDF5 file

    Returns:
        Tuple of (traces list, metadata dict)
    """
    try:
        import h5py
    except ImportError:
        logger.error("h5py is required for HDF5 loading. Install with: pip install h5py")
        raise ImportError("h5py not installed")

    traces = []
    metadata = {}

    with h5py.File(input_path, "r") as f:
        # Load metadata
        if "metadata" in f:
            meta_group = f["metadata"]
            for key in meta_group.attrs:
                value = meta_group.attrs[key]
                # Try to parse JSON strings
                if isinstance(value, str) and value.startswith("{"):
                    try:
                        metadata[key] = json.loads(value)
                    except json.JSONDecodeError:
                        metadata[key] = value
                else:
                    metadata[key] = value

        # Load traces
        if "traces" in f:
            traces_group = f["traces"]
            for trace_name in sorted(traces_group.keys()):
                trace_group = traces_group[trace_name]
                trace_dict = {}

                # Load attributes
                for key in trace_group.attrs:
                    value = trace_group.attrs[key]
                    # Try to parse JSON strings
                    if isinstance(value, str) and (value.startswith("{") or value.startswith("[")):
                        try:
                            trace_dict[key] = json.loads(value)
                        except json.JSONDecodeError:
                            trace_dict[key] = value
                    else:
                        trace_dict[key] = value

                # Load datasets
                for key in trace_group.keys():
                    dataset = trace_group[key]
                    trace_dict[key] = dataset[...].tolist()

                traces.append(trace_dict)

    return traces, metadata


def export_traces(
    traces: List[Any],
    output_path: Union[str, Path],
    format: str = "jsonl",
    compress: bool = False,
    metadata: Optional[Dict[str, Any]] = None,
) -> None:
    """
    Export traces to specified format

    Args:
        traces: List of trace objects
        output_path: Path to save the file
        format: Output format ('jsonl', 'json', 'hdf5')
        compress: Whether to compress output (jsonl only)
        metadata: Optional metadata (json and hdf5 only)
    """
    format = format.lower()

    if format == "jsonl":
        export_traces_jsonl(traces, output_path, compress=compress)
    elif format == "json":
        export_traces_json(traces, output_path, metadata=metadata)
    elif format == "hdf5":
        export_traces_hdf5(traces, output_path, metadata=metadata)
    else:
        raise ValueError(f"Unsupported format: {format}. Use 'jsonl', 'json', or 'hdf5'")


def load_traces(
    input_path: Union[str, Path], format: Optional[str] = None
) -> Union[List[Dict[str, Any]], tuple[List[Dict[str, Any]], Dict[str, Any]]]:
    """
    Load traces from file, auto-detecting format if not specified

    Args:
        input_path: Path to the file
        format: Optional format ('jsonl', 'json', 'hdf5'). Auto-detected if None.

    Returns:
        For JSONL: List of trace dictionaries
        For JSON/HDF5: Tuple of (traces list, metadata dict)
    """
    input_path = Path(input_path)

    # Auto-detect format from extension
    if format is None:
        if input_path.suffix in [".jsonl", ".gz"]:
            format = "jsonl"
        elif input_path.suffix == ".json":
            format = "json"
        elif input_path.suffix in [".h5", ".hdf5"]:
            format = "hdf5"
        else:
            # Try to detect from content
            with open(input_path, "rb") as f:
                first_bytes = f.read(10)
                if first_bytes.startswith(b"\x89HDF"):
                    format = "hdf5"
                elif first_bytes.startswith(b"{"):
                    # Could be JSON or JSONL, check for newlines
                    f.seek(0)
                    content = f.read(1000)
                    if b"\n{" in content or b"\n[" in content:
                        format = "jsonl"
                    else:
                        format = "json"
                else:
                    format = "jsonl"  # Default assumption

    format = format.lower()

    if format == "jsonl":
        return load_traces_jsonl(input_path, compress=input_path.suffix == ".gz")
    elif format == "json":
        return load_traces_json(input_path)
    elif format == "hdf5":
        return load_traces_hdf5(input_path)
    else:
        raise ValueError(f"Unsupported format: {format}")