File size: 14,033 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 | #!/usr/bin/env python3
"""Run excluded-domain builders and conversion into a private output tree."""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
from pathlib import Path
PROCESSING = Path(__file__).resolve().parents[1]
RELEASE = PROCESSING.parent
DOMAINS = ("covla", "cuhk_x_har", "mimic_death", "mimic_disch", "pixelrec", "sp500")
IMAGE_DOMAINS = {"mimic_death", "mimic_disch", "pixelrec", "sp500"}
def run_stage(script: str, *arguments: object) -> None:
"""Use the current interpreter and keep bytecode out of the release."""
group = script.split("/", 1)[0]
if group in DOMAINS:
modality = "image-timeseries" if group in IMAGE_DOMAINS else "video-timeseries"
path = RELEASE / "sample" / modality / script
else:
path = PROCESSING / script
subprocess.run(
[sys.executable, "-B", str(path), *map(str, arguments)],
check=True,
)
def require_path(parser: argparse.ArgumentParser, path: Path | None, option: str) -> Path:
if path is None or not path.exists():
parser.error(f"{option} must identify an existing local input")
return path.resolve()
def build_prompts(
args: argparse.Namespace, parser: argparse.ArgumentParser, output: Path,
) -> Path:
if args.input_jsonl:
return require_path(parser, args.input_jsonl, "--input-jsonl")
prompts = output / "intermediate"
if args.domain in {"mimic_death", "mimic_disch"}:
hosp = require_path(parser, args.mimic_hosp_dir, "--mimic-hosp-dir")
notes = require_path(parser, args.mimic_note_dir, "--mimic-note-dir")
metadata = require_path(parser, args.cxr_metadata_csv, "--cxr-metadata-csv")
images = require_path(parser, args.cxr_jpg_root, "--cxr-jpg-root")
prompts.mkdir()
buckets = args.chartevents_root
if buckets is None:
events = require_path(parser, args.chartevents, "--chartevents")
buckets = prompts / "chartevents_bucketed"
run_stage("mimic_death/bucket_chartevents.py", "--input", events,
"--output-root", buckets, "--chunksize", args.chunksize)
else:
buckets = require_path(parser, buckets, "--chartevents-root")
raw = prompts / "patients.jsonl"
common = ["--mimic-hosp-dir", hosp, "--mimic-note-dir", notes,
"--cxr-metadata-csv", metadata, "--cxr-jpg-root", images,
"--chartevents-root", buckets, "--out-jsonl", raw,
"--qc-csv", prompts / "patient_qc.csv", "--seed", args.seed]
if args.domain == "mimic_death":
icu = require_path(parser, args.mimic_icu_dir, "--mimic-icu-dir")
run_stage("mimic_death/build_json_QA_death.py", *common,
"--mimic-icu-dir", icu, "--n-death", args.n_positive,
"--n-alive", args.n_negative, "--require-image-file-exists")
prompt_script = "mimic_death/json_prompt_death.py"
else:
run_stage("mimic_disch/build_json_QA.py", *common,
"--max-pos", args.n_positive, "--max-neg", args.n_negative)
prompt_script = "mimic_disch/json_prompt.py"
all_prompts = prompts / "all.jsonl"
run_stage(prompt_script, "--in-jsonl", raw, "--out-jsonl", all_prompts)
run_stage("mimic_death/split_dataset.py", all_prompts,
"--out-dir", prompts, "--seed", args.seed + (args.domain == "mimic_disch"))
(prompts / "all_train.jsonl").rename(prompts / "train.jsonl")
(prompts / "all_test.jsonl").rename(prompts / "test.jsonl")
elif args.domain == "covla":
source = require_path(parser, args.source_root, "--source-root")
for name in ("states", "front_car", "metadata.jsonl"):
require_path(parser, source / name, f"--source-root/{name}")
prompts.mkdir()
brakes = prompts / "brake_reasons"
run_stage("covla/extract_brake_reasons.py", "--root", source, "--output-dir", brakes)
enriched = prompts / "enriched.jsonl"
run_stage(
"covla/enrich_segments.py", "--root", source,
"--input", brakes / "all_brake_reasons.jsonl", "--output", enriched,
"--sample-output", prompts / "enriched_inspection.jsonl",
)
all_prompts = prompts / "all.jsonl"
run_stage(
"covla/build_prompts.py", "--root", source, "--input", enriched,
"--output", all_prompts, "--sample-output", prompts / "inspection.jsonl",
)
run_stage(
"covla/split_dataset.py", "--root", source, "--input", all_prompts,
"--train-output", prompts / "train.jsonl", "--test-output", prompts / "test.jsonl",
"--stats-output", prompts / "split_stats.json", "--seed", args.seed,
)
elif args.domain == "cuhk_x_har":
source = require_path(parser, args.source_root, "--source-root")
skeleton = require_path(parser, args.skeleton_root or source / "Skeleton", "--skeleton-root")
prompts.mkdir()
if args.aligned_jsonl:
aligned = require_path(parser, args.aligned_jsonl, "--aligned-jsonl")
else:
imu = require_path(parser, args.imu_root or source / "IMU", "--imu-root")
local_imu = prompts / "IMU"
local_skeleton = prompts / "Skeleton"
run_stage("cuhk_x_har/xlsx_to_csv.py", "--input-root", imu,
"--output-root", local_imu)
run_stage("cuhk_x_har/images_to_video.py", skeleton,
"--output-root", local_skeleton, "--fps", args.fps,
"--split-mode", args.skeleton_crop)
aligned = prompts / "imu_skeleton_aligned.jsonl"
run_stage("cuhk_x_har/imu_skeleton_to_jsonl.py", "--imu-root", local_imu,
"--skeleton-root", local_skeleton, "--output", aligned)
run_stage(
"cuhk_x_har/prepare.py", "--root", source, "--input", aligned,
"--skeleton-root", skeleton, "--train-output", prompts / "train.jsonl",
"--test-output", prompts / "test.jsonl",
"--train-sample-output", prompts / "train_inspection.jsonl",
"--test-sample-output", prompts / "test_inspection.jsonl", "--seed", args.seed,
)
elif args.domain == "pixelrec":
interactions = require_path(parser, args.interactions, "--interactions")
item_info = require_path(parser, args.item_info, "--item-info")
images = require_path(parser, args.image_root, "--image-root")
prompts.mkdir()
run_stage(
"pixelrec/prepare.py", "--interactions", interactions, "--item-info", item_info,
"--image-root", images, "--output", prompts / f"{args.split}.jsonl",
"--limit", args.limit or 0,
)
elif args.domain == "sp500":
prices = require_path(parser, args.time_series_dir, "--time-series-dir")
news = require_path(parser, args.news_dir, "--news-dir")
images = require_path(parser, args.image_root, "--image-root")
prompts.mkdir()
run_stage(
"sp500/prepare.py", "--time-series-dir", prices, "--news-dir", news,
"--image-dir", images, "--out-jsonl", prompts / f"{args.split}.jsonl",
"--max-files", args.limit or -1, "--fut-len", args.horizon,
"--news-timezone", args.news_timezone,
)
return prompts / f"{args.split}.jsonl"
def main(domain: str) -> None:
if domain not in DOMAINS:
raise ValueError(f"Unsupported excluded domain: {domain}")
parser = argparse.ArgumentParser(description=__doc__)
parser.set_defaults(domain=domain, input_jsonl=None)
parser.add_argument("--output-dir", type=Path, required=True,
help="New private workspace outside MMTA-v1.0; a domain child is created.")
if domain != "sp500":
parser.add_argument("--input-jsonl", type=Path,
help="Optional existing task prompts to convert.")
parser.add_argument("--source-root", type=Path, help="Local source root or base for relative media.")
parser.add_argument("--path-map", action="append", default=[], metavar="OLD=NEW")
parser.add_argument("--split", choices=("train", "test"), default="test")
parser.add_argument("--limit", type=int, help="Maximum converted records; default processes all.")
if domain in {"covla", "cuhk_x_har", "mimic_death", "mimic_disch"}:
parser.add_argument("--seed", type=int, default=42)
if domain in {"covla", "cuhk_x_har"}:
parser.add_argument("--num-workers", type=int, default=1)
if domain == "cuhk_x_har":
parser.add_argument("--aligned-jsonl", type=Path, help="Optional existing aligned IMU/skeleton input.")
parser.add_argument("--imu-root", type=Path, help="Defaults to <source-root>/IMU.")
parser.add_argument("--skeleton-root", type=Path, help="Skeleton action directory tree.")
parser.add_argument("--fps", type=int, default=20)
parser.add_argument("--skeleton-crop", choices=("left-half", "auto", "none"), default="left-half")
if domain in {"mimic_death", "mimic_disch"}:
parser.add_argument("--mimic-hosp-dir", type=Path)
parser.add_argument("--mimic-icu-dir", type=Path)
parser.add_argument("--mimic-note-dir", type=Path)
parser.add_argument("--cxr-metadata-csv", type=Path)
parser.add_argument("--cxr-jpg-root", type=Path)
events = parser.add_mutually_exclusive_group()
events.add_argument("--chartevents", type=Path, help="Raw chartevents.csv or chartevents.csv.gz.")
events.add_argument("--chartevents-root", type=Path, help="Existing subject/admission buckets.")
parser.add_argument("--chunksize", type=int, default=1000000)
parser.add_argument("--n-positive", type=int, default=20 if domain == "mimic_death" else 50)
parser.add_argument("--n-negative", type=int, default=130 if domain == "mimic_death" else 100)
if domain == "pixelrec":
parser.add_argument("--interactions", type=Path)
parser.add_argument("--item-info", type=Path)
parser.add_argument("--image-root", type=Path)
if domain == "sp500":
parser.add_argument("--time-series-dir", type=Path)
parser.add_argument("--news-dir", type=Path)
parser.add_argument("--image-root", "--image-dir", type=Path)
parser.add_argument("--horizon", type=int, default=12)
parser.add_argument("--news-timezone", default="America/New_York")
args = parser.parse_args()
if args.limit is not None and args.limit < 1:
parser.error("--limit must be positive")
if getattr(args, "num_workers", 1) < 1:
parser.error("--num-workers must be positive")
if getattr(args, "fps", 1) < 1 or getattr(args, "chunksize", 1) < 1:
parser.error("--fps and --chunksize must be positive")
if domain in {"mimic_death", "mimic_disch"} and (args.n_positive < 0 or args.n_negative < 0):
parser.error("--n-positive and --n-negative must be nonnegative")
if any("=" not in item for item in args.path_map):
parser.error("--path-map must have the form OLD=NEW")
output = args.output_dir.expanduser().resolve() / domain
if output.is_relative_to(RELEASE):
parser.error("Restricted output must be outside MMTA-v1.0")
if output.exists():
parser.error(f"Output already exists: {output}; choose a new workspace")
output.mkdir(parents=True)
input_jsonl = build_prompts(args, parser, output)
output_jsonl = output / f"{domain}.omnits.jsonl"
arguments: list[object] = [
"--in-jsonl", input_jsonl, "--out-jsonl", output_jsonl,
"--csv-dir", output / "timeseries", "--dataset-name", f"{domain}_{args.split}",
]
if args.source_root:
arguments.extend(("--source-root", args.source_root.resolve()))
for item in args.path_map:
arguments.extend(("--path-map", item))
if args.limit:
arguments.extend(("--limit", args.limit))
if domain in IMAGE_DOMAINS:
task = "prediction" if domain in {"pixelrec", "sp500"} else "classification"
arguments.extend(("--default-task", task))
run_stage("common/convert_images.py", *arguments)
else:
arguments.extend(("--clip-dir", output / "video_clips", "--num-workers", args.num_workers))
run_stage("common/convert_videos.py", *arguments)
# Keep converted assets and relative references local to this private tree.
temporary = output_jsonl.with_suffix(".tmp")
count = 0
with output_jsonl.open(encoding="utf-8") as source, temporary.open("w", encoding="utf-8") as target:
for line in source:
record = json.loads(line)
if "id" not in record:
record["id"] = f"{domain}_{args.split}_{Path(record['timeseries_path']).stem}"
record.pop("video_id", None)
record.setdefault("task", "classification")
record.update(domain=domain, split=args.split, variant="original")
for field in ("timeseries_path", "video_path", "image_path"):
if field not in record:
continue
values = record[field] if isinstance(record[field], list) else [record[field]]
paths = [os.path.relpath(Path(value).resolve(), output).replace(os.sep, "/") for value in values]
record[field] = paths if isinstance(record[field], list) else paths[0]
target.write(json.dumps(record, ensure_ascii=False, allow_nan=False) + "\n")
count += 1
if not count:
raise RuntimeError("No local tasks were generated")
temporary.replace(output_jsonl)
print(json.dumps({"domain": domain, "split": args.split, "records": count,
"output": str(output_jsonl), "path_base": str(output),
"scope": "private_local_reconstruction"}, indent=2))
|