File size: 23,423 Bytes
2e6f68f | 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 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 | #!/usr/bin/env python3
"""Convert image+timeseries jsonl into a unified OmniTS-style jsonl.
Output row keys:
id, image_path, timeseries_path, prompt, answer, image_meta, ts_shape, task
Notes:
* This script writes per-sample CSV files from timeseries content.
* It does NOT copy or move image files.
* `image_meta` stores image shape as (W, H, C).
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
from pathlib import Path
from typing import Any
import cv2
import pandas as pd
TS_BLOCK_RE = re.compile(r"<timeseries>(.*?)</timeseries>", re.DOTALL)
HISTORY_BLOCK_RE = re.compile(r"<history>(.*?)</history>", re.DOTALL)
DATA_LINE_RE = re.compile(r"^[^:]+:\s*(.+)$")
TASK_CHOICES = {"classification", "prediction"}
PROMPT_INLINE_TS_RE = re.compile(r"\(([^()]+)\)")
def safe_filename_component(value: str) -> str:
safe_value = re.sub(r"[^A-Za-z0-9_.-]+", "_", value).strip("_")
return safe_value or "unknown"
def source_cache_key(value: str) -> str:
return hashlib.sha1(value.encode("utf-8")).hexdigest()[:10]
SOURCE_ROOT: Path | None = None
PATH_MAPS: list[tuple[str, str]] = []
def resolve_source_image_path(image_path: str, jsonl_path: Path) -> Path:
"""Resolve portable input paths and explicitly configured legacy prefixes."""
for old, new in PATH_MAPS:
if image_path == old or image_path.startswith(old.rstrip("/") + "/"):
image_path = new.rstrip("/") + image_path[len(old.rstrip("/")):]
break
path = Path(image_path).expanduser()
return path.resolve() if path.is_absolute() else ((SOURCE_ROOT or jsonl_path.parent) / path).resolve()
def _dedupe_keep_order(items: list[str]) -> list[str]:
seen = set()
out: list[str] = []
for item in items:
if item in seen:
continue
seen.add(item)
out.append(item)
return out
def choose_image_paths_from_value(value: Any) -> list[str]:
if isinstance(value, str):
v = value.strip()
if not v:
raise ValueError("image_path string is empty")
return [v]
if isinstance(value, list):
paths = [item.strip() for item in value if isinstance(item, str) and item.strip()]
paths = _dedupe_keep_order(paths)
if not paths:
raise ValueError("image_path list has no usable string element")
return paths
if isinstance(value, dict):
paths: list[str] = []
preferred = ("satellite", "relief", "image", "img", "path")
for key in preferred:
v = value.get(key)
if isinstance(v, str) and v.strip():
paths.append(v.strip())
for _, v in value.items():
if isinstance(v, str) and v.strip():
paths.append(v.strip())
paths = _dedupe_keep_order(paths)
if not paths:
raise ValueError("image_path dict has no usable string value")
return paths
raise ValueError(f"unsupported image_path type: {type(value).__name__}")
def stable_sample_id(
entry: dict,
dataset_name: str,
id_field: str,
image_field: str,
line_no: int,
) -> str:
existing = entry.get(id_field)
if existing:
return safe_filename_component(str(existing))
identity = {
"dataset": dataset_name,
"line_no": line_no,
"task_id": entry.get("task_id"),
"image_path": entry.get(image_field),
}
digest = source_cache_key(json.dumps(identity, sort_keys=True, ensure_ascii=False))
return f"{safe_filename_component(dataset_name)}_{line_no}_{digest}"
def parse_timeseries_data_line(line: str) -> dict[str, Any] | None:
stripped = line.strip()
if not stripped:
return None
# Tuple style: "(timestamp, value[, value2, ...])"
# Also tolerate missing trailing ")" in noisy prompt text.
if stripped.startswith("("):
inner = stripped[1:].strip()
if inner.endswith(")"):
inner = inner[:-1].strip()
if not inner:
return None
row: dict[str, Any] = {}
comma_pos = inner.find(",")
colon_pos = inner.find(":")
# Terra-style: "(timestamp: v1, v2, ...)"
if colon_pos != -1 and (comma_pos == -1 or colon_pos < comma_pos):
ts, rest = inner.split(":", 1)
timestamp = ts.strip()
values = [part.strip() for part in rest.split(",")]
else:
# Standard tuple style: "(timestamp, v1, v2, ...)"
parts = [part.strip() for part in inner.split(",")]
if len(parts) < 2:
return None
timestamp = parts[0]
values = parts[1:]
row["timestamp"] = timestamp
for idx, raw_value in enumerate(values):
if raw_value in ("null", "None", "nan", "NaN", ""):
value = float("nan")
else:
try:
value = float(raw_value)
except ValueError:
continue
key = "value" if len(values) == 1 else f"v{idx}"
row[key] = value
if len(row) <= 1:
return None
return row
timestamp = ""
if "=" in stripped:
# Robust split for lines like:
# 2133-09-08T02:29:00: heart_rate_bpm=63.0, ...
# Use the last ":" before the first "=" as separator.
eq_pos = stripped.find("=")
sep_pos = stripped.rfind(":", 0, eq_pos)
if sep_pos != -1:
timestamp = stripped[:sep_pos].strip()
kv_part = stripped[sep_pos + 1 :].strip()
else:
kv_part = stripped
elif ":" in stripped:
timestamp, kv_part = stripped.split(":", 1)
timestamp = timestamp.strip()
kv_part = kv_part.strip()
elif "," in stripped:
timestamp, kv_part = stripped.split(",", 1)
timestamp = timestamp.strip()
kv_part = kv_part.strip()
else:
return None
if "..." in kv_part:
return None
row: dict[str, Any] = {}
row["timestamp"] = timestamp
parts = [part.strip() for part in kv_part.split(",") if part.strip()]
for idx, part in enumerate(parts):
if "=" in part:
key, value = part.split("=", 1)
key = key.strip()
value = value.strip()
else:
key = f"v{idx}"
value = part.strip()
if not key:
continue
if value in ("null", "None", "nan", "NaN", ""):
row[key] = float("nan")
continue
try:
row[key] = float(value)
except ValueError:
# Skip non-numeric values (e.g., timestamp strings in mixed rows).
continue
if len(row) <= 1:
return None
return row
def _timeseries_lines_from_field(entry: dict) -> list[str]:
raw = entry.get("timeseries")
if raw is not None:
if isinstance(raw, str):
return raw.splitlines()
if isinstance(raw, list):
lines: list[str] = []
for idx, item in enumerate(raw):
if isinstance(item, str):
lines.append(item)
elif isinstance(item, dict):
parts = [f"{k}={v}" for k, v in item.items()]
lines.append(f"{idx}: " + ", ".join(parts))
return lines
if isinstance(raw, dict):
parts = [f"{k}={v}" for k, v in raw.items()]
return ["0: " + ", ".join(parts)]
# Terra: historical arrays and optional time index; targets are never inputs.
his_keys = sorted([k for k in entry.keys() if isinstance(k, str) and k.startswith("his_") and k != "his_time_index"])
if his_keys:
lines: list[str] = []
his_time = entry.get("his_time_index")
def build_group(keys: list[str], time_values: Any, prefix: str) -> list[str]:
if not keys:
return []
arrays = []
for key in keys:
val = entry.get(key)
arrays.append(val if isinstance(val, list) else [])
length = min([len(arr) for arr in arrays] or [0])
if length <= 0:
return []
out: list[str] = []
for i in range(length):
t = None
if isinstance(time_values, list) and i < len(time_values):
t = time_values[i]
tlabel = str(t) if t is not None else f"{prefix}_{i}"
parts = []
for key, arr in zip(keys, arrays):
ch = key.replace(prefix + "_", "", 1)
parts.append(f"{ch}={arr[i]}")
out.append(f"{tlabel}: " + ", ".join(parts))
return out
lines.extend(build_group(his_keys, his_time, "his"))
if lines:
return lines
# SP500 / PixelRec style: time_series_data list of scalars or vectors.
tsd = entry.get("time_series_data")
if isinstance(tsd, list) and tsd:
lines: list[str] = []
for i, item in enumerate(tsd):
if isinstance(item, list):
parts = [f"v{j}={v}" for j, v in enumerate(item)]
lines.append(f"{i}: " + ", ".join(parts))
elif isinstance(item, dict):
parts = [f"{k}={v}" for k, v in item.items()]
lines.append(f"{i}: " + ", ".join(parts))
else:
lines.append(f"{i}: value={item}")
return lines
# MIMIC style: vitals_aligned dict of channel->list.
va = entry.get("vitals_aligned")
if isinstance(va, dict) and va:
channels = []
arrays = []
for key, value in va.items():
if isinstance(value, list):
channels.append(str(key))
arrays.append(value)
length = min([len(arr) for arr in arrays] or [0])
if length > 0:
lines = []
for i in range(length):
parts = [f"{ch}={arr[i]}" for ch, arr in zip(channels, arrays)]
lines.append(f"{i}: " + ", ".join(parts))
return lines
# PixelRec style: hist_* series fields.
hist_keys = sorted(
[
k
for k in entry.keys()
if isinstance(k, str)
and k.startswith("hist_")
and k != "hist_timestamp"
and isinstance(entry.get(k), list)
and entry.get(k)
and all(isinstance(x, (int, float)) or x is None for x in entry.get(k))
]
)
if hist_keys:
arrays = [entry[k] for k in hist_keys]
length = min([len(arr) for arr in arrays] or [0])
if length > 0:
ts = entry.get("hist_timestamp")
lines = []
for i in range(length):
tlabel = str(ts[i]) if isinstance(ts, list) and i < len(ts) else str(i)
parts = [f"{k.replace('hist_', '', 1)}={arr[i]}" for k, arr in zip(hist_keys, arrays)]
lines.append(f"{tlabel}: " + ", ".join(parts))
return lines
return []
def _timeseries_lines_from_prompt(prompt: str) -> list[str]:
# Parse lines like "(timestamp: v1, v2, ...)" into "timestamp: v0=..., ..."
lines: list[str] = []
for m in PROMPT_INLINE_TS_RE.finditer(prompt):
inner = m.group(1).strip()
if ":" not in inner:
continue
t, rest = inner.split(":", 1)
t = t.strip()
rest = rest.strip()
if not t or not rest:
continue
segments = [seg.strip() for seg in rest.split(",")]
kv_parts: list[str] = []
for idx, seg in enumerate(segments):
if not seg:
continue
if "=" in seg:
k, v = seg.split("=", 1)
kv_parts.append(f"{k.strip()}={v.strip()}")
else:
kv_parts.append(f"v{idx}={seg}")
if kv_parts:
lines.append(f"{t}: " + ", ".join(kv_parts))
return lines
def _timeseries_lines_from_entry_fallback(entry: dict) -> list[str]:
# Generic fallback for dict[str, list] numeric fields with optional time index.
series_keys = []
arrays = []
for key, value in entry.items():
if isinstance(value, list) and value and all(
isinstance(x, (int, float)) or x is None for x in value
):
series_keys.append(str(key))
arrays.append(value)
if not arrays:
return []
length = min(len(arr) for arr in arrays)
if length <= 0:
return []
# Prefer explicit time index fields when available.
time_candidates = ("his_time_index", "time_index", "timestamp", "hist_timestamp")
t_values = None
for tk in time_candidates:
val = entry.get(tk)
if isinstance(val, list) and len(val) >= length:
t_values = val
break
lines: list[str] = []
for i in range(length):
tlabel = str(t_values[i]) if isinstance(t_values, list) else str(i)
parts = [f"{k}={arr[i]}" for k, arr in zip(series_keys, arrays)]
lines.append(f"{tlabel}: " + ", ".join(parts))
return lines
def extract_or_build_timeseries_block(prompt: str, entry: dict) -> tuple[str, str]:
match = TS_BLOCK_RE.search(prompt)
if match:
return prompt, match.group(1).strip()
history_match = HISTORY_BLOCK_RE.search(prompt)
if history_match:
body = history_match.group(1).strip()
normalized_prompt = HISTORY_BLOCK_RE.sub(
lambda m: f"<timeseries>{m.group(1)}</timeseries>",
prompt,
)
return normalized_prompt, body
lines = _timeseries_lines_from_field(entry)
if not lines:
lines = _timeseries_lines_from_prompt(prompt)
if not lines:
lines = _timeseries_lines_from_entry_fallback(entry)
body = "\n".join(line.rstrip() for line in lines if line.strip()).strip()
if not body:
raise ValueError("no <timeseries> block in prompt and no usable entry['timeseries']")
block = f"<timeseries>\n{body}\n</timeseries>"
if prompt.strip():
updated_prompt = prompt.rstrip() + "\n\n" + block
else:
updated_prompt = block
return updated_prompt, body
def parse_timeseries_body_to_df(body: str) -> pd.DataFrame:
records: list[dict[str, float]] = []
for line in body.splitlines():
row = parse_timeseries_data_line(line)
if row:
records.append(row)
if not records:
raise ValueError("<timeseries> block had no data rows")
return pd.DataFrame.from_records(records)
def probe_image_meta(image_path: Path, allow_missing: bool = False) -> dict[str, int]:
image = cv2.imread(str(image_path), cv2.IMREAD_UNCHANGED)
if image is None:
if allow_missing:
return {"width": -1, "height": -1, "channels": -1}
raise FileNotFoundError(f"failed to read image: {image_path}")
if len(image.shape) == 2:
height, width = image.shape
channels = 1
else:
height, width, channels = image.shape[:3]
return {
"width": int(width),
"height": int(height),
"channels": int(channels),
}
def resolve_task_value(entry: dict, task_field: str, default_task: str) -> str:
raw = entry.get(task_field)
if isinstance(raw, str) and raw.lower() in TASK_CHOICES:
return raw.lower()
return default_task
def normalize_answer_value(value: Any) -> str:
if isinstance(value, str):
return value
if isinstance(value, (int, float, bool)):
return str(value)
if isinstance(value, list):
return json.dumps(value, ensure_ascii=False)
if isinstance(value, dict):
return json.dumps(value, ensure_ascii=False)
return str(value)
def format_forecast_answer_if_possible(entry: dict, answer_value: Any) -> str | None:
if isinstance(answer_value, str):
stripped = answer_value.strip()
if "<forecast>" in stripped and "</forecast>" in stripped:
return answer_value
return None
if not isinstance(answer_value, list) or not answer_value:
return None
meta_info = entry.get("meta_info")
if not isinstance(meta_info, dict):
return None
future_ts = meta_info.get("future_timestamps")
if not isinstance(future_ts, list) or not future_ts:
return None
if len(future_ts) != len(answer_value):
return None
lines = ["<forecast>"]
for ts, v in zip(future_ts, answer_value):
values = v if isinstance(v, list) else [v]
lines.append(f"({ts}: {', '.join(str(value) for value in values)})")
lines.append("</forecast>")
return "\n".join(lines)
def convert_entry(
entry: dict,
jsonl_path: Path,
csv_dir: Path,
dataset_name: str,
line_no: int,
id_field: str,
image_field: str,
prompt_field: str,
answer_field: str,
task_field: str,
default_task: str,
allow_missing_image: bool,
) -> dict:
prompt_value = entry.get(prompt_field)
if not isinstance(prompt_value, str):
raise ValueError(f"{prompt_field} must be a string")
image_value = entry.get(image_field)
image_path_values = choose_image_paths_from_value(image_value)
answer_value = entry.get(answer_field)
if answer_value is None:
answer_value = entry.get("answer")
if answer_value is None:
answer_value = entry.get("ground_truth")
if answer_value is None:
raise ValueError("missing answer value")
sample_id = stable_sample_id(
entry=entry,
dataset_name=dataset_name,
id_field=id_field,
image_field=image_field,
line_no=line_no,
)
src_image_paths = [resolve_source_image_path(p, jsonl_path) for p in image_path_values]
image_metas = [probe_image_meta(p, allow_missing=allow_missing_image) for p in src_image_paths]
updated_prompt, ts_body = extract_or_build_timeseries_block(prompt_value, entry)
ts_df = parse_timeseries_body_to_df(ts_body)
csv_name = f"{sample_id}.csv"
csv_path = (csv_dir / csv_name).resolve()
ts_df.to_csv(csv_path, index=False)
formatted_answer = format_forecast_answer_if_possible(entry, answer_value)
output = {
"id": sample_id,
"image_path": [str(p) for p in src_image_paths],
"timeseries_path": str(csv_path),
"prompt": updated_prompt,
"answer": formatted_answer if formatted_answer is not None else normalize_answer_value(answer_value),
"image_meta": image_metas,
"ts_shape": [int(ts_df.shape[0]), sum(str(column).lower() not in {"timestamp", "time", "datetime"} for column in ts_df.columns)],
"task": resolve_task_value(entry, task_field, default_task),
}
return output
def main() -> None:
parser = argparse.ArgumentParser(
description="Convert image+timeseries jsonl to unified image OmniTS jsonl."
)
parser.add_argument("--in-jsonl", type=Path, required=True)
parser.add_argument("--out-jsonl", type=Path, required=True)
parser.add_argument("--csv-dir", type=Path, required=True)
parser.add_argument("--dataset-name", default="image_dataset")
parser.add_argument("--id-field", default="id")
parser.add_argument("--image-field", default="image_path")
parser.add_argument("--prompt-field", default="prompt")
parser.add_argument("--answer-field", default="ground_truth")
parser.add_argument("--task-field", default="task")
parser.add_argument(
"--default-task",
choices=sorted(TASK_CHOICES),
default="classification",
help="Fallback task value when task field is missing/invalid.",
)
parser.add_argument("--limit", type=int, default=None, help="Convert first N rows only.")
parser.add_argument(
"--start-line",
type=int,
default=1,
help="1-based inclusive source line number to start processing from.",
)
parser.add_argument(
"--end-line",
type=int,
default=None,
help="1-based inclusive source line number to stop processing at.",
)
parser.add_argument(
"--skip-errors",
action="store_true",
help="Skip rows that fail conversion and continue.",
)
parser.add_argument(
"--allow-missing-image",
action="store_true",
help="Allow missing/unreadable images and write image_meta as -1 placeholders.",
)
parser.add_argument("--source-root", type=Path, help="Base directory for relative input image paths.")
parser.add_argument("--path-map", action="append", default=[], metavar="OLD=NEW",
help="Remap a legacy path prefix; repeat for multiple roots.")
args = parser.parse_args()
global SOURCE_ROOT, PATH_MAPS
SOURCE_ROOT = args.source_root.resolve() if args.source_root else None
PATH_MAPS = []
for item in args.path_map:
if "=" not in item:
parser.error("--path-map must have the form OLD=NEW")
PATH_MAPS.append(tuple(item.split("=", 1)))
in_jsonl = args.in_jsonl.resolve()
out_jsonl = args.out_jsonl.resolve()
csv_dir = args.csv_dir.resolve()
out_jsonl.parent.mkdir(parents=True, exist_ok=True)
csv_dir.mkdir(parents=True, exist_ok=True)
converted = 0
skipped: list[tuple[int, str]] = []
if args.start_line < 1:
raise ValueError("--start-line must be >= 1")
if args.end_line is not None and args.end_line < args.start_line:
raise ValueError("--end-line must be >= --start-line")
with in_jsonl.open("r", encoding="utf-8") as fin, out_jsonl.open("w", encoding="utf-8") as fout:
for line_no, line in enumerate(fin, start=1):
if line_no < args.start_line:
continue
if args.end_line is not None and line_no > args.end_line:
break
if args.limit is not None and converted >= args.limit:
break
if not line.strip():
continue
try:
entry = json.loads(line)
row = convert_entry(
entry=entry,
jsonl_path=in_jsonl,
csv_dir=csv_dir,
dataset_name=args.dataset_name,
line_no=line_no,
id_field=args.id_field,
image_field=args.image_field,
prompt_field=args.prompt_field,
answer_field=args.answer_field,
task_field=args.task_field,
default_task=args.default_task,
allow_missing_image=args.allow_missing_image,
)
except Exception as exc: # noqa: BLE001
if args.skip_errors:
skipped.append((line_no, str(exc)))
continue
raise RuntimeError(f"line {line_no}: {exc}") from exc
fout.write(json.dumps(row, ensure_ascii=False) + "\n")
converted += 1
print(f"converted {converted} entries -> {out_jsonl}")
if skipped:
print(f"skipped {len(skipped)} entries")
for line_no, reason in skipped[:20]:
print(f" line {line_no}: {reason}")
if len(skipped) > 20:
print(f" ... {len(skipped) - 20} more")
if __name__ == "__main__":
main()
|