MMTA-v1.0 / processing /common /convert_images.py
Lishenyi04's picture
Add six source-processing recipes and document local reconstruction
2e6f68f verified
Raw History Blame Contribute Delete
23.4 kB
#!/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()