Add six source-processing recipes and document local reconstruction
Browse files- README.md +84 -7
- processing/CODE_PROVENANCE.md +28 -0
- processing/README.md +51 -0
- processing/common/convert_images.py +674 -0
- processing/common/convert_videos.py +623 -0
- processing/common/local_generation.py +260 -0
- processing/common/probe.py +33 -0
- processing/common/test_convert_videos.py +34 -0
- processing/download.py +265 -0
- processing/provenance.json +184 -0
- processing/requirements.txt +10 -0
- sample/image-timeseries/mimic_death/README.md +27 -0
- sample/image-timeseries/mimic_death/bucket_chartevents.py +53 -0
- sample/image-timeseries/mimic_death/build_json_QA_death.py +572 -0
- sample/image-timeseries/mimic_death/download.py +12 -0
- sample/image-timeseries/mimic_death/generate.py +12 -0
- sample/image-timeseries/mimic_death/json_prompt_death.py +228 -0
- sample/image-timeseries/mimic_death/source_tables.py +51 -0
- sample/image-timeseries/mimic_death/split_dataset.py +170 -0
- sample/image-timeseries/mimic_disch/README.md +26 -0
- sample/image-timeseries/mimic_disch/build_json_QA.py +483 -0
- sample/image-timeseries/mimic_disch/download.py +12 -0
- sample/image-timeseries/mimic_disch/generate.py +12 -0
- sample/image-timeseries/mimic_disch/json_prompt.py +331 -0
- sample/image-timeseries/pixelrec/README.md +22 -0
- sample/image-timeseries/pixelrec/download.py +12 -0
- sample/image-timeseries/pixelrec/generate.py +13 -0
- sample/image-timeseries/pixelrec/prepare.py +89 -0
- sample/image-timeseries/sp500/README.md +22 -0
- sample/image-timeseries/sp500/download.py +12 -0
- sample/image-timeseries/sp500/generate.py +13 -0
- sample/image-timeseries/sp500/prepare.py +398 -0
- sample/image-timeseries/sp500/test_news_cutoff.py +111 -0
- sample/video-timeseries/covla/README.md +19 -0
- sample/video-timeseries/covla/build_prompts.py +274 -0
- sample/video-timeseries/covla/download.py +12 -0
- sample/video-timeseries/covla/enrich_segments.py +214 -0
- sample/video-timeseries/covla/extract_brake_reasons.py +197 -0
- sample/video-timeseries/covla/generate.py +13 -0
- sample/video-timeseries/covla/split_dataset.py +160 -0
- sample/video-timeseries/cuhk_x_har/README.md +19 -0
- sample/video-timeseries/cuhk_x_har/download.py +12 -0
- sample/video-timeseries/cuhk_x_har/generate.py +13 -0
- sample/video-timeseries/cuhk_x_har/images_to_video.py +239 -0
- sample/video-timeseries/cuhk_x_har/imu_skeleton_to_jsonl.py +215 -0
- sample/video-timeseries/cuhk_x_har/prepare.py +498 -0
- sample/video-timeseries/cuhk_x_har/xlsx_to_csv.py +50 -0
README.md
CHANGED
|
@@ -42,9 +42,10 @@ configs:
|
|
| 42 |
# MMTA-v1.0
|
| 43 |
|
| 44 |
MMTA evaluates multimodal temporal analysis using images, videos, text and
|
| 45 |
-
time-series observations. This repository contains a
|
| 46 |
**1,322 original test records** and **1,400 alternative Terra channel views**.
|
| 47 |
-
All five configurations use the `test` split.
|
|
|
|
| 48 |
|
| 49 |
| Configuration | Records | Task |
|
| 50 |
|---|---:|---|
|
|
@@ -56,8 +57,10 @@ All five configurations use the `test` split.
|
|
| 56 |
|
| 57 |
The Terra channel views reuse the same 200 original instances and images.
|
| 58 |
They are alternative evaluation views and should not be counted as additional
|
| 59 |
-
independent original examples.
|
| 60 |
-
|
|
|
|
|
|
|
| 61 |
|
| 62 |
The 6,393 referenced assets occupy approximately **11.65 GiB**: 1,149 images,
|
| 63 |
1,122 video clips, 2,722 history CSVs and 1,400 forecast target CSVs.
|
|
@@ -92,10 +95,63 @@ with (root / record["timeseries_path"]).open(encoding="utf-8", newline="") as ha
|
|
| 92 |
history = list(csv.DictReader(handle))
|
| 93 |
```
|
| 94 |
|
| 95 |
-
Resolve every record path relative to the **repository root**. The directory
|
| 96 |
-
`sample/` contains
|
|
|
|
| 97 |
are evaluation references; exclude them from model inputs.
|
| 98 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
## Files and format
|
| 100 |
|
| 101 |
```text
|
|
@@ -106,10 +162,25 @@ sample/
|
|
| 106 |
images/
|
| 107 |
timeseries/
|
| 108 |
forecast_targets/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
video-timeseries/{agibot,future_factories,holo_assist}/
|
| 110 |
<domain>.omnits.jsonl
|
| 111 |
video_clips/
|
| 112 |
timeseries/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
```
|
| 114 |
|
| 115 |
JSONL is UTF-8 with one JSON object per line. IDs are unique across manifests. The release supports image/time-series prediction and video/sensor classification.
|
|
@@ -198,6 +269,12 @@ Factories supplies paired-camera cycle videos and PLC histories. HoloAssist
|
|
| 198 |
supplies coarse-action segments with synchronized sensors and correctness labels.
|
| 199 |
|
| 200 |
The full benchmark also uses MIMIC, PixelRec, CoVLA, CUHK-X and SP500/FinMultiTime.
|
| 201 |
-
Their data are absent from this
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
Questions about this release can be posted in this repository's Discussions.
|
|
|
|
| 42 |
# MMTA-v1.0
|
| 43 |
|
| 44 |
MMTA evaluates multimodal temporal analysis using images, videos, text and
|
| 45 |
+
time-series observations. This repository contains a distributable test subset with
|
| 46 |
**1,322 original test records** and **1,400 alternative Terra channel views**.
|
| 47 |
+
All five configurations use the `test` split. It also includes **processing
|
| 48 |
+
recipes for six additional task domains** whose source data are not redistributed.
|
| 49 |
|
| 50 |
| Configuration | Records | Task |
|
| 51 |
|---|---:|---|
|
|
|
|
| 57 |
|
| 58 |
The Terra channel views reuse the same 200 original instances and images.
|
| 59 |
They are alternative evaluation views and should not be counted as additional
|
| 60 |
+
independent original examples. The released records cover four source domains.
|
| 61 |
+
The additional recipe directories contain code and instructions for local
|
| 62 |
+
reconstruction; their source data and generated task records are not included
|
| 63 |
+
and do not increase the record counts above.
|
| 64 |
|
| 65 |
The 6,393 referenced assets occupy approximately **11.65 GiB**: 1,149 images,
|
| 66 |
1,122 video clips, 2,722 history CSVs and 1,400 forecast target CSVs.
|
|
|
|
| 95 |
history = list(csv.DictReader(handle))
|
| 96 |
```
|
| 97 |
|
| 98 |
+
Resolve every released record path relative to the **repository root**. The directory
|
| 99 |
+
`sample/` contains both released test data and the recipe-only directories
|
| 100 |
+
listed below. `answer` and `forecast_target_path`
|
| 101 |
are evaluation references; exclude them from model inputs.
|
| 102 |
|
| 103 |
+
## Processing recipes for sources that are not redistributed
|
| 104 |
+
|
| 105 |
+
The following directories provide download entry points, source-processing
|
| 106 |
+
scripts and local generation instructions. Because of upstream sharing terms
|
| 107 |
+
and access requirements, this repository distributes **processing code only**
|
| 108 |
+
for these domains. It includes no source datasets, images, videos, patient
|
| 109 |
+
records or generated benchmark records for them.
|
| 110 |
+
|
| 111 |
+
| Recipe directory | Local task | Source access and instructions |
|
| 112 |
+
|---|---|---|
|
| 113 |
+
| `sample/image-timeseries/mimic_death/` | In-hospital mortality classification | [MIMIC mortality instructions](sample/image-timeseries/mimic_death/README.md); obtain the required MIMIC tables, notes and chest images through your own approved PhysioNet account. |
|
| 114 |
+
| `sample/image-timeseries/mimic_disch/` | Discharge-within-48-hours classification | [MIMIC discharge instructions](sample/image-timeseries/mimic_disch/README.md); the same credentialed source access is required. |
|
| 115 |
+
| `sample/image-timeseries/pixelrec/` | Cover-image-conditioned interaction forecasting | [PixelRec instructions](sample/image-timeseries/pixelrec/README.md); obtain interactions, item metadata and covers from the upstream project. |
|
| 116 |
+
| `sample/image-timeseries/sp500/` | Financial forecasting with charts and dated news | [SP500 / FinMultiTime instructions](sample/image-timeseries/sp500/README.md); obtain the upstream prices, news and charts. |
|
| 117 |
+
| `sample/video-timeseries/covla/` | Driving/braking classification | [CoVLA instructions](sample/video-timeseries/covla/README.md); complete upstream Hugging Face access requirements and obtain states, front-car signals and videos. |
|
| 118 |
+
| `sample/video-timeseries/cuhk_x_har/` | Human activity classification | [CUHK-X HAR instructions](sample/video-timeseries/cuhk_x_har/README.md); complete the source data-use agreement and obtain the matching IMU and skeleton archives. |
|
| 119 |
+
|
| 120 |
+
Use your own upstream account and follow each source's current terms. These
|
| 121 |
+
scripts do not grant access to restricted datasets or permission to share them
|
| 122 |
+
or their derivatives. Download and unpack sources locally, then run the
|
| 123 |
+
corresponding `generate.py` to build task prompts and image/video/CSV records.
|
| 124 |
+
Shared download and conversion dependencies are included in `processing/`;
|
| 125 |
+
see the [setup instructions](processing/README.md).
|
| 126 |
+
|
| 127 |
+
For the commands in the per-domain READMEs, run from the directory containing
|
| 128 |
+
your downloaded `MMTA-v1.0` folder:
|
| 129 |
+
|
| 130 |
+
```bash
|
| 131 |
+
python -m pip install -r MMTA-v1.0/processing/requirements.txt
|
| 132 |
+
|
| 133 |
+
# Inspect an upstream download plan without downloading data.
|
| 134 |
+
python -B MMTA-v1.0/sample/image-timeseries/pixelrec/download.py \
|
| 135 |
+
--output local_sources/pixelrec --dry-run
|
| 136 |
+
|
| 137 |
+
# Inspect the inputs accepted by the local task builder.
|
| 138 |
+
python -B MMTA-v1.0/sample/image-timeseries/pixelrec/generate.py --help
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
Install `ffmpeg` and `ffprobe` for video processing, and `wget` for credentialed
|
| 142 |
+
PhysioNet downloads. Actual downloads require `--accept-terms` after completing
|
| 143 |
+
the upstream requirements; a dry run requires no source access. Keep
|
| 144 |
+
`local_sources/` and generated `local_work/` directories outside `MMTA-v1.0/`.
|
| 145 |
+
Locally generated record paths are relative to the generated domain directory,
|
| 146 |
+
as described in each recipe README; released record paths remain relative to
|
| 147 |
+
this repository root.
|
| 148 |
+
|
| 149 |
+
These six recipes are not Hugging Face dataset configurations. `load_dataset`
|
| 150 |
+
loads the five released configurations shown above; `snapshot_download`
|
| 151 |
+
also retrieves the processing scripts. Locally reconstructed records are not
|
| 152 |
+
guaranteed to reproduce the exact original benchmark selection, since available
|
| 153 |
+
upstream versions and files may differ.
|
| 154 |
+
|
| 155 |
## Files and format
|
| 156 |
|
| 157 |
```text
|
|
|
|
| 162 |
images/
|
| 163 |
timeseries/
|
| 164 |
forecast_targets/
|
| 165 |
+
image-timeseries/{mimic_death,mimic_disch,pixelrec,sp500}/
|
| 166 |
+
README.md
|
| 167 |
+
download.py
|
| 168 |
+
generate.py
|
| 169 |
+
<source processing scripts>.py
|
| 170 |
video-timeseries/{agibot,future_factories,holo_assist}/
|
| 171 |
<domain>.omnits.jsonl
|
| 172 |
video_clips/
|
| 173 |
timeseries/
|
| 174 |
+
video-timeseries/{covla,cuhk_x_har}/
|
| 175 |
+
README.md
|
| 176 |
+
download.py
|
| 177 |
+
generate.py
|
| 178 |
+
<source processing scripts>.py
|
| 179 |
+
processing/
|
| 180 |
+
README.md
|
| 181 |
+
requirements.txt
|
| 182 |
+
download.py
|
| 183 |
+
common/
|
| 184 |
```
|
| 185 |
|
| 186 |
JSONL is UTF-8 with one JSON object per line. IDs are unique across manifests. The release supports image/time-series prediction and video/sensor classification.
|
|
|
|
| 269 |
supplies coarse-action segments with synchronized sensors and correctness labels.
|
| 270 |
|
| 271 |
The full benchmark also uses MIMIC, PixelRec, CoVLA, CUHK-X and SP500/FinMultiTime.
|
| 272 |
+
Their data are absent from this subset because of source sharing terms and
|
| 273 |
+
access requirements. The recipe directories above provide processing code for
|
| 274 |
+
users who obtain those sources themselves. Source agreements remain applicable
|
| 275 |
+
to locally downloaded data and generated records. Script origins and existing
|
| 276 |
+
code notices are documented in [processing/CODE_PROVENANCE.md](processing/CODE_PROVENANCE.md)
|
| 277 |
+
and [processing/provenance.json](processing/provenance.json); no new license is
|
| 278 |
+
assigned to third-party code.
|
| 279 |
|
| 280 |
Questions about this release can be posted in this repository's Discussions.
|
processing/CODE_PROVENANCE.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Code provenance
|
| 2 |
+
|
| 3 |
+
The restored builders and shared converters come from the maintainer's archived
|
| 4 |
+
MMTA processing scripts. [provenance.json](provenance.json) retains the source
|
| 5 |
+
labels, original source hashes and packaged script hashes for the included code.
|
| 6 |
+
Paths in that file are relative to the repository root. Archived scripts were
|
| 7 |
+
copied without changing their contents.
|
| 8 |
+
|
| 9 |
+
MIMIC patient joins, mortality/discharge labels, prompt construction and splitting
|
| 10 |
+
are adapted from the original task scripts. The adaptations provide portable
|
| 11 |
+
CLI paths, compressed-table inputs, matching image fields and prevention of
|
| 12 |
+
repeated mortality stays. Mortality uses the first 48 hours after ICU admission;
|
| 13 |
+
discharge uses a radiology-report anchor and a 48-hour vital-sign lookback.
|
| 14 |
+
|
| 15 |
+
CUHK-X alignment, Excel-to-CSV conversion and skeleton-video rendering preserve
|
| 16 |
+
trial matching, stream selection, per-second sampling and 20 fps rendering.
|
| 17 |
+
Generated tables and videos use a new output tree. Original source column names
|
| 18 |
+
are supported through Unicode aliases.
|
| 19 |
+
|
| 20 |
+
SP500 news selection requires valid dates strictly before the first forecast
|
| 21 |
+
day, sorts eligible articles and retains selection metadata. The common video
|
| 22 |
+
converter excludes timestamp-free format examples from sensor observations.
|
| 23 |
+
The included regression tests cover these behaviors.
|
| 24 |
+
|
| 25 |
+
Existing source licenses and notices remain applicable. This restoration does
|
| 26 |
+
not assign a new license to third-party code. Original MMTA contributions retain
|
| 27 |
+
the repository's [CC BY 4.0 declaration](../LICENSE); upstream dataset agreements
|
| 28 |
+
and access conditions apply independently to source data and local derivatives.
|
processing/README.md
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Setup for local source processing
|
| 2 |
+
|
| 3 |
+
This directory contains the shared download and image/video conversion helpers
|
| 4 |
+
used by the six recipe-only directories under `sample/`. Their source data and
|
| 5 |
+
generated records are not distributed by this repository.
|
| 6 |
+
|
| 7 |
+
Use Python 3.10 or later. From the directory containing `MMTA-v1.0/`, install
|
| 8 |
+
the dependencies:
|
| 9 |
+
|
| 10 |
+
```bash
|
| 11 |
+
python -m pip install -r MMTA-v1.0/processing/requirements.txt
|
| 12 |
+
```
|
| 13 |
+
|
| 14 |
+
Install `ffmpeg` and `ffprobe` for video processing. Credentialed PhysioNet
|
| 15 |
+
downloads also require `wget` and an interactive terminal.
|
| 16 |
+
|
| 17 |
+
| Domain | Download and generation instructions |
|
| 18 |
+
|---|---|
|
| 19 |
+
| MIMIC mortality | [mimic_death](../sample/image-timeseries/mimic_death/README.md) |
|
| 20 |
+
| MIMIC discharge | [mimic_disch](../sample/image-timeseries/mimic_disch/README.md) |
|
| 21 |
+
| PixelRec | [pixelrec](../sample/image-timeseries/pixelrec/README.md) |
|
| 22 |
+
| SP500 / FinMultiTime | [sp500](../sample/image-timeseries/sp500/README.md) |
|
| 23 |
+
| CoVLA | [covla](../sample/video-timeseries/covla/README.md) |
|
| 24 |
+
| CUHK-X HAR | [cuhk_x_har](../sample/video-timeseries/cuhk_x_har/README.md) |
|
| 25 |
+
|
| 26 |
+
Complete each upstream source's access requirements with your own account before
|
| 27 |
+
downloading. `download.py --dry-run` prints a plan without contacting a source or
|
| 28 |
+
writing data; actual downloads require `--accept-terms`. Use `--help` on each
|
| 29 |
+
domain's `download.py` and `generate.py` to inspect all available options.
|
| 30 |
+
Downloaded archives must be unpacked before building.
|
| 31 |
+
|
| 32 |
+
Keep source data and outputs outside `MMTA-v1.0/`, for example in sibling
|
| 33 |
+
`local_sources/` and `local_work/` directories. Generation writes a new domain
|
| 34 |
+
directory containing task JSONL, sensor CSVs and intermediate prompts. Video
|
| 35 |
+
recipes also write cropped videos; image recipes reference the local source
|
| 36 |
+
images rather than copying them. Generated paths are relative to that local
|
| 37 |
+
domain directory, and can refer to source images outside it.
|
| 38 |
+
|
| 39 |
+
`common/local_generation.py` orchestrates the per-domain builders and the common
|
| 40 |
+
converters. Optional `--input-jsonl` skips source prompt construction for all
|
| 41 |
+
recipes except SP500, which rebuilds inputs using source-dated news strictly
|
| 42 |
+
before the forecast cutoff. MIMIC discharge also uses the table, bucketing and
|
| 43 |
+
splitting helpers in `sample/image-timeseries/mimic_death/`; retain both MIMIC
|
| 44 |
+
directories when copying scripts.
|
| 45 |
+
|
| 46 |
+
The recipes support local reconstruction, whose exact records may depend on the
|
| 47 |
+
available upstream versions. They are not additional `load_dataset`
|
| 48 |
+
configurations and do not change the five released test splits.
|
| 49 |
+
|
| 50 |
+
See [CODE_PROVENANCE.md](CODE_PROVENANCE.md) and
|
| 51 |
+
[provenance.json](provenance.json) for script origins and retained notices.
|
processing/common/convert_images.py
ADDED
|
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Convert image+timeseries jsonl into a unified OmniTS-style jsonl.
|
| 3 |
+
|
| 4 |
+
Output row keys:
|
| 5 |
+
id, image_path, timeseries_path, prompt, answer, image_meta, ts_shape, task
|
| 6 |
+
|
| 7 |
+
Notes:
|
| 8 |
+
* This script writes per-sample CSV files from timeseries content.
|
| 9 |
+
* It does NOT copy or move image files.
|
| 10 |
+
* `image_meta` stores image shape as (W, H, C).
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import hashlib
|
| 17 |
+
import json
|
| 18 |
+
import re
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Any
|
| 21 |
+
|
| 22 |
+
import cv2
|
| 23 |
+
import pandas as pd
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
TS_BLOCK_RE = re.compile(r"<timeseries>(.*?)</timeseries>", re.DOTALL)
|
| 27 |
+
HISTORY_BLOCK_RE = re.compile(r"<history>(.*?)</history>", re.DOTALL)
|
| 28 |
+
DATA_LINE_RE = re.compile(r"^[^:]+:\s*(.+)$")
|
| 29 |
+
TASK_CHOICES = {"classification", "prediction"}
|
| 30 |
+
PROMPT_INLINE_TS_RE = re.compile(r"\(([^()]+)\)")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def safe_filename_component(value: str) -> str:
|
| 34 |
+
safe_value = re.sub(r"[^A-Za-z0-9_.-]+", "_", value).strip("_")
|
| 35 |
+
return safe_value or "unknown"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def source_cache_key(value: str) -> str:
|
| 39 |
+
return hashlib.sha1(value.encode("utf-8")).hexdigest()[:10]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
SOURCE_ROOT: Path | None = None
|
| 43 |
+
PATH_MAPS: list[tuple[str, str]] = []
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def resolve_source_image_path(image_path: str, jsonl_path: Path) -> Path:
|
| 47 |
+
"""Resolve portable input paths and explicitly configured legacy prefixes."""
|
| 48 |
+
for old, new in PATH_MAPS:
|
| 49 |
+
if image_path == old or image_path.startswith(old.rstrip("/") + "/"):
|
| 50 |
+
image_path = new.rstrip("/") + image_path[len(old.rstrip("/")):]
|
| 51 |
+
break
|
| 52 |
+
path = Path(image_path).expanduser()
|
| 53 |
+
return path.resolve() if path.is_absolute() else ((SOURCE_ROOT or jsonl_path.parent) / path).resolve()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _dedupe_keep_order(items: list[str]) -> list[str]:
|
| 57 |
+
seen = set()
|
| 58 |
+
out: list[str] = []
|
| 59 |
+
for item in items:
|
| 60 |
+
if item in seen:
|
| 61 |
+
continue
|
| 62 |
+
seen.add(item)
|
| 63 |
+
out.append(item)
|
| 64 |
+
return out
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def choose_image_paths_from_value(value: Any) -> list[str]:
|
| 68 |
+
if isinstance(value, str):
|
| 69 |
+
v = value.strip()
|
| 70 |
+
if not v:
|
| 71 |
+
raise ValueError("image_path string is empty")
|
| 72 |
+
return [v]
|
| 73 |
+
|
| 74 |
+
if isinstance(value, list):
|
| 75 |
+
paths = [item.strip() for item in value if isinstance(item, str) and item.strip()]
|
| 76 |
+
paths = _dedupe_keep_order(paths)
|
| 77 |
+
if not paths:
|
| 78 |
+
raise ValueError("image_path list has no usable string element")
|
| 79 |
+
return paths
|
| 80 |
+
|
| 81 |
+
if isinstance(value, dict):
|
| 82 |
+
paths: list[str] = []
|
| 83 |
+
preferred = ("satellite", "relief", "image", "img", "path")
|
| 84 |
+
for key in preferred:
|
| 85 |
+
v = value.get(key)
|
| 86 |
+
if isinstance(v, str) and v.strip():
|
| 87 |
+
paths.append(v.strip())
|
| 88 |
+
for _, v in value.items():
|
| 89 |
+
if isinstance(v, str) and v.strip():
|
| 90 |
+
paths.append(v.strip())
|
| 91 |
+
paths = _dedupe_keep_order(paths)
|
| 92 |
+
if not paths:
|
| 93 |
+
raise ValueError("image_path dict has no usable string value")
|
| 94 |
+
return paths
|
| 95 |
+
|
| 96 |
+
raise ValueError(f"unsupported image_path type: {type(value).__name__}")
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def stable_sample_id(
|
| 100 |
+
entry: dict,
|
| 101 |
+
dataset_name: str,
|
| 102 |
+
id_field: str,
|
| 103 |
+
image_field: str,
|
| 104 |
+
line_no: int,
|
| 105 |
+
) -> str:
|
| 106 |
+
existing = entry.get(id_field)
|
| 107 |
+
if existing:
|
| 108 |
+
return safe_filename_component(str(existing))
|
| 109 |
+
|
| 110 |
+
identity = {
|
| 111 |
+
"dataset": dataset_name,
|
| 112 |
+
"line_no": line_no,
|
| 113 |
+
"task_id": entry.get("task_id"),
|
| 114 |
+
"image_path": entry.get(image_field),
|
| 115 |
+
}
|
| 116 |
+
digest = source_cache_key(json.dumps(identity, sort_keys=True, ensure_ascii=False))
|
| 117 |
+
return f"{safe_filename_component(dataset_name)}_{line_no}_{digest}"
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def parse_timeseries_data_line(line: str) -> dict[str, Any] | None:
|
| 121 |
+
stripped = line.strip()
|
| 122 |
+
if not stripped:
|
| 123 |
+
return None
|
| 124 |
+
|
| 125 |
+
# Tuple style: "(timestamp, value[, value2, ...])"
|
| 126 |
+
# Also tolerate missing trailing ")" in noisy prompt text.
|
| 127 |
+
if stripped.startswith("("):
|
| 128 |
+
inner = stripped[1:].strip()
|
| 129 |
+
if inner.endswith(")"):
|
| 130 |
+
inner = inner[:-1].strip()
|
| 131 |
+
if not inner:
|
| 132 |
+
return None
|
| 133 |
+
row: dict[str, Any] = {}
|
| 134 |
+
|
| 135 |
+
comma_pos = inner.find(",")
|
| 136 |
+
colon_pos = inner.find(":")
|
| 137 |
+
# Terra-style: "(timestamp: v1, v2, ...)"
|
| 138 |
+
if colon_pos != -1 and (comma_pos == -1 or colon_pos < comma_pos):
|
| 139 |
+
ts, rest = inner.split(":", 1)
|
| 140 |
+
timestamp = ts.strip()
|
| 141 |
+
values = [part.strip() for part in rest.split(",")]
|
| 142 |
+
else:
|
| 143 |
+
# Standard tuple style: "(timestamp, v1, v2, ...)"
|
| 144 |
+
parts = [part.strip() for part in inner.split(",")]
|
| 145 |
+
if len(parts) < 2:
|
| 146 |
+
return None
|
| 147 |
+
timestamp = parts[0]
|
| 148 |
+
values = parts[1:]
|
| 149 |
+
|
| 150 |
+
row["timestamp"] = timestamp
|
| 151 |
+
for idx, raw_value in enumerate(values):
|
| 152 |
+
if raw_value in ("null", "None", "nan", "NaN", ""):
|
| 153 |
+
value = float("nan")
|
| 154 |
+
else:
|
| 155 |
+
try:
|
| 156 |
+
value = float(raw_value)
|
| 157 |
+
except ValueError:
|
| 158 |
+
continue
|
| 159 |
+
key = "value" if len(values) == 1 else f"v{idx}"
|
| 160 |
+
row[key] = value
|
| 161 |
+
if len(row) <= 1:
|
| 162 |
+
return None
|
| 163 |
+
return row
|
| 164 |
+
|
| 165 |
+
timestamp = ""
|
| 166 |
+
if "=" in stripped:
|
| 167 |
+
# Robust split for lines like:
|
| 168 |
+
# 2133-09-08T02:29:00: heart_rate_bpm=63.0, ...
|
| 169 |
+
# Use the last ":" before the first "=" as separator.
|
| 170 |
+
eq_pos = stripped.find("=")
|
| 171 |
+
sep_pos = stripped.rfind(":", 0, eq_pos)
|
| 172 |
+
if sep_pos != -1:
|
| 173 |
+
timestamp = stripped[:sep_pos].strip()
|
| 174 |
+
kv_part = stripped[sep_pos + 1 :].strip()
|
| 175 |
+
else:
|
| 176 |
+
kv_part = stripped
|
| 177 |
+
elif ":" in stripped:
|
| 178 |
+
timestamp, kv_part = stripped.split(":", 1)
|
| 179 |
+
timestamp = timestamp.strip()
|
| 180 |
+
kv_part = kv_part.strip()
|
| 181 |
+
elif "," in stripped:
|
| 182 |
+
timestamp, kv_part = stripped.split(",", 1)
|
| 183 |
+
timestamp = timestamp.strip()
|
| 184 |
+
kv_part = kv_part.strip()
|
| 185 |
+
else:
|
| 186 |
+
return None
|
| 187 |
+
|
| 188 |
+
if "..." in kv_part:
|
| 189 |
+
return None
|
| 190 |
+
|
| 191 |
+
row: dict[str, Any] = {}
|
| 192 |
+
row["timestamp"] = timestamp
|
| 193 |
+
parts = [part.strip() for part in kv_part.split(",") if part.strip()]
|
| 194 |
+
for idx, part in enumerate(parts):
|
| 195 |
+
if "=" in part:
|
| 196 |
+
key, value = part.split("=", 1)
|
| 197 |
+
key = key.strip()
|
| 198 |
+
value = value.strip()
|
| 199 |
+
else:
|
| 200 |
+
key = f"v{idx}"
|
| 201 |
+
value = part.strip()
|
| 202 |
+
if not key:
|
| 203 |
+
continue
|
| 204 |
+
|
| 205 |
+
if value in ("null", "None", "nan", "NaN", ""):
|
| 206 |
+
row[key] = float("nan")
|
| 207 |
+
continue
|
| 208 |
+
|
| 209 |
+
try:
|
| 210 |
+
row[key] = float(value)
|
| 211 |
+
except ValueError:
|
| 212 |
+
# Skip non-numeric values (e.g., timestamp strings in mixed rows).
|
| 213 |
+
continue
|
| 214 |
+
if len(row) <= 1:
|
| 215 |
+
return None
|
| 216 |
+
return row
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def _timeseries_lines_from_field(entry: dict) -> list[str]:
|
| 220 |
+
raw = entry.get("timeseries")
|
| 221 |
+
if raw is not None:
|
| 222 |
+
if isinstance(raw, str):
|
| 223 |
+
return raw.splitlines()
|
| 224 |
+
if isinstance(raw, list):
|
| 225 |
+
lines: list[str] = []
|
| 226 |
+
for idx, item in enumerate(raw):
|
| 227 |
+
if isinstance(item, str):
|
| 228 |
+
lines.append(item)
|
| 229 |
+
elif isinstance(item, dict):
|
| 230 |
+
parts = [f"{k}={v}" for k, v in item.items()]
|
| 231 |
+
lines.append(f"{idx}: " + ", ".join(parts))
|
| 232 |
+
return lines
|
| 233 |
+
if isinstance(raw, dict):
|
| 234 |
+
parts = [f"{k}={v}" for k, v in raw.items()]
|
| 235 |
+
return ["0: " + ", ".join(parts)]
|
| 236 |
+
# Terra: historical arrays and optional time index; targets are never inputs.
|
| 237 |
+
his_keys = sorted([k for k in entry.keys() if isinstance(k, str) and k.startswith("his_") and k != "his_time_index"])
|
| 238 |
+
if his_keys:
|
| 239 |
+
lines: list[str] = []
|
| 240 |
+
his_time = entry.get("his_time_index")
|
| 241 |
+
|
| 242 |
+
def build_group(keys: list[str], time_values: Any, prefix: str) -> list[str]:
|
| 243 |
+
if not keys:
|
| 244 |
+
return []
|
| 245 |
+
arrays = []
|
| 246 |
+
for key in keys:
|
| 247 |
+
val = entry.get(key)
|
| 248 |
+
arrays.append(val if isinstance(val, list) else [])
|
| 249 |
+
length = min([len(arr) for arr in arrays] or [0])
|
| 250 |
+
if length <= 0:
|
| 251 |
+
return []
|
| 252 |
+
out: list[str] = []
|
| 253 |
+
for i in range(length):
|
| 254 |
+
t = None
|
| 255 |
+
if isinstance(time_values, list) and i < len(time_values):
|
| 256 |
+
t = time_values[i]
|
| 257 |
+
tlabel = str(t) if t is not None else f"{prefix}_{i}"
|
| 258 |
+
parts = []
|
| 259 |
+
for key, arr in zip(keys, arrays):
|
| 260 |
+
ch = key.replace(prefix + "_", "", 1)
|
| 261 |
+
parts.append(f"{ch}={arr[i]}")
|
| 262 |
+
out.append(f"{tlabel}: " + ", ".join(parts))
|
| 263 |
+
return out
|
| 264 |
+
|
| 265 |
+
lines.extend(build_group(his_keys, his_time, "his"))
|
| 266 |
+
if lines:
|
| 267 |
+
return lines
|
| 268 |
+
|
| 269 |
+
# SP500 / PixelRec style: time_series_data list of scalars or vectors.
|
| 270 |
+
tsd = entry.get("time_series_data")
|
| 271 |
+
if isinstance(tsd, list) and tsd:
|
| 272 |
+
lines: list[str] = []
|
| 273 |
+
for i, item in enumerate(tsd):
|
| 274 |
+
if isinstance(item, list):
|
| 275 |
+
parts = [f"v{j}={v}" for j, v in enumerate(item)]
|
| 276 |
+
lines.append(f"{i}: " + ", ".join(parts))
|
| 277 |
+
elif isinstance(item, dict):
|
| 278 |
+
parts = [f"{k}={v}" for k, v in item.items()]
|
| 279 |
+
lines.append(f"{i}: " + ", ".join(parts))
|
| 280 |
+
else:
|
| 281 |
+
lines.append(f"{i}: value={item}")
|
| 282 |
+
return lines
|
| 283 |
+
|
| 284 |
+
# MIMIC style: vitals_aligned dict of channel->list.
|
| 285 |
+
va = entry.get("vitals_aligned")
|
| 286 |
+
if isinstance(va, dict) and va:
|
| 287 |
+
channels = []
|
| 288 |
+
arrays = []
|
| 289 |
+
for key, value in va.items():
|
| 290 |
+
if isinstance(value, list):
|
| 291 |
+
channels.append(str(key))
|
| 292 |
+
arrays.append(value)
|
| 293 |
+
length = min([len(arr) for arr in arrays] or [0])
|
| 294 |
+
if length > 0:
|
| 295 |
+
lines = []
|
| 296 |
+
for i in range(length):
|
| 297 |
+
parts = [f"{ch}={arr[i]}" for ch, arr in zip(channels, arrays)]
|
| 298 |
+
lines.append(f"{i}: " + ", ".join(parts))
|
| 299 |
+
return lines
|
| 300 |
+
|
| 301 |
+
# PixelRec style: hist_* series fields.
|
| 302 |
+
hist_keys = sorted(
|
| 303 |
+
[
|
| 304 |
+
k
|
| 305 |
+
for k in entry.keys()
|
| 306 |
+
if isinstance(k, str)
|
| 307 |
+
and k.startswith("hist_")
|
| 308 |
+
and k != "hist_timestamp"
|
| 309 |
+
and isinstance(entry.get(k), list)
|
| 310 |
+
and entry.get(k)
|
| 311 |
+
and all(isinstance(x, (int, float)) or x is None for x in entry.get(k))
|
| 312 |
+
]
|
| 313 |
+
)
|
| 314 |
+
if hist_keys:
|
| 315 |
+
arrays = [entry[k] for k in hist_keys]
|
| 316 |
+
length = min([len(arr) for arr in arrays] or [0])
|
| 317 |
+
if length > 0:
|
| 318 |
+
ts = entry.get("hist_timestamp")
|
| 319 |
+
lines = []
|
| 320 |
+
for i in range(length):
|
| 321 |
+
tlabel = str(ts[i]) if isinstance(ts, list) and i < len(ts) else str(i)
|
| 322 |
+
parts = [f"{k.replace('hist_', '', 1)}={arr[i]}" for k, arr in zip(hist_keys, arrays)]
|
| 323 |
+
lines.append(f"{tlabel}: " + ", ".join(parts))
|
| 324 |
+
return lines
|
| 325 |
+
|
| 326 |
+
return []
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def _timeseries_lines_from_prompt(prompt: str) -> list[str]:
|
| 330 |
+
# Parse lines like "(timestamp: v1, v2, ...)" into "timestamp: v0=..., ..."
|
| 331 |
+
lines: list[str] = []
|
| 332 |
+
for m in PROMPT_INLINE_TS_RE.finditer(prompt):
|
| 333 |
+
inner = m.group(1).strip()
|
| 334 |
+
if ":" not in inner:
|
| 335 |
+
continue
|
| 336 |
+
t, rest = inner.split(":", 1)
|
| 337 |
+
t = t.strip()
|
| 338 |
+
rest = rest.strip()
|
| 339 |
+
if not t or not rest:
|
| 340 |
+
continue
|
| 341 |
+
|
| 342 |
+
segments = [seg.strip() for seg in rest.split(",")]
|
| 343 |
+
kv_parts: list[str] = []
|
| 344 |
+
for idx, seg in enumerate(segments):
|
| 345 |
+
if not seg:
|
| 346 |
+
continue
|
| 347 |
+
if "=" in seg:
|
| 348 |
+
k, v = seg.split("=", 1)
|
| 349 |
+
kv_parts.append(f"{k.strip()}={v.strip()}")
|
| 350 |
+
else:
|
| 351 |
+
kv_parts.append(f"v{idx}={seg}")
|
| 352 |
+
if kv_parts:
|
| 353 |
+
lines.append(f"{t}: " + ", ".join(kv_parts))
|
| 354 |
+
return lines
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def _timeseries_lines_from_entry_fallback(entry: dict) -> list[str]:
|
| 358 |
+
# Generic fallback for dict[str, list] numeric fields with optional time index.
|
| 359 |
+
series_keys = []
|
| 360 |
+
arrays = []
|
| 361 |
+
for key, value in entry.items():
|
| 362 |
+
if isinstance(value, list) and value and all(
|
| 363 |
+
isinstance(x, (int, float)) or x is None for x in value
|
| 364 |
+
):
|
| 365 |
+
series_keys.append(str(key))
|
| 366 |
+
arrays.append(value)
|
| 367 |
+
if not arrays:
|
| 368 |
+
return []
|
| 369 |
+
|
| 370 |
+
length = min(len(arr) for arr in arrays)
|
| 371 |
+
if length <= 0:
|
| 372 |
+
return []
|
| 373 |
+
|
| 374 |
+
# Prefer explicit time index fields when available.
|
| 375 |
+
time_candidates = ("his_time_index", "time_index", "timestamp", "hist_timestamp")
|
| 376 |
+
t_values = None
|
| 377 |
+
for tk in time_candidates:
|
| 378 |
+
val = entry.get(tk)
|
| 379 |
+
if isinstance(val, list) and len(val) >= length:
|
| 380 |
+
t_values = val
|
| 381 |
+
break
|
| 382 |
+
|
| 383 |
+
lines: list[str] = []
|
| 384 |
+
for i in range(length):
|
| 385 |
+
tlabel = str(t_values[i]) if isinstance(t_values, list) else str(i)
|
| 386 |
+
parts = [f"{k}={arr[i]}" for k, arr in zip(series_keys, arrays)]
|
| 387 |
+
lines.append(f"{tlabel}: " + ", ".join(parts))
|
| 388 |
+
return lines
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def extract_or_build_timeseries_block(prompt: str, entry: dict) -> tuple[str, str]:
|
| 392 |
+
match = TS_BLOCK_RE.search(prompt)
|
| 393 |
+
if match:
|
| 394 |
+
return prompt, match.group(1).strip()
|
| 395 |
+
|
| 396 |
+
history_match = HISTORY_BLOCK_RE.search(prompt)
|
| 397 |
+
if history_match:
|
| 398 |
+
body = history_match.group(1).strip()
|
| 399 |
+
normalized_prompt = HISTORY_BLOCK_RE.sub(
|
| 400 |
+
lambda m: f"<timeseries>{m.group(1)}</timeseries>",
|
| 401 |
+
prompt,
|
| 402 |
+
)
|
| 403 |
+
return normalized_prompt, body
|
| 404 |
+
|
| 405 |
+
lines = _timeseries_lines_from_field(entry)
|
| 406 |
+
if not lines:
|
| 407 |
+
lines = _timeseries_lines_from_prompt(prompt)
|
| 408 |
+
if not lines:
|
| 409 |
+
lines = _timeseries_lines_from_entry_fallback(entry)
|
| 410 |
+
body = "\n".join(line.rstrip() for line in lines if line.strip()).strip()
|
| 411 |
+
if not body:
|
| 412 |
+
raise ValueError("no <timeseries> block in prompt and no usable entry['timeseries']")
|
| 413 |
+
|
| 414 |
+
block = f"<timeseries>\n{body}\n</timeseries>"
|
| 415 |
+
if prompt.strip():
|
| 416 |
+
updated_prompt = prompt.rstrip() + "\n\n" + block
|
| 417 |
+
else:
|
| 418 |
+
updated_prompt = block
|
| 419 |
+
return updated_prompt, body
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def parse_timeseries_body_to_df(body: str) -> pd.DataFrame:
|
| 423 |
+
records: list[dict[str, float]] = []
|
| 424 |
+
for line in body.splitlines():
|
| 425 |
+
row = parse_timeseries_data_line(line)
|
| 426 |
+
if row:
|
| 427 |
+
records.append(row)
|
| 428 |
+
if not records:
|
| 429 |
+
raise ValueError("<timeseries> block had no data rows")
|
| 430 |
+
return pd.DataFrame.from_records(records)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def probe_image_meta(image_path: Path, allow_missing: bool = False) -> dict[str, int]:
|
| 434 |
+
image = cv2.imread(str(image_path), cv2.IMREAD_UNCHANGED)
|
| 435 |
+
if image is None:
|
| 436 |
+
if allow_missing:
|
| 437 |
+
return {"width": -1, "height": -1, "channels": -1}
|
| 438 |
+
raise FileNotFoundError(f"failed to read image: {image_path}")
|
| 439 |
+
|
| 440 |
+
if len(image.shape) == 2:
|
| 441 |
+
height, width = image.shape
|
| 442 |
+
channels = 1
|
| 443 |
+
else:
|
| 444 |
+
height, width, channels = image.shape[:3]
|
| 445 |
+
return {
|
| 446 |
+
"width": int(width),
|
| 447 |
+
"height": int(height),
|
| 448 |
+
"channels": int(channels),
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def resolve_task_value(entry: dict, task_field: str, default_task: str) -> str:
|
| 453 |
+
raw = entry.get(task_field)
|
| 454 |
+
if isinstance(raw, str) and raw.lower() in TASK_CHOICES:
|
| 455 |
+
return raw.lower()
|
| 456 |
+
return default_task
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def normalize_answer_value(value: Any) -> str:
|
| 460 |
+
if isinstance(value, str):
|
| 461 |
+
return value
|
| 462 |
+
if isinstance(value, (int, float, bool)):
|
| 463 |
+
return str(value)
|
| 464 |
+
if isinstance(value, list):
|
| 465 |
+
return json.dumps(value, ensure_ascii=False)
|
| 466 |
+
if isinstance(value, dict):
|
| 467 |
+
return json.dumps(value, ensure_ascii=False)
|
| 468 |
+
return str(value)
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
def format_forecast_answer_if_possible(entry: dict, answer_value: Any) -> str | None:
|
| 472 |
+
if isinstance(answer_value, str):
|
| 473 |
+
stripped = answer_value.strip()
|
| 474 |
+
if "<forecast>" in stripped and "</forecast>" in stripped:
|
| 475 |
+
return answer_value
|
| 476 |
+
return None
|
| 477 |
+
|
| 478 |
+
if not isinstance(answer_value, list) or not answer_value:
|
| 479 |
+
return None
|
| 480 |
+
|
| 481 |
+
meta_info = entry.get("meta_info")
|
| 482 |
+
if not isinstance(meta_info, dict):
|
| 483 |
+
return None
|
| 484 |
+
future_ts = meta_info.get("future_timestamps")
|
| 485 |
+
if not isinstance(future_ts, list) or not future_ts:
|
| 486 |
+
return None
|
| 487 |
+
if len(future_ts) != len(answer_value):
|
| 488 |
+
return None
|
| 489 |
+
|
| 490 |
+
lines = ["<forecast>"]
|
| 491 |
+
for ts, v in zip(future_ts, answer_value):
|
| 492 |
+
values = v if isinstance(v, list) else [v]
|
| 493 |
+
lines.append(f"({ts}: {', '.join(str(value) for value in values)})")
|
| 494 |
+
lines.append("</forecast>")
|
| 495 |
+
return "\n".join(lines)
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
def convert_entry(
|
| 499 |
+
entry: dict,
|
| 500 |
+
jsonl_path: Path,
|
| 501 |
+
csv_dir: Path,
|
| 502 |
+
dataset_name: str,
|
| 503 |
+
line_no: int,
|
| 504 |
+
id_field: str,
|
| 505 |
+
image_field: str,
|
| 506 |
+
prompt_field: str,
|
| 507 |
+
answer_field: str,
|
| 508 |
+
task_field: str,
|
| 509 |
+
default_task: str,
|
| 510 |
+
allow_missing_image: bool,
|
| 511 |
+
) -> dict:
|
| 512 |
+
prompt_value = entry.get(prompt_field)
|
| 513 |
+
if not isinstance(prompt_value, str):
|
| 514 |
+
raise ValueError(f"{prompt_field} must be a string")
|
| 515 |
+
|
| 516 |
+
image_value = entry.get(image_field)
|
| 517 |
+
image_path_values = choose_image_paths_from_value(image_value)
|
| 518 |
+
|
| 519 |
+
answer_value = entry.get(answer_field)
|
| 520 |
+
if answer_value is None:
|
| 521 |
+
answer_value = entry.get("answer")
|
| 522 |
+
if answer_value is None:
|
| 523 |
+
answer_value = entry.get("ground_truth")
|
| 524 |
+
if answer_value is None:
|
| 525 |
+
raise ValueError("missing answer value")
|
| 526 |
+
|
| 527 |
+
sample_id = stable_sample_id(
|
| 528 |
+
entry=entry,
|
| 529 |
+
dataset_name=dataset_name,
|
| 530 |
+
id_field=id_field,
|
| 531 |
+
image_field=image_field,
|
| 532 |
+
line_no=line_no,
|
| 533 |
+
)
|
| 534 |
+
|
| 535 |
+
src_image_paths = [resolve_source_image_path(p, jsonl_path) for p in image_path_values]
|
| 536 |
+
image_metas = [probe_image_meta(p, allow_missing=allow_missing_image) for p in src_image_paths]
|
| 537 |
+
|
| 538 |
+
updated_prompt, ts_body = extract_or_build_timeseries_block(prompt_value, entry)
|
| 539 |
+
ts_df = parse_timeseries_body_to_df(ts_body)
|
| 540 |
+
|
| 541 |
+
csv_name = f"{sample_id}.csv"
|
| 542 |
+
csv_path = (csv_dir / csv_name).resolve()
|
| 543 |
+
ts_df.to_csv(csv_path, index=False)
|
| 544 |
+
|
| 545 |
+
formatted_answer = format_forecast_answer_if_possible(entry, answer_value)
|
| 546 |
+
output = {
|
| 547 |
+
"id": sample_id,
|
| 548 |
+
"image_path": [str(p) for p in src_image_paths],
|
| 549 |
+
"timeseries_path": str(csv_path),
|
| 550 |
+
"prompt": updated_prompt,
|
| 551 |
+
"answer": formatted_answer if formatted_answer is not None else normalize_answer_value(answer_value),
|
| 552 |
+
"image_meta": image_metas,
|
| 553 |
+
"ts_shape": [int(ts_df.shape[0]), sum(str(column).lower() not in {"timestamp", "time", "datetime"} for column in ts_df.columns)],
|
| 554 |
+
"task": resolve_task_value(entry, task_field, default_task),
|
| 555 |
+
}
|
| 556 |
+
return output
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
def main() -> None:
|
| 560 |
+
parser = argparse.ArgumentParser(
|
| 561 |
+
description="Convert image+timeseries jsonl to unified image OmniTS jsonl."
|
| 562 |
+
)
|
| 563 |
+
parser.add_argument("--in-jsonl", type=Path, required=True)
|
| 564 |
+
parser.add_argument("--out-jsonl", type=Path, required=True)
|
| 565 |
+
parser.add_argument("--csv-dir", type=Path, required=True)
|
| 566 |
+
parser.add_argument("--dataset-name", default="image_dataset")
|
| 567 |
+
parser.add_argument("--id-field", default="id")
|
| 568 |
+
parser.add_argument("--image-field", default="image_path")
|
| 569 |
+
parser.add_argument("--prompt-field", default="prompt")
|
| 570 |
+
parser.add_argument("--answer-field", default="ground_truth")
|
| 571 |
+
parser.add_argument("--task-field", default="task")
|
| 572 |
+
parser.add_argument(
|
| 573 |
+
"--default-task",
|
| 574 |
+
choices=sorted(TASK_CHOICES),
|
| 575 |
+
default="classification",
|
| 576 |
+
help="Fallback task value when task field is missing/invalid.",
|
| 577 |
+
)
|
| 578 |
+
parser.add_argument("--limit", type=int, default=None, help="Convert first N rows only.")
|
| 579 |
+
parser.add_argument(
|
| 580 |
+
"--start-line",
|
| 581 |
+
type=int,
|
| 582 |
+
default=1,
|
| 583 |
+
help="1-based inclusive source line number to start processing from.",
|
| 584 |
+
)
|
| 585 |
+
parser.add_argument(
|
| 586 |
+
"--end-line",
|
| 587 |
+
type=int,
|
| 588 |
+
default=None,
|
| 589 |
+
help="1-based inclusive source line number to stop processing at.",
|
| 590 |
+
)
|
| 591 |
+
parser.add_argument(
|
| 592 |
+
"--skip-errors",
|
| 593 |
+
action="store_true",
|
| 594 |
+
help="Skip rows that fail conversion and continue.",
|
| 595 |
+
)
|
| 596 |
+
parser.add_argument(
|
| 597 |
+
"--allow-missing-image",
|
| 598 |
+
action="store_true",
|
| 599 |
+
help="Allow missing/unreadable images and write image_meta as -1 placeholders.",
|
| 600 |
+
)
|
| 601 |
+
parser.add_argument("--source-root", type=Path, help="Base directory for relative input image paths.")
|
| 602 |
+
parser.add_argument("--path-map", action="append", default=[], metavar="OLD=NEW",
|
| 603 |
+
help="Remap a legacy path prefix; repeat for multiple roots.")
|
| 604 |
+
args = parser.parse_args()
|
| 605 |
+
global SOURCE_ROOT, PATH_MAPS
|
| 606 |
+
SOURCE_ROOT = args.source_root.resolve() if args.source_root else None
|
| 607 |
+
PATH_MAPS = []
|
| 608 |
+
for item in args.path_map:
|
| 609 |
+
if "=" not in item:
|
| 610 |
+
parser.error("--path-map must have the form OLD=NEW")
|
| 611 |
+
PATH_MAPS.append(tuple(item.split("=", 1)))
|
| 612 |
+
|
| 613 |
+
in_jsonl = args.in_jsonl.resolve()
|
| 614 |
+
out_jsonl = args.out_jsonl.resolve()
|
| 615 |
+
csv_dir = args.csv_dir.resolve()
|
| 616 |
+
|
| 617 |
+
out_jsonl.parent.mkdir(parents=True, exist_ok=True)
|
| 618 |
+
csv_dir.mkdir(parents=True, exist_ok=True)
|
| 619 |
+
|
| 620 |
+
converted = 0
|
| 621 |
+
skipped: list[tuple[int, str]] = []
|
| 622 |
+
|
| 623 |
+
if args.start_line < 1:
|
| 624 |
+
raise ValueError("--start-line must be >= 1")
|
| 625 |
+
if args.end_line is not None and args.end_line < args.start_line:
|
| 626 |
+
raise ValueError("--end-line must be >= --start-line")
|
| 627 |
+
|
| 628 |
+
with in_jsonl.open("r", encoding="utf-8") as fin, out_jsonl.open("w", encoding="utf-8") as fout:
|
| 629 |
+
for line_no, line in enumerate(fin, start=1):
|
| 630 |
+
if line_no < args.start_line:
|
| 631 |
+
continue
|
| 632 |
+
if args.end_line is not None and line_no > args.end_line:
|
| 633 |
+
break
|
| 634 |
+
if args.limit is not None and converted >= args.limit:
|
| 635 |
+
break
|
| 636 |
+
if not line.strip():
|
| 637 |
+
continue
|
| 638 |
+
|
| 639 |
+
try:
|
| 640 |
+
entry = json.loads(line)
|
| 641 |
+
row = convert_entry(
|
| 642 |
+
entry=entry,
|
| 643 |
+
jsonl_path=in_jsonl,
|
| 644 |
+
csv_dir=csv_dir,
|
| 645 |
+
dataset_name=args.dataset_name,
|
| 646 |
+
line_no=line_no,
|
| 647 |
+
id_field=args.id_field,
|
| 648 |
+
image_field=args.image_field,
|
| 649 |
+
prompt_field=args.prompt_field,
|
| 650 |
+
answer_field=args.answer_field,
|
| 651 |
+
task_field=args.task_field,
|
| 652 |
+
default_task=args.default_task,
|
| 653 |
+
allow_missing_image=args.allow_missing_image,
|
| 654 |
+
)
|
| 655 |
+
except Exception as exc: # noqa: BLE001
|
| 656 |
+
if args.skip_errors:
|
| 657 |
+
skipped.append((line_no, str(exc)))
|
| 658 |
+
continue
|
| 659 |
+
raise RuntimeError(f"line {line_no}: {exc}") from exc
|
| 660 |
+
|
| 661 |
+
fout.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 662 |
+
converted += 1
|
| 663 |
+
|
| 664 |
+
print(f"converted {converted} entries -> {out_jsonl}")
|
| 665 |
+
if skipped:
|
| 666 |
+
print(f"skipped {len(skipped)} entries")
|
| 667 |
+
for line_no, reason in skipped[:20]:
|
| 668 |
+
print(f" line {line_no}: {reason}")
|
| 669 |
+
if len(skipped) > 20:
|
| 670 |
+
print(f" ... {len(skipped) - 20} more")
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
if __name__ == "__main__":
|
| 674 |
+
main()
|
processing/common/convert_videos.py
ADDED
|
@@ -0,0 +1,623 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Convert prompt JSONL into sensor CSVs, cropped videos and OmniTS metadata.
|
| 3 |
+
|
| 4 |
+
Supported video domains include CoVLA, AgiBot, CUHK-X, Future Factories and
|
| 5 |
+
HoloAssist. Intermediate outputs may use local paths; package_release.py
|
| 6 |
+
copies referenced assets and writes relative paths for distribution.
|
| 7 |
+
Video stream copying preserves the original pipeline's keyframe behavior.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import hashlib
|
| 14 |
+
import json
|
| 15 |
+
import re
|
| 16 |
+
import shutil
|
| 17 |
+
import subprocess
|
| 18 |
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import pandas as pd
|
| 22 |
+
|
| 23 |
+
from probe import probe_ts_shape, probe_video_meta
|
| 24 |
+
|
| 25 |
+
TS_BLOCK_RE = re.compile(r"<timeseries>(.*?)</timeseries>", re.DOTALL)
|
| 26 |
+
DATA_LINE_RE = re.compile(r"^[\d.]+:\s*(.+)$")
|
| 27 |
+
TEMPORAL_FIELD_KEYS = ("frames", "segment", "start_frame", "end_frame", "start", "end")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def safe_filename_component(value: str) -> str:
|
| 31 |
+
safe_value = re.sub(r"[^A-Za-z0-9_.-]+", "_", value).strip("_")
|
| 32 |
+
return safe_value or "unknown"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def source_cache_key(value: str) -> str:
|
| 36 |
+
return hashlib.sha1(value.encode("utf-8")).hexdigest()[:10]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def stable_video_id(entry: dict, dataset_name: str) -> str:
|
| 40 |
+
"""Use existing video_id when present; otherwise create a stable trace id."""
|
| 41 |
+
existing = entry.get("video_id")
|
| 42 |
+
if existing:
|
| 43 |
+
return safe_filename_component(str(existing))
|
| 44 |
+
|
| 45 |
+
identity = {
|
| 46 |
+
"dataset": dataset_name,
|
| 47 |
+
"task_id": entry.get("task_id"),
|
| 48 |
+
"video_path": entry.get("video_path"),
|
| 49 |
+
"frames": entry.get("frames"),
|
| 50 |
+
"segment": entry.get("segment"),
|
| 51 |
+
"start_frame": entry.get("start_frame"),
|
| 52 |
+
"end_frame": entry.get("end_frame"),
|
| 53 |
+
"start": entry.get("start"),
|
| 54 |
+
"end": entry.get("end"),
|
| 55 |
+
}
|
| 56 |
+
digest = source_cache_key(json.dumps(identity, sort_keys=True, ensure_ascii=False))
|
| 57 |
+
task_id = safe_filename_component(str(entry.get("task_id", "no_task_id")))
|
| 58 |
+
dataset_part = safe_filename_component(dataset_name)
|
| 59 |
+
return f"{dataset_part}_{task_id}_{digest}"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def has_temporal_bounds(entry: dict) -> bool:
|
| 63 |
+
"""Return True when a row has the temporal fields used by video preprocessing."""
|
| 64 |
+
if entry.get("frames") is not None or entry.get("segment") is not None:
|
| 65 |
+
return True
|
| 66 |
+
if entry.get("start_frame") is not None and entry.get("end_frame") is not None:
|
| 67 |
+
return True
|
| 68 |
+
return entry.get("start") is not None and entry.get("end") is not None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def has_frame_bounds(entry: dict) -> bool:
|
| 72 |
+
"""Frame bounds take priority over time bounds, as in preprocess_video_segments."""
|
| 73 |
+
if isinstance(entry.get("frames"), dict):
|
| 74 |
+
return True
|
| 75 |
+
return entry.get("start_frame") is not None and entry.get("end_frame") is not None
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def extract_frame_bounds(entry: dict) -> tuple[int, int]:
|
| 79 |
+
"""Extract [start_frame, end_frame] from ``frames`` or top-level fields."""
|
| 80 |
+
frames = entry.get("frames")
|
| 81 |
+
if isinstance(frames, dict):
|
| 82 |
+
start = int(frames.get("start_frame", entry.get("start_frame", 0)))
|
| 83 |
+
end = int(frames.get("end_frame", entry.get("end_frame", 0)))
|
| 84 |
+
else:
|
| 85 |
+
start = int(entry.get("start_frame", 0))
|
| 86 |
+
end = int(entry.get("end_frame", 0))
|
| 87 |
+
if end < start:
|
| 88 |
+
raise ValueError(f"invalid frame range: start={start}, end={end}")
|
| 89 |
+
return start, end
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def extract_time_bounds(entry: dict) -> tuple[float, float]:
|
| 93 |
+
"""Extract [start, end] seconds from ``segment`` or top-level fields."""
|
| 94 |
+
segment = entry.get("segment")
|
| 95 |
+
if isinstance(segment, dict):
|
| 96 |
+
start = segment.get("start")
|
| 97 |
+
end = segment.get("end")
|
| 98 |
+
if start is not None and end is not None:
|
| 99 |
+
start = float(start)
|
| 100 |
+
end = float(end)
|
| 101 |
+
if end < start:
|
| 102 |
+
raise ValueError(f"invalid time range: start={start}, end={end}")
|
| 103 |
+
return start, end
|
| 104 |
+
|
| 105 |
+
start = entry.get("start")
|
| 106 |
+
end = entry.get("end")
|
| 107 |
+
if start is not None and end is not None:
|
| 108 |
+
start = float(start)
|
| 109 |
+
end = float(end)
|
| 110 |
+
if end < start:
|
| 111 |
+
raise ValueError(f"invalid time range: start={start}, end={end}")
|
| 112 |
+
return start, end
|
| 113 |
+
|
| 114 |
+
raise KeyError("no valid time bounds found")
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _video_meta_dict(meta) -> dict | None:
|
| 118 |
+
"""Shape the 5-tuple from probe_video_meta into the jsonl dict form."""
|
| 119 |
+
if meta is None:
|
| 120 |
+
return None
|
| 121 |
+
w, h, sfps, nf, dur = meta
|
| 122 |
+
return {
|
| 123 |
+
"width": int(w), "height": int(h),
|
| 124 |
+
"source_fps": float(sfps),
|
| 125 |
+
"nb_frames": int(nf),
|
| 126 |
+
"duration": float(dur),
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def parse_timeseries_data_line(line: str) -> dict[str, float] | None:
|
| 131 |
+
"""Parse one prompt timeseries row into numeric channel values.
|
| 132 |
+
|
| 133 |
+
Supported prompt row shapes:
|
| 134 |
+
* ``12.345: x=1, y=2`` used by CoVLA/Holo/AgiBot/CUHK-X
|
| 135 |
+
* ``2023-...Z, x=1, y=2`` used by Future Factories
|
| 136 |
+
"""
|
| 137 |
+
stripped = line.strip()
|
| 138 |
+
if not stripped:
|
| 139 |
+
return None
|
| 140 |
+
|
| 141 |
+
m = DATA_LINE_RE.match(stripped)
|
| 142 |
+
if m:
|
| 143 |
+
kv_part = m.group(1)
|
| 144 |
+
elif "," in stripped:
|
| 145 |
+
timestamp, kv_part = stripped.split(",", 1)
|
| 146 |
+
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}(?:[T ].+)?", timestamp.strip()):
|
| 147 |
+
return None
|
| 148 |
+
else:
|
| 149 |
+
return None
|
| 150 |
+
|
| 151 |
+
if "..." in kv_part:
|
| 152 |
+
return None
|
| 153 |
+
|
| 154 |
+
row: dict[str, float] = {}
|
| 155 |
+
for pair in kv_part.split(","):
|
| 156 |
+
if "=" not in pair:
|
| 157 |
+
continue
|
| 158 |
+
k, v = pair.split("=", 1)
|
| 159 |
+
k, v = k.strip(), v.strip()
|
| 160 |
+
if not k:
|
| 161 |
+
continue
|
| 162 |
+
if v in ("null", "None", "nan", "NaN", ""):
|
| 163 |
+
row[k] = float("nan")
|
| 164 |
+
else:
|
| 165 |
+
row[k] = float(v)
|
| 166 |
+
return row or None
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def parse_timeseries_block(text: str) -> pd.DataFrame:
|
| 170 |
+
"""Extract numeric rows from a <timeseries>...</timeseries> block into a DataFrame.
|
| 171 |
+
|
| 172 |
+
Each data line looks like: "25.5: vEgo=6.517, aEgo=0.197, ..., lead_a=null".
|
| 173 |
+
Returns a DataFrame with one column per variable; "null" or empty becomes NaN.
|
| 174 |
+
"""
|
| 175 |
+
match = TS_BLOCK_RE.search(text)
|
| 176 |
+
if not match:
|
| 177 |
+
raise ValueError("no <timeseries> block found")
|
| 178 |
+
body = match.group(1)
|
| 179 |
+
|
| 180 |
+
records: list[dict[str, float]] = []
|
| 181 |
+
for line in body.splitlines():
|
| 182 |
+
row = parse_timeseries_data_line(line)
|
| 183 |
+
if row:
|
| 184 |
+
records.append(row)
|
| 185 |
+
|
| 186 |
+
if not records:
|
| 187 |
+
raise ValueError("<timeseries> block had no data rows")
|
| 188 |
+
|
| 189 |
+
return pd.DataFrame.from_records(records)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def probe_video_fps(video_path: Path) -> float:
|
| 193 |
+
"""Use ffprobe to read the source video's avg_frame_rate as a float."""
|
| 194 |
+
result = subprocess.run(
|
| 195 |
+
[
|
| 196 |
+
"ffprobe", "-v", "error", "-select_streams", "v:0",
|
| 197 |
+
"-show_entries", "stream=avg_frame_rate",
|
| 198 |
+
"-of", "default=nw=1:nk=1",
|
| 199 |
+
str(video_path),
|
| 200 |
+
],
|
| 201 |
+
capture_output=True, text=True, check=True,
|
| 202 |
+
)
|
| 203 |
+
num, den = result.stdout.strip().split("/")
|
| 204 |
+
num_f, den_f = float(num), float(den)
|
| 205 |
+
if den_f == 0:
|
| 206 |
+
return 0.0
|
| 207 |
+
return num_f / den_f
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def probe_video_frame_count(video_path: Path) -> int:
|
| 211 |
+
"""Use ffprobe to estimate total frames for whole-clip conversion."""
|
| 212 |
+
meta = probe_video_meta(str(video_path))
|
| 213 |
+
if meta is None:
|
| 214 |
+
return 0
|
| 215 |
+
_width, _height, source_fps, nb_frames, duration = meta
|
| 216 |
+
if nb_frames > 0:
|
| 217 |
+
return int(nb_frames)
|
| 218 |
+
if source_fps > 0 and duration > 0:
|
| 219 |
+
return max(1, int(duration * source_fps))
|
| 220 |
+
return 0
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def get_video_fps(src_video: Path, fps_cache: dict[Path, float]) -> float:
|
| 224 |
+
"""Read and cache source fps for frame/time conversion."""
|
| 225 |
+
if src_video not in fps_cache:
|
| 226 |
+
fps_cache[src_video] = probe_video_fps(src_video)
|
| 227 |
+
fps = fps_cache[src_video]
|
| 228 |
+
if fps <= 0:
|
| 229 |
+
raise RuntimeError(f"could not probe fps for {src_video}")
|
| 230 |
+
return fps
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def time_to_frame_bounds(start_time: float, end_time: float, fps: float) -> tuple[int, int]:
|
| 234 |
+
"""Convert seconds to inclusive frame bounds, matching preprocess_video_segments."""
|
| 235 |
+
if fps <= 0:
|
| 236 |
+
raise RuntimeError(f"cannot convert time bounds with invalid fps={fps}")
|
| 237 |
+
start_frame = max(0, int(start_time * fps))
|
| 238 |
+
end_frame = max(start_frame, int(end_time * fps))
|
| 239 |
+
return start_frame, end_frame
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def resolve_frame_bounds(
|
| 243 |
+
entry: dict,
|
| 244 |
+
src_video: Path,
|
| 245 |
+
fps_cache: dict[Path, float],
|
| 246 |
+
) -> tuple[int, int]:
|
| 247 |
+
"""Resolve supported temporal fields into inclusive frame bounds.
|
| 248 |
+
|
| 249 |
+
``preprocess_video_segments.py`` accepts both frame fields and time fields.
|
| 250 |
+
This converter keeps the same precedence: explicit frame bounds are used
|
| 251 |
+
directly; otherwise ``segment`` / ``start`` / ``end`` are converted through
|
| 252 |
+
the source video's fps.
|
| 253 |
+
"""
|
| 254 |
+
if has_frame_bounds(entry):
|
| 255 |
+
return extract_frame_bounds(entry)
|
| 256 |
+
|
| 257 |
+
if has_temporal_bounds(entry):
|
| 258 |
+
start_sec, end_sec = extract_time_bounds(entry)
|
| 259 |
+
fps = get_video_fps(src_video, fps_cache)
|
| 260 |
+
return time_to_frame_bounds(start_sec, end_sec, fps)
|
| 261 |
+
|
| 262 |
+
total_frames = probe_video_frame_count(src_video)
|
| 263 |
+
if total_frames <= 0:
|
| 264 |
+
raise KeyError(
|
| 265 |
+
"no temporal bounds found and failed to probe whole-video frame count; "
|
| 266 |
+
"expected frames, segment, start_frame/end_frame, or start/end"
|
| 267 |
+
)
|
| 268 |
+
return 0, total_frames - 1
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def frame_bounds_to_seconds(
|
| 272 |
+
start_frame: int,
|
| 273 |
+
end_frame: int,
|
| 274 |
+
src_video: Path,
|
| 275 |
+
fps_cache: dict[Path, float],
|
| 276 |
+
) -> tuple[float, float]:
|
| 277 |
+
"""Convert inclusive frame bounds to ffmpeg -ss / -t seconds."""
|
| 278 |
+
fps = get_video_fps(src_video, fps_cache)
|
| 279 |
+
start_sec = start_frame / fps
|
| 280 |
+
duration_sec = max(1e-3, (end_frame - start_frame + 1) / fps)
|
| 281 |
+
return start_sec, duration_sec
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def slice_video(src: Path, dst: Path, start_sec: float, duration_sec: float) -> None:
|
| 285 |
+
"""Copy a segment with -c copy (stream copy, near-instant). Overwrites dst.
|
| 286 |
+
|
| 287 |
+
Caveat: `-ss` before `-i` with `-c copy` seeks to the nearest keyframe, so
|
| 288 |
+
clip start may be offset by up to the GOP length (typically ≤ 1s). For
|
| 289 |
+
video-QA training on multi-second segments this is acceptable.
|
| 290 |
+
"""
|
| 291 |
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
| 292 |
+
if shutil.which("ffmpeg") is None:
|
| 293 |
+
raise RuntimeError("ffmpeg not found on PATH")
|
| 294 |
+
cmd = [
|
| 295 |
+
"ffmpeg", "-y", "-loglevel", "error",
|
| 296 |
+
"-ss", f"{start_sec:.3f}",
|
| 297 |
+
"-i", str(src),
|
| 298 |
+
"-t", f"{duration_sec:.3f}",
|
| 299 |
+
"-an",
|
| 300 |
+
"-c", "copy",
|
| 301 |
+
"-avoid_negative_ts", "make_zero",
|
| 302 |
+
str(dst),
|
| 303 |
+
]
|
| 304 |
+
subprocess.run(cmd, check=True, capture_output=True)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def convert_entry(
|
| 308 |
+
entry: dict,
|
| 309 |
+
csv_dir: Path,
|
| 310 |
+
clip_dir: Path,
|
| 311 |
+
fps_cache: dict[Path, float],
|
| 312 |
+
prompt_only: bool = False,
|
| 313 |
+
dataset_name: str = "dataset",
|
| 314 |
+
copy_full_video: bool = True,
|
| 315 |
+
) -> dict:
|
| 316 |
+
"""Convert one CoVLA row into the unified OmniTS row.
|
| 317 |
+
|
| 318 |
+
Returns: ``{video_id, video_path, timeseries_path, prompt, answer}`` where
|
| 319 |
+
``prompt`` retains the inline ``<timeseries>...</timeseries>`` body.
|
| 320 |
+
|
| 321 |
+
``prompt_only=True`` skips TS-CSV writing and video slicing. The derived
|
| 322 |
+
paths must already exist on disk. Use this to refresh prompts after the
|
| 323 |
+
source prompt text changes without re-running the expensive work.
|
| 324 |
+
"""
|
| 325 |
+
csv_dir = Path(csv_dir).resolve()
|
| 326 |
+
clip_dir = Path(clip_dir).resolve()
|
| 327 |
+
if not prompt_only:
|
| 328 |
+
csv_dir.mkdir(parents=True, exist_ok=True)
|
| 329 |
+
clip_dir.mkdir(parents=True, exist_ok=True)
|
| 330 |
+
|
| 331 |
+
video_id = stable_video_id(entry, dataset_name)
|
| 332 |
+
src_video = Path(entry["video_path"]).expanduser().resolve()
|
| 333 |
+
start_frame, end_frame = resolve_frame_bounds(
|
| 334 |
+
entry=entry,
|
| 335 |
+
src_video=src_video,
|
| 336 |
+
fps_cache=fps_cache,
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
# 1. Time-series CSV. In prompt-only mode we read the shape from the
|
| 340 |
+
# existing file; in fresh mode we use the in-memory DataFrame's shape
|
| 341 |
+
# directly (no extra IO).
|
| 342 |
+
csv_name = f"{video_id}_{start_frame}_{end_frame}.csv"
|
| 343 |
+
csv_path = csv_dir / csv_name
|
| 344 |
+
if prompt_only:
|
| 345 |
+
if not csv_path.exists():
|
| 346 |
+
raise FileNotFoundError(f"prompt-only mode: missing csv {csv_path}")
|
| 347 |
+
ts_shape = probe_ts_shape(str(csv_path))
|
| 348 |
+
else:
|
| 349 |
+
df = parse_timeseries_block(entry["prompt"])
|
| 350 |
+
df.to_csv(csv_path, index=False)
|
| 351 |
+
ts_shape = (int(df.shape[0]), int(df.shape[1]))
|
| 352 |
+
|
| 353 |
+
# 2. Video clip (ffmpeg-sliced). Reuse if it already exists.
|
| 354 |
+
clip_name = f"{video_id}_{start_frame}_{end_frame}.mp4"
|
| 355 |
+
clip_path = clip_dir / clip_name
|
| 356 |
+
if prompt_only:
|
| 357 |
+
if not (clip_path.exists() and clip_path.stat().st_size > 0):
|
| 358 |
+
raise FileNotFoundError(f"prompt-only mode: missing clip {clip_path}")
|
| 359 |
+
elif not (clip_path.exists() and clip_path.stat().st_size > 0):
|
| 360 |
+
if copy_full_video and not has_temporal_bounds(entry):
|
| 361 |
+
clip_path.parent.mkdir(parents=True, exist_ok=True)
|
| 362 |
+
shutil.copy2(src_video, clip_path)
|
| 363 |
+
else:
|
| 364 |
+
start_sec, duration_sec = frame_bounds_to_seconds(
|
| 365 |
+
start_frame=start_frame,
|
| 366 |
+
end_frame=end_frame,
|
| 367 |
+
src_video=src_video,
|
| 368 |
+
fps_cache=fps_cache,
|
| 369 |
+
)
|
| 370 |
+
slice_video(src_video, clip_path, start_sec, duration_sec)
|
| 371 |
+
|
| 372 |
+
# 2b. Probe the sliced clip for the meta that `compute_exact_lengths`
|
| 373 |
+
# needs — same whether we just wrote it or are reusing an existing clip.
|
| 374 |
+
video_meta = _video_meta_dict(probe_video_meta(str(clip_path)))
|
| 375 |
+
|
| 376 |
+
# 3. Unified row — prompt retains inline TS body; baseline uses it as-is,
|
| 377 |
+
# omnits strips it in the collator via strip_ts_block(). video_meta /
|
| 378 |
+
# ts_shape are optional hints consumed by the length estimator.
|
| 379 |
+
row: dict = {
|
| 380 |
+
"video_id": video_id,
|
| 381 |
+
"video_path": str(clip_path),
|
| 382 |
+
"timeseries_path": str(csv_path),
|
| 383 |
+
"prompt": entry["prompt"],
|
| 384 |
+
"answer": entry["ground_truth"],
|
| 385 |
+
}
|
| 386 |
+
if video_meta is not None:
|
| 387 |
+
row["video_meta"] = video_meta
|
| 388 |
+
if ts_shape is not None:
|
| 389 |
+
row["ts_shape"] = [int(ts_shape[0]), int(ts_shape[1])]
|
| 390 |
+
return row
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def _worker_convert(args: tuple[dict, str, str, bool, str, bool]) -> tuple[int, dict]:
|
| 394 |
+
"""Worker for ProcessPoolExecutor: convert a single entry.
|
| 395 |
+
|
| 396 |
+
Returns (line_no, row). fps_cache is per-worker (no sharing).
|
| 397 |
+
"""
|
| 398 |
+
entry, csv_dir, clip_dir, prompt_only, dataset_name, copy_full_video = args
|
| 399 |
+
line_no = entry["_line_no"]
|
| 400 |
+
_entry = {k: v for k, v in entry.items() if k != "_line_no"}
|
| 401 |
+
row = convert_entry(
|
| 402 |
+
_entry, csv_dir=Path(csv_dir), clip_dir=Path(clip_dir),
|
| 403 |
+
fps_cache={}, prompt_only=prompt_only, dataset_name=dataset_name,
|
| 404 |
+
copy_full_video=copy_full_video,
|
| 405 |
+
)
|
| 406 |
+
return line_no, row
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def _annotate_only(jsonl_path: Path, num_workers: int, force: bool) -> None:
|
| 410 |
+
"""Backfill video_meta / ts_shape into an existing unified OmniTS jsonl.
|
| 411 |
+
|
| 412 |
+
Use when clips + csvs already exist on disk and you only need the meta
|
| 413 |
+
fields added. Rewrites `jsonl_path` in place via .tmp + rename. Skips
|
| 414 |
+
rows that already have both fields unless --force is passed."""
|
| 415 |
+
with jsonl_path.open() as f:
|
| 416 |
+
rows = [json.loads(l) for l in f if l.strip()]
|
| 417 |
+
print(f"[ANNOTATE] loaded {len(rows)} rows from {jsonl_path}")
|
| 418 |
+
|
| 419 |
+
v_todo = [
|
| 420 |
+
i for i, r in enumerate(rows)
|
| 421 |
+
if force or not isinstance(r.get("video_meta"), dict)
|
| 422 |
+
]
|
| 423 |
+
t_todo = [
|
| 424 |
+
i for i, r in enumerate(rows)
|
| 425 |
+
if r.get("timeseries_path") and
|
| 426 |
+
(force or not isinstance(r.get("ts_shape"), (list, tuple)))
|
| 427 |
+
]
|
| 428 |
+
print(f"[ANNOTATE] to probe: {len(v_todo)} videos, {len(t_todo)} TS csvs "
|
| 429 |
+
f"(workers={num_workers})")
|
| 430 |
+
|
| 431 |
+
if v_todo:
|
| 432 |
+
done = 0
|
| 433 |
+
with ProcessPoolExecutor(max_workers=num_workers) as pool:
|
| 434 |
+
futs = {pool.submit(probe_video_meta, rows[i]["video_path"]): i for i in v_todo}
|
| 435 |
+
for fut in as_completed(futs):
|
| 436 |
+
i = futs[fut]
|
| 437 |
+
vm = _video_meta_dict(fut.result())
|
| 438 |
+
if vm is not None:
|
| 439 |
+
rows[i]["video_meta"] = vm
|
| 440 |
+
done += 1
|
| 441 |
+
if done % 1000 == 0:
|
| 442 |
+
print(f"[ANNOTATE] video {done}/{len(v_todo)}", flush=True)
|
| 443 |
+
|
| 444 |
+
if t_todo:
|
| 445 |
+
done = 0
|
| 446 |
+
with ProcessPoolExecutor(max_workers=num_workers) as pool:
|
| 447 |
+
futs = {pool.submit(probe_ts_shape, rows[i]["timeseries_path"]): i for i in t_todo}
|
| 448 |
+
for fut in as_completed(futs):
|
| 449 |
+
i = futs[fut]
|
| 450 |
+
shape = fut.result()
|
| 451 |
+
if shape is not None:
|
| 452 |
+
rows[i]["ts_shape"] = [int(shape[0]), int(shape[1])]
|
| 453 |
+
done += 1
|
| 454 |
+
if done % 2000 == 0:
|
| 455 |
+
print(f"[ANNOTATE] ts {done}/{len(t_todo)}", flush=True)
|
| 456 |
+
|
| 457 |
+
tmp = jsonl_path.with_suffix(jsonl_path.suffix + ".tmp")
|
| 458 |
+
with tmp.open("w") as f:
|
| 459 |
+
for r in rows:
|
| 460 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 461 |
+
tmp.replace(jsonl_path)
|
| 462 |
+
|
| 463 |
+
n_vm = sum(1 for r in rows if isinstance(r.get("video_meta"), dict))
|
| 464 |
+
n_ts = sum(1 for r in rows if isinstance(r.get("ts_shape"), (list, tuple)))
|
| 465 |
+
print(f"[ANNOTATE] wrote {jsonl_path}: {n_vm}/{len(rows)} video_meta, "
|
| 466 |
+
f"{n_ts}/{len(rows)} ts_shape")
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def main() -> None:
|
| 470 |
+
ap = argparse.ArgumentParser()
|
| 471 |
+
ap.add_argument(
|
| 472 |
+
"--annotate-only", action="store_true",
|
| 473 |
+
help="Skip slicing/parsing. Probe existing clips+csvs and write "
|
| 474 |
+
"video_meta / ts_shape back into --jsonl in place.",
|
| 475 |
+
)
|
| 476 |
+
ap.add_argument("--jsonl", type=Path,
|
| 477 |
+
help="[annotate-only mode] path to unified omnits jsonl to update in place.")
|
| 478 |
+
ap.add_argument("--force", action="store_true",
|
| 479 |
+
help="[annotate-only mode] re-probe rows that already have meta.")
|
| 480 |
+
ap.add_argument("--in-jsonl", type=Path)
|
| 481 |
+
ap.add_argument("--out-jsonl", type=Path)
|
| 482 |
+
ap.add_argument("--csv-dir", type=Path)
|
| 483 |
+
ap.add_argument("--clip-dir", type=Path)
|
| 484 |
+
ap.add_argument(
|
| 485 |
+
"--dataset-name",
|
| 486 |
+
default="dataset",
|
| 487 |
+
help="Prefix used when rows do not already contain video_id.",
|
| 488 |
+
)
|
| 489 |
+
ap.add_argument("--limit", type=int, default=None, help="First N rows only (smoke).")
|
| 490 |
+
ap.add_argument(
|
| 491 |
+
"--num-workers",
|
| 492 |
+
type=int,
|
| 493 |
+
default=1,
|
| 494 |
+
help="Parallel ffmpeg / probe workers. 1 = sequential.",
|
| 495 |
+
)
|
| 496 |
+
ap.add_argument(
|
| 497 |
+
"--prompt-only",
|
| 498 |
+
action="store_true",
|
| 499 |
+
help="Refresh prompts only: reuse existing TS CSVs and video clips, "
|
| 500 |
+
"skip ffmpeg slicing and TS parsing. Fails if derived files are missing.",
|
| 501 |
+
)
|
| 502 |
+
ap.add_argument(
|
| 503 |
+
"--slice-full-video",
|
| 504 |
+
action="store_true",
|
| 505 |
+
help="When a row has no temporal bounds, still rewrite the whole video with ffmpeg. "
|
| 506 |
+
"Default is to copy the already-segmented video into --clip-dir.",
|
| 507 |
+
)
|
| 508 |
+
ap.add_argument(
|
| 509 |
+
"--skip-errors",
|
| 510 |
+
action="store_true",
|
| 511 |
+
help="Skip rows that fail conversion and report their line numbers instead of stopping.",
|
| 512 |
+
)
|
| 513 |
+
ap.add_argument("--source-root", type=Path, help="Base directory for relative input video paths.")
|
| 514 |
+
ap.add_argument("--path-map", action="append", default=[], metavar="OLD=NEW",
|
| 515 |
+
help="Remap a legacy path prefix; repeat for multiple roots.")
|
| 516 |
+
args = ap.parse_args()
|
| 517 |
+
path_maps = []
|
| 518 |
+
for item in args.path_map:
|
| 519 |
+
if "=" not in item:
|
| 520 |
+
ap.error("--path-map must have the form OLD=NEW")
|
| 521 |
+
path_maps.append(tuple(item.split("=", 1)))
|
| 522 |
+
|
| 523 |
+
if args.annotate_only:
|
| 524 |
+
if args.jsonl is None:
|
| 525 |
+
ap.error("--annotate-only requires --jsonl")
|
| 526 |
+
_annotate_only(args.jsonl, args.num_workers, args.force)
|
| 527 |
+
return
|
| 528 |
+
|
| 529 |
+
missing = [n for n in ("in_jsonl", "out_jsonl", "csv_dir", "clip_dir")
|
| 530 |
+
if getattr(args, n) is None]
|
| 531 |
+
if missing:
|
| 532 |
+
ap.error(f"missing required args for conversion: {missing}")
|
| 533 |
+
|
| 534 |
+
args.out_jsonl.parent.mkdir(parents=True, exist_ok=True)
|
| 535 |
+
entries: list[dict] = []
|
| 536 |
+
with args.in_jsonl.open() as fin:
|
| 537 |
+
for line_no, line in enumerate(fin, 1):
|
| 538 |
+
if args.limit is not None and line_no > args.limit:
|
| 539 |
+
break
|
| 540 |
+
entry = json.loads(line)
|
| 541 |
+
raw = entry["video_path"]
|
| 542 |
+
for old, new in path_maps:
|
| 543 |
+
if raw == old or raw.startswith(old.rstrip("/") + "/"):
|
| 544 |
+
raw = new.rstrip("/") + raw[len(old.rstrip("/")):]
|
| 545 |
+
break
|
| 546 |
+
source_video = Path(raw).expanduser()
|
| 547 |
+
if not source_video.is_absolute():
|
| 548 |
+
source_video = (args.source_root or args.in_jsonl.resolve().parent) / source_video
|
| 549 |
+
entry["video_path"] = str(source_video.resolve())
|
| 550 |
+
entry["_line_no"] = line_no
|
| 551 |
+
entries.append(entry)
|
| 552 |
+
|
| 553 |
+
fout = args.out_jsonl.open("w")
|
| 554 |
+
n = 0
|
| 555 |
+
skipped: list[tuple[int, str]] = []
|
| 556 |
+
|
| 557 |
+
if args.num_workers <= 1:
|
| 558 |
+
fps_cache: dict[Path, float] = {}
|
| 559 |
+
try:
|
| 560 |
+
for entry in entries:
|
| 561 |
+
line_no = entry.pop("_line_no")
|
| 562 |
+
try:
|
| 563 |
+
row = convert_entry(
|
| 564 |
+
entry, csv_dir=args.csv_dir, clip_dir=args.clip_dir,
|
| 565 |
+
fps_cache=fps_cache, prompt_only=args.prompt_only,
|
| 566 |
+
dataset_name=args.dataset_name,
|
| 567 |
+
copy_full_video=not args.slice_full_video,
|
| 568 |
+
)
|
| 569 |
+
except (ValueError, KeyError, RuntimeError,
|
| 570 |
+
subprocess.CalledProcessError) as exc:
|
| 571 |
+
if args.skip_errors:
|
| 572 |
+
skipped.append((line_no, str(exc)))
|
| 573 |
+
continue
|
| 574 |
+
raise RuntimeError(f"line {line_no}: {exc}") from exc
|
| 575 |
+
fout.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 576 |
+
n += 1
|
| 577 |
+
finally:
|
| 578 |
+
fout.close()
|
| 579 |
+
else:
|
| 580 |
+
# Parallel: write rows as they complete (no order guarantee — shuffle-safe).
|
| 581 |
+
work = [
|
| 582 |
+
(
|
| 583 |
+
e,
|
| 584 |
+
str(args.csv_dir),
|
| 585 |
+
str(args.clip_dir),
|
| 586 |
+
args.prompt_only,
|
| 587 |
+
args.dataset_name,
|
| 588 |
+
not args.slice_full_video,
|
| 589 |
+
)
|
| 590 |
+
for e in entries
|
| 591 |
+
]
|
| 592 |
+
try:
|
| 593 |
+
with ProcessPoolExecutor(max_workers=args.num_workers) as pool:
|
| 594 |
+
for future in as_completed(
|
| 595 |
+
[pool.submit(_worker_convert, w) for w in work]
|
| 596 |
+
):
|
| 597 |
+
try:
|
| 598 |
+
_line_no, row = future.result()
|
| 599 |
+
except Exception as exc:
|
| 600 |
+
if args.skip_errors:
|
| 601 |
+
skipped.append((-1, str(exc)))
|
| 602 |
+
continue
|
| 603 |
+
raise
|
| 604 |
+
fout.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 605 |
+
fout.flush()
|
| 606 |
+
n += 1
|
| 607 |
+
if n % 200 == 0:
|
| 608 |
+
print(f" converted {n}/{len(entries)}", flush=True)
|
| 609 |
+
finally:
|
| 610 |
+
fout.close()
|
| 611 |
+
|
| 612 |
+
print(f"converted {n} entries → {args.out_jsonl}")
|
| 613 |
+
if skipped:
|
| 614 |
+
print(f"skipped {len(skipped)} entries")
|
| 615 |
+
for line_no, reason in skipped[:20]:
|
| 616 |
+
location = f"line {line_no}" if line_no > 0 else "worker"
|
| 617 |
+
print(f" {location}: {reason}")
|
| 618 |
+
if len(skipped) > 20:
|
| 619 |
+
print(f" ... {len(skipped) - 20} more")
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
if __name__ == "__main__":
|
| 623 |
+
main()
|
processing/common/local_generation.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Run excluded-domain builders and conversion into a private output tree."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
PROCESSING = Path(__file__).resolve().parents[1]
|
| 15 |
+
RELEASE = PROCESSING.parent
|
| 16 |
+
DOMAINS = ("covla", "cuhk_x_har", "mimic_death", "mimic_disch", "pixelrec", "sp500")
|
| 17 |
+
IMAGE_DOMAINS = {"mimic_death", "mimic_disch", "pixelrec", "sp500"}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def run_stage(script: str, *arguments: object) -> None:
|
| 21 |
+
"""Use the current interpreter and keep bytecode out of the release."""
|
| 22 |
+
group = script.split("/", 1)[0]
|
| 23 |
+
if group in DOMAINS:
|
| 24 |
+
modality = "image-timeseries" if group in IMAGE_DOMAINS else "video-timeseries"
|
| 25 |
+
path = RELEASE / "sample" / modality / script
|
| 26 |
+
else:
|
| 27 |
+
path = PROCESSING / script
|
| 28 |
+
subprocess.run(
|
| 29 |
+
[sys.executable, "-B", str(path), *map(str, arguments)],
|
| 30 |
+
check=True,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def require_path(parser: argparse.ArgumentParser, path: Path | None, option: str) -> Path:
|
| 35 |
+
if path is None or not path.exists():
|
| 36 |
+
parser.error(f"{option} must identify an existing local input")
|
| 37 |
+
return path.resolve()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def build_prompts(
|
| 41 |
+
args: argparse.Namespace, parser: argparse.ArgumentParser, output: Path,
|
| 42 |
+
) -> Path:
|
| 43 |
+
if args.input_jsonl:
|
| 44 |
+
return require_path(parser, args.input_jsonl, "--input-jsonl")
|
| 45 |
+
prompts = output / "intermediate"
|
| 46 |
+
if args.domain in {"mimic_death", "mimic_disch"}:
|
| 47 |
+
hosp = require_path(parser, args.mimic_hosp_dir, "--mimic-hosp-dir")
|
| 48 |
+
notes = require_path(parser, args.mimic_note_dir, "--mimic-note-dir")
|
| 49 |
+
metadata = require_path(parser, args.cxr_metadata_csv, "--cxr-metadata-csv")
|
| 50 |
+
images = require_path(parser, args.cxr_jpg_root, "--cxr-jpg-root")
|
| 51 |
+
prompts.mkdir()
|
| 52 |
+
buckets = args.chartevents_root
|
| 53 |
+
if buckets is None:
|
| 54 |
+
events = require_path(parser, args.chartevents, "--chartevents")
|
| 55 |
+
buckets = prompts / "chartevents_bucketed"
|
| 56 |
+
run_stage("mimic_death/bucket_chartevents.py", "--input", events,
|
| 57 |
+
"--output-root", buckets, "--chunksize", args.chunksize)
|
| 58 |
+
else:
|
| 59 |
+
buckets = require_path(parser, buckets, "--chartevents-root")
|
| 60 |
+
raw = prompts / "patients.jsonl"
|
| 61 |
+
common = ["--mimic-hosp-dir", hosp, "--mimic-note-dir", notes,
|
| 62 |
+
"--cxr-metadata-csv", metadata, "--cxr-jpg-root", images,
|
| 63 |
+
"--chartevents-root", buckets, "--out-jsonl", raw,
|
| 64 |
+
"--qc-csv", prompts / "patient_qc.csv", "--seed", args.seed]
|
| 65 |
+
if args.domain == "mimic_death":
|
| 66 |
+
icu = require_path(parser, args.mimic_icu_dir, "--mimic-icu-dir")
|
| 67 |
+
run_stage("mimic_death/build_json_QA_death.py", *common,
|
| 68 |
+
"--mimic-icu-dir", icu, "--n-death", args.n_positive,
|
| 69 |
+
"--n-alive", args.n_negative, "--require-image-file-exists")
|
| 70 |
+
prompt_script = "mimic_death/json_prompt_death.py"
|
| 71 |
+
else:
|
| 72 |
+
run_stage("mimic_disch/build_json_QA.py", *common,
|
| 73 |
+
"--max-pos", args.n_positive, "--max-neg", args.n_negative)
|
| 74 |
+
prompt_script = "mimic_disch/json_prompt.py"
|
| 75 |
+
all_prompts = prompts / "all.jsonl"
|
| 76 |
+
run_stage(prompt_script, "--in-jsonl", raw, "--out-jsonl", all_prompts)
|
| 77 |
+
run_stage("mimic_death/split_dataset.py", all_prompts,
|
| 78 |
+
"--out-dir", prompts, "--seed", args.seed + (args.domain == "mimic_disch"))
|
| 79 |
+
(prompts / "all_train.jsonl").rename(prompts / "train.jsonl")
|
| 80 |
+
(prompts / "all_test.jsonl").rename(prompts / "test.jsonl")
|
| 81 |
+
elif args.domain == "covla":
|
| 82 |
+
source = require_path(parser, args.source_root, "--source-root")
|
| 83 |
+
for name in ("states", "front_car", "metadata.jsonl"):
|
| 84 |
+
require_path(parser, source / name, f"--source-root/{name}")
|
| 85 |
+
prompts.mkdir()
|
| 86 |
+
brakes = prompts / "brake_reasons"
|
| 87 |
+
run_stage("covla/extract_brake_reasons.py", "--root", source, "--output-dir", brakes)
|
| 88 |
+
enriched = prompts / "enriched.jsonl"
|
| 89 |
+
run_stage(
|
| 90 |
+
"covla/enrich_segments.py", "--root", source,
|
| 91 |
+
"--input", brakes / "all_brake_reasons.jsonl", "--output", enriched,
|
| 92 |
+
"--sample-output", prompts / "enriched_inspection.jsonl",
|
| 93 |
+
)
|
| 94 |
+
all_prompts = prompts / "all.jsonl"
|
| 95 |
+
run_stage(
|
| 96 |
+
"covla/build_prompts.py", "--root", source, "--input", enriched,
|
| 97 |
+
"--output", all_prompts, "--sample-output", prompts / "inspection.jsonl",
|
| 98 |
+
)
|
| 99 |
+
run_stage(
|
| 100 |
+
"covla/split_dataset.py", "--root", source, "--input", all_prompts,
|
| 101 |
+
"--train-output", prompts / "train.jsonl", "--test-output", prompts / "test.jsonl",
|
| 102 |
+
"--stats-output", prompts / "split_stats.json", "--seed", args.seed,
|
| 103 |
+
)
|
| 104 |
+
elif args.domain == "cuhk_x_har":
|
| 105 |
+
source = require_path(parser, args.source_root, "--source-root")
|
| 106 |
+
skeleton = require_path(parser, args.skeleton_root or source / "Skeleton", "--skeleton-root")
|
| 107 |
+
prompts.mkdir()
|
| 108 |
+
if args.aligned_jsonl:
|
| 109 |
+
aligned = require_path(parser, args.aligned_jsonl, "--aligned-jsonl")
|
| 110 |
+
else:
|
| 111 |
+
imu = require_path(parser, args.imu_root or source / "IMU", "--imu-root")
|
| 112 |
+
local_imu = prompts / "IMU"
|
| 113 |
+
local_skeleton = prompts / "Skeleton"
|
| 114 |
+
run_stage("cuhk_x_har/xlsx_to_csv.py", "--input-root", imu,
|
| 115 |
+
"--output-root", local_imu)
|
| 116 |
+
run_stage("cuhk_x_har/images_to_video.py", skeleton,
|
| 117 |
+
"--output-root", local_skeleton, "--fps", args.fps,
|
| 118 |
+
"--split-mode", args.skeleton_crop)
|
| 119 |
+
aligned = prompts / "imu_skeleton_aligned.jsonl"
|
| 120 |
+
run_stage("cuhk_x_har/imu_skeleton_to_jsonl.py", "--imu-root", local_imu,
|
| 121 |
+
"--skeleton-root", local_skeleton, "--output", aligned)
|
| 122 |
+
run_stage(
|
| 123 |
+
"cuhk_x_har/prepare.py", "--root", source, "--input", aligned,
|
| 124 |
+
"--skeleton-root", skeleton, "--train-output", prompts / "train.jsonl",
|
| 125 |
+
"--test-output", prompts / "test.jsonl",
|
| 126 |
+
"--train-sample-output", prompts / "train_inspection.jsonl",
|
| 127 |
+
"--test-sample-output", prompts / "test_inspection.jsonl", "--seed", args.seed,
|
| 128 |
+
)
|
| 129 |
+
elif args.domain == "pixelrec":
|
| 130 |
+
interactions = require_path(parser, args.interactions, "--interactions")
|
| 131 |
+
item_info = require_path(parser, args.item_info, "--item-info")
|
| 132 |
+
images = require_path(parser, args.image_root, "--image-root")
|
| 133 |
+
prompts.mkdir()
|
| 134 |
+
run_stage(
|
| 135 |
+
"pixelrec/prepare.py", "--interactions", interactions, "--item-info", item_info,
|
| 136 |
+
"--image-root", images, "--output", prompts / f"{args.split}.jsonl",
|
| 137 |
+
"--limit", args.limit or 0,
|
| 138 |
+
)
|
| 139 |
+
elif args.domain == "sp500":
|
| 140 |
+
prices = require_path(parser, args.time_series_dir, "--time-series-dir")
|
| 141 |
+
news = require_path(parser, args.news_dir, "--news-dir")
|
| 142 |
+
images = require_path(parser, args.image_root, "--image-root")
|
| 143 |
+
prompts.mkdir()
|
| 144 |
+
run_stage(
|
| 145 |
+
"sp500/prepare.py", "--time-series-dir", prices, "--news-dir", news,
|
| 146 |
+
"--image-dir", images, "--out-jsonl", prompts / f"{args.split}.jsonl",
|
| 147 |
+
"--max-files", args.limit or -1, "--fut-len", args.horizon,
|
| 148 |
+
"--news-timezone", args.news_timezone,
|
| 149 |
+
)
|
| 150 |
+
return prompts / f"{args.split}.jsonl"
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def main(domain: str) -> None:
|
| 154 |
+
if domain not in DOMAINS:
|
| 155 |
+
raise ValueError(f"Unsupported excluded domain: {domain}")
|
| 156 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 157 |
+
parser.set_defaults(domain=domain, input_jsonl=None)
|
| 158 |
+
parser.add_argument("--output-dir", type=Path, required=True,
|
| 159 |
+
help="New private workspace outside MMTA-v1.0; a domain child is created.")
|
| 160 |
+
if domain != "sp500":
|
| 161 |
+
parser.add_argument("--input-jsonl", type=Path,
|
| 162 |
+
help="Optional existing task prompts to convert.")
|
| 163 |
+
parser.add_argument("--source-root", type=Path, help="Local source root or base for relative media.")
|
| 164 |
+
parser.add_argument("--path-map", action="append", default=[], metavar="OLD=NEW")
|
| 165 |
+
parser.add_argument("--split", choices=("train", "test"), default="test")
|
| 166 |
+
parser.add_argument("--limit", type=int, help="Maximum converted records; default processes all.")
|
| 167 |
+
if domain in {"covla", "cuhk_x_har", "mimic_death", "mimic_disch"}:
|
| 168 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 169 |
+
if domain in {"covla", "cuhk_x_har"}:
|
| 170 |
+
parser.add_argument("--num-workers", type=int, default=1)
|
| 171 |
+
if domain == "cuhk_x_har":
|
| 172 |
+
parser.add_argument("--aligned-jsonl", type=Path, help="Optional existing aligned IMU/skeleton input.")
|
| 173 |
+
parser.add_argument("--imu-root", type=Path, help="Defaults to <source-root>/IMU.")
|
| 174 |
+
parser.add_argument("--skeleton-root", type=Path, help="Skeleton action directory tree.")
|
| 175 |
+
parser.add_argument("--fps", type=int, default=20)
|
| 176 |
+
parser.add_argument("--skeleton-crop", choices=("left-half", "auto", "none"), default="left-half")
|
| 177 |
+
if domain in {"mimic_death", "mimic_disch"}:
|
| 178 |
+
parser.add_argument("--mimic-hosp-dir", type=Path)
|
| 179 |
+
parser.add_argument("--mimic-icu-dir", type=Path)
|
| 180 |
+
parser.add_argument("--mimic-note-dir", type=Path)
|
| 181 |
+
parser.add_argument("--cxr-metadata-csv", type=Path)
|
| 182 |
+
parser.add_argument("--cxr-jpg-root", type=Path)
|
| 183 |
+
events = parser.add_mutually_exclusive_group()
|
| 184 |
+
events.add_argument("--chartevents", type=Path, help="Raw chartevents.csv or chartevents.csv.gz.")
|
| 185 |
+
events.add_argument("--chartevents-root", type=Path, help="Existing subject/admission buckets.")
|
| 186 |
+
parser.add_argument("--chunksize", type=int, default=1000000)
|
| 187 |
+
parser.add_argument("--n-positive", type=int, default=20 if domain == "mimic_death" else 50)
|
| 188 |
+
parser.add_argument("--n-negative", type=int, default=130 if domain == "mimic_death" else 100)
|
| 189 |
+
if domain == "pixelrec":
|
| 190 |
+
parser.add_argument("--interactions", type=Path)
|
| 191 |
+
parser.add_argument("--item-info", type=Path)
|
| 192 |
+
parser.add_argument("--image-root", type=Path)
|
| 193 |
+
if domain == "sp500":
|
| 194 |
+
parser.add_argument("--time-series-dir", type=Path)
|
| 195 |
+
parser.add_argument("--news-dir", type=Path)
|
| 196 |
+
parser.add_argument("--image-root", "--image-dir", type=Path)
|
| 197 |
+
parser.add_argument("--horizon", type=int, default=12)
|
| 198 |
+
parser.add_argument("--news-timezone", default="America/New_York")
|
| 199 |
+
args = parser.parse_args()
|
| 200 |
+
if args.limit is not None and args.limit < 1:
|
| 201 |
+
parser.error("--limit must be positive")
|
| 202 |
+
if getattr(args, "num_workers", 1) < 1:
|
| 203 |
+
parser.error("--num-workers must be positive")
|
| 204 |
+
if getattr(args, "fps", 1) < 1 or getattr(args, "chunksize", 1) < 1:
|
| 205 |
+
parser.error("--fps and --chunksize must be positive")
|
| 206 |
+
if domain in {"mimic_death", "mimic_disch"} and (args.n_positive < 0 or args.n_negative < 0):
|
| 207 |
+
parser.error("--n-positive and --n-negative must be nonnegative")
|
| 208 |
+
if any("=" not in item for item in args.path_map):
|
| 209 |
+
parser.error("--path-map must have the form OLD=NEW")
|
| 210 |
+
output = args.output_dir.expanduser().resolve() / domain
|
| 211 |
+
if output.is_relative_to(RELEASE):
|
| 212 |
+
parser.error("Restricted output must be outside MMTA-v1.0")
|
| 213 |
+
if output.exists():
|
| 214 |
+
parser.error(f"Output already exists: {output}; choose a new workspace")
|
| 215 |
+
output.mkdir(parents=True)
|
| 216 |
+
input_jsonl = build_prompts(args, parser, output)
|
| 217 |
+
output_jsonl = output / f"{domain}.omnits.jsonl"
|
| 218 |
+
arguments: list[object] = [
|
| 219 |
+
"--in-jsonl", input_jsonl, "--out-jsonl", output_jsonl,
|
| 220 |
+
"--csv-dir", output / "timeseries", "--dataset-name", f"{domain}_{args.split}",
|
| 221 |
+
]
|
| 222 |
+
if args.source_root:
|
| 223 |
+
arguments.extend(("--source-root", args.source_root.resolve()))
|
| 224 |
+
for item in args.path_map:
|
| 225 |
+
arguments.extend(("--path-map", item))
|
| 226 |
+
if args.limit:
|
| 227 |
+
arguments.extend(("--limit", args.limit))
|
| 228 |
+
if domain in IMAGE_DOMAINS:
|
| 229 |
+
task = "prediction" if domain in {"pixelrec", "sp500"} else "classification"
|
| 230 |
+
arguments.extend(("--default-task", task))
|
| 231 |
+
run_stage("common/convert_images.py", *arguments)
|
| 232 |
+
else:
|
| 233 |
+
arguments.extend(("--clip-dir", output / "video_clips", "--num-workers", args.num_workers))
|
| 234 |
+
run_stage("common/convert_videos.py", *arguments)
|
| 235 |
+
|
| 236 |
+
# Keep converted assets and relative references local to this private tree.
|
| 237 |
+
temporary = output_jsonl.with_suffix(".tmp")
|
| 238 |
+
count = 0
|
| 239 |
+
with output_jsonl.open(encoding="utf-8") as source, temporary.open("w", encoding="utf-8") as target:
|
| 240 |
+
for line in source:
|
| 241 |
+
record = json.loads(line)
|
| 242 |
+
if "id" not in record:
|
| 243 |
+
record["id"] = f"{domain}_{args.split}_{Path(record['timeseries_path']).stem}"
|
| 244 |
+
record.pop("video_id", None)
|
| 245 |
+
record.setdefault("task", "classification")
|
| 246 |
+
record.update(domain=domain, split=args.split, variant="original")
|
| 247 |
+
for field in ("timeseries_path", "video_path", "image_path"):
|
| 248 |
+
if field not in record:
|
| 249 |
+
continue
|
| 250 |
+
values = record[field] if isinstance(record[field], list) else [record[field]]
|
| 251 |
+
paths = [os.path.relpath(Path(value).resolve(), output).replace(os.sep, "/") for value in values]
|
| 252 |
+
record[field] = paths if isinstance(record[field], list) else paths[0]
|
| 253 |
+
target.write(json.dumps(record, ensure_ascii=False, allow_nan=False) + "\n")
|
| 254 |
+
count += 1
|
| 255 |
+
if not count:
|
| 256 |
+
raise RuntimeError("No local tasks were generated")
|
| 257 |
+
temporary.replace(output_jsonl)
|
| 258 |
+
print(json.dumps({"domain": domain, "split": args.split, "records": count,
|
| 259 |
+
"output": str(output_jsonl), "path_base": str(output),
|
| 260 |
+
"scope": "private_local_reconstruction"}, indent=2))
|
processing/common/probe.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Standalone CSV shape and ffprobe helpers for the video converter."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import csv
|
| 7 |
+
import json
|
| 8 |
+
import subprocess
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def probe_ts_shape(path: str) -> tuple[int, int]:
|
| 13 |
+
with Path(path).open(encoding="utf-8", newline="") as handle:
|
| 14 |
+
reader = csv.reader(handle)
|
| 15 |
+
header = next(reader)
|
| 16 |
+
columns = sum(name.lower() not in {"timestamp", "time", "datetime"} for name in header)
|
| 17 |
+
return sum(1 for _ in reader), columns
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def probe_video_meta(path: str) -> tuple[int, int, float, int, float]:
|
| 21 |
+
result = subprocess.run(
|
| 22 |
+
["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
|
| 23 |
+
"stream=width,height,avg_frame_rate,nb_frames,duration:format=duration", "-of", "json", path],
|
| 24 |
+
capture_output=True, text=True, timeout=60, check=True,
|
| 25 |
+
)
|
| 26 |
+
data = json.loads(result.stdout)
|
| 27 |
+
stream = data["streams"][0]
|
| 28 |
+
numerator, denominator = stream["avg_frame_rate"].split("/")
|
| 29 |
+
fps = float(numerator) / float(denominator)
|
| 30 |
+
duration = float(stream.get("duration", data.get("format", {}).get("duration", 0)))
|
| 31 |
+
frame_count = stream.get("nb_frames", "N/A")
|
| 32 |
+
frames = int(frame_count) if frame_count != "N/A" else round(duration * fps)
|
| 33 |
+
return int(stream["width"]), int(stream["height"]), fps, frames, duration
|
processing/common/test_convert_videos.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Regression tests for distinguishing observed sensor rows from instructions."""
|
| 3 |
+
|
| 4 |
+
import unittest
|
| 5 |
+
|
| 6 |
+
from convert_videos import parse_timeseries_block, parse_timeseries_data_line
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class SensorRowTests(unittest.TestCase):
|
| 10 |
+
def test_format_example_is_not_an_observation(self) -> None:
|
| 11 |
+
self.assertIsNone(parse_timeseries_data_line("t(s): speed=, acceleration=, steering="))
|
| 12 |
+
|
| 13 |
+
def test_instruction_with_commas_is_not_an_observation(self) -> None:
|
| 14 |
+
self.assertIsNone(parse_timeseries_data_line("Per-frame sensor data, missing = unavailable:"))
|
| 15 |
+
|
| 16 |
+
def test_actual_missing_observations_are_preserved(self) -> None:
|
| 17 |
+
row = parse_timeseries_data_line("1.5: speed=10, acceleration=null")
|
| 18 |
+
self.assertEqual(row["speed"], 10)
|
| 19 |
+
self.assertNotEqual(row["acceleration"], row["acceleration"])
|
| 20 |
+
|
| 21 |
+
def test_iso_timestamp_rows_are_still_supported(self) -> None:
|
| 22 |
+
self.assertEqual(parse_timeseries_data_line("2024-06-30T12:00:00Z, speed=10"), {"speed": 10})
|
| 23 |
+
|
| 24 |
+
def test_template_line_does_not_increase_sequence_length(self) -> None:
|
| 25 |
+
frame = parse_timeseries_block(
|
| 26 |
+
"<timeseries>\nOne-line format example:\nt(s): speed=, acceleration=\n"
|
| 27 |
+
"1.0: speed=10, acceleration=null\n1.5: speed=9, acceleration=-1\n</timeseries>"
|
| 28 |
+
)
|
| 29 |
+
self.assertEqual(frame.shape, (2, 2))
|
| 30 |
+
self.assertEqual(frame["speed"].tolist(), [10, 9])
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if __name__ == "__main__":
|
| 34 |
+
unittest.main()
|
processing/download.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Download original datasets from official sources for local reconstruction.
|
| 3 |
+
|
| 4 |
+
Run with --dry-run to inspect a download plan. No restricted data are hosted
|
| 5 |
+
by MMTA. Account approval and source agreements must be completed upstream.
|
| 6 |
+
Downloads and private derivatives must remain outside this release tree.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import fnmatch
|
| 13 |
+
import hashlib
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
import shutil
|
| 17 |
+
import subprocess
|
| 18 |
+
import sys
|
| 19 |
+
import urllib.parse
|
| 20 |
+
import urllib.request
|
| 21 |
+
from pathlib import Path, PurePosixPath
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
RELEASE = Path(__file__).resolve().parents[1]
|
| 25 |
+
CUHK_PORTAL = "https://aiot-public-dataset-cuhk-x.cuhkaiot.com"
|
| 26 |
+
HF_REPOS = {
|
| 27 |
+
"covla": "turing-motors/CoVLA-Dataset",
|
| 28 |
+
"agibot": "agibot-world/AgiBotWorld2026",
|
| 29 |
+
"sp500": "Wenyan0110/Multimodal-Dataset-Image_Text_Table_TimeSeries-for-Financial-Time-Series-Forecasting",
|
| 30 |
+
"terra": "onedean/Terra",
|
| 31 |
+
}
|
| 32 |
+
PIXELREC = {
|
| 33 |
+
"covers": ("file", "17V70KN6UOAdphNEc0wXlocFwgmI7hVOo", "covers.archive"),
|
| 34 |
+
"interactions": ("folder", "1vR1lgQUZCy1cuhzPkM2q7AsdYRP43feQ", "interactions"),
|
| 35 |
+
"item-info": ("folder", "1rXBM-zi5sSdLHNshXWtGgVReWLuYNgDB", "item-info"),
|
| 36 |
+
"pixel200k": ("file", "1fu0tqCmmXkte5PAsyMo0DQrDS0zofTLH", "Pixel200K.archive"),
|
| 37 |
+
}
|
| 38 |
+
HOLOASSIST = {
|
| 39 |
+
"videos": "video_compress.tar", "eyes": "eyes.tar", "head": "head.tar", "imu": "imu.tar",
|
| 40 |
+
"annotations": "data-annotation-trainval-v1_1.json", "splits": "data-splits-v1_2.zip",
|
| 41 |
+
}
|
| 42 |
+
PHYSIONET = {"mimiciv": "3.1", "mimic-cxr-jpg": "2.1.0", "mimic-cxr": "2.1.0", "mimic-iv-note": "2.2"}
|
| 43 |
+
TERRA_PORTAL = "https://hkustgz-my.sharepoint.com/:f:/g/personal/wchen110_connect_hkust-gz_edu_cn/Ev1pUSErKghFkzmXb5j7svgBf2XwMn095VNz1kOOtjhTXA?e=lUCxZb"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def relative_path(raw: str) -> str:
|
| 47 |
+
path = PurePosixPath(raw)
|
| 48 |
+
if not raw or path.is_absolute() or any(x in {"..", "."} for x in path.parts) or "\\" in raw or ":" in raw or raw != path.as_posix():
|
| 49 |
+
raise ValueError(f"Expected a normalized relative file path: {raw}")
|
| 50 |
+
return raw
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def download_url(url: str, target: Path, expected_sha256: str | None = None) -> None:
|
| 54 |
+
"""Stream a public URL to an atomic file and reject failed/HTML downloads."""
|
| 55 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 56 |
+
partial = target.with_name(target.name + ".partial")
|
| 57 |
+
request = urllib.request.Request(url, headers={"User-Agent": "MMTA-source-downloader/1.0"})
|
| 58 |
+
digest = hashlib.sha256()
|
| 59 |
+
received = 0
|
| 60 |
+
with urllib.request.urlopen(request, timeout=120) as response, partial.open("wb") as handle:
|
| 61 |
+
content_type = response.headers.get("Content-Type", "").lower()
|
| 62 |
+
expected_length = response.headers.get("Content-Length")
|
| 63 |
+
if "text/html" in content_type:
|
| 64 |
+
raise RuntimeError("The source returned a web/login page. Complete upstream access steps and obtain a file-download URL.")
|
| 65 |
+
first = True
|
| 66 |
+
while block := response.read(8 * 1024 * 1024):
|
| 67 |
+
if first and block.lstrip().lower().startswith((b"<!doctype html", b"<html")):
|
| 68 |
+
raise RuntimeError("The source returned HTML instead of a data file")
|
| 69 |
+
first = False
|
| 70 |
+
digest.update(block)
|
| 71 |
+
handle.write(block)
|
| 72 |
+
received += len(block)
|
| 73 |
+
if not partial.stat().st_size:
|
| 74 |
+
raise RuntimeError("The download was empty")
|
| 75 |
+
if expected_length and received != int(expected_length):
|
| 76 |
+
raise RuntimeError("The source download ended before all advertised bytes were received")
|
| 77 |
+
if expected_sha256 and digest.hexdigest() != expected_sha256:
|
| 78 |
+
raise RuntimeError("The downloaded file failed SHA-256 verification")
|
| 79 |
+
partial.replace(target)
|
| 80 |
+
print(json.dumps({"file": str(target), "bytes": target.stat().st_size, "sha256": digest.hexdigest()}))
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def hf_download(args: argparse.Namespace) -> None:
|
| 84 |
+
repo = HF_REPOS[args.dataset]
|
| 85 |
+
patterns = args.include or (["*.tar.gz", "*.jsonl", "metadata*", "README.md"] if args.dataset == "covla" else ["*"])
|
| 86 |
+
if args.dataset == "agibot" and not args.include:
|
| 87 |
+
patterns = ["task_3641/*", "task_3777/*", "task3641/*", "task3777/*", "README.md"]
|
| 88 |
+
if args.dry_run:
|
| 89 |
+
print(json.dumps({"method": "huggingface_hub.snapshot_download", "repo_id": repo, "revision": args.revision,
|
| 90 |
+
"allow_patterns": patterns, "output": str(args.output), "token_environment": "HF_TOKEN"}, indent=2))
|
| 91 |
+
return
|
| 92 |
+
try:
|
| 93 |
+
from huggingface_hub import HfApi, snapshot_download
|
| 94 |
+
except ImportError as exc:
|
| 95 |
+
raise RuntimeError("Install huggingface-hub from processing/requirements.txt") from exc
|
| 96 |
+
token = os.environ.get("HF_TOKEN") or None
|
| 97 |
+
info = HfApi().dataset_info(repo_id=repo, revision=args.revision, token=token)
|
| 98 |
+
matched = [entry.rfilename for entry in info.siblings if any(fnmatch.fnmatch(entry.rfilename, pattern) for pattern in patterns)]
|
| 99 |
+
if not matched:
|
| 100 |
+
raise RuntimeError("No upstream files matched --include")
|
| 101 |
+
snapshot_download(repo_id=repo, repo_type="dataset", revision=info.sha, local_dir=args.output,
|
| 102 |
+
allow_patterns=patterns, token=token, max_workers=args.workers)
|
| 103 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 104 |
+
(args.output / "download-provenance.json").write_text(json.dumps({"source": repo, "revision": info.sha, "files": matched}, indent=2) + "\n")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def pixelrec_download(args: argparse.Namespace) -> None:
|
| 108 |
+
components = args.component or ["pixel200k"]
|
| 109 |
+
for name in components:
|
| 110 |
+
if name not in PIXELREC:
|
| 111 |
+
raise ValueError(f"PixelRec components: {', '.join(PIXELREC)}")
|
| 112 |
+
kind, identifier, filename = PIXELREC[name]
|
| 113 |
+
url = f"https://drive.google.com/{'file/d' if kind == 'file' else 'drive/folders'}/{identifier}"
|
| 114 |
+
if args.dry_run:
|
| 115 |
+
print(json.dumps({"component": name, "url": url, "method": "gdown", "output": str(args.output / filename)}))
|
| 116 |
+
continue
|
| 117 |
+
try:
|
| 118 |
+
import gdown
|
| 119 |
+
except ImportError as exc:
|
| 120 |
+
raise RuntimeError("Install gdown from processing/requirements.txt") from exc
|
| 121 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 122 |
+
if kind == "folder":
|
| 123 |
+
result = gdown.download_folder(url=url, output=str(args.output / filename), quiet=False, remaining_ok=True)
|
| 124 |
+
else:
|
| 125 |
+
result = gdown.download(id=identifier, output=str(args.output / filename), quiet=False, resume=True)
|
| 126 |
+
if not result:
|
| 127 |
+
raise RuntimeError(f"Official Google Drive download failed for {name}; use the upstream README to obtain access")
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def mimic_download(args: argparse.Namespace) -> None:
|
| 131 |
+
if args.physionet_dataset not in PHYSIONET:
|
| 132 |
+
raise ValueError("Unknown PhysioNet dataset")
|
| 133 |
+
version = args.version or PHYSIONET[args.physionet_dataset]
|
| 134 |
+
if not version or any(character not in "0123456789." for character in version):
|
| 135 |
+
raise ValueError("Expected a numeric PhysioNet version")
|
| 136 |
+
base = f"https://physionet.org/files/{args.physionet_dataset}/{version}/"
|
| 137 |
+
paths = list(args.file or [])
|
| 138 |
+
if args.file_list:
|
| 139 |
+
paths.extend(line.strip() for line in args.file_list.read_text().splitlines() if line.strip() and not line.lstrip().startswith("#"))
|
| 140 |
+
if not paths:
|
| 141 |
+
raise ValueError("Use --file or --file-list to select personally authorized source files; whole medical datasets are not downloaded implicitly")
|
| 142 |
+
for raw in paths:
|
| 143 |
+
path = relative_path(raw)
|
| 144 |
+
url = base + urllib.parse.quote(path, safe="/")
|
| 145 |
+
command = ["wget", "--continue", "--no-verbose", "--user", args.username or "PHYSIONET_USERNAME", "--ask-password",
|
| 146 |
+
"--output-document", str(args.output / args.physionet_dataset / path), url]
|
| 147 |
+
if args.dry_run:
|
| 148 |
+
print(json.dumps({"command": command, "access": "PhysioNet credentialing, training and dataset DUA acceptance are required."}))
|
| 149 |
+
continue
|
| 150 |
+
if not args.username:
|
| 151 |
+
raise ValueError("Supply --username or PHYSIONET_USERNAME; the password is requested by wget and is never written to the command line")
|
| 152 |
+
if not shutil.which("wget"):
|
| 153 |
+
raise RuntimeError("Install wget to download credentialed PhysioNet files")
|
| 154 |
+
if not sys.stdin.isatty():
|
| 155 |
+
raise RuntimeError("Run in a terminal so wget can ask for your PhysioNet password")
|
| 156 |
+
target = args.output / args.physionet_dataset / path
|
| 157 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 158 |
+
subprocess.run(command, check=True)
|
| 159 |
+
if not target.stat().st_size:
|
| 160 |
+
raise RuntimeError("PhysioNet returned an empty file")
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def cuhk_download(args: argparse.Namespace) -> None:
|
| 164 |
+
files = [relative_path(raw) for raw in args.file or []]
|
| 165 |
+
if args.list_directory is not None:
|
| 166 |
+
directory = args.list_directory.strip("/")
|
| 167 |
+
if directory:
|
| 168 |
+
directory = relative_path(directory)
|
| 169 |
+
url = CUHK_PORTAL + "/api/files/" + urllib.parse.quote(directory, safe="/") + ("/" if directory else "")
|
| 170 |
+
if args.dry_run:
|
| 171 |
+
print(json.dumps({"listing_url": url}))
|
| 172 |
+
else:
|
| 173 |
+
with urllib.request.urlopen(url, timeout=60) as response:
|
| 174 |
+
print(json.dumps(json.load(response), indent=2))
|
| 175 |
+
return
|
| 176 |
+
if not files:
|
| 177 |
+
raise ValueError("Select official portal files with --file; use --list-directory CUHK-S/HAR to inspect archive names. Complete the upstream DUA first.")
|
| 178 |
+
for raw in files:
|
| 179 |
+
url = CUHK_PORTAL + "/data/" + urllib.parse.quote(raw, safe="/")
|
| 180 |
+
if args.dry_run:
|
| 181 |
+
print(json.dumps({"url": url, "output": str(args.output / raw)}))
|
| 182 |
+
else:
|
| 183 |
+
download_url(url, args.output / raw)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def public_download(args: argparse.Namespace) -> None:
|
| 187 |
+
if args.dataset == "holo_assist":
|
| 188 |
+
for component in args.component or ["annotations", "splits"]:
|
| 189 |
+
if component not in HOLOASSIST:
|
| 190 |
+
raise ValueError(f"HoloAssist components: {', '.join(HOLOASSIST)}")
|
| 191 |
+
filename = HOLOASSIST[component]
|
| 192 |
+
base = "https://holoassist.github.io/label_files/" if component == "splits" else "https://hl2data.z5.web.core.windows.net/holoassist-data-release/"
|
| 193 |
+
if args.dry_run:
|
| 194 |
+
print(json.dumps({"url": base + filename, "output": str(args.output / filename)}))
|
| 195 |
+
else:
|
| 196 |
+
download_url(base + filename, args.output / filename)
|
| 197 |
+
elif args.dataset == "future_factories":
|
| 198 |
+
command = ["kaggle", "datasets", "download", "-d", "ramyharik/ff-2024-08-13-multi-modal-dataset-33", "-p", str(args.output)]
|
| 199 |
+
if args.dry_run:
|
| 200 |
+
print(json.dumps({"command": command, "version": 1, "note": "Configure your own Kaggle account; this source archive is about 104 GB."}))
|
| 201 |
+
else:
|
| 202 |
+
if not shutil.which("kaggle"):
|
| 203 |
+
raise RuntimeError("Install the Kaggle CLI and configure your own Kaggle credentials")
|
| 204 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 205 |
+
subprocess.run(command, check=True)
|
| 206 |
+
elif args.dataset == "terra":
|
| 207 |
+
if not args.url or not args.filename:
|
| 208 |
+
print(json.dumps({"official_dataset_folder": TERRA_PORTAL, "next_step": "Use the official folder to obtain a direct file-download URL, then pass --url and --filename."}, indent=2))
|
| 209 |
+
if not args.dry_run:
|
| 210 |
+
raise ValueError("Terra's public SharePoint folder is not a file URL. --url and --filename are required for an actual download")
|
| 211 |
+
return
|
| 212 |
+
parsed = urllib.parse.urlsplit(args.url)
|
| 213 |
+
if parsed.scheme != "https" or not parsed.hostname or not (parsed.hostname.endswith(".sharepoint.com") or parsed.hostname.endswith(".1drv.com")):
|
| 214 |
+
raise ValueError("Use a direct HTTPS file link from Terra's official SharePoint source")
|
| 215 |
+
name = relative_path(args.filename)
|
| 216 |
+
if args.dry_run:
|
| 217 |
+
print(json.dumps({"method": "official SharePoint direct file", "filename": name, "output": str(args.output / name)}))
|
| 218 |
+
else:
|
| 219 |
+
download_url(args.url, args.output / name, args.sha256)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def main(dataset: str | None = None) -> None:
|
| 223 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 224 |
+
parser.add_argument("--dataset", choices=["mimic", "pixelrec", "covla", "cuhk_x_har", "agibot", "sp500", "terra", "future_factories", "holo_assist"], required=dataset is None, default=dataset)
|
| 225 |
+
parser.add_argument("--output", type=Path, required=True, help="Local source directory outside the public release.")
|
| 226 |
+
parser.add_argument("--dry-run", action="store_true", help="Print a plan without network access or file writes.")
|
| 227 |
+
parser.add_argument("--accept-terms", action="store_true", help="Confirm that your own upstream access and source agreement requirements have been completed.")
|
| 228 |
+
parser.add_argument("--component", action="append", help="Source component to download; repeat as needed.")
|
| 229 |
+
parser.add_argument("--include", action="append", help="Hugging Face filename pattern; repeat as needed.")
|
| 230 |
+
parser.add_argument("--revision", default="main", help="Hugging Face revision; the resolved commit is recorded locally.")
|
| 231 |
+
parser.add_argument("--workers", type=int, default=4)
|
| 232 |
+
parser.add_argument("--file", action="append", help="Source-relative PhysioNet or CUHK file path.")
|
| 233 |
+
parser.add_argument("--file-list", type=Path, help="Private file list for PhysioNet, one source-relative path per line.")
|
| 234 |
+
parser.add_argument("--physionet-dataset", choices=list(PHYSIONET), default="mimiciv")
|
| 235 |
+
parser.add_argument("--version", help="PhysioNet version (defaults match the original benchmark sources).")
|
| 236 |
+
parser.add_argument("--username", default=os.environ.get("PHYSIONET_USERNAME"))
|
| 237 |
+
parser.add_argument("--list-directory", help="List a CUHK official portal directory.")
|
| 238 |
+
parser.add_argument("--url", help="Direct Terra file URL from the official SharePoint folder.")
|
| 239 |
+
parser.add_argument("--terra-source", choices=["sharepoint", "huggingface"], default="sharepoint",
|
| 240 |
+
help="Terra source: current SharePoint folder or original Hugging Face files. The original repository has no satellite archive.")
|
| 241 |
+
parser.add_argument("--filename", help="Local Terra download filename.")
|
| 242 |
+
parser.add_argument("--sha256", help="Optional expected Terra file SHA-256.")
|
| 243 |
+
args = parser.parse_args()
|
| 244 |
+
args.output = args.output.expanduser().resolve()
|
| 245 |
+
if args.output.is_relative_to(RELEASE):
|
| 246 |
+
parser.error("Raw downloads must be stored outside the MMTA public release directory")
|
| 247 |
+
if not args.dry_run and not args.accept_terms:
|
| 248 |
+
parser.error("Complete upstream requirements, then pass --accept-terms; --dry-run needs no access")
|
| 249 |
+
try:
|
| 250 |
+
if args.dataset in HF_REPOS and (args.dataset != "terra" or args.terra_source == "huggingface"):
|
| 251 |
+
hf_download(args)
|
| 252 |
+
elif args.dataset == "mimic":
|
| 253 |
+
mimic_download(args)
|
| 254 |
+
elif args.dataset == "pixelrec":
|
| 255 |
+
pixelrec_download(args)
|
| 256 |
+
elif args.dataset == "cuhk_x_har":
|
| 257 |
+
cuhk_download(args)
|
| 258 |
+
else:
|
| 259 |
+
public_download(args)
|
| 260 |
+
except (ValueError, RuntimeError, OSError, subprocess.CalledProcessError) as exc:
|
| 261 |
+
raise SystemExit(str(exc)) from exc
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
if __name__ == "__main__":
|
| 265 |
+
main()
|
processing/provenance.json
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"path_base": "release_root",
|
| 3 |
+
"revision_date": "2026-10-13",
|
| 4 |
+
"scope": "Source acquisition and local reconstruction code for six recipe-only domains; no upstream data or generated records included.",
|
| 5 |
+
"adapted_scripts": [
|
| 6 |
+
{
|
| 7 |
+
"script": "processing/common/convert_images.py",
|
| 8 |
+
"source_label": "common/convert_image_jsonl.py",
|
| 9 |
+
"source_sha256": "dbaf7a30f6df8c3c61ee2e7225ca4ea15ed407893ffc86877cbabfb2f024e169",
|
| 10 |
+
"packaged_sha256": "1b9b78e9cbe0dcd700c3f1245ad34ce55bd079a63b7293df1289e1281a56a9bf",
|
| 11 |
+
"changes": "Portable media roots and prefix remapping; signal shape excludes timestamp columns; blank forecast history values keep their column positions; array fallback includes history only, never future targets. English CLI/docs and source parsing preserved otherwise. Vector reference answers are formatted as comma-separated numerical channels."
|
| 12 |
+
},
|
| 13 |
+
{
|
| 14 |
+
"script": "processing/common/convert_videos.py",
|
| 15 |
+
"source_label": "common/convert_covla.py",
|
| 16 |
+
"source_sha256": "a2b82a280ac0ac41be293ad1106b6aee851eea74b4626c0f4f3343bd2e25e4fd",
|
| 17 |
+
"packaged_sha256": "65a5496d1f8b2bbb859a4db93582bd40e4cbb66322b9e281bd8544cfdc37a54b",
|
| 18 |
+
"changes": "English documentation and CLI text; portable defaults; standalone media probes and explicit source-path remapping where needed. Timestamp-free template and prose lines are now excluded from sensor observations; ISO-dated and numeric observations remain supported."
|
| 19 |
+
},
|
| 20 |
+
{
|
| 21 |
+
"script": "sample/video-timeseries/covla/extract_brake_reasons.py",
|
| 22 |
+
"source_label": "covla/extract_brake_reasons.py",
|
| 23 |
+
"source_sha256": "de74e6b57aa99b205c9499062ab0933649af35e86fa26fceadd58fc4c85e0919",
|
| 24 |
+
"packaged_sha256": "9a0d6169d95b20560ffcb4346b4de37b3ab52117de6dad979c0ded8ed1fb1203",
|
| 25 |
+
"changes": "English documentation and CLI text; portable defaults; standalone media probes and explicit source-path remapping where needed."
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"script": "sample/video-timeseries/covla/enrich_segments.py",
|
| 29 |
+
"source_label": "covla/build_brake_reason_dataset.py",
|
| 30 |
+
"source_sha256": "56b408dca809580d91852e55246971343ec9dd8f02a004c76c404b438f7a658f",
|
| 31 |
+
"packaged_sha256": "2183e11568d3cea03c058108e36f1c887bde663a1439bee8e83a6b6617b65428",
|
| 32 |
+
"changes": "English documentation and CLI text; portable defaults; standalone media probes and explicit source-path remapping where needed."
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"script": "sample/video-timeseries/covla/build_prompts.py",
|
| 36 |
+
"source_label": "covla/build_prompt_dataset.py",
|
| 37 |
+
"source_sha256": "c1d7d9260a21e14b9a383b8eb4c32b71f1ca2ae6087f696809b52216859cfb8b",
|
| 38 |
+
"packaged_sha256": "d3f061e344a92dc4f9ea238eff1db46e83a6be730227bbb47a22cb691fe4be25",
|
| 39 |
+
"changes": "English documentation and CLI text; portable defaults; standalone media probes and explicit source-path remapping where needed."
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"script": "sample/video-timeseries/covla/split_dataset.py",
|
| 43 |
+
"source_label": "covla/split_brake_dataset.py",
|
| 44 |
+
"source_sha256": "b12976b11ff095dc44d573ceb8cc99a9350a01172b33f13088559ec5b722f9f7",
|
| 45 |
+
"packaged_sha256": "a81a76c1d8b6e53b7df7113155004513e3398451b3a08604d44d974f02f04349",
|
| 46 |
+
"changes": "English documentation and CLI text; portable defaults; standalone media probes and explicit source-path remapping where needed."
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"script": "sample/image-timeseries/sp500/prepare.py",
|
| 50 |
+
"source_label": "sp500/build_jsonl_forcast_withoutpng.py",
|
| 51 |
+
"source_sha256": "b9901e8ecc46e8bf74826d609dc051003adceebdfe8505c4fd255a64f04510ba",
|
| 52 |
+
"packaged_sha256": "12a63395c73d6d300bfaa91acc2b908acd76d930889793490e98b2049305ba6f",
|
| 53 |
+
"changes": "English CLI/docs and portable roots. The first-half-2024 price history and target horizon remain. News selection was corrected: mandatory forecast-day cutoff in a documented timezone, valid source ISO Date required, strict pre-cutoff filtering, chronological latest-three selection and per-record selection metadata."
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"script": "sample/video-timeseries/cuhk_x_har/prepare.py",
|
| 57 |
+
"source_label": "cuhk_x_har/build_cuhkx_action_prompt_jsonl.py",
|
| 58 |
+
"source_sha256": "2c96996a7ba25588c1b7a01a1322cca7a4dc3e2b814921b3130447dfe3a0bb96",
|
| 59 |
+
"packaged_sha256": "ad086660e0dbad56b94a359cb5436007c7e73ecc87eef96d993ebfd5f7baf628",
|
| 60 |
+
"changes": "English documentation and CLI text; portable defaults; standalone media probes and explicit source-path remapping where needed.",
|
| 61 |
+
"source_location": "original_dataset_directory"
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"script": "sample/image-timeseries/pixelrec/prepare.py",
|
| 65 |
+
"source_label": "PixelRec/build_day.py",
|
| 66 |
+
"source_sha256": "d5712923fa7323ff16e2f0bcf5a3a7d803ec424f5011fd89b7a71df6f9096883",
|
| 67 |
+
"changes": "Refactored daily longest-consecutive-segment forecasting as a CLI; English documentation, explicit input paths, deterministic item traversal and required image checks. Original translated metadata and exact split membership are not asserted to be reproduced.",
|
| 68 |
+
"packaged_sha256": "913bb0bfaedffe0ee13d56cd762aa6b5556149abc95670d92e2110fa65cb6df9"
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"script": "sample/image-timeseries/mimic_death/build_json_QA_death.py",
|
| 72 |
+
"source_label": "mimic/python/build_json_QA_death.py",
|
| 73 |
+
"source_sha256": "ad0e50d4cbd0bfcb93ff1582828b5b11e38313e96063d7915079ff25f11264d7",
|
| 74 |
+
"source_location": "original_dataset_directory",
|
| 75 |
+
"changes": "Portable CLI paths, compressed inputs, English code and JSON-safe values; original patient and encounter joins, temporal windows and labels retained. Image fields are consistent and record IDs are unique. Mortality stays are not duplicated to fill quotas.",
|
| 76 |
+
"packaged_sha256": "6290dd36fab73fa91644135e7f46bff9f3a5e3b94e9fda3b275125abdadd23f8"
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"script": "sample/image-timeseries/mimic_death/json_prompt_death.py",
|
| 80 |
+
"source_label": "mimic/python/json_prompt_death.py",
|
| 81 |
+
"source_sha256": "8e4acc9c8ba64faf0c225777dc9433c80a1afd11f504d962576ea87e1695737e",
|
| 82 |
+
"source_location": "original_dataset_directory",
|
| 83 |
+
"changes": "Portable CLI paths, compressed inputs, English code and JSON-safe values; original patient and encounter joins, temporal windows and labels retained. Image fields are consistent and record IDs are unique. Mortality stays are not duplicated to fill quotas.",
|
| 84 |
+
"packaged_sha256": "71cd42b2b8c01f5d79c1fd7ec35fcb07eb44080d978ffa18a3ee3de6d3df20fa"
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"script": "sample/image-timeseries/mimic_disch/build_json_QA.py",
|
| 88 |
+
"source_label": "mimic/python/build_json_QA.py",
|
| 89 |
+
"source_sha256": "6adc0f28ce7554509dfef980db5b56390405dc2228a0d36580194c94219a36d6",
|
| 90 |
+
"source_location": "original_dataset_directory",
|
| 91 |
+
"changes": "Portable CLI paths, compressed inputs, English code and JSON-safe values; original patient and encounter joins, temporal windows and labels retained. Image fields are consistent and record IDs are unique. Mortality stays are not duplicated to fill quotas.",
|
| 92 |
+
"packaged_sha256": "84c2fd9807a0eef8ff30e5893d558869c2acf4fcd08ea0d4898f5a63fdbad0cf"
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"script": "sample/image-timeseries/mimic_disch/json_prompt.py",
|
| 96 |
+
"source_label": "mimic/python/json_prompt.py",
|
| 97 |
+
"source_sha256": "f027f60a90b2235b2d1645f831510301e03feb43051552ce835a7970b3061f35",
|
| 98 |
+
"source_location": "original_dataset_directory",
|
| 99 |
+
"changes": "Portable CLI paths, compressed inputs, English code and JSON-safe values; original patient and encounter joins, temporal windows and labels retained. Image fields are consistent and record IDs are unique. Mortality stays are not duplicated to fill quotas.",
|
| 100 |
+
"packaged_sha256": "6fe8b8c53cb8fb998b9c1aad9f0a8348a59ba72b742a2efe28d0574f1a3b4c88"
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"script": "sample/image-timeseries/mimic_death/split_dataset.py",
|
| 104 |
+
"source_label": "mimic/python/split_jsonl_train_test_stratified.py",
|
| 105 |
+
"source_sha256": "4870fe3ec136d0236ef84c9cca2e91d25e32fa521715fd2e09ff3bcdf49dca37",
|
| 106 |
+
"source_location": "original_dataset_directory",
|
| 107 |
+
"changes": "Portable CLI paths, compressed inputs, English code and JSON-safe values; original patient and encounter joins, temporal windows and labels retained. Image fields are consistent and record IDs are unique. Mortality stays are not duplicated to fill quotas.",
|
| 108 |
+
"packaged_sha256": "f7f7586d6b8dbca9ef795f17964346eac46c90504890d8f2a39db37be2546f8c"
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"script": "sample/video-timeseries/cuhk_x_har/imu_skeleton_to_jsonl.py",
|
| 112 |
+
"source_label": "cuhk-x/imu_skeleton_to_jsonl.py",
|
| 113 |
+
"source_sha256": "6ef1638d2c33497a04a9af2e2755ea74d949ec69f1f13dc12b908ec40bd7da6b",
|
| 114 |
+
"source_location": "original_dataset_directory",
|
| 115 |
+
"changes": "Portable CLI paths and English code; original trial matching, stream selection, per-second sampling and 20 fps rendering retained. Generated tables and videos are written to a separate output tree. Original column names are supported through Unicode aliases.",
|
| 116 |
+
"packaged_sha256": "901019d61c74640dd96263e5fb781d2f5f43cd3eb2121f1beb4ebae0c0e9394a"
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"script": "sample/video-timeseries/cuhk_x_har/images_to_video.py",
|
| 120 |
+
"source_label": "cuhk-x/images_to_video_20fps.py",
|
| 121 |
+
"source_sha256": "c0cf7f251ea3b2b9227b9443b0aaf88970ce33cc548ad9a589792b49821ee095",
|
| 122 |
+
"source_location": "original_dataset_directory",
|
| 123 |
+
"changes": "Portable CLI paths and English code; original trial matching, stream selection, per-second sampling and 20 fps rendering retained. Generated tables and videos are written to a separate output tree. Original column names are supported through Unicode aliases.",
|
| 124 |
+
"packaged_sha256": "1c83937ceebeebaa83795c96359612f907d2a26a70e3841ba5ff4ec115293bd0"
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"script": "sample/image-timeseries/mimic_death/bucket_chartevents.py",
|
| 128 |
+
"source_label": "mimic/python/csv_split.py",
|
| 129 |
+
"source_sha256": "fd782af054c35389fd407ada022d479562ed5d90b64abfb92a1d608800fe233f",
|
| 130 |
+
"source_location": "original_dataset_directory",
|
| 131 |
+
"changes": "Explicit chartevents input replaces the original labevents default; stream subject/admission grouping to a new output tree and retain the five columns used by the task builders.",
|
| 132 |
+
"packaged_sha256": "54de1a5ab6255166a87ca376adf1dd1c9f06ed275a22d73ed5ba44802de9f3d1"
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"script": "sample/video-timeseries/cuhk_x_har/xlsx_to_csv.py",
|
| 136 |
+
"source_label": "cuhk-x/xlsx_to_csv.py",
|
| 137 |
+
"source_sha256": "82eef22f3a0962ec353d81bd24f924fd8ce631f7597bd1440eed9771171f1bcb",
|
| 138 |
+
"source_location": "original_dataset_directory",
|
| 139 |
+
"changes": "Portable CLI paths and English code; original trial matching, stream selection, per-second sampling and 20 fps rendering retained. Generated tables and videos are written to a separate output tree. Original column names are supported through Unicode aliases.",
|
| 140 |
+
"packaged_sha256": "06b68b5b53c91cd17d6d1bc49590b73e7addff2dc9499c48732ae36e31c1d54a"
|
| 141 |
+
}
|
| 142 |
+
],
|
| 143 |
+
"new_scripts": [
|
| 144 |
+
"processing/common/local_generation.py",
|
| 145 |
+
"processing/common/probe.py",
|
| 146 |
+
"processing/common/test_convert_videos.py",
|
| 147 |
+
"processing/download.py",
|
| 148 |
+
"sample/image-timeseries/mimic_death/download.py",
|
| 149 |
+
"sample/image-timeseries/mimic_death/generate.py",
|
| 150 |
+
"sample/image-timeseries/mimic_death/source_tables.py",
|
| 151 |
+
"sample/image-timeseries/mimic_disch/download.py",
|
| 152 |
+
"sample/image-timeseries/mimic_disch/generate.py",
|
| 153 |
+
"sample/image-timeseries/pixelrec/download.py",
|
| 154 |
+
"sample/image-timeseries/pixelrec/generate.py",
|
| 155 |
+
"sample/image-timeseries/sp500/download.py",
|
| 156 |
+
"sample/image-timeseries/sp500/generate.py",
|
| 157 |
+
"sample/image-timeseries/sp500/test_news_cutoff.py",
|
| 158 |
+
"sample/video-timeseries/covla/download.py",
|
| 159 |
+
"sample/video-timeseries/covla/generate.py",
|
| 160 |
+
"sample/video-timeseries/cuhk_x_har/download.py",
|
| 161 |
+
"sample/video-timeseries/cuhk_x_har/generate.py"
|
| 162 |
+
],
|
| 163 |
+
"new_script_hashes": {
|
| 164 |
+
"processing/common/local_generation.py": "af00dadb5c8e4426eebae3f48d4420f4107ff9df30041fffb5348751d19352de",
|
| 165 |
+
"processing/common/probe.py": "55aae997c410d00574796cc289873cba655dec1b603447c7555341892c98bfff",
|
| 166 |
+
"processing/common/test_convert_videos.py": "f76ecfdde59cd94fca6e541df3a4ef58479dcf9e8f9007c91f641f0f81dfe4ac",
|
| 167 |
+
"processing/download.py": "043037ca6338af10da9bc764c5310497e48337696a95221b023c17aba20c8786",
|
| 168 |
+
"sample/image-timeseries/mimic_death/download.py": "74a57466a27215b53929c6b77f3ce2aa8a53685e20cdd635b4990373be7c4ad3",
|
| 169 |
+
"sample/image-timeseries/mimic_death/generate.py": "feeb788569344338789e3c59247943317a4b77331ea566115bc8a893518e6f8f",
|
| 170 |
+
"sample/image-timeseries/mimic_death/source_tables.py": "d4528e9a9eec1e1e9e2c69f736492d4b2fa91f5856da96940c6a0d40255dae81",
|
| 171 |
+
"sample/image-timeseries/mimic_disch/download.py": "74a57466a27215b53929c6b77f3ce2aa8a53685e20cdd635b4990373be7c4ad3",
|
| 172 |
+
"sample/image-timeseries/mimic_disch/generate.py": "484c4b62831722adcc325d03f6f143af27f2c7d5344ec038be67b55ac1c28ac6",
|
| 173 |
+
"sample/image-timeseries/pixelrec/download.py": "1ae7b74455119f3ba7c9ba791136c3b81608949f7d80fdb33f110ee0fa9e81ea",
|
| 174 |
+
"sample/image-timeseries/pixelrec/generate.py": "93eb4357d97652199487d5ccc9e607b3ecaf321d1d182139717f36e299466a70",
|
| 175 |
+
"sample/image-timeseries/sp500/download.py": "262e885f1d468e661aadae2b02f2ad65b0f441459c2f5ea610487e1972612000",
|
| 176 |
+
"sample/image-timeseries/sp500/generate.py": "de3c90d97492d158a24fb19d06c17840b1ed271af893b3eaaeb28ce4b7b92b6c",
|
| 177 |
+
"sample/image-timeseries/sp500/test_news_cutoff.py": "609489ed7ac2c27cfdc963e12c226ee202b11cf955c053c5cec37ddf892cb0f7",
|
| 178 |
+
"sample/video-timeseries/covla/download.py": "2fc4a588c292adabf5a5581a9f319005473b830a9991899b4950f2bd5ba14bb2",
|
| 179 |
+
"sample/video-timeseries/covla/generate.py": "b135bac2c71c3389a3859356a03eff2734095fcd753cc8f0633fd222ee913407",
|
| 180 |
+
"sample/video-timeseries/cuhk_x_har/download.py": "84c5093a46b38518b33fd1d880a957809ac00b547a956b9181fa5213c0277de7",
|
| 181 |
+
"sample/video-timeseries/cuhk_x_har/generate.py": "16f8f14216371bc3b3522af7e9edc67063354e706fee6a10980ca40949eebca9"
|
| 182 |
+
},
|
| 183 |
+
"local_generation_note": "Excluded-domain recipes are in sample/<modality>/<domain>/. MIMIC patient joins, labels, prompts and splitting and CUHK-X raw IMU/skeleton alignment use original source scripts. SP500 requires source-dated news strictly before the forecast-day cutoff."
|
| 184 |
+
}
|
processing/requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy>=1.23
|
| 2 |
+
pandas>=1.5
|
| 3 |
+
Pillow>=9
|
| 4 |
+
opencv-python-headless>=4.7
|
| 5 |
+
pyarrow>=12
|
| 6 |
+
jsonschema>=4.18
|
| 7 |
+
huggingface-hub>=0.24
|
| 8 |
+
gdown>=5.2
|
| 9 |
+
openpyxl>=3.1
|
| 10 |
+
xlrd>=2.0
|
sample/image-timeseries/mimic_death/README.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIMIC mortality
|
| 2 |
+
|
| 3 |
+
**Processing code only:** source data and generated task records are not
|
| 4 |
+
included. Obtain the sources with your own approved access and follow their
|
| 5 |
+
terms. See the [shared setup instructions](../../../processing/README.md).
|
| 6 |
+
Run the commands below from the directory containing `MMTA-v1.0/`, keeping
|
| 7 |
+
`local_sources/` and `local_work/` outside the release folder.
|
| 8 |
+
|
| 9 |
+
Download MIMIC-IV 3.1, MIMIC-IV-Note 2.2 and MIMIC-CXR-JPG 2.1.0 from [PhysioNet](https://physionet.org/) using your approved account. Required tables: patients, admissions, chartevents, radiology and CXR metadata; mortality also needs icustays. `download.py` accepts `--file` or `--file-list` for each selected source.
|
| 10 |
+
|
| 11 |
+
```bash
|
| 12 |
+
python -B MMTA-v1.0/sample/image-timeseries/mimic_death/download.py \
|
| 13 |
+
--output local_sources/mimic --physionet-dataset mimiciv \
|
| 14 |
+
--file icu/chartevents.csv.gz --username YOUR_USERNAME --accept-terms
|
| 15 |
+
python -B MMTA-v1.0/sample/image-timeseries/mimic_death/generate.py \
|
| 16 |
+
--mimic-hosp-dir local_sources/mimic/mimiciv/hosp \
|
| 17 |
+
--mimic-icu-dir local_sources/mimic/mimiciv/icu \
|
| 18 |
+
--mimic-note-dir local_sources/mimic/mimic-iv-note/note \
|
| 19 |
+
--cxr-metadata-csv local_sources/mimic/mimic-cxr-jpg/mimic-cxr-2.0.0-metadata.csv.gz \
|
| 20 |
+
--cxr-jpg-root local_sources/mimic/mimic-cxr-jpg/files \
|
| 21 |
+
--chartevents local_sources/mimic/mimiciv/icu/chartevents.csv.gz \
|
| 22 |
+
--output-dir local_work/mimic_death_build
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
Join ICU stays, admissions, radiology reports and same-day chest images. Use the first 48 hours after ICU admission, exclude deaths during the observation window, and label later in-hospital deaths (20 positive / 130 negative). The command buckets raw vitals, constructs labels and prompts, makes a 50/50 stratified split, and exports image/CSV records. Existing buckets can be supplied with `--chartevents-root`.
|
| 26 |
+
|
| 27 |
+
Output: `--output-dir/mimic_death/mimic_death.omnits.jsonl`, with `timeseries/` and intermediate train/test JSONL. Images stay in the source tree; paths are relative to the output domain directory. `--split train` selects the training output.
|
sample/image-timeseries/mimic_death/bucket_chartevents.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Split raw MIMIC chartevents into subject/admission CSV buckets."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def split_chartevents_by_subject_hadm(
|
| 13 |
+
chartevents_csv: Path,
|
| 14 |
+
output_root: Path,
|
| 15 |
+
chunksize: int = 1000000,
|
| 16 |
+
) -> None:
|
| 17 |
+
"""Adapt the original csv_split.py grouping to an explicit input path."""
|
| 18 |
+
if output_root.exists():
|
| 19 |
+
raise ValueError(f"Choose a new bucket directory: {output_root}")
|
| 20 |
+
output_root.mkdir(parents=True)
|
| 21 |
+
columns = ["subject_id", "hadm_id", "charttime", "itemid", "valuenum"]
|
| 22 |
+
reader = pd.read_csv(
|
| 23 |
+
chartevents_csv,
|
| 24 |
+
usecols=columns,
|
| 25 |
+
chunksize=chunksize,
|
| 26 |
+
dtype={"subject_id": "Int64", "hadm_id": "Int64"},
|
| 27 |
+
low_memory=False,
|
| 28 |
+
)
|
| 29 |
+
for index, chunk in enumerate(reader, 1):
|
| 30 |
+
chunk = chunk.dropna(subset=["subject_id", "hadm_id"])
|
| 31 |
+
for (subject, admission), rows in chunk.groupby(
|
| 32 |
+
["subject_id", "hadm_id"], sort=False
|
| 33 |
+
):
|
| 34 |
+
directory = output_root / str(int(subject)) / str(int(admission))
|
| 35 |
+
directory.mkdir(parents=True, exist_ok=True)
|
| 36 |
+
target = directory / "chartevents.csv"
|
| 37 |
+
rows.to_csv(target, index=False, mode="a", header=not target.exists())
|
| 38 |
+
print(f"Processed chunk {index}: {len(chunk)} rows")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def main() -> None:
|
| 42 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 43 |
+
parser.add_argument("--input", type=Path, required=True)
|
| 44 |
+
parser.add_argument("--output-root", type=Path, required=True)
|
| 45 |
+
parser.add_argument("--chunksize", type=int, default=1000000)
|
| 46 |
+
args = parser.parse_args()
|
| 47 |
+
if args.chunksize < 1:
|
| 48 |
+
parser.error("--chunksize must be positive")
|
| 49 |
+
split_chartevents_by_subject_hadm(args.input, args.output_root, args.chunksize)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
if __name__ == "__main__":
|
| 53 |
+
main()
|
sample/image-timeseries/mimic_death/build_json_QA_death.py
ADDED
|
@@ -0,0 +1,572 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Adapted from the original dataset construction script."""
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
import random
|
| 8 |
+
from datetime import timedelta
|
| 9 |
+
from typing import Dict, List, Optional, Tuple, Any
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import sys
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
sys.dont_write_bytecode = True
|
| 15 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "mimic_death"))
|
| 16 |
+
from source_tables import json_safe, study_date, table_path
|
| 17 |
+
|
| 18 |
+
FIXED_VITAL_ITEMIDS = {
|
| 19 |
+
220045: "heart_rate_bpm",
|
| 20 |
+
220210: "resp_rate_insp_per_min",
|
| 21 |
+
220277: "spo2_percent",
|
| 22 |
+
223762: "temp_c",
|
| 23 |
+
220179: "nbp_systolic_mmhg",
|
| 24 |
+
220180: "nbp_diastolic_mmhg",
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def parse_args():
|
| 29 |
+
ap = argparse.ArgumentParser()
|
| 30 |
+
ap.add_argument("--mimic_hosp_dir", "--mimic-hosp-dir", required=True)
|
| 31 |
+
ap.add_argument("--mimic_icu_dir", "--mimic-icu-dir", required=True)
|
| 32 |
+
ap.add_argument("--mimic_note_dir", "--mimic-note-dir", required=True)
|
| 33 |
+
ap.add_argument("--cxr_metadata_csv", "--cxr-metadata-csv", required=True)
|
| 34 |
+
ap.add_argument("--cxr_jpg_root", "--cxr-jpg-root", required=True)
|
| 35 |
+
ap.add_argument(
|
| 36 |
+
"--chartevents_root",
|
| 37 |
+
"--chartevents-root",
|
| 38 |
+
help="Bucketed chartevents root: <root>/<subject_id>/<hadm_id>/chartevents.csv",
|
| 39 |
+
required=True,
|
| 40 |
+
)
|
| 41 |
+
ap.add_argument("--out_jsonl", "--out-jsonl", required=True)
|
| 42 |
+
ap.add_argument("--qc_csv", "--qc-csv", required=True)
|
| 43 |
+
ap.add_argument("--seed", type=int, default=42)
|
| 44 |
+
ap.add_argument("--window_hours", "--window-hours", type=int, default=48)
|
| 45 |
+
ap.add_argument("--n_death", "--n-death", type=int, default=20)
|
| 46 |
+
ap.add_argument("--n_alive", "--n-alive", type=int, default=130)
|
| 47 |
+
ap.add_argument("--max_notes_per_stay", "--max-notes-per-stay", type=int, default=3)
|
| 48 |
+
ap.add_argument(
|
| 49 |
+
"--max_images_per_stay", "--max-images-per-stay", type=int, default=4
|
| 50 |
+
)
|
| 51 |
+
ap.add_argument("--image_day_slack", "--image-day-slack", type=int, default=0)
|
| 52 |
+
ap.add_argument("--k_per_var", "--k-per-var", type=int, default=16)
|
| 53 |
+
ap.add_argument(
|
| 54 |
+
"--require_image_file_exists",
|
| 55 |
+
"--require-image-file-exists",
|
| 56 |
+
action="store_true",
|
| 57 |
+
)
|
| 58 |
+
ap.add_argument(
|
| 59 |
+
"--max_passes_over_pool", "--max-passes-over-pool", type=int, default=3
|
| 60 |
+
)
|
| 61 |
+
return ap.parse_args()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def to_date_str_yyyy_mm_dd_from_studydate(x) -> Optional[str]:
|
| 65 |
+
return study_date(x)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def subject_folder(subject_id: int) -> str:
|
| 69 |
+
s = str(int(subject_id))
|
| 70 |
+
return f"p{s[:2]}"
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def build_jpg_path(
|
| 74 |
+
cxr_jpg_root: str, subject_id: int, study_id: int, dicom_id: str
|
| 75 |
+
) -> str:
|
| 76 |
+
return os.path.abspath(
|
| 77 |
+
os.path.join(
|
| 78 |
+
cxr_jpg_root,
|
| 79 |
+
subject_folder(subject_id),
|
| 80 |
+
f"p{int(subject_id)}",
|
| 81 |
+
f"s{int(study_id)}",
|
| 82 |
+
f"{dicom_id}.jpg",
|
| 83 |
+
)
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def load_radiology_rr_notes(note_dir: str) -> pd.DataFrame:
|
| 88 |
+
path = table_path(note_dir, "radiology.csv")
|
| 89 |
+
r = pd.read_csv(path)
|
| 90 |
+
r = r[r["note_type"].astype(str).eq("RR")].copy()
|
| 91 |
+
r["charttime"] = pd.to_datetime(r["charttime"], errors="coerce")
|
| 92 |
+
r = r[r["charttime"].notna()].copy()
|
| 93 |
+
r = r[r["text"].notna()].copy()
|
| 94 |
+
r = r[r["hadm_id"].notna()].copy()
|
| 95 |
+
r["subject_id"] = r["subject_id"].astype(int)
|
| 96 |
+
r["hadm_id"] = r["hadm_id"].astype(int)
|
| 97 |
+
r["note_date"] = r["charttime"].dt.date.astype(str)
|
| 98 |
+
return r
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def load_cxr_metadata(meta_csv: str) -> pd.DataFrame:
|
| 102 |
+
m = pd.read_csv(meta_csv)
|
| 103 |
+
missing = {"dicom_id", "subject_id", "study_id", "StudyDate"} - set(m.columns)
|
| 104 |
+
if missing:
|
| 105 |
+
raise RuntimeError(f"metadata missing required columns: {missing}")
|
| 106 |
+
m["subject_id"] = m["subject_id"].astype(int)
|
| 107 |
+
m["study_id"] = m["study_id"].astype(int)
|
| 108 |
+
m["dicom_id"] = m["dicom_id"].astype(str)
|
| 109 |
+
m["study_date"] = m["StudyDate"].apply(to_date_str_yyyy_mm_dd_from_studydate)
|
| 110 |
+
return m
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def load_patients(hosp_dir: str) -> Dict[int, Dict]:
|
| 114 |
+
path = table_path(hosp_dir, "patients.csv")
|
| 115 |
+
p = pd.read_csv(
|
| 116 |
+
path,
|
| 117 |
+
usecols=lambda c: c
|
| 118 |
+
in {"subject_id", "gender", "anchor_age", "anchor_year", "anchor_year_group"},
|
| 119 |
+
)
|
| 120 |
+
p["subject_id"] = p["subject_id"].astype(int)
|
| 121 |
+
return p.set_index("subject_id").to_dict(orient="index")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def load_admissions_df(hosp_dir: str) -> pd.DataFrame:
|
| 125 |
+
path = table_path(hosp_dir, "admissions.csv")
|
| 126 |
+
cols = {
|
| 127 |
+
"subject_id",
|
| 128 |
+
"hadm_id",
|
| 129 |
+
"admittime",
|
| 130 |
+
"dischtime",
|
| 131 |
+
"deathtime",
|
| 132 |
+
"admission_type",
|
| 133 |
+
"insurance",
|
| 134 |
+
"language",
|
| 135 |
+
"marital_status",
|
| 136 |
+
"race",
|
| 137 |
+
"hospital_expire_flag",
|
| 138 |
+
}
|
| 139 |
+
a = pd.read_csv(path, usecols=lambda c: c in cols)
|
| 140 |
+
a["subject_id"] = a["subject_id"].astype(int)
|
| 141 |
+
a["hadm_id"] = a["hadm_id"].astype(int)
|
| 142 |
+
a["admittime"] = pd.to_datetime(a["admittime"], errors="coerce")
|
| 143 |
+
a["dischtime"] = pd.to_datetime(a["dischtime"], errors="coerce")
|
| 144 |
+
a["deathtime"] = pd.to_datetime(a["deathtime"], errors="coerce")
|
| 145 |
+
a = a[a["admittime"].notna() & a["dischtime"].notna()].copy()
|
| 146 |
+
return a
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def load_icustays_df(icu_dir: str) -> pd.DataFrame:
|
| 150 |
+
path = table_path(icu_dir, "icustays.csv")
|
| 151 |
+
cols = {
|
| 152 |
+
"subject_id",
|
| 153 |
+
"hadm_id",
|
| 154 |
+
"stay_id",
|
| 155 |
+
"intime",
|
| 156 |
+
"outtime",
|
| 157 |
+
"first_careunit",
|
| 158 |
+
"last_careunit",
|
| 159 |
+
}
|
| 160 |
+
icu = pd.read_csv(path, usecols=lambda c: c in cols)
|
| 161 |
+
icu["subject_id"] = icu["subject_id"].astype(int)
|
| 162 |
+
icu["hadm_id"] = icu["hadm_id"].astype(int)
|
| 163 |
+
icu["stay_id"] = icu["stay_id"].astype(int)
|
| 164 |
+
icu["intime"] = pd.to_datetime(icu["intime"], errors="coerce")
|
| 165 |
+
icu["outtime"] = pd.to_datetime(icu["outtime"], errors="coerce")
|
| 166 |
+
icu = icu[icu["intime"].notna()].copy()
|
| 167 |
+
return icu
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def match_images_for_note_relaxed(
|
| 171 |
+
note_row: Dict[str, Any],
|
| 172 |
+
cxr_by_subject: Dict[int, pd.DataFrame],
|
| 173 |
+
cxr_jpg_root: str,
|
| 174 |
+
day_slack: int = 1,
|
| 175 |
+
require_exists: bool = False,
|
| 176 |
+
) -> Tuple[List[str], List[Dict[str, Any]]]:
|
| 177 |
+
sid = int(note_row["subject_id"])
|
| 178 |
+
note_date = pd.to_datetime(str(note_row["note_date"])).date()
|
| 179 |
+
subm = cxr_by_subject.get(sid)
|
| 180 |
+
if subm is None or subm.empty:
|
| 181 |
+
return ([], [])
|
| 182 |
+
ok_dates = set(
|
| 183 |
+
(
|
| 184 |
+
(note_date + timedelta(days=d)).isoformat()
|
| 185 |
+
for d in range(-day_slack, day_slack + 1)
|
| 186 |
+
)
|
| 187 |
+
)
|
| 188 |
+
matched = subm[subm["study_date"].isin(ok_dates)].copy()
|
| 189 |
+
if matched.empty:
|
| 190 |
+
return ([], [])
|
| 191 |
+
matched = matched.drop_duplicates(["study_id", "dicom_id"])
|
| 192 |
+
images, metas = ([], [])
|
| 193 |
+
for _, r in matched.iterrows():
|
| 194 |
+
jpg = build_jpg_path(cxr_jpg_root, sid, int(r["study_id"]), str(r["dicom_id"]))
|
| 195 |
+
if require_exists and (not os.path.exists(jpg)):
|
| 196 |
+
continue
|
| 197 |
+
images.append(jpg)
|
| 198 |
+
metas.append(
|
| 199 |
+
{
|
| 200 |
+
"dicom_id": str(r["dicom_id"]),
|
| 201 |
+
"study_id": int(r["study_id"]),
|
| 202 |
+
"StudyDate": r.get("StudyDate"),
|
| 203 |
+
"StudyTime": r.get("StudyTime"),
|
| 204 |
+
"ViewPosition": r.get("ViewPosition"),
|
| 205 |
+
}
|
| 206 |
+
)
|
| 207 |
+
return (images, metas)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def iter_chartevents_window(
|
| 211 |
+
chartevents_root: str,
|
| 212 |
+
subject_id: int,
|
| 213 |
+
hadm_id: int,
|
| 214 |
+
itemids: set,
|
| 215 |
+
t_start: pd.Timestamp,
|
| 216 |
+
t_end: pd.Timestamp,
|
| 217 |
+
chunksize: int = 200000,
|
| 218 |
+
filename: str = "chartevents.csv",
|
| 219 |
+
) -> pd.DataFrame:
|
| 220 |
+
p = os.path.join(
|
| 221 |
+
chartevents_root, str(int(subject_id)), str(int(hadm_id)), filename
|
| 222 |
+
)
|
| 223 |
+
usecols = ["charttime", "itemid", "valuenum"]
|
| 224 |
+
if not os.path.exists(p):
|
| 225 |
+
return pd.DataFrame(columns=["charttime", "itemid", "valuenum"])
|
| 226 |
+
out = []
|
| 227 |
+
for chunk in pd.read_csv(
|
| 228 |
+
p, usecols=lambda c: c in set(usecols), chunksize=chunksize
|
| 229 |
+
):
|
| 230 |
+
if "itemid" not in chunk.columns:
|
| 231 |
+
continue
|
| 232 |
+
chunk = chunk[chunk["itemid"].isin(itemids)].copy()
|
| 233 |
+
if chunk.empty:
|
| 234 |
+
continue
|
| 235 |
+
chunk["charttime"] = pd.to_datetime(chunk["charttime"], errors="coerce")
|
| 236 |
+
chunk = chunk[chunk["charttime"].notna()].copy()
|
| 237 |
+
chunk = chunk[
|
| 238 |
+
(chunk["charttime"] >= t_start) & (chunk["charttime"] <= t_end)
|
| 239 |
+
].copy()
|
| 240 |
+
if chunk.empty:
|
| 241 |
+
continue
|
| 242 |
+
chunk["valuenum"] = pd.to_numeric(chunk["valuenum"], errors="coerce")
|
| 243 |
+
chunk = chunk[chunk["valuenum"].notna()].copy()
|
| 244 |
+
if chunk.empty:
|
| 245 |
+
continue
|
| 246 |
+
out.append(chunk[["charttime", "itemid", "valuenum"]])
|
| 247 |
+
if not out:
|
| 248 |
+
return pd.DataFrame(columns=["charttime", "itemid", "valuenum"])
|
| 249 |
+
df = pd.concat(out, ignore_index=True)
|
| 250 |
+
df = df.sort_values("charttime")
|
| 251 |
+
return df
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def take_last_k_per_var(
|
| 255 |
+
df: pd.DataFrame, itemid_to_var: Dict[int, str], k: int
|
| 256 |
+
) -> Dict[str, List[Dict[str, Any]]]:
|
| 257 |
+
out: Dict[str, List[Dict[str, Any]]] = {v: [] for v in itemid_to_var.values()}
|
| 258 |
+
if df.empty:
|
| 259 |
+
return out
|
| 260 |
+
df = df.copy()
|
| 261 |
+
df["var"] = df["itemid"].map(itemid_to_var)
|
| 262 |
+
df = df[df["var"].notna()].copy()
|
| 263 |
+
for v in out.keys():
|
| 264 |
+
sub = df[df["var"] == v].sort_values("charttime")
|
| 265 |
+
if sub.empty:
|
| 266 |
+
continue
|
| 267 |
+
sub = sub.tail(k)
|
| 268 |
+
out[v] = [
|
| 269 |
+
{"t": t.isoformat(), "v": float(val)}
|
| 270 |
+
for (t, val) in zip(sub["charttime"], sub["valuenum"])
|
| 271 |
+
]
|
| 272 |
+
return out
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def build_sample_for_stay(
|
| 276 |
+
stay_row: Dict[str, Any],
|
| 277 |
+
notes_grouped: Dict[Tuple[int, int], pd.DataFrame],
|
| 278 |
+
cxr_by_subject: Dict[int, pd.DataFrame],
|
| 279 |
+
patients_map: Dict[int, Dict],
|
| 280 |
+
args,
|
| 281 |
+
itemids: set,
|
| 282 |
+
itemid_to_var: Dict[int, str],
|
| 283 |
+
) -> Tuple[Optional[Dict[str, Any]], str, Dict[str, Any]]:
|
| 284 |
+
sid = int(stay_row["subject_id"])
|
| 285 |
+
hadm_id = int(stay_row["hadm_id"])
|
| 286 |
+
stay_id = int(stay_row["stay_id"])
|
| 287 |
+
t0 = pd.to_datetime(stay_row["t0"])
|
| 288 |
+
t1 = pd.to_datetime(stay_row["t1"])
|
| 289 |
+
label = int(stay_row["label_death_in_hosp"])
|
| 290 |
+
g = notes_grouped.get((sid, hadm_id))
|
| 291 |
+
if g is None or g.empty:
|
| 292 |
+
return (None, "NO_NOTE_FOR_ADMISSION", {})
|
| 293 |
+
notes_win = g[(g["charttime"] >= t0) & (g["charttime"] <= t1)].copy()
|
| 294 |
+
if notes_win.empty:
|
| 295 |
+
return (None, "NO_NOTE_IN_WINDOW", {})
|
| 296 |
+
notes_win = notes_win.sort_values("charttime").head(args.max_notes_per_stay)
|
| 297 |
+
kept_notes: List[Dict[str, Any]] = []
|
| 298 |
+
all_images: List[str] = []
|
| 299 |
+
all_image_meta: List[Dict[str, Any]] = []
|
| 300 |
+
for _, nr in notes_win.iterrows():
|
| 301 |
+
note_row = nr.to_dict()
|
| 302 |
+
kept_notes.append(
|
| 303 |
+
{
|
| 304 |
+
"charttime": pd.to_datetime(nr["charttime"]).isoformat(),
|
| 305 |
+
"note_date": str(nr["note_date"]),
|
| 306 |
+
"text": str(nr["text"]),
|
| 307 |
+
"note_type": str(nr.get("note_type", "RR")),
|
| 308 |
+
}
|
| 309 |
+
)
|
| 310 |
+
imgs, metas = match_images_for_note_relaxed(
|
| 311 |
+
note_row,
|
| 312 |
+
cxr_by_subject=cxr_by_subject,
|
| 313 |
+
cxr_jpg_root=args.cxr_jpg_root,
|
| 314 |
+
day_slack=args.image_day_slack,
|
| 315 |
+
require_exists=args.require_image_file_exists,
|
| 316 |
+
)
|
| 317 |
+
if imgs:
|
| 318 |
+
all_images.extend(imgs)
|
| 319 |
+
all_image_meta.extend(metas)
|
| 320 |
+
seen = set()
|
| 321 |
+
uniq_images, uniq_meta = ([], [])
|
| 322 |
+
for img, meta in zip(all_images, all_image_meta):
|
| 323 |
+
if img in seen:
|
| 324 |
+
continue
|
| 325 |
+
seen.add(img)
|
| 326 |
+
uniq_images.append(img)
|
| 327 |
+
uniq_meta.append(meta)
|
| 328 |
+
uniq_images = uniq_images[: args.max_images_per_stay]
|
| 329 |
+
uniq_meta = uniq_meta[: args.max_images_per_stay]
|
| 330 |
+
if not kept_notes:
|
| 331 |
+
return (None, "NO_NOTE_AFTER_FILTER", {})
|
| 332 |
+
if not uniq_images:
|
| 333 |
+
return (None, "NO_IMAGE_MATCHED", {"n_notes": len(kept_notes)})
|
| 334 |
+
ce = iter_chartevents_window(
|
| 335 |
+
chartevents_root=args.chartevents_root,
|
| 336 |
+
subject_id=sid,
|
| 337 |
+
hadm_id=hadm_id,
|
| 338 |
+
itemids=itemids,
|
| 339 |
+
t_start=t0,
|
| 340 |
+
t_end=t1,
|
| 341 |
+
chunksize=200000,
|
| 342 |
+
)
|
| 343 |
+
vitals = take_last_k_per_var(ce, itemid_to_var, k=args.k_per_var)
|
| 344 |
+
n_nonempty_vars = sum((1 for v in vitals.keys() if len(vitals[v]) > 0))
|
| 345 |
+
if n_nonempty_vars < 1:
|
| 346 |
+
return (
|
| 347 |
+
None,
|
| 348 |
+
"ALL_VITALS_EMPTY",
|
| 349 |
+
{"n_notes": len(kept_notes), "n_images": len(uniq_images)},
|
| 350 |
+
)
|
| 351 |
+
pat = patients_map.get(sid, {})
|
| 352 |
+
sample = {
|
| 353 |
+
"subject_id": sid,
|
| 354 |
+
"hadm_id": hadm_id,
|
| 355 |
+
"stay_id": stay_id,
|
| 356 |
+
"icu_intime": (
|
| 357 |
+
pd.to_datetime(stay_row["intime"]).isoformat()
|
| 358 |
+
if pd.notna(stay_row.get("intime"))
|
| 359 |
+
else None
|
| 360 |
+
),
|
| 361 |
+
"icu_outtime": (
|
| 362 |
+
pd.to_datetime(stay_row["outtime"]).isoformat()
|
| 363 |
+
if pd.notna(stay_row.get("outtime"))
|
| 364 |
+
else None
|
| 365 |
+
),
|
| 366 |
+
"window_start": t0.isoformat(),
|
| 367 |
+
"window_end": t1.isoformat(),
|
| 368 |
+
"window_hours": float(args.window_hours),
|
| 369 |
+
"label_death_in_hosp": label,
|
| 370 |
+
"admission": {
|
| 371 |
+
"admittime": (
|
| 372 |
+
pd.to_datetime(stay_row["admittime"]).isoformat()
|
| 373 |
+
if pd.notna(stay_row.get("admittime"))
|
| 374 |
+
else None
|
| 375 |
+
),
|
| 376 |
+
"dischtime": (
|
| 377 |
+
pd.to_datetime(stay_row["dischtime"]).isoformat()
|
| 378 |
+
if pd.notna(stay_row.get("dischtime"))
|
| 379 |
+
else None
|
| 380 |
+
),
|
| 381 |
+
"deathtime": (
|
| 382 |
+
pd.to_datetime(stay_row["deathtime"]).isoformat()
|
| 383 |
+
if pd.notna(stay_row.get("deathtime"))
|
| 384 |
+
else None
|
| 385 |
+
),
|
| 386 |
+
"hospital_expire_flag": (
|
| 387 |
+
int(stay_row["hospital_expire_flag"])
|
| 388 |
+
if pd.notna(stay_row.get("hospital_expire_flag"))
|
| 389 |
+
else None
|
| 390 |
+
),
|
| 391 |
+
},
|
| 392 |
+
"notes_rr_in_window": kept_notes,
|
| 393 |
+
"images_path": uniq_images,
|
| 394 |
+
"image_meta": uniq_meta,
|
| 395 |
+
"vitals_in_window": vitals,
|
| 396 |
+
"stats": {
|
| 397 |
+
"n_notes": len(kept_notes),
|
| 398 |
+
"n_images": len(uniq_images),
|
| 399 |
+
"n_vital_vars_nonempty": int(n_nonempty_vars),
|
| 400 |
+
},
|
| 401 |
+
}
|
| 402 |
+
return (
|
| 403 |
+
sample,
|
| 404 |
+
"OK",
|
| 405 |
+
{
|
| 406 |
+
"n_notes": len(kept_notes),
|
| 407 |
+
"n_images": len(uniq_images),
|
| 408 |
+
"n_vital_vars_nonempty": int(n_nonempty_vars),
|
| 409 |
+
},
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def main():
|
| 414 |
+
args = parse_args()
|
| 415 |
+
random.seed(args.seed)
|
| 416 |
+
patients_map = load_patients(args.mimic_hosp_dir)
|
| 417 |
+
adm_df = load_admissions_df(args.mimic_hosp_dir)
|
| 418 |
+
icu_df = load_icustays_df(args.mimic_icu_dir)
|
| 419 |
+
notes_df = load_radiology_rr_notes(args.mimic_note_dir)
|
| 420 |
+
cxr_meta = load_cxr_metadata(args.cxr_metadata_csv)
|
| 421 |
+
cxr_by_subject = {sid: df for (sid, df) in cxr_meta.groupby("subject_id")}
|
| 422 |
+
itemid_to_var = dict(FIXED_VITAL_ITEMIDS)
|
| 423 |
+
itemids = set(itemid_to_var.keys())
|
| 424 |
+
stays = icu_df.merge(adm_df, on=["subject_id", "hadm_id"], how="inner").copy()
|
| 425 |
+
stays["t0"] = stays["intime"]
|
| 426 |
+
stays["t1"] = stays["intime"] + pd.Timedelta(hours=float(args.window_hours))
|
| 427 |
+
mask_die_le_48h = (
|
| 428 |
+
stays["deathtime"].notna()
|
| 429 |
+
& (stays["deathtime"] >= stays["t0"])
|
| 430 |
+
& (stays["deathtime"] <= stays["t1"])
|
| 431 |
+
)
|
| 432 |
+
stays = stays[~mask_die_le_48h].copy()
|
| 433 |
+
stays["label_death_in_hosp"] = (
|
| 434 |
+
stays["deathtime"].notna() & (stays["deathtime"] > stays["t1"])
|
| 435 |
+
).astype(int)
|
| 436 |
+
notes_grouped: Dict[Tuple[int, int], pd.DataFrame] = {}
|
| 437 |
+
for (sid, hadm), g in notes_df.groupby(["subject_id", "hadm_id"]):
|
| 438 |
+
notes_grouped[int(sid), int(hadm)] = g.sort_values("charttime")
|
| 439 |
+
pos_pool = (
|
| 440 |
+
stays[stays["label_death_in_hosp"] == 1]
|
| 441 |
+
.sample(frac=1, random_state=args.seed)
|
| 442 |
+
.to_dict(orient="records")
|
| 443 |
+
)
|
| 444 |
+
neg_pool = (
|
| 445 |
+
stays[stays["label_death_in_hosp"] == 0]
|
| 446 |
+
.sample(frac=1, random_state=args.seed)
|
| 447 |
+
.to_dict(orient="records")
|
| 448 |
+
)
|
| 449 |
+
if args.n_death and len(pos_pool) == 0:
|
| 450 |
+
raise RuntimeError(
|
| 451 |
+
"No positive (death-after-window) ICU stays found after leakage guard."
|
| 452 |
+
)
|
| 453 |
+
if args.n_alive and len(neg_pool) == 0:
|
| 454 |
+
raise RuntimeError("No negative (alive) ICU stays found after leakage guard.")
|
| 455 |
+
os.makedirs(os.path.dirname(args.out_jsonl) or ".", exist_ok=True)
|
| 456 |
+
os.makedirs(os.path.dirname(args.qc_csv) or ".", exist_ok=True)
|
| 457 |
+
qc_rows: List[Dict[str, Any]] = []
|
| 458 |
+
need_pos = int(args.n_death)
|
| 459 |
+
need_neg = int(args.n_alive)
|
| 460 |
+
pos_written = 0
|
| 461 |
+
neg_written = 0
|
| 462 |
+
max_passes = max(1, int(args.max_passes_over_pool))
|
| 463 |
+
written_stays = set()
|
| 464 |
+
with open(args.out_jsonl, "w", encoding="utf-8") as f:
|
| 465 |
+
for pass_id in range(max_passes):
|
| 466 |
+
if pos_written >= need_pos and neg_written >= need_neg:
|
| 467 |
+
break
|
| 468 |
+
random.shuffle(pos_pool)
|
| 469 |
+
random.shuffle(neg_pool)
|
| 470 |
+
if pos_written < need_pos:
|
| 471 |
+
for stay_row in pos_pool:
|
| 472 |
+
if pos_written >= need_pos:
|
| 473 |
+
break
|
| 474 |
+
key = (
|
| 475 |
+
int(stay_row["subject_id"]),
|
| 476 |
+
int(stay_row["hadm_id"]),
|
| 477 |
+
int(stay_row["stay_id"]),
|
| 478 |
+
)
|
| 479 |
+
if key in written_stays:
|
| 480 |
+
continue
|
| 481 |
+
sample, status, extra = build_sample_for_stay(
|
| 482 |
+
stay_row,
|
| 483 |
+
notes_grouped,
|
| 484 |
+
cxr_by_subject,
|
| 485 |
+
patients_map,
|
| 486 |
+
args,
|
| 487 |
+
itemids,
|
| 488 |
+
itemid_to_var,
|
| 489 |
+
)
|
| 490 |
+
sid = int(stay_row["subject_id"])
|
| 491 |
+
hadm_id = int(stay_row["hadm_id"])
|
| 492 |
+
stay_id = int(stay_row["stay_id"])
|
| 493 |
+
qc = {
|
| 494 |
+
"subject_id": sid,
|
| 495 |
+
"hadm_id": hadm_id,
|
| 496 |
+
"stay_id": stay_id,
|
| 497 |
+
"label": 1,
|
| 498 |
+
"status": status,
|
| 499 |
+
"pass": pass_id,
|
| 500 |
+
}
|
| 501 |
+
qc.update(extra)
|
| 502 |
+
qc_rows.append(qc)
|
| 503 |
+
if status != "OK":
|
| 504 |
+
continue
|
| 505 |
+
written_stays.add(key)
|
| 506 |
+
f.write(
|
| 507 |
+
json.dumps(
|
| 508 |
+
json_safe(sample), ensure_ascii=False, allow_nan=False
|
| 509 |
+
)
|
| 510 |
+
+ "\n"
|
| 511 |
+
)
|
| 512 |
+
pos_written += 1
|
| 513 |
+
if neg_written < need_neg:
|
| 514 |
+
for stay_row in neg_pool:
|
| 515 |
+
if neg_written >= need_neg:
|
| 516 |
+
break
|
| 517 |
+
key = (
|
| 518 |
+
int(stay_row["subject_id"]),
|
| 519 |
+
int(stay_row["hadm_id"]),
|
| 520 |
+
int(stay_row["stay_id"]),
|
| 521 |
+
)
|
| 522 |
+
if key in written_stays:
|
| 523 |
+
continue
|
| 524 |
+
sample, status, extra = build_sample_for_stay(
|
| 525 |
+
stay_row,
|
| 526 |
+
notes_grouped,
|
| 527 |
+
cxr_by_subject,
|
| 528 |
+
patients_map,
|
| 529 |
+
args,
|
| 530 |
+
itemids,
|
| 531 |
+
itemid_to_var,
|
| 532 |
+
)
|
| 533 |
+
sid = int(stay_row["subject_id"])
|
| 534 |
+
hadm_id = int(stay_row["hadm_id"])
|
| 535 |
+
stay_id = int(stay_row["stay_id"])
|
| 536 |
+
qc = {
|
| 537 |
+
"subject_id": sid,
|
| 538 |
+
"hadm_id": hadm_id,
|
| 539 |
+
"stay_id": stay_id,
|
| 540 |
+
"label": 0,
|
| 541 |
+
"status": status,
|
| 542 |
+
"pass": pass_id,
|
| 543 |
+
}
|
| 544 |
+
qc.update(extra)
|
| 545 |
+
qc_rows.append(qc)
|
| 546 |
+
if status != "OK":
|
| 547 |
+
continue
|
| 548 |
+
written_stays.add(key)
|
| 549 |
+
f.write(
|
| 550 |
+
json.dumps(
|
| 551 |
+
json_safe(sample), ensure_ascii=False, allow_nan=False
|
| 552 |
+
)
|
| 553 |
+
+ "\n"
|
| 554 |
+
)
|
| 555 |
+
neg_written += 1
|
| 556 |
+
qc_df = pd.DataFrame(qc_rows)
|
| 557 |
+
qc_df.to_csv(args.qc_csv, index=False)
|
| 558 |
+
written = pos_written + neg_written
|
| 559 |
+
print(
|
| 560 |
+
f"[DONE] wrote={written} (pos={pos_written}/{need_pos}, neg={neg_written}/{need_neg}) -> {args.out_jsonl}"
|
| 561 |
+
)
|
| 562 |
+
print(f"[DONE] qc rows={len(qc_df)} -> {args.qc_csv}")
|
| 563 |
+
if pos_written < need_pos or neg_written < need_neg:
|
| 564 |
+
bad = qc_df[qc_df["status"] != "OK"]
|
| 565 |
+
top = bad["status"].value_counts().head(10).to_dict() if not bad.empty else {}
|
| 566 |
+
raise RuntimeError(
|
| 567 |
+
f"Only wrote pos={pos_written}/{need_pos}, neg={neg_written}/{need_neg}. Top failure reasons: {top}. See patient_qc.csv for filtering reasons."
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
if __name__ == "__main__":
|
| 572 |
+
main()
|
sample/image-timeseries/mimic_death/download.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Acquire official MIMIC files with the user's own credentialed access."""
|
| 3 |
+
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
sys.dont_write_bytecode = True
|
| 8 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "processing"))
|
| 9 |
+
from download import main
|
| 10 |
+
|
| 11 |
+
if __name__ == "__main__":
|
| 12 |
+
main("mimic")
|
sample/image-timeseries/mimic_death/generate.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Generate local mortality records from MIMIC source tables."""
|
| 3 |
+
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
sys.dont_write_bytecode = True
|
| 8 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "processing" / "common"))
|
| 9 |
+
from local_generation import main
|
| 10 |
+
|
| 11 |
+
if __name__ == "__main__":
|
| 12 |
+
main("mimic_death")
|
sample/image-timeseries/mimic_death/json_prompt_death.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Adapted from the original dataset construction script."""
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
VITAL_DESC = {
|
| 10 |
+
"heart_rate_bpm": "Heart rate in beats per minute (bpm), reflecting the patient’s cardiovascular rate and physiologic stress level.",
|
| 11 |
+
"resp_rate_insp_per_min": "Respiratory rate in breaths per minute, indicating how frequently the patient is breathing and potential respiratory distress.",
|
| 12 |
+
"spo2_percent": "Peripheral oxygen saturation (SpO₂) as a percentage, estimating arterial oxygenation measured by pulse oximetry.",
|
| 13 |
+
"temp_c": "Body temperature in degrees Celsius (°C), used to screen for fever, hypothermia, or systemic inflammatory response.",
|
| 14 |
+
"nbp_systolic_mmhg": "Non-invasive systolic blood pressure (mmHg), representing peak arterial pressure during cardiac contraction and overall perfusion pressure.",
|
| 15 |
+
"nbp_diastolic_mmhg": "Non-invasive diastolic blood pressure (mmHg), representing arterial pressure between heartbeats and reflecting vascular tone and baseline perfusion.",
|
| 16 |
+
}
|
| 17 |
+
VITAL_VARS = [
|
| 18 |
+
"heart_rate_bpm",
|
| 19 |
+
"resp_rate_insp_per_min",
|
| 20 |
+
"spo2_percent",
|
| 21 |
+
"temp_c",
|
| 22 |
+
"nbp_systolic_mmhg",
|
| 23 |
+
"nbp_diastolic_mmhg",
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def determine_decimals(values: List[float], decimals: int = None) -> int:
|
| 28 |
+
"""Same rule as your reference: choose decimals based on avg abs diff."""
|
| 29 |
+
if len(values) == 0:
|
| 30 |
+
return 0
|
| 31 |
+
if len(values) > 1:
|
| 32 |
+
diffs = [abs(values[i + 1] - values[i]) for i in range(len(values) - 1)]
|
| 33 |
+
avg_diff = float(np.mean(diffs)) if diffs else 0.0
|
| 34 |
+
else:
|
| 35 |
+
avg_diff = abs(values[0]) * 0.01 if values[0] != 0 else 1.0
|
| 36 |
+
if decimals is None:
|
| 37 |
+
if avg_diff == 0:
|
| 38 |
+
decimals = 0
|
| 39 |
+
elif avg_diff >= 10:
|
| 40 |
+
decimals = 0
|
| 41 |
+
elif avg_diff >= 1:
|
| 42 |
+
decimals = 1
|
| 43 |
+
elif avg_diff >= 0.1:
|
| 44 |
+
decimals = 2
|
| 45 |
+
elif avg_diff >= 0.01:
|
| 46 |
+
decimals = 3
|
| 47 |
+
elif avg_diff >= 0.001:
|
| 48 |
+
decimals = 4
|
| 49 |
+
else:
|
| 50 |
+
decimals = 5
|
| 51 |
+
return int(decimals)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def safe_float(x) -> Optional[float]:
|
| 55 |
+
try:
|
| 56 |
+
if x is None:
|
| 57 |
+
return None
|
| 58 |
+
v = float(x)
|
| 59 |
+
if np.isnan(v) or np.isinf(v):
|
| 60 |
+
return None
|
| 61 |
+
return v
|
| 62 |
+
except Exception:
|
| 63 |
+
return None
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _fmt_img_time(meta: Dict[str, Any]) -> str:
|
| 67 |
+
sd = meta.get("StudyDate")
|
| 68 |
+
st = meta.get("StudyTime")
|
| 69 |
+
vp = meta.get("ViewPosition")
|
| 70 |
+
study_id = meta.get("study_id")
|
| 71 |
+
dicom_id = meta.get("dicom_id")
|
| 72 |
+
sd_s = str(sd) if sd is not None and str(sd).strip() != "" else "UNKNOWN_DATE"
|
| 73 |
+
st_s = str(st) if st is not None and str(st).strip() != "" else "UNKNOWN_TIME"
|
| 74 |
+
vp_s = str(vp) if vp is not None and str(vp).strip() != "" else "UNKNOWN_VIEW"
|
| 75 |
+
extras = []
|
| 76 |
+
if study_id is not None:
|
| 77 |
+
extras.append(f"study_id={study_id}")
|
| 78 |
+
if dicom_id is not None:
|
| 79 |
+
extras.append(f"dicom_id={dicom_id}")
|
| 80 |
+
extras.append(f"view={vp_s}")
|
| 81 |
+
return f"{sd_s} {st_s} ({', '.join(extras)})"
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _val_to_str(x: Any) -> str:
|
| 85 |
+
return "" if x is None else str(x)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def build_prompt(sample: Dict[str, Any]) -> str:
|
| 89 |
+
images: List[str] = sample.get("images_path", sample.get("image_path", sample.get("images", []))) or []
|
| 90 |
+
image_meta: List[Dict[str, Any]] = sample.get("image_meta", []) or []
|
| 91 |
+
notes: List[Dict[str, Any]] = sample.get("notes_rr_in_window", []) or []
|
| 92 |
+
vit_aligned: Dict[str, Any] = sample.get("vitals_aligned", {}) or {}
|
| 93 |
+
timestamps: List[str] = vit_aligned.get("timestamps", []) or []
|
| 94 |
+
img_path_lines = []
|
| 95 |
+
for p in images:
|
| 96 |
+
img_path_lines.append(f"<image>{p}</image>")
|
| 97 |
+
img_path_block = "\n".join(img_path_lines).strip()
|
| 98 |
+
img_info_lines = []
|
| 99 |
+
if images:
|
| 100 |
+
for i, p in enumerate(images):
|
| 101 |
+
meta = (
|
| 102 |
+
image_meta[i]
|
| 103 |
+
if i < len(image_meta) and isinstance(image_meta[i], dict)
|
| 104 |
+
else {}
|
| 105 |
+
)
|
| 106 |
+
img_info_lines.append(f"- Image {i + 1}: {p}")
|
| 107 |
+
img_info_lines.append(
|
| 108 |
+
f" Acquisition time (from metadata): {_fmt_img_time(meta)}"
|
| 109 |
+
)
|
| 110 |
+
img_info_block = "\n".join(img_info_lines).strip()
|
| 111 |
+
report_lines = []
|
| 112 |
+
for i, n in enumerate(notes):
|
| 113 |
+
ct = n.get("charttime", "")
|
| 114 |
+
txt = n.get("text", "")
|
| 115 |
+
report_lines.append(f"[RR Note {i + 1} | charttime={ct}]\n{txt}".strip())
|
| 116 |
+
report_block = "\n\n".join(report_lines).strip()
|
| 117 |
+
var_lines = []
|
| 118 |
+
for v in VITAL_VARS:
|
| 119 |
+
var_lines.append(f"- {v}: {VITAL_DESC.get(v, v)}")
|
| 120 |
+
var_block = "\n".join(var_lines)
|
| 121 |
+
ts_lines = []
|
| 122 |
+
arrays = {v: vit_aligned.get(v, []) or [] for v in VITAL_VARS}
|
| 123 |
+
for idx, t in enumerate(timestamps):
|
| 124 |
+
parts = [
|
| 125 |
+
f"{v}={(_val_to_str(arrays[v][idx]) if idx < len(arrays[v]) else '')}"
|
| 126 |
+
for v in VITAL_VARS
|
| 127 |
+
]
|
| 128 |
+
ts_lines.append(f"{t}: " + ", ".join(parts))
|
| 129 |
+
timeseries_block = "\n".join(ts_lines).strip()
|
| 130 |
+
question = "Question: Based on the chest X-ray image(s), radiology report(s), and the ICU first-48-hour vital signs, will the patient die during this hospital admission?"
|
| 131 |
+
options = "Answer (choose one option):\nA. Yes.\nB. No.\n\nReturn only the option letter (A or B)."
|
| 132 |
+
prompt = f"\nYou are given a question-answering (QA) task.\n\nUse the chest X-ray image(s), radiology report(s), and ICU first-48-hour vital signs as evidence to answer the multiple-choice question.\nDo NOT output any analysis. Return only the option letter.\n\n<image>\nMIMIC-CXR-JPG images: Each image is a JPG converted from an original DICOM chest X-ray.\nMetadata includes StudyDate (an anonymized date; per-patient ordering and time intervals are preserved) and StudyTime (time-of-day; not modified during de-identification).\nBelow are the image paths and acquisition times from metadata:\n{img_info_block}\n</image>\n\n<report>\nRadiology report(s) (RR notes) within ICU first 48 hours:\n{report_block}\n</report>\n\n<variables>\nVital sign variables (within ICU first 48 hours):\n{var_block}\n</variables>\n\n<timeseries>\nAligned time series (each line is one timestamp; missing values are empty):\n{timeseries_block}\n</timeseries>\n\n{question}\n{options}\n"
|
| 133 |
+
return "\n".join([ln.rstrip() for ln in prompt.splitlines()]).strip()
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def align_and_round_vitals(
|
| 137 |
+
vitals_in_window: Dict[str, Any],
|
| 138 |
+
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
| 139 |
+
var_points: Dict[str, List[Tuple[str, float]]] = {v: [] for v in VITAL_VARS}
|
| 140 |
+
if isinstance(vitals_in_window, dict):
|
| 141 |
+
for var in VITAL_VARS:
|
| 142 |
+
seq = vitals_in_window.get(var, [])
|
| 143 |
+
if not isinstance(seq, list):
|
| 144 |
+
continue
|
| 145 |
+
for p in seq:
|
| 146 |
+
if not isinstance(p, dict):
|
| 147 |
+
continue
|
| 148 |
+
t = p.get("t")
|
| 149 |
+
v = safe_float(p.get("v"))
|
| 150 |
+
if isinstance(t, str) and t and (v is not None):
|
| 151 |
+
var_points[var].append((t, v))
|
| 152 |
+
vitals_rounding: Dict[str, int] = {}
|
| 153 |
+
var_maps: Dict[str, Dict[str, float]] = {}
|
| 154 |
+
for var in VITAL_VARS:
|
| 155 |
+
pts = sorted(var_points[var], key=lambda x: x[0])
|
| 156 |
+
values = [v for (_, v) in pts]
|
| 157 |
+
dec = determine_decimals(values)
|
| 158 |
+
vitals_rounding[var] = dec
|
| 159 |
+
m: Dict[str, float] = {}
|
| 160 |
+
for t, v in pts:
|
| 161 |
+
m[t] = round(v, dec)
|
| 162 |
+
var_maps[var] = m
|
| 163 |
+
all_ts = set()
|
| 164 |
+
for var in VITAL_VARS:
|
| 165 |
+
all_ts.update(var_maps[var].keys())
|
| 166 |
+
timestamps = sorted(all_ts)
|
| 167 |
+
vitals_aligned: Dict[str, Any] = {"timestamps": timestamps}
|
| 168 |
+
for var in VITAL_VARS:
|
| 169 |
+
m = var_maps[var]
|
| 170 |
+
vitals_aligned[var] = [m.get(t, None) for t in timestamps]
|
| 171 |
+
return (vitals_aligned, vitals_rounding)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def parse_args():
|
| 175 |
+
ap = argparse.ArgumentParser()
|
| 176 |
+
ap.add_argument("--in_jsonl", "--in-jsonl", required=True)
|
| 177 |
+
ap.add_argument("--out_jsonl", "--out-jsonl", required=True)
|
| 178 |
+
ap.add_argument("--start_id", "--start-id", type=int, default=0)
|
| 179 |
+
return ap.parse_args()
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def main():
|
| 183 |
+
args = parse_args()
|
| 184 |
+
task_id = int(args.start_id)
|
| 185 |
+
n_in = 0
|
| 186 |
+
n_out = 0
|
| 187 |
+
with open(args.in_jsonl, "r", encoding="utf-8") as fin, open(
|
| 188 |
+
args.out_jsonl, "w", encoding="utf-8"
|
| 189 |
+
) as fout:
|
| 190 |
+
for line in fin:
|
| 191 |
+
line = line.strip()
|
| 192 |
+
if not line:
|
| 193 |
+
continue
|
| 194 |
+
n_in += 1
|
| 195 |
+
obj = json.loads(line)
|
| 196 |
+
obj["image_path"] = obj.get("images_path", obj.get("image_path", []))
|
| 197 |
+
obj["task_id"] = f"MIMIC_death{task_id}"
|
| 198 |
+
obj["task_type"] = "mimic_task"
|
| 199 |
+
obj["dimension"] = "complementary evidence"
|
| 200 |
+
obj["sub_dimension"] = "mimicIV_QA"
|
| 201 |
+
obj["sub2_dimension"] = "death"
|
| 202 |
+
obj["evaluation_type"] = "QA"
|
| 203 |
+
vit_raw = (
|
| 204 |
+
obj.get("time_series_recent")
|
| 205 |
+
or obj.get("vitals_lookback")
|
| 206 |
+
or obj.get("vitals_in_window")
|
| 207 |
+
or {}
|
| 208 |
+
)
|
| 209 |
+
vitals_aligned, vitals_rounding = align_and_round_vitals(vit_raw)
|
| 210 |
+
obj["question"] = (
|
| 211 |
+
"Question: Based on the chest X-ray image(s), radiology report(s), and the ICU first-48-hour vital signs, will the patient die during this hospital admission?"
|
| 212 |
+
)
|
| 213 |
+
obj["vitals_aligned"] = vitals_aligned
|
| 214 |
+
obj["vitals_rounding"] = vitals_rounding
|
| 215 |
+
obj["prompt"] = build_prompt(obj)
|
| 216 |
+
if obj["label_death_in_hosp"] == 1:
|
| 217 |
+
obj["ground_truth"] = "A"
|
| 218 |
+
else:
|
| 219 |
+
obj["ground_truth"] = "B"
|
| 220 |
+
fout.write(json.dumps(obj, ensure_ascii=False, allow_nan=False) + "\n")
|
| 221 |
+
task_id += 1
|
| 222 |
+
n_out += 1
|
| 223 |
+
print(f"[DONE] in={n_in}, out={n_out}")
|
| 224 |
+
print(f"[DONE] wrote -> {args.out_jsonl}")
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
if __name__ == "__main__":
|
| 228 |
+
main()
|
sample/image-timeseries/mimic_death/source_tables.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Input and JSON helpers for the recovered MIMIC task builders."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import math
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def table_path(directory: str, name: str) -> str:
|
| 14 |
+
path = Path(directory) / name
|
| 15 |
+
if path.is_file():
|
| 16 |
+
return str(path)
|
| 17 |
+
compressed = path.with_suffix(path.suffix + ".gz")
|
| 18 |
+
if compressed.is_file():
|
| 19 |
+
return str(compressed)
|
| 20 |
+
raise FileNotFoundError(f"Missing source table: {path}")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def study_date(value) -> str | None:
|
| 24 |
+
if pd.isna(value):
|
| 25 |
+
return None
|
| 26 |
+
text = str(value).strip().removesuffix(".0")
|
| 27 |
+
stamp = (
|
| 28 |
+
pd.to_datetime(text, format="%Y%m%d", errors="coerce")
|
| 29 |
+
if len(text) == 8 and text.isdigit()
|
| 30 |
+
else pd.to_datetime(text, errors="coerce")
|
| 31 |
+
)
|
| 32 |
+
return None if pd.isna(stamp) else stamp.date().isoformat()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def json_safe(value):
|
| 36 |
+
if isinstance(value, dict):
|
| 37 |
+
return {key: json_safe(item) for key, item in value.items()}
|
| 38 |
+
if isinstance(value, (list, tuple)):
|
| 39 |
+
return [json_safe(item) for item in value]
|
| 40 |
+
if isinstance(value, np.generic):
|
| 41 |
+
value = value.item()
|
| 42 |
+
if (
|
| 43 |
+
isinstance(value, float)
|
| 44 |
+
and not math.isfinite(value)
|
| 45 |
+
or value is pd.NA
|
| 46 |
+
or value is pd.NaT
|
| 47 |
+
):
|
| 48 |
+
return None
|
| 49 |
+
if isinstance(value, pd.Timestamp):
|
| 50 |
+
return value.isoformat()
|
| 51 |
+
return value
|
sample/image-timeseries/mimic_death/split_dataset.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Adapted from the original dataset construction script."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import math
|
| 8 |
+
import random
|
| 9 |
+
from collections import defaultdict
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Dict, List, Sequence, Tuple
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def read_jsonl(path: Path) -> List[dict]:
|
| 15 |
+
items: List[dict] = []
|
| 16 |
+
with path.open("r", encoding="utf-8") as f:
|
| 17 |
+
for line_no, line in enumerate(f, start=1):
|
| 18 |
+
line = line.strip()
|
| 19 |
+
if not line:
|
| 20 |
+
continue
|
| 21 |
+
try:
|
| 22 |
+
items.append(json.loads(line))
|
| 23 |
+
except json.JSONDecodeError as e:
|
| 24 |
+
raise ValueError(f"Invalid JSON at {path}:{line_no}") from e
|
| 25 |
+
return items
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def write_jsonl(path: Path, items: Sequence[dict]) -> None:
|
| 29 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 30 |
+
with path.open("w", encoding="utf-8") as f:
|
| 31 |
+
for obj in items:
|
| 32 |
+
f.write(json.dumps(obj, ensure_ascii=False) + "\n")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def stratified_split(
|
| 36 |
+
items: List[dict], train_ratio: float, seed: int
|
| 37 |
+
) -> Tuple[List[dict], List[dict]]:
|
| 38 |
+
if not items:
|
| 39 |
+
return ([], [])
|
| 40 |
+
rng = random.Random(seed)
|
| 41 |
+
groups: Dict[str, List[dict]] = defaultdict(list)
|
| 42 |
+
for obj in items:
|
| 43 |
+
label = str(obj.get("ground_truth", ""))
|
| 44 |
+
groups[label].append(obj)
|
| 45 |
+
for group_items in groups.values():
|
| 46 |
+
rng.shuffle(group_items)
|
| 47 |
+
n = len(items)
|
| 48 |
+
train_target = int(round(n * train_ratio))
|
| 49 |
+
train_target = max(0, min(n, train_target))
|
| 50 |
+
test_target = n - train_target
|
| 51 |
+
labels = sorted(groups.keys())
|
| 52 |
+
train_counts: Dict[str, int] = {}
|
| 53 |
+
fractions: List[Tuple[float, str]] = []
|
| 54 |
+
for label in labels:
|
| 55 |
+
cnt = len(groups[label])
|
| 56 |
+
exact = cnt * train_ratio
|
| 57 |
+
base = math.floor(exact)
|
| 58 |
+
train_counts[label] = base
|
| 59 |
+
fractions.append((exact - base, label))
|
| 60 |
+
current = sum(train_counts.values())
|
| 61 |
+
need = train_target - current
|
| 62 |
+
if need > 0:
|
| 63 |
+
fractions.sort(reverse=True)
|
| 64 |
+
i = 0
|
| 65 |
+
while need > 0 and fractions:
|
| 66 |
+
_, label = fractions[i % len(fractions)]
|
| 67 |
+
if train_counts[label] < len(groups[label]):
|
| 68 |
+
train_counts[label] += 1
|
| 69 |
+
need -= 1
|
| 70 |
+
i += 1
|
| 71 |
+
elif need < 0:
|
| 72 |
+
fractions.sort()
|
| 73 |
+
i = 0
|
| 74 |
+
while need < 0 and fractions:
|
| 75 |
+
_, label = fractions[i % len(fractions)]
|
| 76 |
+
if train_counts[label] > 0:
|
| 77 |
+
train_counts[label] -= 1
|
| 78 |
+
need += 1
|
| 79 |
+
i += 1
|
| 80 |
+
train_items: List[dict] = []
|
| 81 |
+
test_items: List[dict] = []
|
| 82 |
+
for label in labels:
|
| 83 |
+
group_items = groups[label]
|
| 84 |
+
k = train_counts[label]
|
| 85 |
+
train_items.extend(group_items[:k])
|
| 86 |
+
test_items.extend(group_items[k:])
|
| 87 |
+
rng.shuffle(train_items)
|
| 88 |
+
rng.shuffle(test_items)
|
| 89 |
+
assert len(train_items) + len(test_items) == n
|
| 90 |
+
assert len(train_items) == train_target
|
| 91 |
+
assert len(test_items) == test_target
|
| 92 |
+
return (train_items, test_items)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def split_one_file(
|
| 96 |
+
in_path: Path, out_train: Path, out_test: Path, seed: int, train_ratio: float
|
| 97 |
+
) -> None:
|
| 98 |
+
items = read_jsonl(in_path)
|
| 99 |
+
train_items, test_items = stratified_split(
|
| 100 |
+
items, train_ratio=train_ratio, seed=seed
|
| 101 |
+
)
|
| 102 |
+
write_jsonl(out_train, train_items)
|
| 103 |
+
write_jsonl(out_test, test_items)
|
| 104 |
+
|
| 105 |
+
def ratio(xs: Sequence[dict]) -> Dict[str, int]:
|
| 106 |
+
c: Dict[str, int] = defaultdict(int)
|
| 107 |
+
for x in xs:
|
| 108 |
+
c[str(x.get("ground_truth", ""))] += 1
|
| 109 |
+
return dict(c)
|
| 110 |
+
|
| 111 |
+
print(
|
| 112 |
+
f"[DONE] {in_path.name}: total={len(items)} train={len(train_items)} test={len(test_items)}"
|
| 113 |
+
)
|
| 114 |
+
print(f" train label counts: {ratio(train_items)}")
|
| 115 |
+
print(f" test label counts: {ratio(test_items)}")
|
| 116 |
+
print(f" wrote -> {out_train}")
|
| 117 |
+
print(f" wrote -> {out_test}")
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def default_output_paths(in_path: Path) -> Tuple[Path, Path]:
|
| 121 |
+
stem = in_path.with_suffix("")
|
| 122 |
+
return (
|
| 123 |
+
stem.with_name(stem.name + "_train.jsonl"),
|
| 124 |
+
stem.with_name(stem.name + "_test.jsonl"),
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def main() -> None:
|
| 129 |
+
ap = argparse.ArgumentParser(
|
| 130 |
+
description="Split JSONL into train/test with stratification by ground_truth"
|
| 131 |
+
)
|
| 132 |
+
ap.add_argument("inputs", nargs="+", help="JSONL input paths.")
|
| 133 |
+
ap.add_argument(
|
| 134 |
+
"--train_ratio",
|
| 135 |
+
"--train-ratio",
|
| 136 |
+
type=float,
|
| 137 |
+
default=0.5,
|
| 138 |
+
help="Training fraction.",
|
| 139 |
+
)
|
| 140 |
+
ap.add_argument("--seed", type=int, default=42, help="Random seed.")
|
| 141 |
+
ap.add_argument(
|
| 142 |
+
"--out_dir",
|
| 143 |
+
"--out-dir",
|
| 144 |
+
default="",
|
| 145 |
+
help="Output directory; defaults to the input directory.",
|
| 146 |
+
)
|
| 147 |
+
args = ap.parse_args()
|
| 148 |
+
if not 0.0 < args.train_ratio < 1.0:
|
| 149 |
+
raise ValueError("--train-ratio must be between zero and one")
|
| 150 |
+
for idx, in_file in enumerate(args.inputs):
|
| 151 |
+
in_path = Path(in_file)
|
| 152 |
+
if not in_path.exists():
|
| 153 |
+
raise FileNotFoundError(f"Input file not found: {in_path}")
|
| 154 |
+
if args.out_dir:
|
| 155 |
+
out_dir = Path(args.out_dir)
|
| 156 |
+
out_train = out_dir / (in_path.stem + "_train.jsonl")
|
| 157 |
+
out_test = out_dir / (in_path.stem + "_test.jsonl")
|
| 158 |
+
else:
|
| 159 |
+
out_train, out_test = default_output_paths(in_path)
|
| 160 |
+
split_one_file(
|
| 161 |
+
in_path,
|
| 162 |
+
out_train,
|
| 163 |
+
out_test,
|
| 164 |
+
seed=args.seed + idx,
|
| 165 |
+
train_ratio=args.train_ratio,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
if __name__ == "__main__":
|
| 170 |
+
main()
|
sample/image-timeseries/mimic_disch/README.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIMIC discharge
|
| 2 |
+
|
| 3 |
+
**Processing code only:** source data and generated task records are not
|
| 4 |
+
included. Obtain the sources with your own approved access and follow their
|
| 5 |
+
terms. See the [shared setup instructions](../../../processing/README.md).
|
| 6 |
+
Run the commands below from the directory containing `MMTA-v1.0/`, keeping
|
| 7 |
+
`local_sources/` and `local_work/` outside the release folder.
|
| 8 |
+
|
| 9 |
+
Download MIMIC-IV 3.1, MIMIC-IV-Note 2.2 and MIMIC-CXR-JPG 2.1.0 from [PhysioNet](https://physionet.org/) using your approved account. Required tables: patients, admissions, chartevents, radiology and CXR metadata. `download.py` accepts `--file` or `--file-list` for each selected source.
|
| 10 |
+
|
| 11 |
+
```bash
|
| 12 |
+
python -B MMTA-v1.0/sample/image-timeseries/mimic_disch/download.py \
|
| 13 |
+
--output local_sources/mimic --physionet-dataset mimiciv \
|
| 14 |
+
--file icu/chartevents.csv.gz --username YOUR_USERNAME --accept-terms
|
| 15 |
+
python -B MMTA-v1.0/sample/image-timeseries/mimic_disch/generate.py \
|
| 16 |
+
--mimic-hosp-dir local_sources/mimic/mimiciv/hosp \
|
| 17 |
+
--mimic-note-dir local_sources/mimic/mimic-iv-note/note \
|
| 18 |
+
--cxr-metadata-csv local_sources/mimic/mimic-cxr-jpg/mimic-cxr-2.0.0-metadata.csv.gz \
|
| 19 |
+
--cxr-jpg-root local_sources/mimic/mimic-cxr-jpg/files \
|
| 20 |
+
--chartevents local_sources/mimic/mimiciv/icu/chartevents.csv.gz \
|
| 21 |
+
--output-dir local_work/mimic_disch_build
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
Join admissions, radiology reports and same-day chest images. Use 48 hours of vital signs before the report anchor and label discharge within the following 48 hours (50 positive / 100 negative); positive anchors are sampled within 24 hours before discharge. The command buckets raw vitals, constructs labels and prompts, makes a 50/50 stratified split, and exports image/CSV records. Existing buckets can be supplied with `--chartevents-root`.
|
| 25 |
+
|
| 26 |
+
Output: `--output-dir/mimic_disch/mimic_disch.omnits.jsonl`, with `timeseries/` and intermediate train/test JSONL. Images stay in the source tree; paths are relative to the output domain directory. `--split train` selects the training output.
|
sample/image-timeseries/mimic_disch/build_json_QA.py
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Adapted from the original dataset construction script."""
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
import random
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import sys
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
sys.dont_write_bytecode = True
|
| 13 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "mimic_death"))
|
| 14 |
+
from source_tables import json_safe, study_date, table_path
|
| 15 |
+
from typing import Dict, List, Optional, Tuple, Any
|
| 16 |
+
|
| 17 |
+
FIXED_VITAL_ITEMIDS = {
|
| 18 |
+
220045: "heart_rate_bpm",
|
| 19 |
+
220210: "resp_rate_insp_per_min",
|
| 20 |
+
220277: "spo2_percent",
|
| 21 |
+
223762: "temp_c",
|
| 22 |
+
220179: "nbp_systolic_mmhg",
|
| 23 |
+
220180: "nbp_diastolic_mmhg",
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def parse_args():
|
| 28 |
+
ap = argparse.ArgumentParser()
|
| 29 |
+
ap.add_argument("--mimic_hosp_dir", "--mimic-hosp-dir", required=True)
|
| 30 |
+
ap.add_argument("--mimic_note_dir", "--mimic-note-dir", required=True)
|
| 31 |
+
ap.add_argument("--cxr_metadata_csv", "--cxr-metadata-csv", required=True)
|
| 32 |
+
ap.add_argument("--cxr_jpg_root", "--cxr-jpg-root", required=True)
|
| 33 |
+
ap.add_argument(
|
| 34 |
+
"--chartevents_root",
|
| 35 |
+
"--chartevents-root",
|
| 36 |
+
help="Bucketed chartevents root: <root>/<subject_id>/<hadm_id>/chartevents.csv",
|
| 37 |
+
required=True,
|
| 38 |
+
)
|
| 39 |
+
ap.add_argument("--out_jsonl", "--out-jsonl", required=True)
|
| 40 |
+
ap.add_argument(
|
| 41 |
+
"--qc_csv", "--qc-csv", help="Write per-sample QC summary here", required=True
|
| 42 |
+
)
|
| 43 |
+
ap.add_argument("--seed", type=int, default=42)
|
| 44 |
+
ap.add_argument("--n_samples", "--n-samples", type=int, default=120)
|
| 45 |
+
ap.add_argument(
|
| 46 |
+
"--min_complete_vars",
|
| 47 |
+
"--min-complete-vars",
|
| 48 |
+
type=int,
|
| 49 |
+
default=2,
|
| 50 |
+
help="Require at least this many variables have full k_per_var observations in lookback window",
|
| 51 |
+
)
|
| 52 |
+
ap.add_argument(
|
| 53 |
+
"--complete_requires_full_k",
|
| 54 |
+
"--complete-requires-full-k",
|
| 55 |
+
action="store_true",
|
| 56 |
+
help="If set, 'complete' means len==k_per_var; otherwise len>=1 counts as complete (not recommended)",
|
| 57 |
+
)
|
| 58 |
+
ap.add_argument(
|
| 59 |
+
"--horizon_hours",
|
| 60 |
+
"--horizon-hours",
|
| 61 |
+
type=int,
|
| 62 |
+
default=48,
|
| 63 |
+
help="Predict discharge within this many hours after anchor",
|
| 64 |
+
)
|
| 65 |
+
ap.add_argument(
|
| 66 |
+
"--pos_short_window_hours",
|
| 67 |
+
"--pos-short-window-hours",
|
| 68 |
+
type=int,
|
| 69 |
+
default=24,
|
| 70 |
+
help="For positives, require note+image within this many hours before discharge",
|
| 71 |
+
)
|
| 72 |
+
ap.add_argument(
|
| 73 |
+
"--lookback_hours",
|
| 74 |
+
"--lookback-hours",
|
| 75 |
+
type=int,
|
| 76 |
+
default=48,
|
| 77 |
+
help="Search vitals in [anchor-lookback, anchor]",
|
| 78 |
+
)
|
| 79 |
+
ap.add_argument(
|
| 80 |
+
"--k_per_var",
|
| 81 |
+
"--k-per-var",
|
| 82 |
+
type=int,
|
| 83 |
+
default=12,
|
| 84 |
+
help="Keep last k observations per variable",
|
| 85 |
+
)
|
| 86 |
+
ap.add_argument(
|
| 87 |
+
"--max_pos",
|
| 88 |
+
"--max-pos",
|
| 89 |
+
type=int,
|
| 90 |
+
default=50,
|
| 91 |
+
help="limit positives, -1 means no limit",
|
| 92 |
+
)
|
| 93 |
+
ap.add_argument(
|
| 94 |
+
"--max_neg",
|
| 95 |
+
"--max-neg",
|
| 96 |
+
type=int,
|
| 97 |
+
default=100,
|
| 98 |
+
help="limit negatives, -1 means no limit",
|
| 99 |
+
)
|
| 100 |
+
ap.add_argument(
|
| 101 |
+
"--drop_if_all_vars_empty", "--drop-if-all-vars-empty", action="store_true"
|
| 102 |
+
)
|
| 103 |
+
return ap.parse_args()
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def to_date_str_yyyy_mm_dd_from_studydate(x) -> Optional[str]:
|
| 107 |
+
return study_date(x)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def subject_folder(subject_id: int) -> str:
|
| 111 |
+
s = str(int(subject_id))
|
| 112 |
+
return f"p{s[:2]}"
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def build_jpg_path(
|
| 116 |
+
cxr_jpg_root: str, subject_id: int, study_id: int, dicom_id: str
|
| 117 |
+
) -> str:
|
| 118 |
+
return os.path.abspath(
|
| 119 |
+
os.path.join(
|
| 120 |
+
cxr_jpg_root,
|
| 121 |
+
subject_folder(subject_id),
|
| 122 |
+
f"p{int(subject_id)}",
|
| 123 |
+
f"s{int(study_id)}",
|
| 124 |
+
f"{dicom_id}.jpg",
|
| 125 |
+
)
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def load_radiology_rr_notes(note_dir: str) -> pd.DataFrame:
|
| 130 |
+
path = table_path(note_dir, "radiology.csv")
|
| 131 |
+
r = pd.read_csv(path)
|
| 132 |
+
r = r[r["note_type"].astype(str).eq("RR")].copy()
|
| 133 |
+
r["charttime"] = pd.to_datetime(r["charttime"], errors="coerce")
|
| 134 |
+
r = r[r["charttime"].notna()].copy()
|
| 135 |
+
r = r[r["text"].notna()].copy()
|
| 136 |
+
r = r[r["hadm_id"].notna()].copy()
|
| 137 |
+
r["subject_id"] = r["subject_id"].astype(int)
|
| 138 |
+
r["hadm_id"] = r["hadm_id"].astype(int)
|
| 139 |
+
r["note_date"] = r["charttime"].dt.date.astype(str)
|
| 140 |
+
return r
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def load_cxr_metadata(meta_csv: str) -> pd.DataFrame:
|
| 144 |
+
m = pd.read_csv(meta_csv)
|
| 145 |
+
missing = {"dicom_id", "subject_id", "study_id", "StudyDate"} - set(m.columns)
|
| 146 |
+
if missing:
|
| 147 |
+
raise RuntimeError(f"metadata missing required columns: {missing}")
|
| 148 |
+
m["subject_id"] = m["subject_id"].astype(int)
|
| 149 |
+
m["study_id"] = m["study_id"].astype(int)
|
| 150 |
+
m["dicom_id"] = m["dicom_id"].astype(str)
|
| 151 |
+
m["study_date"] = m["StudyDate"].apply(to_date_str_yyyy_mm_dd_from_studydate)
|
| 152 |
+
return m
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def load_patients(hosp_dir: str) -> Dict[int, Dict]:
|
| 156 |
+
path = table_path(hosp_dir, "patients.csv")
|
| 157 |
+
p = pd.read_csv(
|
| 158 |
+
path,
|
| 159 |
+
usecols=lambda c: c
|
| 160 |
+
in {"subject_id", "gender", "anchor_age", "anchor_year", "anchor_year_group"},
|
| 161 |
+
)
|
| 162 |
+
p["subject_id"] = p["subject_id"].astype(int)
|
| 163 |
+
return p.set_index("subject_id").to_dict(orient="index")
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def load_admissions_df(hosp_dir: str) -> pd.DataFrame:
|
| 167 |
+
path = table_path(hosp_dir, "admissions.csv")
|
| 168 |
+
cols = {
|
| 169 |
+
"subject_id",
|
| 170 |
+
"hadm_id",
|
| 171 |
+
"admittime",
|
| 172 |
+
"dischtime",
|
| 173 |
+
"admission_type",
|
| 174 |
+
"insurance",
|
| 175 |
+
"language",
|
| 176 |
+
"marital_status",
|
| 177 |
+
"race",
|
| 178 |
+
"hospital_expire_flag",
|
| 179 |
+
}
|
| 180 |
+
a = pd.read_csv(path, usecols=lambda c: c in cols)
|
| 181 |
+
a["subject_id"] = a["subject_id"].astype(int)
|
| 182 |
+
a["hadm_id"] = a["hadm_id"].astype(int)
|
| 183 |
+
a["admittime"] = pd.to_datetime(a["admittime"], errors="coerce")
|
| 184 |
+
a["dischtime"] = pd.to_datetime(a["dischtime"], errors="coerce")
|
| 185 |
+
a = a[a["dischtime"].notna() & a["admittime"].notna()].copy()
|
| 186 |
+
return a
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def admissions_maps(
|
| 190 |
+
adm_df: pd.DataFrame,
|
| 191 |
+
) -> Tuple[Dict[Tuple[int, int], Dict], Dict[Tuple[int, int], pd.Timestamp]]:
|
| 192 |
+
out = adm_df.copy()
|
| 193 |
+
out2 = out.copy()
|
| 194 |
+
out["admittime"] = out["admittime"].astype("datetime64[ns]").astype(str)
|
| 195 |
+
out["dischtime"] = out["dischtime"].astype("datetime64[ns]").astype(str)
|
| 196 |
+
info_map = out.set_index(["subject_id", "hadm_id"]).to_dict(orient="index")
|
| 197 |
+
disch_map = out2.set_index(["subject_id", "hadm_id"])["dischtime"].to_dict()
|
| 198 |
+
return (info_map, disch_map)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def match_all_images_for_note(
|
| 202 |
+
note_row, cxr_by_subject: Dict[int, pd.DataFrame], cxr_jpg_root: str
|
| 203 |
+
):
|
| 204 |
+
sid = int(note_row["subject_id"])
|
| 205 |
+
date_str = str(note_row["note_date"])
|
| 206 |
+
subm = cxr_by_subject.get(sid)
|
| 207 |
+
if subm is None:
|
| 208 |
+
return ([], [])
|
| 209 |
+
matched = subm[subm["study_date"].eq(date_str)].copy()
|
| 210 |
+
if matched.empty:
|
| 211 |
+
return ([], [])
|
| 212 |
+
matched = matched.drop_duplicates(["study_id", "dicom_id"])
|
| 213 |
+
images, metas = ([], [])
|
| 214 |
+
for _, r in matched.iterrows():
|
| 215 |
+
images.append(
|
| 216 |
+
build_jpg_path(cxr_jpg_root, sid, int(r["study_id"]), str(r["dicom_id"]))
|
| 217 |
+
)
|
| 218 |
+
metas.append(
|
| 219 |
+
{
|
| 220 |
+
"dicom_id": str(r["dicom_id"]),
|
| 221 |
+
"study_id": int(r["study_id"]),
|
| 222 |
+
"StudyDate": r.get("StudyDate"),
|
| 223 |
+
"StudyTime": r.get("StudyTime"),
|
| 224 |
+
"ViewPosition": r.get("ViewPosition"),
|
| 225 |
+
"Rows": r.get("Rows"),
|
| 226 |
+
"Columns": r.get("Columns"),
|
| 227 |
+
"PerformedProcedureStepDescription": r.get(
|
| 228 |
+
"PerformedProcedureStepDescription"
|
| 229 |
+
),
|
| 230 |
+
"ProcedureCodeSequence_CodeMeaning": r.get(
|
| 231 |
+
"ProcedureCodeSequence_CodeMeaning"
|
| 232 |
+
),
|
| 233 |
+
"ViewCodeSequence_CodeMeaning": r.get("ViewCodeSequence_CodeMeaning"),
|
| 234 |
+
"PatientOrientationCodeSequence_CodeMeaning": r.get(
|
| 235 |
+
"PatientOrientationCodeSequence_CodeMeaning"
|
| 236 |
+
),
|
| 237 |
+
}
|
| 238 |
+
)
|
| 239 |
+
return (images, metas)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def iter_chartevents_window(
|
| 243 |
+
chartevents_root: str,
|
| 244 |
+
subject_id: int,
|
| 245 |
+
hadm_id: int,
|
| 246 |
+
itemids: set,
|
| 247 |
+
t_start: pd.Timestamp,
|
| 248 |
+
t_end: pd.Timestamp,
|
| 249 |
+
chunksize: int,
|
| 250 |
+
filename: str = "chartevents.csv",
|
| 251 |
+
) -> pd.DataFrame:
|
| 252 |
+
p = os.path.join(
|
| 253 |
+
chartevents_root, str(int(subject_id)), str(int(hadm_id)), filename
|
| 254 |
+
)
|
| 255 |
+
usecols = ["charttime", "itemid", "valuenum"]
|
| 256 |
+
if not os.path.exists(p):
|
| 257 |
+
return pd.DataFrame(columns=["charttime", "itemid", "valuenum"])
|
| 258 |
+
out = []
|
| 259 |
+
for chunk in pd.read_csv(
|
| 260 |
+
p, usecols=lambda c: c in set(usecols), chunksize=chunksize
|
| 261 |
+
):
|
| 262 |
+
if "itemid" not in chunk.columns:
|
| 263 |
+
continue
|
| 264 |
+
chunk = chunk[chunk["itemid"].isin(itemids)].copy()
|
| 265 |
+
if chunk.empty:
|
| 266 |
+
continue
|
| 267 |
+
chunk["charttime"] = pd.to_datetime(chunk["charttime"], errors="coerce")
|
| 268 |
+
chunk = chunk[chunk["charttime"].notna()].copy()
|
| 269 |
+
chunk = chunk[
|
| 270 |
+
(chunk["charttime"] >= t_start) & (chunk["charttime"] <= t_end)
|
| 271 |
+
].copy()
|
| 272 |
+
if chunk.empty:
|
| 273 |
+
continue
|
| 274 |
+
chunk["valuenum"] = pd.to_numeric(chunk["valuenum"], errors="coerce")
|
| 275 |
+
chunk = chunk[chunk["valuenum"].notna()].copy()
|
| 276 |
+
if chunk.empty:
|
| 277 |
+
continue
|
| 278 |
+
out.append(chunk[["charttime", "itemid", "valuenum"]])
|
| 279 |
+
if not out:
|
| 280 |
+
return pd.DataFrame(columns=["charttime", "itemid", "valuenum"])
|
| 281 |
+
df = pd.concat(out, ignore_index=True)
|
| 282 |
+
df = df.sort_values("charttime")
|
| 283 |
+
return df
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def take_last_k_per_var(
|
| 287 |
+
df: pd.DataFrame, itemid_to_var: Dict[int, str], k: int
|
| 288 |
+
) -> Dict[str, List[Dict[str, Any]]]:
|
| 289 |
+
out: Dict[str, List[Dict[str, Any]]] = {v: [] for v in itemid_to_var.values()}
|
| 290 |
+
if df.empty:
|
| 291 |
+
return out
|
| 292 |
+
df = df.copy()
|
| 293 |
+
df["var"] = df["itemid"].map(itemid_to_var)
|
| 294 |
+
df = df[df["var"].notna()].copy()
|
| 295 |
+
for v in out.keys():
|
| 296 |
+
sub = df[df["var"] == v].sort_values("charttime")
|
| 297 |
+
if sub.empty:
|
| 298 |
+
continue
|
| 299 |
+
sub = sub.tail(k)
|
| 300 |
+
out[v] = [
|
| 301 |
+
{"t": t.isoformat(), "v": float(val)}
|
| 302 |
+
for (t, val) in zip(sub["charttime"], sub["valuenum"])
|
| 303 |
+
]
|
| 304 |
+
return out
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def main():
|
| 308 |
+
args = parse_args()
|
| 309 |
+
random.seed(args.seed)
|
| 310 |
+
notes = load_radiology_rr_notes(args.mimic_note_dir)
|
| 311 |
+
cxr_meta = load_cxr_metadata(args.cxr_metadata_csv)
|
| 312 |
+
cxr_by_subject = {sid: df for (sid, df) in cxr_meta.groupby("subject_id")}
|
| 313 |
+
patient_map = load_patients(args.mimic_hosp_dir)
|
| 314 |
+
adm_df = load_admissions_df(args.mimic_hosp_dir)
|
| 315 |
+
admission_map, disch_map = admissions_maps(adm_df)
|
| 316 |
+
itemid_to_var = dict(FIXED_VITAL_ITEMIDS)
|
| 317 |
+
itemids = set(itemid_to_var.keys())
|
| 318 |
+
m = cxr_meta[["subject_id", "study_date"]].dropna().drop_duplicates()
|
| 319 |
+
notes = notes.merge(
|
| 320 |
+
m,
|
| 321 |
+
left_on=["subject_id", "note_date"],
|
| 322 |
+
right_on=["subject_id", "study_date"],
|
| 323 |
+
how="inner",
|
| 324 |
+
).drop(columns=["study_date"])
|
| 325 |
+
notes = notes.merge(
|
| 326 |
+
adm_df[["subject_id", "hadm_id", "dischtime"]],
|
| 327 |
+
on=["subject_id", "hadm_id"],
|
| 328 |
+
how="inner",
|
| 329 |
+
)
|
| 330 |
+
notes["dischtime"] = pd.to_datetime(notes["dischtime"], errors="coerce")
|
| 331 |
+
notes = notes[notes["dischtime"].notna()].copy()
|
| 332 |
+
notes = notes[notes["charttime"] <= notes["dischtime"]].copy()
|
| 333 |
+
notes["delta_to_discharge_hours"] = (
|
| 334 |
+
notes["dischtime"] - notes["charttime"]
|
| 335 |
+
).dt.total_seconds() / 3600.0
|
| 336 |
+
notes["label_discharge_48h"] = (
|
| 337 |
+
notes["delta_to_discharge_hours"] <= float(args.horizon_hours)
|
| 338 |
+
).astype(int)
|
| 339 |
+
pos = notes[
|
| 340 |
+
(notes["label_discharge_48h"] == 1)
|
| 341 |
+
& (notes["delta_to_discharge_hours"] <= float(args.pos_short_window_hours))
|
| 342 |
+
].copy()
|
| 343 |
+
neg = notes[notes["label_discharge_48h"] == 0].copy()
|
| 344 |
+
pos = (
|
| 345 |
+
pos.sort_values(["subject_id", "hadm_id", "delta_to_discharge_hours"])
|
| 346 |
+
.groupby(["subject_id", "hadm_id"], as_index=False)
|
| 347 |
+
.head(1)
|
| 348 |
+
)
|
| 349 |
+
neg_grouped = []
|
| 350 |
+
for (sid, hadm), g in neg.groupby(["subject_id", "hadm_id"]):
|
| 351 |
+
neg_grouped.append(g.sample(n=1, random_state=args.seed))
|
| 352 |
+
neg = pd.concat(neg_grouped, ignore_index=True) if neg_grouped else neg
|
| 353 |
+
pos_rows = pos.to_dict(orient="records")
|
| 354 |
+
neg_rows = neg.to_dict(orient="records")
|
| 355 |
+
random.shuffle(pos_rows)
|
| 356 |
+
random.shuffle(neg_rows)
|
| 357 |
+
need_pos = 100 if args.max_pos < 0 else args.max_pos
|
| 358 |
+
need_neg = 200 if args.max_neg < 0 else args.max_neg
|
| 359 |
+
pos_rows = pos.to_dict(orient="records")
|
| 360 |
+
neg_rows = neg.to_dict(orient="records")
|
| 361 |
+
random.shuffle(pos_rows)
|
| 362 |
+
random.shuffle(neg_rows)
|
| 363 |
+
candidates = [("pos", r) for r in pos_rows] + [("neg", r) for r in neg_rows]
|
| 364 |
+
random.shuffle(candidates)
|
| 365 |
+
args.n_samples = need_pos + need_neg
|
| 366 |
+
os.makedirs(os.path.dirname(args.out_jsonl) or ".", exist_ok=True)
|
| 367 |
+
os.makedirs(os.path.dirname(args.qc_csv) or ".", exist_ok=True)
|
| 368 |
+
qc_rows = []
|
| 369 |
+
written = 0
|
| 370 |
+
task_id = 0
|
| 371 |
+
pos_written = 0
|
| 372 |
+
neg_written = 0
|
| 373 |
+
with open(args.out_jsonl, "w", encoding="utf-8") as f:
|
| 374 |
+
for tag, row in candidates:
|
| 375 |
+
if pos_written >= need_pos and neg_written >= need_neg:
|
| 376 |
+
break
|
| 377 |
+
label = int(row["label_discharge_48h"])
|
| 378 |
+
if tag == "pos" and label != 1:
|
| 379 |
+
continue
|
| 380 |
+
if tag == "neg" and label != 0:
|
| 381 |
+
continue
|
| 382 |
+
if label == 1 and pos_written >= need_pos:
|
| 383 |
+
continue
|
| 384 |
+
if label == 0 and neg_written >= need_neg:
|
| 385 |
+
continue
|
| 386 |
+
sid = int(row["subject_id"])
|
| 387 |
+
hadm_id = int(row["hadm_id"])
|
| 388 |
+
anchor_time = pd.to_datetime(row["charttime"])
|
| 389 |
+
dischtime = pd.to_datetime(row["dischtime"])
|
| 390 |
+
images, image_meta = match_all_images_for_note(
|
| 391 |
+
row, cxr_by_subject, args.cxr_jpg_root
|
| 392 |
+
)
|
| 393 |
+
if not images:
|
| 394 |
+
qc_rows.append(
|
| 395 |
+
{
|
| 396 |
+
"subject_id": sid,
|
| 397 |
+
"hadm_id": hadm_id,
|
| 398 |
+
"label": label,
|
| 399 |
+
"status": "NO_IMAGE",
|
| 400 |
+
}
|
| 401 |
+
)
|
| 402 |
+
continue
|
| 403 |
+
t_start = anchor_time - pd.Timedelta(hours=args.lookback_hours)
|
| 404 |
+
t_end = anchor_time
|
| 405 |
+
df = iter_chartevents_window(
|
| 406 |
+
chartevents_root=args.chartevents_root,
|
| 407 |
+
subject_id=sid,
|
| 408 |
+
hadm_id=hadm_id,
|
| 409 |
+
itemids=itemids,
|
| 410 |
+
t_start=t_start,
|
| 411 |
+
t_end=t_end,
|
| 412 |
+
chunksize=20000000,
|
| 413 |
+
)
|
| 414 |
+
series = take_last_k_per_var(df, itemid_to_var, k=args.k_per_var)
|
| 415 |
+
per_var_n = {v: len(series[v]) for v in series}
|
| 416 |
+
if args.complete_requires_full_k:
|
| 417 |
+
n_complete = sum((1 for n in per_var_n.values() if n == args.k_per_var))
|
| 418 |
+
else:
|
| 419 |
+
n_complete = sum((1 for n in per_var_n.values() if n >= 1))
|
| 420 |
+
if n_complete < args.min_complete_vars:
|
| 421 |
+
qc_rows.append(
|
| 422 |
+
{
|
| 423 |
+
"subject_id": sid,
|
| 424 |
+
"hadm_id": hadm_id,
|
| 425 |
+
"label": label,
|
| 426 |
+
"n_complete_vars": int(n_complete),
|
| 427 |
+
"status": "TOO_FEW_COMPLETE_VARS",
|
| 428 |
+
**{f"n_{v}": int(n) for (v, n) in per_var_n.items()},
|
| 429 |
+
}
|
| 430 |
+
)
|
| 431 |
+
continue
|
| 432 |
+
sample = {
|
| 433 |
+
"task_id": f"mimicIV_{task_id}",
|
| 434 |
+
"task_type": "mimicIV",
|
| 435 |
+
"dimension": "complementary evidence",
|
| 436 |
+
"sub_dimension": "mimicIV_QA",
|
| 437 |
+
"Class": "mimic",
|
| 438 |
+
"subject_id": sid,
|
| 439 |
+
"hadm_id": hadm_id,
|
| 440 |
+
"t_anchor": anchor_time.isoformat(),
|
| 441 |
+
"label": label,
|
| 442 |
+
"horizon_hours": int(args.horizon_hours),
|
| 443 |
+
"lookback_hours": int(args.lookback_hours),
|
| 444 |
+
"k_per_var": int(args.k_per_var),
|
| 445 |
+
"time_series_recent": series,
|
| 446 |
+
"vars": list(FIXED_VITAL_ITEMIDS.values()),
|
| 447 |
+
"text": str(row["text"]),
|
| 448 |
+
"note_id": str(row.get("note_id", "")),
|
| 449 |
+
"note_seq": (
|
| 450 |
+
int(row.get("note_seq", 0))
|
| 451 |
+
if not pd.isna(row.get("note_seq", 0))
|
| 452 |
+
else 0
|
| 453 |
+
),
|
| 454 |
+
"images_path": images,
|
| 455 |
+
"image_meta": image_meta,
|
| 456 |
+
"patient_info": patient_map.get(sid, {}),
|
| 457 |
+
"admission_info": admission_map.get((sid, hadm_id), {}),
|
| 458 |
+
}
|
| 459 |
+
f.write(
|
| 460 |
+
json.dumps(json_safe(sample), ensure_ascii=False, allow_nan=False)
|
| 461 |
+
+ "\n"
|
| 462 |
+
)
|
| 463 |
+
task_id += 1
|
| 464 |
+
if label == 1:
|
| 465 |
+
pos_written += 1
|
| 466 |
+
else:
|
| 467 |
+
neg_written += 1
|
| 468 |
+
written = pos_written + neg_written
|
| 469 |
+
pd.DataFrame(qc_rows).to_csv(args.qc_csv, index=False, encoding="utf-8")
|
| 470 |
+
print(f"[DONE] wrote={written} -> {args.out_jsonl}")
|
| 471 |
+
print(f"[DONE] qc rows={len(qc_rows)} -> {args.qc_csv}")
|
| 472 |
+
if pos_written < need_pos or neg_written < need_neg:
|
| 473 |
+
raise RuntimeError(
|
| 474 |
+
f"Only wrote pos={pos_written}/{need_pos}, neg={neg_written}/{need_neg}. See QC for dominant failure reasons."
|
| 475 |
+
)
|
| 476 |
+
if written < args.n_samples:
|
| 477 |
+
raise RuntimeError(
|
| 478 |
+
f"Only wrote {written} samples. Try increasing candidate pool or relaxing pos_short_window_hours / drop_if_all_vars_empty."
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
if __name__ == "__main__":
|
| 483 |
+
main()
|
sample/image-timeseries/mimic_disch/download.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Acquire official MIMIC files with the user's own credentialed access."""
|
| 3 |
+
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
sys.dont_write_bytecode = True
|
| 8 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "processing"))
|
| 9 |
+
from download import main
|
| 10 |
+
|
| 11 |
+
if __name__ == "__main__":
|
| 12 |
+
main("mimic")
|
sample/image-timeseries/mimic_disch/generate.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Generate local discharge records from MIMIC source tables."""
|
| 3 |
+
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
sys.dont_write_bytecode = True
|
| 8 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "processing" / "common"))
|
| 9 |
+
from local_generation import main
|
| 10 |
+
|
| 11 |
+
if __name__ == "__main__":
|
| 12 |
+
main("mimic_disch")
|
sample/image-timeseries/mimic_disch/json_prompt.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Adapted from the original dataset construction script."""
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
VITAL_VARS = [
|
| 10 |
+
"heart_rate_bpm",
|
| 11 |
+
"resp_rate_insp_per_min",
|
| 12 |
+
"spo2_percent",
|
| 13 |
+
"temp_c",
|
| 14 |
+
"nbp_systolic_mmhg",
|
| 15 |
+
"nbp_diastolic_mmhg",
|
| 16 |
+
]
|
| 17 |
+
VITAL_DESC = {
|
| 18 |
+
"heart_rate_bpm": "Heart rate in beats per minute (bpm), reflecting the patient’s cardiovascular rate and overall physiologic stress.",
|
| 19 |
+
"resp_rate_insp_per_min": "Respiratory rate in breaths per minute, indicating ventilation demand and potential respiratory distress.",
|
| 20 |
+
"spo2_percent": "Peripheral oxygen saturation (SpO₂) in percent, a pulse-oximetry estimate of arterial oxygenation.",
|
| 21 |
+
"temp_c": "Body temperature in degrees Celsius (°C), used to screen for fever/hypothermia and systemic inflammatory response.",
|
| 22 |
+
"nbp_systolic_mmhg": "Non-invasive systolic blood pressure (mmHg), the peak arterial pressure during cardiac contraction related to perfusion.",
|
| 23 |
+
"nbp_diastolic_mmhg": "Non-invasive diastolic blood pressure (mmHg), the arterial pressure between beats reflecting vascular tone and baseline perfusion.",
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def determine_decimals(values: List[float], decimals: int = None) -> int:
|
| 28 |
+
"""Same rule as your reference: choose decimals based on avg abs diff."""
|
| 29 |
+
if len(values) == 0:
|
| 30 |
+
return 0
|
| 31 |
+
if len(values) > 1:
|
| 32 |
+
diffs = [abs(values[i + 1] - values[i]) for i in range(len(values) - 1)]
|
| 33 |
+
avg_diff = float(np.mean(diffs)) if diffs else 0.0
|
| 34 |
+
else:
|
| 35 |
+
avg_diff = abs(values[0]) * 0.01 if values[0] != 0 else 1.0
|
| 36 |
+
if decimals is None:
|
| 37 |
+
if avg_diff == 0:
|
| 38 |
+
decimals = 0
|
| 39 |
+
elif avg_diff >= 10:
|
| 40 |
+
decimals = 0
|
| 41 |
+
elif avg_diff >= 1:
|
| 42 |
+
decimals = 1
|
| 43 |
+
elif avg_diff >= 0.1:
|
| 44 |
+
decimals = 2
|
| 45 |
+
elif avg_diff >= 0.01:
|
| 46 |
+
decimals = 3
|
| 47 |
+
elif avg_diff >= 0.001:
|
| 48 |
+
decimals = 4
|
| 49 |
+
else:
|
| 50 |
+
decimals = 5
|
| 51 |
+
return int(decimals)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def safe_float(x) -> Optional[float]:
|
| 55 |
+
try:
|
| 56 |
+
if x is None:
|
| 57 |
+
return None
|
| 58 |
+
v = float(x)
|
| 59 |
+
if np.isnan(v) or np.isinf(v):
|
| 60 |
+
return None
|
| 61 |
+
return v
|
| 62 |
+
except Exception:
|
| 63 |
+
return None
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _val_to_str(x: Any) -> str:
|
| 67 |
+
return "" if x is None else str(x)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _fmt_img_time(meta: Dict[str, Any]) -> str:
|
| 71 |
+
"""
|
| 72 |
+
MIMIC-CXR-JPG metadata:
|
| 73 |
+
- StudyDate: anonymized date; per-patient ordering and time intervals are preserved
|
| 74 |
+
- StudyTime: time-of-day; not modified during de-identification
|
| 75 |
+
"""
|
| 76 |
+
sd = meta.get("StudyDate")
|
| 77 |
+
st = meta.get("StudyTime")
|
| 78 |
+
vp = meta.get("ViewPosition")
|
| 79 |
+
study_id = meta.get("study_id")
|
| 80 |
+
dicom_id = meta.get("dicom_id")
|
| 81 |
+
sd_s = str(sd) if sd is not None and str(sd).strip() != "" else "UNKNOWN_DATE"
|
| 82 |
+
st_s = str(st) if st is not None and str(st).strip() != "" else "UNKNOWN_TIME"
|
| 83 |
+
vp_s = str(vp) if vp is not None and str(vp).strip() != "" else "UNKNOWN_VIEW"
|
| 84 |
+
extras = []
|
| 85 |
+
if study_id is not None:
|
| 86 |
+
extras.append(f"study_id={study_id}")
|
| 87 |
+
if dicom_id is not None:
|
| 88 |
+
extras.append(f"dicom_id={dicom_id}")
|
| 89 |
+
extras.append(f"view={vp_s}")
|
| 90 |
+
return f"{sd_s} {st_s} ({', '.join(extras)})"
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def align_and_round_vitals(
|
| 94 |
+
vitals_raw: Dict[str, Any],
|
| 95 |
+
) -> Tuple[Dict[str, Any], Dict[str, int]]:
|
| 96 |
+
if isinstance(vitals_raw, dict) and "timestamps" in vitals_raw:
|
| 97 |
+
rounding = vitals_raw.get("vitals_rounding", {})
|
| 98 |
+
return (vitals_raw, rounding if isinstance(rounding, dict) else {})
|
| 99 |
+
var_points: Dict[str, List[Tuple[str, float]]] = {v: [] for v in VITAL_VARS}
|
| 100 |
+
if isinstance(vitals_raw, dict):
|
| 101 |
+
for var in VITAL_VARS:
|
| 102 |
+
seq = vitals_raw.get(var, [])
|
| 103 |
+
if not isinstance(seq, list):
|
| 104 |
+
continue
|
| 105 |
+
for p in seq:
|
| 106 |
+
if not isinstance(p, dict):
|
| 107 |
+
continue
|
| 108 |
+
t = p.get("t")
|
| 109 |
+
v = safe_float(p.get("v"))
|
| 110 |
+
if isinstance(t, str) and t and (v is not None):
|
| 111 |
+
var_points[var].append((t, v))
|
| 112 |
+
vitals_rounding: Dict[str, int] = {}
|
| 113 |
+
var_maps: Dict[str, Dict[str, float]] = {}
|
| 114 |
+
for var in VITAL_VARS:
|
| 115 |
+
pts = sorted(var_points[var], key=lambda x: x[0])
|
| 116 |
+
values = [v for (_, v) in pts]
|
| 117 |
+
dec = determine_decimals(values)
|
| 118 |
+
vitals_rounding[var] = dec
|
| 119 |
+
m: Dict[str, float] = {}
|
| 120 |
+
for t, v in pts:
|
| 121 |
+
m[t] = round(v, dec)
|
| 122 |
+
var_maps[var] = m
|
| 123 |
+
all_ts = set()
|
| 124 |
+
for var in VITAL_VARS:
|
| 125 |
+
all_ts.update(var_maps[var].keys())
|
| 126 |
+
timestamps = sorted(all_ts)
|
| 127 |
+
vitals_aligned: Dict[str, Any] = {"timestamps": timestamps}
|
| 128 |
+
for var in VITAL_VARS:
|
| 129 |
+
m = var_maps[var]
|
| 130 |
+
vitals_aligned[var] = [m.get(t, None) for t in timestamps]
|
| 131 |
+
return (vitals_aligned, vitals_rounding)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def pick_anchor_time(sample: Dict[str, Any]) -> str:
|
| 135 |
+
v = sample.get("t_anchor")
|
| 136 |
+
if isinstance(v, str) and v.strip():
|
| 137 |
+
return v.strip()
|
| 138 |
+
return ""
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def normalize_rr_notes(sample: Dict[str, Any]) -> List[Dict[str, Any]]:
|
| 142 |
+
"""
|
| 143 |
+
Return a list of RR-note-like dicts, each with at least:
|
| 144 |
+
- charttime (string, may be empty)
|
| 145 |
+
- text (string)
|
| 146 |
+
- note_id (optional)
|
| 147 |
+
- note_seq (optional)
|
| 148 |
+
|
| 149 |
+
Supports:
|
| 150 |
+
A) death-style: notes_rr_in_window / notes_rr / notes (list of dicts)
|
| 151 |
+
B) discharge-style: flat fields: text + note_id/note_seq (+ optional charttime)
|
| 152 |
+
"""
|
| 153 |
+
for k in ["notes_rr_in_window", "notes_rr", "notes"]:
|
| 154 |
+
v = sample.get(k)
|
| 155 |
+
if isinstance(v, list) and v:
|
| 156 |
+
out = []
|
| 157 |
+
for it in v:
|
| 158 |
+
if not isinstance(it, dict):
|
| 159 |
+
continue
|
| 160 |
+
out.append(
|
| 161 |
+
{
|
| 162 |
+
"charttime": str(it.get("charttime", "") or ""),
|
| 163 |
+
"text": str(it.get("text", "") or ""),
|
| 164 |
+
"note_id": it.get("note_id"),
|
| 165 |
+
"note_seq": it.get("note_seq"),
|
| 166 |
+
}
|
| 167 |
+
)
|
| 168 |
+
out = [x for x in out if x["text"].strip() != ""]
|
| 169 |
+
return out
|
| 170 |
+
txt = sample.get("text")
|
| 171 |
+
if isinstance(txt, str) and txt.strip():
|
| 172 |
+
ct = (
|
| 173 |
+
sample.get("note_charttime")
|
| 174 |
+
or sample.get("charttime")
|
| 175 |
+
or sample.get("t_note")
|
| 176 |
+
or sample.get("t_anchor")
|
| 177 |
+
or ""
|
| 178 |
+
)
|
| 179 |
+
return [
|
| 180 |
+
{
|
| 181 |
+
"charttime": str(ct or ""),
|
| 182 |
+
"text": txt,
|
| 183 |
+
"note_id": sample.get("note_id"),
|
| 184 |
+
"note_seq": sample.get("note_seq"),
|
| 185 |
+
}
|
| 186 |
+
]
|
| 187 |
+
return []
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def build_prompt_discharge(
|
| 191 |
+
sample: Dict[str, Any],
|
| 192 |
+
horizon_hours_default: int = 48,
|
| 193 |
+
lookback_hours_default: int = 48,
|
| 194 |
+
) -> str:
|
| 195 |
+
images: List[str] = sample.get("images_path", sample.get("image_path", sample.get("images", []))) or []
|
| 196 |
+
image_meta: List[Dict[str, Any]] = sample.get("image_meta", []) or []
|
| 197 |
+
notes = normalize_rr_notes(sample)
|
| 198 |
+
vit_raw = (
|
| 199 |
+
sample.get("time_series_recent")
|
| 200 |
+
or sample.get("vitals_lookback")
|
| 201 |
+
or sample.get("vitals_in_window")
|
| 202 |
+
or {}
|
| 203 |
+
)
|
| 204 |
+
vit_aligned = sample.get("vitals_aligned", None)
|
| 205 |
+
if not isinstance(vit_aligned, dict) or "timestamps" not in vit_aligned:
|
| 206 |
+
vit_aligned, _ = align_and_round_vitals(vit_raw)
|
| 207 |
+
timestamps: List[str] = vit_aligned.get("timestamps", []) or []
|
| 208 |
+
arrays = {v: vit_aligned.get(v, []) or [] for v in VITAL_VARS}
|
| 209 |
+
horizon = sample.get("horizon_hours", horizon_hours_default)
|
| 210 |
+
lookback = sample.get("lookback_hours", lookback_hours_default)
|
| 211 |
+
try:
|
| 212 |
+
horizon = int(horizon)
|
| 213 |
+
except Exception:
|
| 214 |
+
horizon = horizon_hours_default
|
| 215 |
+
try:
|
| 216 |
+
lookback = int(lookback)
|
| 217 |
+
except Exception:
|
| 218 |
+
lookback = lookback_hours_default
|
| 219 |
+
anchor_time = pick_anchor_time(sample)
|
| 220 |
+
img_path_block = "\n".join([f"<image>{p}</image>" for p in images]).strip()
|
| 221 |
+
img_info_lines = []
|
| 222 |
+
for i, p in enumerate(images):
|
| 223 |
+
meta = (
|
| 224 |
+
image_meta[i]
|
| 225 |
+
if i < len(image_meta) and isinstance(image_meta[i], dict)
|
| 226 |
+
else {}
|
| 227 |
+
)
|
| 228 |
+
img_info_lines.append(f"- Image {i + 1}: {p}")
|
| 229 |
+
img_info_lines.append(
|
| 230 |
+
f" Acquisition time (from metadata): {_fmt_img_time(meta)}"
|
| 231 |
+
)
|
| 232 |
+
img_info_block = "\n".join(img_info_lines).strip()
|
| 233 |
+
report_lines = []
|
| 234 |
+
for i, n in enumerate(notes):
|
| 235 |
+
if not isinstance(n, dict):
|
| 236 |
+
continue
|
| 237 |
+
ct = n.get("charttime", "")
|
| 238 |
+
txt = n.get("text", "")
|
| 239 |
+
report_lines.append(f"[RR Note {i + 1} | charttime={ct}]\n{txt}".strip())
|
| 240 |
+
report_block = "\n\n".join(report_lines).strip()
|
| 241 |
+
var_block = "\n".join([f"- {v}: {VITAL_DESC.get(v, v)}" for v in VITAL_VARS])
|
| 242 |
+
ts_lines = []
|
| 243 |
+
for idx, t in enumerate(timestamps):
|
| 244 |
+
parts = []
|
| 245 |
+
for v in VITAL_VARS:
|
| 246 |
+
val = arrays[v][idx] if idx < len(arrays[v]) else None
|
| 247 |
+
parts.append(f"{v}={_val_to_str(val)}")
|
| 248 |
+
ts_lines.append(f"{t}: " + ", ".join(parts))
|
| 249 |
+
timeseries_block = "\n".join(ts_lines).strip()
|
| 250 |
+
question = f"Question: Using the chest X-ray image(s), radiology report(s), and the vital signs observed in the {lookback}-hour lookback window ending at the anchor time, will the patient be discharged within the next {horizon} hours after the anchor time?"
|
| 251 |
+
options = "Answer (choose one option):\nA. Yes.\nB. No.\n\nReturn only the option letter (A or B)."
|
| 252 |
+
anchor_line = (
|
| 253 |
+
f"Anchor time: {anchor_time}" if anchor_time else "Anchor time: (not provided)"
|
| 254 |
+
)
|
| 255 |
+
prompt = f"\nYou are given a question-answering (QA) task.\n\nUse the chest X-ray image(s), radiology report(s), and vital signs as evidence to answer the multiple-choice question.\nDo NOT output any analysis. Return only the option letter.\n\n<image>\nMIMIC-CXR-JPG images: Each image is a JPG converted from an original DICOM chest X-ray.\nMetadata includes StudyDate (an anonymized date; per-patient ordering and time intervals are preserved) and StudyTime (time-of-day; not modified during de-identification).\nBelow are the image paths and acquisition times from metadata:\n{img_info_block}\n</image>\n\n<context>\n{anchor_line}\nVital signs are provided as an aligned time series covering the lookback window ending at the anchor time.\n</context>\n\n<report>\nRadiology report(s) (RR notes) associated with the imaging evidence:\n{report_block}\n</report>\n\n<variables>\nVital sign variables:\n{var_block}\n</variables>\n\n<timeseries>\nAligned time series (each line is one timestamp; missing values are empty):\n{timeseries_block}\n</timeseries>\n\n{question}\n{options}\n"
|
| 256 |
+
return "\n".join([ln.rstrip() for ln in prompt.splitlines()]).strip()
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def parse_args():
|
| 260 |
+
ap = argparse.ArgumentParser()
|
| 261 |
+
ap.add_argument("--in_jsonl", "--in-jsonl", required=True)
|
| 262 |
+
ap.add_argument("--out_jsonl", "--out-jsonl", required=True)
|
| 263 |
+
ap.add_argument("--start_id", "--start-id", type=int, default=0)
|
| 264 |
+
ap.add_argument("--task_id_prefix", "--task-id-prefix", default="MIMIC_discharge")
|
| 265 |
+
ap.add_argument("--sub2_dimension", "--sub2-dimension", default="discharge")
|
| 266 |
+
ap.add_argument(
|
| 267 |
+
"--default_horizon_hours", "--default-horizon-hours", type=int, default=48
|
| 268 |
+
)
|
| 269 |
+
ap.add_argument(
|
| 270 |
+
"--default_lookback_hours", "--default-lookback-hours", type=int, default=48
|
| 271 |
+
)
|
| 272 |
+
ap.add_argument(
|
| 273 |
+
"--drop_old_vitals_fields", "--drop-old-vitals-fields", action="store_true"
|
| 274 |
+
)
|
| 275 |
+
return ap.parse_args()
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def main():
|
| 279 |
+
args = parse_args()
|
| 280 |
+
task_id = int(args.start_id)
|
| 281 |
+
n_in = 0
|
| 282 |
+
n_out = 0
|
| 283 |
+
with open(args.in_jsonl, "r", encoding="utf-8") as fin, open(
|
| 284 |
+
args.out_jsonl, "w", encoding="utf-8"
|
| 285 |
+
) as fout:
|
| 286 |
+
for line in fin:
|
| 287 |
+
line = line.strip()
|
| 288 |
+
if not line:
|
| 289 |
+
continue
|
| 290 |
+
n_in += 1
|
| 291 |
+
obj = json.loads(line)
|
| 292 |
+
obj["image_path"] = obj.get("images_path", obj.get("image_path", []))
|
| 293 |
+
vit_raw = (
|
| 294 |
+
obj.get("time_series_recent")
|
| 295 |
+
or obj.get("vitals_lookback")
|
| 296 |
+
or obj.get("vitals_in_window")
|
| 297 |
+
or {}
|
| 298 |
+
)
|
| 299 |
+
vit_aligned, vit_rounding = align_and_round_vitals(vit_raw)
|
| 300 |
+
obj["vitals_aligned"] = vit_aligned
|
| 301 |
+
obj["vitals_rounding"] = vit_rounding
|
| 302 |
+
if args.drop_old_vitals_fields:
|
| 303 |
+
obj.pop("vitals_lookback", None)
|
| 304 |
+
obj.pop("vitals_in_window", None)
|
| 305 |
+
obj["task_id"] = f"MIMIC_disch{task_id}"
|
| 306 |
+
obj["task_type"] = "mimic_task"
|
| 307 |
+
obj["dimension"] = "complementary evidence"
|
| 308 |
+
obj["sub_dimension"] = "mimicIV_QA"
|
| 309 |
+
obj["sub2_dimension"] = "disch"
|
| 310 |
+
obj["evaluation_type"] = "QA"
|
| 311 |
+
obj["prompt"] = build_prompt_discharge(
|
| 312 |
+
obj,
|
| 313 |
+
horizon_hours_default=args.default_horizon_hours,
|
| 314 |
+
lookback_hours_default=args.default_lookback_hours,
|
| 315 |
+
)
|
| 316 |
+
obj["question"] = (
|
| 317 |
+
f"Question: Using the chest X-ray image(s), radiology report(s), and the vital signs observed in the 48-hour lookback window ending at the anchor time, will the patient be discharged within the next 48 hours after the anchor time?"
|
| 318 |
+
)
|
| 319 |
+
if obj["label"] == 1:
|
| 320 |
+
obj["ground_truth"] = "A"
|
| 321 |
+
else:
|
| 322 |
+
obj["ground_truth"] = "B"
|
| 323 |
+
fout.write(json.dumps(obj, ensure_ascii=False, allow_nan=False) + "\n")
|
| 324 |
+
task_id += 1
|
| 325 |
+
n_out += 1
|
| 326 |
+
print(f"[DONE] in={n_in}, out={n_out}")
|
| 327 |
+
print(f"[DONE] wrote -> {args.out_jsonl}")
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
if __name__ == "__main__":
|
| 331 |
+
main()
|
sample/image-timeseries/pixelrec/README.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PixelRec
|
| 2 |
+
|
| 3 |
+
**Processing code only:** source data and generated task records are not
|
| 4 |
+
included. Obtain the sources from the upstream project and follow its terms.
|
| 5 |
+
See the [shared setup instructions](../../../processing/README.md).
|
| 6 |
+
Run the commands below from the directory containing `MMTA-v1.0/`, keeping
|
| 7 |
+
`local_sources/` and `local_work/` outside the release folder.
|
| 8 |
+
|
| 9 |
+
Download the interactions, item metadata and covers from the Google Drive links in the [PixelRec repository](https://github.com/westlake-repl/PixelRec), then unpack the archives.
|
| 10 |
+
|
| 11 |
+
```bash
|
| 12 |
+
python -B MMTA-v1.0/sample/image-timeseries/pixelrec/download.py --output local_sources/pixelrec --component interactions --component item-info --component covers --accept-terms
|
| 13 |
+
python -B MMTA-v1.0/sample/image-timeseries/pixelrec/generate.py \
|
| 14 |
+
--interactions local_sources/pixelrec/Pixel200K.csv \
|
| 15 |
+
--item-info local_sources/pixelrec/item_info.csv \
|
| 16 |
+
--image-root local_sources/pixelrec/image/cover \
|
| 17 |
+
--output-dir local_work/pixelrec_build
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
Build: daily interaction counts -> longest consecutive history -> six-day forecasts -> cover-image/CSV conversion.
|
| 21 |
+
|
| 22 |
+
Output: `--output-dir/pixelrec/pixelrec.omnits.jsonl`, plus media and history CSVs. Paths are relative to that output domain directory.
|
sample/image-timeseries/pixelrec/download.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Download pixelrec from its official source for local processing."""
|
| 3 |
+
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "processing"))
|
| 8 |
+
from download import main
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
if __name__ == "__main__":
|
| 12 |
+
main("pixelrec")
|
sample/image-timeseries/pixelrec/generate.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Generate local PixelRec daily forecasts and unified image/time-series records."""
|
| 3 |
+
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
sys.dont_write_bytecode = True
|
| 8 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "processing" / "common"))
|
| 9 |
+
from local_generation import main
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
if __name__ == "__main__":
|
| 13 |
+
main("pixelrec")
|
sample/image-timeseries/pixelrec/prepare.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Build daily PixelRec forecasting tasks from personally obtained source data.
|
| 3 |
+
|
| 4 |
+
Adapted from PixelRec/build_day.py. This script does not grant permission to
|
| 5 |
+
redistribute its inputs or outputs. Data acquisition terms remain applicable.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import pandas as pd
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def longest_segment(days: list, counts: list[int]) -> tuple[list, list[int]]:
|
| 18 |
+
best_start, best_length, start = 0, 0, 0
|
| 19 |
+
for index in range(1, len(days) + 1):
|
| 20 |
+
if index == len(days) or (days[index] - days[index - 1]).days != 1:
|
| 21 |
+
if index - start > best_length:
|
| 22 |
+
best_start, best_length = start, index - start
|
| 23 |
+
start = index
|
| 24 |
+
return days[best_start:best_start + best_length], counts[best_start:best_start + best_length]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def safe_text(value: object) -> str:
|
| 28 |
+
return "" if pd.isna(value) else str(value).strip()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def main() -> None:
|
| 32 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 33 |
+
parser.add_argument("--interactions", type=Path, required=True, help="Interaction CSV with item_id and Unix-second timestamp.")
|
| 34 |
+
parser.add_argument("--item-info", type=Path, required=True, help="Item metadata CSV with item_id, title, tag and description.")
|
| 35 |
+
parser.add_argument("--image-root", type=Path, required=True, help="Directory containing item cover JPGs.")
|
| 36 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 37 |
+
parser.add_argument("--min-segment-length", type=int, default=20)
|
| 38 |
+
parser.add_argument("--max-segment-length", type=int, default=200)
|
| 39 |
+
parser.add_argument("--horizon", type=int, default=6)
|
| 40 |
+
parser.add_argument("--limit", type=int, default=200, help="Maximum tasks; 0 means all eligible items.")
|
| 41 |
+
args = parser.parse_args()
|
| 42 |
+
if args.horizon < 1 or args.min_segment_length <= args.horizon or args.max_segment_length < args.min_segment_length or args.limit < 0:
|
| 43 |
+
parser.error("Invalid segment length, horizon or limit")
|
| 44 |
+
data = pd.read_csv(args.interactions, dtype={"item_id": str, "user_id": str})
|
| 45 |
+
data["day"] = pd.to_datetime(data["timestamp"], unit="s", utc=True).dt.floor("D").dt.date
|
| 46 |
+
daily = data.groupby(["item_id", "day"]).size().reset_index(name="count").sort_values(["item_id", "day"])
|
| 47 |
+
metadata = pd.read_csv(args.item_info, dtype={"item_id": str}).drop_duplicates("item_id").set_index("item_id")
|
| 48 |
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
| 49 |
+
written = 0
|
| 50 |
+
with args.output.open("w", encoding="utf-8") as handle:
|
| 51 |
+
for item_id, group in daily.groupby("item_id", sort=False):
|
| 52 |
+
days, counts = longest_segment(group["day"].tolist(), group["count"].tolist())
|
| 53 |
+
if len(days) < args.min_segment_length:
|
| 54 |
+
continue
|
| 55 |
+
days, counts = days[-args.max_segment_length:], counts[-args.max_segment_length:]
|
| 56 |
+
image = args.image_root / f"{item_id}.jpg"
|
| 57 |
+
if not image.is_file():
|
| 58 |
+
raise FileNotFoundError(f"Missing cover image for {item_id}: {image}")
|
| 59 |
+
history_days = [day.strftime("%Y-%m-%d") for day in days[:-args.horizon]]
|
| 60 |
+
future_days = [day.strftime("%Y-%m-%d") for day in days[-args.horizon:]]
|
| 61 |
+
history_values, targets = counts[:-args.horizon], counts[-args.horizon:]
|
| 62 |
+
item = metadata.loc[item_id].to_dict() if item_id in metadata.index else {}
|
| 63 |
+
context = "\n".join(f"{key}: {safe_text(item.get(key, ''))}" for key in ("title", "tag", "description"))
|
| 64 |
+
history = "\n".join(f"({timestamp}, {value})" for timestamp, value in zip(history_days, history_values))
|
| 65 |
+
prompt = (
|
| 66 |
+
"I have a time series forecasting task for you.\n\n"
|
| 67 |
+
"Here is some context about the item (title/tag/description). Also note the image above is the item's cover.\n"
|
| 68 |
+
f"<context>\n{context}\n</context>\n\n"
|
| 69 |
+
"Here is a historical time series. Timestamps are daily; values are daily interaction counts.\n"
|
| 70 |
+
f"<history>\n{history}\n</history>\n\n"
|
| 71 |
+
f"Now please predict the value at the following timestamps: {future_days}.\n\n"
|
| 72 |
+
"Return the forecast in (timestamp, value) format in between <forecast> and </forecast> tags.\n"
|
| 73 |
+
"Do not include any other information (e.g., comments) in the forecast.\n"
|
| 74 |
+
)
|
| 75 |
+
record = {"task_id": f"Pixelrec_{written}", "item_id": item_id, "image_path": str(image.resolve()),
|
| 76 |
+
"hist_timestamp": history_days, "hist_interaction_count": history_values,
|
| 77 |
+
"ground_truth": targets, "meta_info": {"future_timestamps": future_days},
|
| 78 |
+
"evaluation_type": "prediction", "task": "prediction", "prompt": prompt}
|
| 79 |
+
handle.write(json.dumps(record, ensure_ascii=False, allow_nan=False) + "\n")
|
| 80 |
+
written += 1
|
| 81 |
+
if args.limit and written >= args.limit:
|
| 82 |
+
break
|
| 83 |
+
if not written:
|
| 84 |
+
raise SystemExit("No eligible tasks were produced")
|
| 85 |
+
print(json.dumps({"records": written, "output": str(args.output)}))
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
if __name__ == "__main__":
|
| 89 |
+
main()
|
sample/image-timeseries/sp500/README.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SP500 / FinMultiTime
|
| 2 |
+
|
| 3 |
+
**Processing code only:** source data and generated task records are not
|
| 4 |
+
included. Obtain the sources from the upstream project and follow its terms.
|
| 5 |
+
See the [shared setup instructions](../../../processing/README.md).
|
| 6 |
+
Run the commands below from the directory containing `MMTA-v1.0/`, keeping
|
| 7 |
+
`local_sources/` and `local_work/` outside the release folder.
|
| 8 |
+
|
| 9 |
+
Download [FinMultiTime](https://huggingface.co/datasets/Wenyan0110/Multimodal-Dataset-Image_Text_Table_TimeSeries-for-Financial-Time-Series-Forecasting) using download.py and unpack the price, news and chart files.
|
| 10 |
+
|
| 11 |
+
```bash
|
| 12 |
+
python -B MMTA-v1.0/sample/image-timeseries/sp500/download.py --output local_sources/finmultitime --accept-terms
|
| 13 |
+
python -B MMTA-v1.0/sample/image-timeseries/sp500/generate.py \
|
| 14 |
+
--time-series-dir local_sources/finmultitime/SP500_time_series \
|
| 15 |
+
--news-dir local_sources/finmultitime/sp500_news \
|
| 16 |
+
--image-root local_sources/finmultitime/image/image \
|
| 17 |
+
--output-dir local_work/sp500_build --limit 200
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
Build: 2024 H1 price history and charts -> next 12 closing-price targets -> three latest eligible articles -> image/CSV conversion. News must be strictly before midnight on the first forecast date in America/New_York; invalid or missing dates are excluded.
|
| 21 |
+
|
| 22 |
+
Output: `--output-dir/sp500/sp500.omnits.jsonl`, plus media and history CSVs. Paths are relative to that output domain directory.
|
sample/image-timeseries/sp500/download.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Download sp500 from its official source for local processing."""
|
| 3 |
+
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "processing"))
|
| 8 |
+
from download import main
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
if __name__ == "__main__":
|
| 12 |
+
main("sp500")
|
sample/image-timeseries/sp500/generate.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Generate local SP500 forecasts with strictly pre-horizon news."""
|
| 3 |
+
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
sys.dont_write_bytecode = True
|
| 8 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "processing" / "common"))
|
| 9 |
+
from local_generation import main
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
if __name__ == "__main__":
|
| 13 |
+
main("sp500")
|
sample/image-timeseries/sp500/prepare.py
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Build SP500 forecasting tasks with strictly pre-horizon news.
|
| 3 |
+
|
| 4 |
+
Adapted from the local build_jsonl_forcast_withoutpng.py. Price histories
|
| 5 |
+
retain the first-half-2024 window. News is filtered by its source Date and
|
| 6 |
+
sorted before selecting the latest three eligible articles.
|
| 7 |
+
"""
|
| 8 |
+
import os
|
| 9 |
+
import json
|
| 10 |
+
import glob
|
| 11 |
+
import argparse
|
| 12 |
+
import re
|
| 13 |
+
from zoneinfo import ZoneInfo
|
| 14 |
+
import pandas as pd
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
DATE_START = "2024-01-01"
|
| 18 |
+
DATE_END = "2024-06-30"
|
| 19 |
+
FUT_LEN = 12
|
| 20 |
+
HIST_TIME_STR = "2024.1.1-2024.6.30"
|
| 21 |
+
|
| 22 |
+
CLASS_NAME = "S&P500"
|
| 23 |
+
NEWS_TIMEZONE = "America/New_York"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def to_day_str_from_any_datetime(x) -> str | None:
|
| 27 |
+
if x is None:
|
| 28 |
+
return None
|
| 29 |
+
s = str(x).strip()
|
| 30 |
+
if not s:
|
| 31 |
+
return None
|
| 32 |
+
|
| 33 |
+
dt = pd.to_datetime(s, errors="coerce", utc=True)
|
| 34 |
+
if pd.isna(dt):
|
| 35 |
+
return None
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
dt = dt.tz_convert("Asia/Shanghai")
|
| 39 |
+
except Exception:
|
| 40 |
+
pass
|
| 41 |
+
|
| 42 |
+
return dt.strftime("%Y-%m-%d")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def find_sp500_image_by_convention(image_root: str, label_lower: str) -> str | None:
|
| 46 |
+
"""
|
| 47 |
+
SP500_image/S&P500_image_a/aa/aa_2024_H1_candlestick.png
|
| 48 |
+
"""
|
| 49 |
+
if not label_lower:
|
| 50 |
+
return None
|
| 51 |
+
bucket = label_lower[0].lower()
|
| 52 |
+
base_dir = os.path.join(image_root, f"S&P500_image_{bucket}", label_lower)
|
| 53 |
+
|
| 54 |
+
exts = ["png", "jpg", "jpeg", "webp", "bmp"]
|
| 55 |
+
candidates = []
|
| 56 |
+
for ext in exts:
|
| 57 |
+
p = os.path.join(base_dir, f"{label_lower}_2024_H1_candlestick.{ext}")
|
| 58 |
+
if os.path.isfile(p):
|
| 59 |
+
candidates.append(p)
|
| 60 |
+
candidates.sort()
|
| 61 |
+
return candidates[0] if candidates else None
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def find_sp500_news_by_convention(news_dir: str, label_upper: str) -> str | None:
|
| 65 |
+
"""
|
| 66 |
+
sp500_news/AA.jsonl
|
| 67 |
+
"""
|
| 68 |
+
p = os.path.join(news_dir, f"{label_upper}.jsonl")
|
| 69 |
+
return p if os.path.isfile(p) else None
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def parse_news_timestamp(value: object, timezone: str) -> pd.Timestamp | None:
|
| 73 |
+
"""Parse an ISO source date; undated and ambiguous records are ineligible."""
|
| 74 |
+
if not isinstance(value, str):
|
| 75 |
+
return None
|
| 76 |
+
value = value.strip()
|
| 77 |
+
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}(?:[T ].+)?", value):
|
| 78 |
+
return None
|
| 79 |
+
try:
|
| 80 |
+
timestamp = pd.Timestamp(value)
|
| 81 |
+
if pd.isna(timestamp):
|
| 82 |
+
return None
|
| 83 |
+
if timestamp.tzinfo is None:
|
| 84 |
+
timestamp = timestamp.tz_localize(timezone, ambiguous="NaT", nonexistent="NaT")
|
| 85 |
+
if pd.isna(timestamp):
|
| 86 |
+
return None
|
| 87 |
+
return timestamp.tz_convert("UTC")
|
| 88 |
+
except (ValueError, TypeError, OverflowError):
|
| 89 |
+
return None
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def load_pre_horizon_news(
|
| 93 |
+
news_file: str,
|
| 94 |
+
*,
|
| 95 |
+
forecast_start: str,
|
| 96 |
+
k: int = 3,
|
| 97 |
+
timezone: str = NEWS_TIMEZONE,
|
| 98 |
+
) -> list[dict[str, str]]:
|
| 99 |
+
"""Select the latest k articles strictly before the first forecast day.
|
| 100 |
+
|
| 101 |
+
The cutoff is midnight at the start of that day in the source timezone.
|
| 102 |
+
Date-only and naive timestamps use that timezone; aware timestamps retain
|
| 103 |
+
their actual instant. Missing or invalid dates never enter the prompt.
|
| 104 |
+
"""
|
| 105 |
+
ZoneInfo(timezone)
|
| 106 |
+
if k < 1:
|
| 107 |
+
raise ValueError("k must be positive")
|
| 108 |
+
if not isinstance(forecast_start, str) or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", forecast_start):
|
| 109 |
+
raise ValueError("forecast_start must be an ISO calendar date")
|
| 110 |
+
cutoff = parse_news_timestamp(forecast_start, timezone)
|
| 111 |
+
if cutoff is None:
|
| 112 |
+
raise ValueError("Invalid forecast_start")
|
| 113 |
+
if not news_file or not os.path.isfile(news_file):
|
| 114 |
+
return []
|
| 115 |
+
|
| 116 |
+
eligible = []
|
| 117 |
+
with open(news_file, "r", encoding="utf-8") as f:
|
| 118 |
+
for line_no, line in enumerate(f, 1):
|
| 119 |
+
line = line.strip()
|
| 120 |
+
if not line:
|
| 121 |
+
continue
|
| 122 |
+
try:
|
| 123 |
+
obj = json.loads(line)
|
| 124 |
+
except json.JSONDecodeError:
|
| 125 |
+
continue
|
| 126 |
+
if not isinstance(obj, dict):
|
| 127 |
+
continue
|
| 128 |
+
published_at = parse_news_timestamp(obj.get("Date"), timezone)
|
| 129 |
+
if published_at is None or published_at >= cutoff:
|
| 130 |
+
continue
|
| 131 |
+
s = obj.get("Article", None)
|
| 132 |
+
if not isinstance(s, str):
|
| 133 |
+
continue
|
| 134 |
+
s = s.strip()
|
| 135 |
+
if not s:
|
| 136 |
+
continue
|
| 137 |
+
eligible.append((published_at, line_no, {
|
| 138 |
+
"date": obj["Date"].strip(),
|
| 139 |
+
"published_at": published_at.isoformat(),
|
| 140 |
+
"article": s,
|
| 141 |
+
"url": str(obj.get("Url") or ""),
|
| 142 |
+
}))
|
| 143 |
+
|
| 144 |
+
eligible.sort(key=lambda item: (item[0], item[1]))
|
| 145 |
+
return [item[2] for item in eligible[-k:]]
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def load_last_k_news_summaries(
|
| 149 |
+
news_file: str,
|
| 150 |
+
*,
|
| 151 |
+
forecast_start: str,
|
| 152 |
+
k: int = 3,
|
| 153 |
+
timezone: str = NEWS_TIMEZONE,
|
| 154 |
+
) -> list[str]:
|
| 155 |
+
"""Return article text using the same mandatory pre-horizon cutoff."""
|
| 156 |
+
return [item["article"] for item in load_pre_horizon_news(
|
| 157 |
+
news_file, forecast_start=forecast_start, k=k, timezone=timezone,
|
| 158 |
+
)]
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def choose_decimals_by_avg_diff(values: list[float]) -> int:
|
| 162 |
+
if len(values) == 0:
|
| 163 |
+
return 0
|
| 164 |
+
if len(values) > 1:
|
| 165 |
+
diffs = [abs(values[i + 1] - values[i]) for i in range(len(values) - 1)]
|
| 166 |
+
avg_diff = float(np.mean(diffs)) if diffs else 0.0
|
| 167 |
+
else:
|
| 168 |
+
avg_diff = abs(values[0]) * 0.01 if values[0] != 0 else 1.0
|
| 169 |
+
|
| 170 |
+
if avg_diff == 0:
|
| 171 |
+
return 0
|
| 172 |
+
if avg_diff >= 10:
|
| 173 |
+
return 0
|
| 174 |
+
if avg_diff >= 1:
|
| 175 |
+
return 1
|
| 176 |
+
if avg_diff >= 0.1:
|
| 177 |
+
return 2
|
| 178 |
+
if avg_diff >= 0.01:
|
| 179 |
+
return 3
|
| 180 |
+
if avg_diff >= 0.001:
|
| 181 |
+
return 4
|
| 182 |
+
return 5
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def format_history_pairs(timestamps: list[str], values: list[float], max_display: int = None) -> str:
|
| 186 |
+
"""Format timestamp/value pairs, with optional display truncation."""
|
| 187 |
+
dec = choose_decimals_by_avg_diff(values)
|
| 188 |
+
|
| 189 |
+
def fmt(v: float) -> str:
|
| 190 |
+
return f"{float(v):.{dec}f}"
|
| 191 |
+
|
| 192 |
+
pairs = [f"({ts}, {fmt(v)})" for ts, v in zip(timestamps, values)]
|
| 193 |
+
|
| 194 |
+
if max_display is None or len(pairs) <= max_display:
|
| 195 |
+
return "\n".join(pairs)
|
| 196 |
+
|
| 197 |
+
first_n = max_display // 2
|
| 198 |
+
last_n = max_display - first_n
|
| 199 |
+
return "\n".join(pairs[:first_n] + ["..."] + pairs[-last_n:])
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def build_prompt_sp500(
|
| 203 |
+
image_abs_path: str,
|
| 204 |
+
label_upper: str,
|
| 205 |
+
history_str: str,
|
| 206 |
+
pred_time: list[str],
|
| 207 |
+
last3_texts: list[str],
|
| 208 |
+
) -> str:
|
| 209 |
+
|
| 210 |
+
context_lines = []
|
| 211 |
+
if last3_texts:
|
| 212 |
+
context_lines.append("Recent news summaries (most recent last):")
|
| 213 |
+
for i, t in enumerate(last3_texts, 1):
|
| 214 |
+
context_lines.append(f"{i}. {t}")
|
| 215 |
+
else:
|
| 216 |
+
context_lines.append("Recent news summaries: (none)")
|
| 217 |
+
|
| 218 |
+
context = "\n".join(context_lines)
|
| 219 |
+
pred_time_str = ", ".join(pred_time)
|
| 220 |
+
|
| 221 |
+
prompt = f"""
|
| 222 |
+
I have a time series forecasting task for you.
|
| 223 |
+
|
| 224 |
+
Here is some context about the task. Make sure to factor in any background knowledge,
|
| 225 |
+
satisfy any constraints, and respect any scenarios.
|
| 226 |
+
<context>
|
| 227 |
+
Asset: {label_upper} (S&P 500 constituent)
|
| 228 |
+
{context}
|
| 229 |
+
</context>
|
| 230 |
+
|
| 231 |
+
Here is a historical time series in (timestamp, value) format:
|
| 232 |
+
<history>
|
| 233 |
+
{history_str}
|
| 234 |
+
</history>
|
| 235 |
+
|
| 236 |
+
Now please predict the value at the following timestamps: {pred_time_str}.
|
| 237 |
+
|
| 238 |
+
Return the forecast in (timestamp, value) format in between <forecast> and </forecast> tags.
|
| 239 |
+
Do not include any other information (e.g., comments) in the forecast.
|
| 240 |
+
|
| 241 |
+
Example:
|
| 242 |
+
<history>
|
| 243 |
+
(t1, v1)
|
| 244 |
+
(t2, v2)
|
| 245 |
+
(t3, v3)
|
| 246 |
+
</history>
|
| 247 |
+
<forecast>
|
| 248 |
+
(t4, v4)
|
| 249 |
+
(t5, v5)
|
| 250 |
+
</forecast>
|
| 251 |
+
"""
|
| 252 |
+
return prompt
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def main():
|
| 256 |
+
ap = argparse.ArgumentParser()
|
| 257 |
+
ap.add_argument("--time-series-dir", "--time_series_dir", dest="time_series_dir", default="SP500_time_series")
|
| 258 |
+
ap.add_argument("--news-dir", "--news_dir", dest="news_dir", default="sp500_news")
|
| 259 |
+
ap.add_argument("--image-dir", "--image_dir", dest="image_dir", default="image/image")
|
| 260 |
+
ap.add_argument("--out-jsonl", "--out_jsonl", dest="out_jsonl", default="sp500_prompt_test.jsonl")
|
| 261 |
+
ap.add_argument("--max-files", "--max_files", dest="max_files", type=int, default=200)
|
| 262 |
+
ap.add_argument("--fut-len", "--fut_len", dest="fut_len", type=int, default=FUT_LEN)
|
| 263 |
+
ap.add_argument("--history-max-display", "--history_max_display", dest="history_max_display", type=int, default=None)
|
| 264 |
+
ap.add_argument("--news-timezone", default=NEWS_TIMEZONE,
|
| 265 |
+
help="Timezone for source date-only and naive news timestamps.")
|
| 266 |
+
args = ap.parse_args()
|
| 267 |
+
if args.fut_len < 1 or args.max_files == 0 or args.max_files < -1:
|
| 268 |
+
ap.error("--fut-len must be positive; --max-files must be positive or -1")
|
| 269 |
+
ZoneInfo(args.news_timezone)
|
| 270 |
+
|
| 271 |
+
ts_files = sorted(glob.glob(os.path.join(args.time_series_dir, "*.csv")))
|
| 272 |
+
target_written = args.max_files
|
| 273 |
+
os.makedirs(os.path.dirname(args.out_jsonl) or ".", exist_ok=True)
|
| 274 |
+
|
| 275 |
+
start_day = pd.to_datetime(DATE_START).date()
|
| 276 |
+
end_day = pd.to_datetime(DATE_END).date()
|
| 277 |
+
|
| 278 |
+
written, skipped = 0, 0
|
| 279 |
+
predict_id = 0
|
| 280 |
+
|
| 281 |
+
with open(args.out_jsonl, "w", encoding="utf-8") as out_f:
|
| 282 |
+
for csv_path in ts_files:
|
| 283 |
+
label_lower = os.path.splitext(os.path.basename(csv_path))[0].strip()
|
| 284 |
+
if not label_lower:
|
| 285 |
+
skipped += 1
|
| 286 |
+
|
| 287 |
+
continue
|
| 288 |
+
label_upper = label_lower.upper()
|
| 289 |
+
|
| 290 |
+
try:
|
| 291 |
+
df = pd.read_csv(csv_path)
|
| 292 |
+
except Exception:
|
| 293 |
+
skipped += 1
|
| 294 |
+
|
| 295 |
+
continue
|
| 296 |
+
|
| 297 |
+
if "Date" not in df.columns or "Close" not in df.columns:
|
| 298 |
+
skipped += 1
|
| 299 |
+
continue
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
dt = pd.to_datetime(df["Date"], errors="coerce", utc=True)
|
| 303 |
+
df = df.assign(_dt=dt).dropna(subset=["_dt"]).copy()
|
| 304 |
+
df["_day"] = df["_dt"].dt.date
|
| 305 |
+
df = df.sort_values("_dt").reset_index(drop=True)
|
| 306 |
+
|
| 307 |
+
hist_df = df[(df["_day"] >= start_day) & (df["_day"] <= end_day)].copy()
|
| 308 |
+
if hist_df.empty:
|
| 309 |
+
skipped += 1
|
| 310 |
+
continue
|
| 311 |
+
|
| 312 |
+
last_hist_pos = hist_df.index.max()
|
| 313 |
+
fut_df = df.iloc[last_hist_pos + 1: last_hist_pos + 1 + args.fut_len].copy()
|
| 314 |
+
if len(fut_df) < args.fut_len:
|
| 315 |
+
skipped += 1
|
| 316 |
+
continue
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
img_path = find_sp500_image_by_convention(args.image_dir, label_lower)
|
| 320 |
+
if img_path is None:
|
| 321 |
+
skipped += 1
|
| 322 |
+
continue
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
image_abs_path = str(os.path.abspath(img_path)).replace("\\", "/")
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
image_path_rel = os.path.relpath(img_path, start=args.image_dir).replace("\\", "/")
|
| 329 |
+
image_path_rel = f"{os.path.basename(args.image_dir)}/{image_path_rel}"
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
hist_timestamps = [d.strftime("%Y-%m-%d") for d in hist_df["_day"].tolist()]
|
| 333 |
+
hist_values = hist_df["Close"].astype(float).tolist()
|
| 334 |
+
|
| 335 |
+
fut_timestamps = [d.strftime("%Y-%m-%d") for d in fut_df["_day"].tolist()]
|
| 336 |
+
fut_values = fut_df["Close"].astype(float).tolist()
|
| 337 |
+
|
| 338 |
+
news_file = find_sp500_news_by_convention(args.news_dir, label_upper)
|
| 339 |
+
selected_news = load_pre_horizon_news(
|
| 340 |
+
news_file, forecast_start=fut_timestamps[0], k=3,
|
| 341 |
+
timezone=args.news_timezone,
|
| 342 |
+
)
|
| 343 |
+
last3_texts = [item["article"] for item in selected_news]
|
| 344 |
+
|
| 345 |
+
history_str = format_history_pairs(
|
| 346 |
+
hist_timestamps, hist_values, max_display=args.history_max_display
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
prompt = build_prompt_sp500(
|
| 350 |
+
image_abs_path=image_abs_path,
|
| 351 |
+
label_upper=label_upper,
|
| 352 |
+
history_str=history_str,
|
| 353 |
+
pred_time=fut_timestamps,
|
| 354 |
+
last3_texts=last3_texts,
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
record = {
|
| 358 |
+
"task_id": f"Fin_{predict_id}",
|
| 359 |
+
"task_type": "Fin",
|
| 360 |
+
"dimension": "complementary evidence",
|
| 361 |
+
"sub_dimension": "Fin_predict",
|
| 362 |
+
"text": last3_texts,
|
| 363 |
+
"prompt": prompt,
|
| 364 |
+
"evaluation_type":"prediction",
|
| 365 |
+
"time_index": list(range(len(hist_timestamps))),
|
| 366 |
+
"timestamp": hist_timestamps,
|
| 367 |
+
"time_series_data": hist_values,
|
| 368 |
+
"ground_truth": fut_values,
|
| 369 |
+
"image_path": image_abs_path,
|
| 370 |
+
"label": label_upper,
|
| 371 |
+
"Class": CLASS_NAME,
|
| 372 |
+
"hist length": len(hist_timestamps),
|
| 373 |
+
"Fut length": args.fut_len,
|
| 374 |
+
"Hist time": HIST_TIME_STR,
|
| 375 |
+
}
|
| 376 |
+
record["meta_info"] = {
|
| 377 |
+
"future_timestamps": fut_timestamps,
|
| 378 |
+
"news_cutoff_exclusive": parse_news_timestamp(
|
| 379 |
+
fut_timestamps[0], args.news_timezone,
|
| 380 |
+
).isoformat(),
|
| 381 |
+
"news_timezone": args.news_timezone,
|
| 382 |
+
"news_selection": "latest_3_strictly_before_forecast_start",
|
| 383 |
+
"selected_news": [
|
| 384 |
+
{key: item[key] for key in ("date", "published_at", "url")}
|
| 385 |
+
for item in selected_news
|
| 386 |
+
],
|
| 387 |
+
}
|
| 388 |
+
out_f.write(json.dumps(record, ensure_ascii=False) + "\n")
|
| 389 |
+
written += 1
|
| 390 |
+
predict_id += 1
|
| 391 |
+
if target_written > 0 and written >= target_written:
|
| 392 |
+
break
|
| 393 |
+
|
| 394 |
+
print(f"Done. written={written}, skipped={skipped}, out={args.out_jsonl}")
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
if __name__ == "__main__":
|
| 398 |
+
main()
|
sample/image-timeseries/sp500/test_news_cutoff.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Regression tests for source news availability at the forecast boundary."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import importlib.util
|
| 7 |
+
import json
|
| 8 |
+
import tempfile
|
| 9 |
+
import unittest
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
SPEC = importlib.util.spec_from_file_location("sp500_prepare", Path(__file__).with_name("prepare.py"))
|
| 14 |
+
BUILDER = importlib.util.module_from_spec(SPEC)
|
| 15 |
+
SPEC.loader.exec_module(BUILDER)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class NewsCutoffTests(unittest.TestCase):
|
| 19 |
+
def setUp(self) -> None:
|
| 20 |
+
self.temporary = tempfile.TemporaryDirectory()
|
| 21 |
+
self.addCleanup(self.temporary.cleanup)
|
| 22 |
+
self.news_file = Path(self.temporary.name) / "news.jsonl"
|
| 23 |
+
|
| 24 |
+
def select(self, records: list[object], **kwargs: object) -> list[str]:
|
| 25 |
+
self.news_file.write_text(
|
| 26 |
+
"\n".join(json.dumps(record) for record in records) + "\n", encoding="utf-8",
|
| 27 |
+
)
|
| 28 |
+
return BUILDER.load_last_k_news_summaries(
|
| 29 |
+
str(self.news_file), forecast_start="2024-07-01", **kwargs,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
def test_excludes_forecast_day_and_later_news(self) -> None:
|
| 33 |
+
selected = self.select([
|
| 34 |
+
{"Date": "2024-06-30", "Article": "available before forecast"},
|
| 35 |
+
{"Date": "2024-07-01", "Article": "at cutoff"},
|
| 36 |
+
{"Date": "2024-07-10", "Article": "during forecast"},
|
| 37 |
+
{"Date": "2025-04-18", "Article": "after forecast"},
|
| 38 |
+
])
|
| 39 |
+
self.assertEqual(selected, ["available before forecast"])
|
| 40 |
+
|
| 41 |
+
def test_sorts_before_selecting_latest_three(self) -> None:
|
| 42 |
+
selected = self.select([
|
| 43 |
+
{"Date": "2024-06-30", "Article": "newest"},
|
| 44 |
+
{"Date": "2024-06-01", "Article": "oldest"},
|
| 45 |
+
{"Date": "2024-06-29", "Article": "middle"},
|
| 46 |
+
{"Date": "2024-06-28", "Article": "third newest"},
|
| 47 |
+
])
|
| 48 |
+
self.assertEqual(selected, ["third newest", "middle", "newest"])
|
| 49 |
+
|
| 50 |
+
def test_missing_invalid_dates_and_empty_articles_are_ineligible(self) -> None:
|
| 51 |
+
selected = self.select([
|
| 52 |
+
{"Article": "undated"}, {"Date": None, "Article": "null date"},
|
| 53 |
+
{"Date": 1719705600, "Article": "ambiguous numeric epoch"},
|
| 54 |
+
{"Date": "06/30/2024", "Article": "ambiguous date format"},
|
| 55 |
+
{"Date": "2024-02-30", "Article": "invalid day"},
|
| 56 |
+
{"Date": "2024-06-30", "Article": " "},
|
| 57 |
+
{"Date": "2024-06-30", "Article": None},
|
| 58 |
+
{"Date": "2024-06-30", "Article": ["invalid article"]},
|
| 59 |
+
["not a news object"],
|
| 60 |
+
])
|
| 61 |
+
self.assertEqual(selected, [])
|
| 62 |
+
|
| 63 |
+
def test_exact_timezone_boundary_is_exclusive(self) -> None:
|
| 64 |
+
selected = self.select([
|
| 65 |
+
{"Date": "2024-06-30T23:59:59-04:00", "Article": "one second before"},
|
| 66 |
+
{"Date": "2024-07-01T04:00:00Z", "Article": "at cutoff in UTC"},
|
| 67 |
+
{"Date": "2024-07-01T12:00:00+08:00", "Article": "same cutoff in Asia"},
|
| 68 |
+
{"Date": "2024-07-01T04:00:01Z", "Article": "one second after"},
|
| 69 |
+
])
|
| 70 |
+
self.assertEqual(selected, ["one second before"])
|
| 71 |
+
|
| 72 |
+
def test_timezone_aware_dates_use_actual_instant(self) -> None:
|
| 73 |
+
selected = self.select([
|
| 74 |
+
{"Date": "2024-07-01T03:59:59Z", "Article": "before New York cutoff"},
|
| 75 |
+
{"Date": "2024-06-30T23:00:00-07:00", "Article": "after New York cutoff"},
|
| 76 |
+
])
|
| 77 |
+
self.assertEqual(selected, ["before New York cutoff"])
|
| 78 |
+
|
| 79 |
+
def test_timezone_is_configurable(self) -> None:
|
| 80 |
+
records = [{"Date": "2024-07-01T03:00:00Z", "Article": "New York only"}]
|
| 81 |
+
self.assertEqual(self.select(records), ["New York only"])
|
| 82 |
+
self.assertEqual(self.select(records, timezone="UTC"), [])
|
| 83 |
+
|
| 84 |
+
def test_invalid_dst_times_are_rejected(self) -> None:
|
| 85 |
+
self.assertIsNone(BUILDER.parse_news_timestamp("2024-11-03T01:30:00", "America/New_York"))
|
| 86 |
+
self.assertIsNone(BUILDER.parse_news_timestamp("2024-03-10T02:30:00", "America/New_York"))
|
| 87 |
+
|
| 88 |
+
def test_selection_preserves_auditable_source_metadata(self) -> None:
|
| 89 |
+
self.select([{"Date": "2024-06-30", "Article": "eligible", "Url": "https://example.org/news"}])
|
| 90 |
+
selected = BUILDER.load_pre_horizon_news(str(self.news_file), forecast_start="2024-07-01")
|
| 91 |
+
self.assertEqual(selected[0]["date"], "2024-06-30")
|
| 92 |
+
self.assertEqual(selected[0]["published_at"], "2024-06-30T04:00:00+00:00")
|
| 93 |
+
self.assertEqual(selected[0]["url"], "https://example.org/news")
|
| 94 |
+
|
| 95 |
+
def test_missing_file_and_no_eligible_news_return_empty(self) -> None:
|
| 96 |
+
self.assertEqual(BUILDER.load_pre_horizon_news(
|
| 97 |
+
str(self.news_file), forecast_start="2024-07-01",
|
| 98 |
+
), [])
|
| 99 |
+
self.assertEqual(self.select([{"Date": "2025-04-18", "Article": "future"}]), [])
|
| 100 |
+
|
| 101 |
+
def test_cutoff_is_mandatory_and_invalid_selection_is_rejected(self) -> None:
|
| 102 |
+
with self.assertRaises(TypeError):
|
| 103 |
+
BUILDER.load_last_k_news_summaries(str(self.news_file))
|
| 104 |
+
with self.assertRaises(ValueError):
|
| 105 |
+
BUILDER.load_pre_horizon_news(str(self.news_file), forecast_start="2024-02-30")
|
| 106 |
+
with self.assertRaises(ValueError):
|
| 107 |
+
BUILDER.load_pre_horizon_news(str(self.news_file), forecast_start="2024-07-01", k=0)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
if __name__ == "__main__":
|
| 111 |
+
unittest.main()
|
sample/video-timeseries/covla/README.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CoVLA
|
| 2 |
+
|
| 3 |
+
**Processing code only:** source data and generated task records are not
|
| 4 |
+
included. Complete the upstream access requirements and follow the source terms.
|
| 5 |
+
See the [shared setup instructions](../../../processing/README.md).
|
| 6 |
+
Run the commands below from the directory containing `MMTA-v1.0/`, keeping
|
| 7 |
+
`local_sources/` and `local_work/` outside the release folder.
|
| 8 |
+
|
| 9 |
+
Download [CoVLA](https://huggingface.co/datasets/turing-motors/CoVLA-Dataset) with an approved Hugging Face account and unpack the states, front-car signals and videos.
|
| 10 |
+
|
| 11 |
+
```bash
|
| 12 |
+
python -B MMTA-v1.0/sample/video-timeseries/covla/download.py --output local_sources/covla --accept-terms
|
| 13 |
+
python -B MMTA-v1.0/sample/video-timeseries/covla/generate.py \
|
| 14 |
+
--source-root local_sources/covla --output-dir local_work/covla_build
|
| 15 |
+
```
|
| 16 |
+
|
| 17 |
+
Build: braking-event extraction -> signal enrichment -> task prompts -> stratified split -> video/CSV conversion.
|
| 18 |
+
|
| 19 |
+
Output: `--output-dir/covla/covla.omnits.jsonl`, plus media and history CSVs. Paths are relative to that output domain directory. Use `--split train` to convert the training split where available.
|
sample/video-timeseries/covla/build_prompts.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Build local brake-reason task prompts from synchronized source signals."""
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# ── Cause options (English, for prompt) ──────────────────────────────────────
|
| 12 |
+
CAUSE_OPTIONS: dict[str, str] = {
|
| 13 |
+
"A": "The leading vehicle suddenly decelerated.",
|
| 14 |
+
"B": "The ego vehicle was making a turn.",
|
| 15 |
+
"C": (
|
| 16 |
+
"Other reason "
|
| 17 |
+
"(e.g., pedestrian about to cross the road, traffic light turning red, "
|
| 18 |
+
"entering a tunnel, etc.)."
|
| 19 |
+
),
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
# ── Variable descriptions (English) ──────────────────────────────────────────
|
| 23 |
+
VAR_DESC: dict[str, str] = {
|
| 24 |
+
"vEgo": (
|
| 25 |
+
"Ego vehicle speed in m/s (forward velocity of the autonomous vehicle)."
|
| 26 |
+
),
|
| 27 |
+
"aEgo": (
|
| 28 |
+
"Ego vehicle longitudinal acceleration in m/s²; "
|
| 29 |
+
"negative values indicate deceleration."
|
| 30 |
+
),
|
| 31 |
+
"steeringAngleDeg": (
|
| 32 |
+
"Steering wheel angle in degrees; "
|
| 33 |
+
"large non-zero values indicate the vehicle is turning."
|
| 34 |
+
),
|
| 35 |
+
"lead_speed_kmh": (
|
| 36 |
+
"Speed of the leading (front) vehicle in km/h; "
|
| 37 |
+
"null if no leading vehicle is detected."
|
| 38 |
+
),
|
| 39 |
+
"lead_a": (
|
| 40 |
+
"Acceleration of the leading vehicle in m/s²; "
|
| 41 |
+
"negative values mean the leading vehicle is decelerating; "
|
| 42 |
+
"null if no leading vehicle is detected."
|
| 43 |
+
),
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
# Variables that go into the prompt timeseries (brake & gas excluded)
|
| 47 |
+
PROMPT_VARS: list[str] = ["vEgo", "aEgo", "steeringAngleDeg", "lead_speed_kmh", "lead_a"]
|
| 48 |
+
|
| 49 |
+
# Array fields to remove from the final record (they live in the prompt now)
|
| 50 |
+
ARRAYS_TO_DROP: list[str] = [
|
| 51 |
+
"timestamps",
|
| 52 |
+
"vEgo",
|
| 53 |
+
"aEgo",
|
| 54 |
+
"steeringAngleDeg",
|
| 55 |
+
"brake",
|
| 56 |
+
"gas",
|
| 57 |
+
"lead_speed_kmh",
|
| 58 |
+
"lead_a",
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# ── Decimal-precision helper ──────────────────────────────────────────────────
|
| 63 |
+
def choose_decimals_by_avg_diff(values: list[float]) -> int:
|
| 64 |
+
if len(values) == 0:
|
| 65 |
+
return 0
|
| 66 |
+
if len(values) > 1:
|
| 67 |
+
diffs = [abs(values[i + 1] - values[i]) for i in range(len(values) - 1)]
|
| 68 |
+
avg_diff = float(np.mean(diffs)) if diffs else 0.0
|
| 69 |
+
else:
|
| 70 |
+
avg_diff = abs(values[0]) * 0.01 if values[0] != 0 else 1.0
|
| 71 |
+
|
| 72 |
+
if avg_diff == 0:
|
| 73 |
+
return 0
|
| 74 |
+
if avg_diff >= 10:
|
| 75 |
+
return 0
|
| 76 |
+
if avg_diff >= 1:
|
| 77 |
+
return 1
|
| 78 |
+
if avg_diff >= 0.1:
|
| 79 |
+
return 2
|
| 80 |
+
if avg_diff >= 0.01:
|
| 81 |
+
return 3
|
| 82 |
+
if avg_diff >= 0.001:
|
| 83 |
+
return 4
|
| 84 |
+
return 5
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def fmt_val(v: Any, decimals: int) -> str:
|
| 88 |
+
if v is None:
|
| 89 |
+
return "null"
|
| 90 |
+
try:
|
| 91 |
+
return f"{float(v):.{decimals}f}"
|
| 92 |
+
except (TypeError, ValueError):
|
| 93 |
+
return str(v)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def ts_str(v: Any) -> str:
|
| 97 |
+
if isinstance(v, (int, float)):
|
| 98 |
+
return f"{v:.1f}s"
|
| 99 |
+
return str(v)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# ── Prompt builder ────────────────────────────────────────────────────────────
|
| 103 |
+
def build_prompt(item: dict[str, Any]) -> str:
|
| 104 |
+
video_path = item.get("video_path") or ""
|
| 105 |
+
start_frame: int = item.get("start_frame", 0)
|
| 106 |
+
end_frame: int = item.get("end_frame", 0)
|
| 107 |
+
frame_count: int = item.get("frame_count", 0)
|
| 108 |
+
timestamps: list[Any] = item.get("timestamps") or []
|
| 109 |
+
|
| 110 |
+
start_ts = timestamps[0] if timestamps else None
|
| 111 |
+
end_ts = timestamps[-1] if timestamps else None
|
| 112 |
+
|
| 113 |
+
# ── Per-variable rounding ────────────────────────────────────────────────
|
| 114 |
+
decimals: dict[str, int] = {}
|
| 115 |
+
rounded: dict[str, list[str]] = {}
|
| 116 |
+
for var in PROMPT_VARS:
|
| 117 |
+
raw: list[Any] = item.get(var) or []
|
| 118 |
+
numeric = [float(v) for v in raw if v is not None]
|
| 119 |
+
dec = choose_decimals_by_avg_diff(numeric)
|
| 120 |
+
decimals[var] = dec
|
| 121 |
+
rounded[var] = [fmt_val(v, dec) for v in raw]
|
| 122 |
+
|
| 123 |
+
# ── Time-series block ────────────────────────────────────────────────────
|
| 124 |
+
example_line = "t(s): vEgo=, aEgo=, steeringAngleDeg=, lead_speed_kmh=, lead_a="
|
| 125 |
+
ts_lines: list[str] = []
|
| 126 |
+
for i, t in enumerate(timestamps):
|
| 127 |
+
t_label = f"{t:.1f}" if isinstance(t, (int, float)) else str(t)
|
| 128 |
+
parts = [
|
| 129 |
+
f"{var}={rounded[var][i] if i < len(rounded.get(var, [])) else 'null'}"
|
| 130 |
+
for var in PROMPT_VARS
|
| 131 |
+
]
|
| 132 |
+
ts_lines.append(f"{t_label}: " + ", ".join(parts))
|
| 133 |
+
timeseries_block = "\n".join(ts_lines)
|
| 134 |
+
|
| 135 |
+
# ── Variable description block ──────────────────────────���────────────────
|
| 136 |
+
var_block = "\n".join(f"- {var}: {VAR_DESC[var]}" for var in PROMPT_VARS)
|
| 137 |
+
|
| 138 |
+
# ── Options block ────────────────────────────────────────────────────────
|
| 139 |
+
options_lines = ["Answer (choose one option):"]
|
| 140 |
+
for k, v in CAUSE_OPTIONS.items():
|
| 141 |
+
options_lines.append(f"{k}. {v}")
|
| 142 |
+
options_lines += ["", "Return only the option letter (A, B, or C)."]
|
| 143 |
+
options_block = "\n".join(options_lines)
|
| 144 |
+
|
| 145 |
+
# ── Question ─────────────────────────────────────────────────────────────
|
| 146 |
+
question = (
|
| 147 |
+
f"Question: Based on the video content and the sensor data above, "
|
| 148 |
+
f"why did the ego vehicle suddenly brake during the segment ?"
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
prompt = f"""\
|
| 152 |
+
You are given a question-answering (QA) task for autonomous driving.
|
| 153 |
+
|
| 154 |
+
You are provided with a dashcam video segment from an autonomous driving system (ego vehicle) \
|
| 155 |
+
traveling on public roads. This video is already temporally cropped to only the braking event, \
|
| 156 |
+
and the per-frame sensor data below is aligned to this same braking segment. \
|
| 157 |
+
Your task is to determine the most likely reason for the sudden braking in this segment.
|
| 158 |
+
|
| 159 |
+
Do NOT output any analysis. Return only the option letter.
|
| 160 |
+
|
| 161 |
+
<video>
|
| 162 |
+
This video clip contains only the braking segment. The braking segment contains \
|
| 163 |
+
{frame_count} frames. No pre-brake or post-brake frames are included in this clip. The sensor \
|
| 164 |
+
data provided below also contains only this exact braking segment.
|
| 165 |
+
</video>
|
| 166 |
+
|
| 167 |
+
<variables>
|
| 168 |
+
Sensor variables recorded per frame only within the braking segment:
|
| 169 |
+
{var_block}
|
| 170 |
+
</variables>
|
| 171 |
+
|
| 172 |
+
<timeseries>
|
| 173 |
+
One-line format example:
|
| 174 |
+
{example_line}
|
| 175 |
+
|
| 176 |
+
Per-frame sensor data only for the braking segment from braking onset to braking offset \
|
| 177 |
+
(null = not available):
|
| 178 |
+
{timeseries_block}
|
| 179 |
+
</timeseries>
|
| 180 |
+
|
| 181 |
+
{question}
|
| 182 |
+
{options_block}"""
|
| 183 |
+
|
| 184 |
+
return "\n".join(ln.rstrip() for ln in prompt.splitlines()).strip()
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def build_question(item: dict[str, Any]) -> str:
|
| 188 |
+
start_frame: int = item.get("start_frame", 0)
|
| 189 |
+
end_frame: int = item.get("end_frame", 0)
|
| 190 |
+
timestamps: list[Any] = item.get("timestamps") or []
|
| 191 |
+
start_ts = timestamps[0] if timestamps else None
|
| 192 |
+
end_ts = timestamps[-1] if timestamps else None
|
| 193 |
+
return (
|
| 194 |
+
f"Based on the video content and the sensor data above, "
|
| 195 |
+
f"why did the ego vehicle suddenly brake during the segment ?"
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# ── Main ──────────────────────────────────────────────────────────────────────
|
| 200 |
+
def main() -> None:
|
| 201 |
+
parser = argparse.ArgumentParser(
|
| 202 |
+
description="Build braking-reason prompts and remove redundant raw arrays"
|
| 203 |
+
)
|
| 204 |
+
parser.add_argument("--root", type=Path, default=Path("."), help="Dataset root directory")
|
| 205 |
+
parser.add_argument(
|
| 206 |
+
"--input",
|
| 207 |
+
type=Path,
|
| 208 |
+
default=Path("all_brake_reasons_enriched.jsonl"),
|
| 209 |
+
help="Input enriched JSONL",
|
| 210 |
+
)
|
| 211 |
+
parser.add_argument(
|
| 212 |
+
"--output",
|
| 213 |
+
type=Path,
|
| 214 |
+
default=Path("all_brake_reasons_final.jsonl"),
|
| 215 |
+
help="Output prompt JSONL",
|
| 216 |
+
)
|
| 217 |
+
parser.add_argument(
|
| 218 |
+
"--sample-output",
|
| 219 |
+
type=Path,
|
| 220 |
+
default=Path("all_brake_reasons_final_sample.jsonl"),
|
| 221 |
+
help="Output inspection JSONL",
|
| 222 |
+
)
|
| 223 |
+
parser.add_argument("--sample-size", type=int, default=8, help="Number of inspection records")
|
| 224 |
+
args = parser.parse_args()
|
| 225 |
+
|
| 226 |
+
root = args.root.resolve()
|
| 227 |
+
input_path = (root / args.input).resolve()
|
| 228 |
+
output_path = (root / args.output).resolve()
|
| 229 |
+
sample_path = (root / args.sample_output).resolve()
|
| 230 |
+
|
| 231 |
+
total = 0
|
| 232 |
+
sample_records: list[dict[str, Any]] = []
|
| 233 |
+
|
| 234 |
+
with (
|
| 235 |
+
input_path.open("r", encoding="utf-8") as src,
|
| 236 |
+
output_path.open("w", encoding="utf-8") as dst,
|
| 237 |
+
):
|
| 238 |
+
for line in src:
|
| 239 |
+
line = line.strip()
|
| 240 |
+
if not line:
|
| 241 |
+
continue
|
| 242 |
+
|
| 243 |
+
item: dict[str, Any] = json.loads(line)
|
| 244 |
+
|
| 245 |
+
# Build prompt & question BEFORE dropping arrays (they need timestamps etc.)
|
| 246 |
+
item["prompt"] = build_prompt(item)
|
| 247 |
+
item["question"] = build_question(item)
|
| 248 |
+
item["ground_truth"] = item.get("cause_option", "C")
|
| 249 |
+
item["frames"] = {
|
| 250 |
+
"start_frame": item.get("start_frame", 0),
|
| 251 |
+
"end_frame": item.get("end_frame", 0),
|
| 252 |
+
"frame_count": item.get("frame_count", 0),
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
# Drop raw array fields that are now represented in the prompt
|
| 256 |
+
for field in ARRAYS_TO_DROP:
|
| 257 |
+
item.pop(field, None)
|
| 258 |
+
|
| 259 |
+
dst.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 260 |
+
total += 1
|
| 261 |
+
if len(sample_records) < args.sample_size:
|
| 262 |
+
sample_records.append(item)
|
| 263 |
+
|
| 264 |
+
with sample_path.open("w", encoding="utf-8") as sf:
|
| 265 |
+
for r in sample_records:
|
| 266 |
+
sf.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 267 |
+
|
| 268 |
+
print(f"Processed {total} records")
|
| 269 |
+
print(f"Complete output: {output_path}")
|
| 270 |
+
print(f"Inspection output: {sample_path} ({len(sample_records)} records)")
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
if __name__ == "__main__":
|
| 274 |
+
main()
|
sample/video-timeseries/covla/download.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Download covla from its official source for local processing."""
|
| 3 |
+
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "processing"))
|
| 8 |
+
from download import main
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
if __name__ == "__main__":
|
| 12 |
+
main("covla")
|
sample/video-timeseries/covla/enrich_segments.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Attach aligned vehicle and lead-car signals to local braking segments."""
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def load_frame_dict(file_path: Path) -> dict[int, dict[str, Any] | None]:
|
| 10 |
+
frame_dict: dict[int, dict[str, Any] | None] = {}
|
| 11 |
+
with file_path.open("r", encoding="utf-8") as file:
|
| 12 |
+
for line in file:
|
| 13 |
+
line = line.strip()
|
| 14 |
+
if not line:
|
| 15 |
+
continue
|
| 16 |
+
item = json.loads(line)
|
| 17 |
+
if not item:
|
| 18 |
+
continue
|
| 19 |
+
frame_key = next(iter(item.keys()))
|
| 20 |
+
frame_idx = int(frame_key)
|
| 21 |
+
frame_dict[frame_idx] = item[frame_key]
|
| 22 |
+
return frame_dict
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def load_metadata_map(metadata_path: Path, root: Path) -> dict[str, str]:
|
| 26 |
+
video_path_map: dict[str, str] = {}
|
| 27 |
+
with metadata_path.open("r", encoding="utf-8") as file:
|
| 28 |
+
for line in file:
|
| 29 |
+
line = line.strip()
|
| 30 |
+
if not line:
|
| 31 |
+
continue
|
| 32 |
+
item = json.loads(line)
|
| 33 |
+
video_id = item.get("video_id")
|
| 34 |
+
file_name = item.get("file_name")
|
| 35 |
+
if not isinstance(video_id, str) or not isinstance(file_name, str):
|
| 36 |
+
continue
|
| 37 |
+
video_path_map[video_id] = str((root / file_name).resolve())
|
| 38 |
+
return video_path_map
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def get_video_start_timestamp(states: dict[int, dict[str, Any] | None]) -> int | None:
|
| 42 |
+
for frame_idx in sorted(states):
|
| 43 |
+
info = states.get(frame_idx)
|
| 44 |
+
if not isinstance(info, dict):
|
| 45 |
+
continue
|
| 46 |
+
timestamp = info.get("timestamp")
|
| 47 |
+
if isinstance(timestamp, (int, float)):
|
| 48 |
+
return int(timestamp)
|
| 49 |
+
return None
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def get_state_value(
|
| 53 |
+
states: dict[int, dict[str, Any] | None], frame: int, key: str
|
| 54 |
+
) -> Any:
|
| 55 |
+
info = states.get(frame)
|
| 56 |
+
if not isinstance(info, dict):
|
| 57 |
+
return None
|
| 58 |
+
return info.get(key)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def get_front_car_value(
|
| 62 |
+
front_car: dict[int, dict[str, Any] | None], frame: int, key: str
|
| 63 |
+
) -> Any:
|
| 64 |
+
info = front_car.get(frame)
|
| 65 |
+
if not isinstance(info, dict):
|
| 66 |
+
return None
|
| 67 |
+
return info.get(key)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def build_record(
|
| 71 |
+
item: dict[str, Any],
|
| 72 |
+
states: dict[int, dict[str, Any] | None],
|
| 73 |
+
front_car: dict[int, dict[str, Any] | None],
|
| 74 |
+
video_abs_path: str | None,
|
| 75 |
+
) -> dict[str, Any]:
|
| 76 |
+
frames = item.get("frames", [])
|
| 77 |
+
if not isinstance(frames, list):
|
| 78 |
+
frames = []
|
| 79 |
+
|
| 80 |
+
video_start_ts = get_video_start_timestamp(states)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
timestamps: list[float | None] = []
|
| 84 |
+
v_ego: list[Any] = []
|
| 85 |
+
a_ego: list[Any] = []
|
| 86 |
+
steering_angle_deg: list[Any] = []
|
| 87 |
+
brake: list[Any] = []
|
| 88 |
+
gas: list[Any] = []
|
| 89 |
+
lead_speed_kmh: list[Any] = []
|
| 90 |
+
lead_a: list[Any] = []
|
| 91 |
+
|
| 92 |
+
for frame in frames:
|
| 93 |
+
if not isinstance(frame, int):
|
| 94 |
+
timestamps.append(None)
|
| 95 |
+
v_ego.append(None)
|
| 96 |
+
a_ego.append(None)
|
| 97 |
+
steering_angle_deg.append(None)
|
| 98 |
+
brake.append(None)
|
| 99 |
+
gas.append(None)
|
| 100 |
+
lead_speed_kmh.append(None)
|
| 101 |
+
lead_a.append(None)
|
| 102 |
+
continue
|
| 103 |
+
|
| 104 |
+
raw_ts = get_state_value(states, frame, "timestamp")
|
| 105 |
+
if isinstance(raw_ts, (int, float)) and video_start_ts is not None:
|
| 106 |
+
timestamps.append(round((float(raw_ts) - float(video_start_ts)) / 1000.0, 3))
|
| 107 |
+
else:
|
| 108 |
+
timestamps.append(None)
|
| 109 |
+
|
| 110 |
+
v_ego.append(get_state_value(states, frame, "vEgo"))
|
| 111 |
+
a_ego.append(get_state_value(states, frame, "aEgo"))
|
| 112 |
+
steering_angle_deg.append(get_state_value(states, frame, "steeringAngleDeg"))
|
| 113 |
+
brake.append(get_state_value(states, frame, "brake"))
|
| 114 |
+
gas.append(get_state_value(states, frame, "gas"))
|
| 115 |
+
lead_speed_kmh.append(get_front_car_value(front_car, frame, "lead_speed_kmh"))
|
| 116 |
+
lead_a.append(get_front_car_value(front_car, frame, "lead_a"))
|
| 117 |
+
|
| 118 |
+
enriched_item = dict(item)
|
| 119 |
+
enriched_item["timestamps"] = timestamps
|
| 120 |
+
enriched_item["vEgo"] = v_ego
|
| 121 |
+
enriched_item["aEgo"] = a_ego
|
| 122 |
+
enriched_item["steeringAngleDeg"] = steering_angle_deg
|
| 123 |
+
enriched_item["brake"] = brake
|
| 124 |
+
enriched_item["gas"] = gas
|
| 125 |
+
enriched_item["lead_speed_kmh"] = lead_speed_kmh
|
| 126 |
+
enriched_item["lead_a"] = lead_a
|
| 127 |
+
enriched_item["video_path"] = video_abs_path
|
| 128 |
+
return enriched_item
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def main() -> None:
|
| 132 |
+
parser = argparse.ArgumentParser(description="Enrich braking segments with synchronized state and lead-vehicle signals")
|
| 133 |
+
parser.add_argument("--root", type=Path, default=Path("."), help="Dataset root directory")
|
| 134 |
+
parser.add_argument(
|
| 135 |
+
"--input",
|
| 136 |
+
type=Path,
|
| 137 |
+
default=Path("all_brake_reasons.jsonl"),
|
| 138 |
+
help="Input merged braking-segment JSONL",
|
| 139 |
+
)
|
| 140 |
+
parser.add_argument(
|
| 141 |
+
"--output",
|
| 142 |
+
type=Path,
|
| 143 |
+
default=Path("all_brake_reasons_enriched.jsonl"),
|
| 144 |
+
help="Output enriched JSONL",
|
| 145 |
+
)
|
| 146 |
+
parser.add_argument(
|
| 147 |
+
"--sample-output",
|
| 148 |
+
type=Path,
|
| 149 |
+
default=Path("all_brake_reasons_enriched_sample.jsonl"),
|
| 150 |
+
help="Small inspection JSONL",
|
| 151 |
+
)
|
| 152 |
+
parser.add_argument(
|
| 153 |
+
"--sample-size",
|
| 154 |
+
type=int,
|
| 155 |
+
default=8,
|
| 156 |
+
help="Number of inspection records (default: 8)",
|
| 157 |
+
)
|
| 158 |
+
args = parser.parse_args()
|
| 159 |
+
|
| 160 |
+
root = args.root.resolve()
|
| 161 |
+
input_path = (root / args.input).resolve()
|
| 162 |
+
output_path = (root / args.output).resolve()
|
| 163 |
+
sample_output_path = (root / args.sample_output).resolve()
|
| 164 |
+
metadata_path = root / "metadata.jsonl"
|
| 165 |
+
states_dir = root / "states"
|
| 166 |
+
front_car_dir = root / "front_car"
|
| 167 |
+
|
| 168 |
+
video_path_map = load_metadata_map(metadata_path, root)
|
| 169 |
+
states_cache: dict[str, dict[int, dict[str, Any] | None]] = {}
|
| 170 |
+
front_car_cache: dict[str, dict[int, dict[str, Any] | None]] = {}
|
| 171 |
+
|
| 172 |
+
total_records = 0
|
| 173 |
+
sample_records: list[dict[str, Any]] = []
|
| 174 |
+
|
| 175 |
+
with input_path.open("r", encoding="utf-8") as src, output_path.open("w", encoding="utf-8") as dst:
|
| 176 |
+
for line in src:
|
| 177 |
+
line = line.strip()
|
| 178 |
+
if not line:
|
| 179 |
+
continue
|
| 180 |
+
|
| 181 |
+
item = json.loads(line)
|
| 182 |
+
video_id = item.get("video_id")
|
| 183 |
+
if not isinstance(video_id, str):
|
| 184 |
+
continue
|
| 185 |
+
|
| 186 |
+
if video_id not in states_cache:
|
| 187 |
+
states_cache[video_id] = load_frame_dict(states_dir / f"{video_id}.jsonl")
|
| 188 |
+
if video_id not in front_car_cache:
|
| 189 |
+
front_car_cache[video_id] = load_frame_dict(front_car_dir / f"{video_id}.jsonl")
|
| 190 |
+
|
| 191 |
+
enriched_item = build_record(
|
| 192 |
+
item=item,
|
| 193 |
+
states=states_cache[video_id],
|
| 194 |
+
front_car=front_car_cache[video_id],
|
| 195 |
+
video_abs_path=video_path_map.get(video_id),
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
dst.write(json.dumps(enriched_item, ensure_ascii=False) + "\n")
|
| 199 |
+
total_records += 1
|
| 200 |
+
|
| 201 |
+
if len(sample_records) < max(args.sample_size, 0):
|
| 202 |
+
sample_records.append(enriched_item)
|
| 203 |
+
|
| 204 |
+
with sample_output_path.open("w", encoding="utf-8") as sample_file:
|
| 205 |
+
for item in sample_records:
|
| 206 |
+
sample_file.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 207 |
+
|
| 208 |
+
print(f"Enriched records written to: {output_path}")
|
| 209 |
+
print(f"Inspection records written to: {sample_output_path}")
|
| 210 |
+
print(f"Processed {total_records} records; inspection set has {len(sample_records)} records.")
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
if __name__ == "__main__":
|
| 214 |
+
main()
|
sample/video-timeseries/covla/extract_brake_reasons.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Extract continuous braking segments with one synchronized cause label."""
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
CAUSE_MAP = {
|
| 10 |
+
"A": "The leading vehicle suddenly decelerated",
|
| 11 |
+
"B": "Turning",
|
| 12 |
+
"C": "Other reasons",
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def load_frame_dict(file_path: Path) -> dict[int, dict[str, Any] | None]:
|
| 17 |
+
frame_dict: dict[int, dict[str, Any] | None] = {}
|
| 18 |
+
with file_path.open("r", encoding="utf-8") as file:
|
| 19 |
+
for line in file:
|
| 20 |
+
line = line.strip()
|
| 21 |
+
if not line:
|
| 22 |
+
continue
|
| 23 |
+
item = json.loads(line)
|
| 24 |
+
if not item:
|
| 25 |
+
continue
|
| 26 |
+
frame_key = next(iter(item.keys()))
|
| 27 |
+
frame_idx = int(frame_key)
|
| 28 |
+
frame_dict[frame_idx] = item[frame_key]
|
| 29 |
+
return frame_dict
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_true_segments(frames: list[int], min_length: int) -> list[list[int]]:
|
| 33 |
+
if not frames:
|
| 34 |
+
return []
|
| 35 |
+
|
| 36 |
+
frames = sorted(frames)
|
| 37 |
+
segments: list[list[int]] = []
|
| 38 |
+
current = [frames[0]]
|
| 39 |
+
|
| 40 |
+
for frame in frames[1:]:
|
| 41 |
+
if frame == current[-1] + 1:
|
| 42 |
+
current.append(frame)
|
| 43 |
+
else:
|
| 44 |
+
if len(current) >= min_length:
|
| 45 |
+
segments.append(current)
|
| 46 |
+
current = [frame]
|
| 47 |
+
|
| 48 |
+
if len(current) >= min_length:
|
| 49 |
+
segments.append(current)
|
| 50 |
+
|
| 51 |
+
return segments
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def condition_a(frame: int, front_car: dict[int, dict[str, Any] | None]) -> bool:
|
| 55 |
+
info = front_car.get(frame)
|
| 56 |
+
if not isinstance(info, dict):
|
| 57 |
+
return False
|
| 58 |
+
lead_a = info.get("lead_a")
|
| 59 |
+
if lead_a is None:
|
| 60 |
+
return False
|
| 61 |
+
try:
|
| 62 |
+
return float(lead_a) < 0
|
| 63 |
+
except (TypeError, ValueError):
|
| 64 |
+
return False
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def condition_b(frame: int, states: dict[int, dict[str, Any] | None]) -> bool:
|
| 68 |
+
info = states.get(frame)
|
| 69 |
+
if not isinstance(info, dict):
|
| 70 |
+
return False
|
| 71 |
+
return bool(info.get("leftBlinker") is True or info.get("rightBlinker") is True)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def detect_segment_cause(
|
| 75 |
+
segment_frames: list[int],
|
| 76 |
+
states: dict[int, dict[str, Any] | None],
|
| 77 |
+
front_car: dict[int, dict[str, Any] | None],
|
| 78 |
+
) -> list[str]:
|
| 79 |
+
a_frames = [frame for frame in segment_frames if condition_a(frame, front_car)]
|
| 80 |
+
b_frames = [frame for frame in segment_frames if condition_b(frame, states)]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
a_hit = bool(get_true_segments(a_frames, min_length=2))
|
| 84 |
+
b_hit = bool(get_true_segments(b_frames, min_length=2))
|
| 85 |
+
|
| 86 |
+
if a_hit and b_hit:
|
| 87 |
+
return ["A", "B"]
|
| 88 |
+
if a_hit:
|
| 89 |
+
return ["A"]
|
| 90 |
+
if b_hit:
|
| 91 |
+
return ["B"]
|
| 92 |
+
return ["C"]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def process_video(
|
| 96 |
+
video_id: str,
|
| 97 |
+
states_path: Path,
|
| 98 |
+
front_car_path: Path,
|
| 99 |
+
min_length: int,
|
| 100 |
+
) -> list[dict[str, Any]]:
|
| 101 |
+
states = load_frame_dict(states_path)
|
| 102 |
+
front_car = load_frame_dict(front_car_path)
|
| 103 |
+
|
| 104 |
+
brake_true_frames = [
|
| 105 |
+
frame
|
| 106 |
+
for frame, info in states.items()
|
| 107 |
+
if isinstance(info, dict) and info.get("brakePressed") is True
|
| 108 |
+
]
|
| 109 |
+
|
| 110 |
+
segments = get_true_segments(brake_true_frames, min_length=min_length)
|
| 111 |
+
results: list[dict[str, Any]] = []
|
| 112 |
+
|
| 113 |
+
for segment in segments:
|
| 114 |
+
causes = detect_segment_cause(segment, states, front_car)
|
| 115 |
+
if len(causes) != 1:
|
| 116 |
+
continue
|
| 117 |
+
|
| 118 |
+
cause = causes[0]
|
| 119 |
+
start_frame = segment[0]
|
| 120 |
+
end_frame = segment[-1]
|
| 121 |
+
start_ts = None
|
| 122 |
+
end_ts = None
|
| 123 |
+
|
| 124 |
+
start_info = states.get(start_frame)
|
| 125 |
+
end_info = states.get(end_frame)
|
| 126 |
+
if isinstance(start_info, dict):
|
| 127 |
+
start_ts = start_info.get("timestamp")
|
| 128 |
+
if isinstance(end_info, dict):
|
| 129 |
+
end_ts = end_info.get("timestamp")
|
| 130 |
+
|
| 131 |
+
results.append(
|
| 132 |
+
{
|
| 133 |
+
"video_id": video_id,
|
| 134 |
+
"start_frame": start_frame,
|
| 135 |
+
"end_frame": end_frame,
|
| 136 |
+
"frame_count": len(segment),
|
| 137 |
+
"frames": segment,
|
| 138 |
+
"start_timestamp": start_ts,
|
| 139 |
+
"end_timestamp": end_ts,
|
| 140 |
+
"cause_option": cause,
|
| 141 |
+
"cause_text": CAUSE_MAP[cause],
|
| 142 |
+
}
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
return results
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def main() -> None:
|
| 149 |
+
parser = argparse.ArgumentParser(description="Extract continuous braking segments with a unique cause label")
|
| 150 |
+
parser.add_argument("--root", type=Path, default=Path("."), help="Dataset root directory")
|
| 151 |
+
parser.add_argument("--output-dir", type=Path, default=Path("brake_reasons"), help="Output directory")
|
| 152 |
+
parser.add_argument("--min-length", type=int, default=6, help="Minimum consecutive braking frames (default: 6)")
|
| 153 |
+
args = parser.parse_args()
|
| 154 |
+
|
| 155 |
+
root = args.root.resolve()
|
| 156 |
+
states_dir = root / "states"
|
| 157 |
+
front_car_dir = root / "front_car"
|
| 158 |
+
output_dir = (root / args.output_dir).resolve()
|
| 159 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 160 |
+
merged_output_file = output_dir / "all_brake_reasons.jsonl"
|
| 161 |
+
|
| 162 |
+
state_files = sorted(states_dir.glob("*.jsonl"))
|
| 163 |
+
total_files = 0
|
| 164 |
+
total_segments = 0
|
| 165 |
+
|
| 166 |
+
with merged_output_file.open("w", encoding="utf-8") as merged_file:
|
| 167 |
+
for states_file in state_files:
|
| 168 |
+
video_id = states_file.stem
|
| 169 |
+
front_car_file = front_car_dir / f"{video_id}.jsonl"
|
| 170 |
+
|
| 171 |
+
if not front_car_file.exists():
|
| 172 |
+
continue
|
| 173 |
+
|
| 174 |
+
results = process_video(
|
| 175 |
+
video_id=video_id,
|
| 176 |
+
states_path=states_file,
|
| 177 |
+
front_car_path=front_car_file,
|
| 178 |
+
min_length=args.min_length,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
out_file = output_dir / f"{video_id}.jsonl"
|
| 182 |
+
with out_file.open("w", encoding="utf-8") as file:
|
| 183 |
+
for item in results:
|
| 184 |
+
line = json.dumps(item, ensure_ascii=False)
|
| 185 |
+
file.write(line + "\n")
|
| 186 |
+
merged_file.write(line + "\n")
|
| 187 |
+
|
| 188 |
+
total_files += 1
|
| 189 |
+
total_segments += len(results)
|
| 190 |
+
|
| 191 |
+
print(f"Processed {total_files} files; wrote {total_segments} uniquely labeled braking segments.")
|
| 192 |
+
print(f"Output directory:{output_dir}")
|
| 193 |
+
print(f"Merged output: {merged_output_file}")
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
if __name__ == "__main__":
|
| 197 |
+
main()
|
sample/video-timeseries/covla/generate.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Generate local CoVLA braking tasks and unified video/time-series records."""
|
| 3 |
+
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
sys.dont_write_bytecode = True
|
| 8 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "processing" / "common"))
|
| 9 |
+
from local_generation import main
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
if __name__ == "__main__":
|
| 13 |
+
main("covla")
|
sample/video-timeseries/covla/split_dataset.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Construct reproducible A/B/C stratified splits from local CoVLA tasks."""
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import random
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def get_label(item: dict[str, Any]) -> str:
|
| 11 |
+
label = item.get("ground_truth") or item.get("cause_option")
|
| 12 |
+
if label in {"A", "B", "C"}:
|
| 13 |
+
return str(label)
|
| 14 |
+
return "C"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def ratio_str(counts: dict[str, int]) -> str:
|
| 18 |
+
return f"A:{counts['A']} B:{counts['B']} C:{counts['C']}"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def split_stratified(
|
| 22 |
+
items: list[dict[str, Any]], test_ratio: float, seed: int
|
| 23 |
+
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, dict[str, int]]]:
|
| 24 |
+
groups: dict[str, list[dict[str, Any]]] = {"A": [], "B": [], "C": []}
|
| 25 |
+
for item in items:
|
| 26 |
+
groups[get_label(item)].append(item)
|
| 27 |
+
|
| 28 |
+
rng = random.Random(seed)
|
| 29 |
+
train: list[dict[str, Any]] = []
|
| 30 |
+
test: list[dict[str, Any]] = []
|
| 31 |
+
|
| 32 |
+
counts = {
|
| 33 |
+
"all": {"A": 0, "B": 0, "C": 0},
|
| 34 |
+
"train": {"A": 0, "B": 0, "C": 0},
|
| 35 |
+
"test": {"A": 0, "B": 0, "C": 0},
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
for cls in ("A", "B", "C"):
|
| 39 |
+
cls_items = groups[cls]
|
| 40 |
+
rng.shuffle(cls_items)
|
| 41 |
+
n = len(cls_items)
|
| 42 |
+
counts["all"][cls] = n
|
| 43 |
+
|
| 44 |
+
# 10:1 => test_ratio = 1/11
|
| 45 |
+
n_test = int(round(n * test_ratio))
|
| 46 |
+
if n > 1 and n_test == 0:
|
| 47 |
+
n_test = 1
|
| 48 |
+
if n_test >= n:
|
| 49 |
+
n_test = max(0, n - 1)
|
| 50 |
+
|
| 51 |
+
cls_test = cls_items[:n_test]
|
| 52 |
+
cls_train = cls_items[n_test:]
|
| 53 |
+
test.extend(cls_test)
|
| 54 |
+
train.extend(cls_train)
|
| 55 |
+
counts["test"][cls] = len(cls_test)
|
| 56 |
+
counts["train"][cls] = len(cls_train)
|
| 57 |
+
|
| 58 |
+
rng.shuffle(train)
|
| 59 |
+
rng.shuffle(test)
|
| 60 |
+
return train, test, counts
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def main() -> None:
|
| 64 |
+
parser = argparse.ArgumentParser(description="Split train/test by A/B/C labels at approximately 10:1")
|
| 65 |
+
parser.add_argument("--root", type=Path, default=Path("."), help="Dataset root directory")
|
| 66 |
+
parser.add_argument(
|
| 67 |
+
"--input",
|
| 68 |
+
type=Path,
|
| 69 |
+
default=Path("all_brake_reasons_final.jsonl"),
|
| 70 |
+
help="Input JSONL",
|
| 71 |
+
)
|
| 72 |
+
parser.add_argument(
|
| 73 |
+
"--train-output",
|
| 74 |
+
type=Path,
|
| 75 |
+
default=Path("all_brake_reasons_final_train.jsonl"),
|
| 76 |
+
help="Output training JSONL",
|
| 77 |
+
)
|
| 78 |
+
parser.add_argument(
|
| 79 |
+
"--test-output",
|
| 80 |
+
type=Path,
|
| 81 |
+
default=Path("all_brake_reasons_final_test.jsonl"),
|
| 82 |
+
help="Output test JSONL",
|
| 83 |
+
)
|
| 84 |
+
parser.add_argument(
|
| 85 |
+
"--stats-output",
|
| 86 |
+
type=Path,
|
| 87 |
+
default=Path("all_brake_reasons_final_split_stats.json"),
|
| 88 |
+
help="Output split statistics",
|
| 89 |
+
)
|
| 90 |
+
parser.add_argument(
|
| 91 |
+
"--seed",
|
| 92 |
+
type=int,
|
| 93 |
+
default=42,
|
| 94 |
+
help="Random seed for reproducibility",
|
| 95 |
+
)
|
| 96 |
+
args = parser.parse_args()
|
| 97 |
+
|
| 98 |
+
root = args.root.resolve()
|
| 99 |
+
input_path = (root / args.input).resolve()
|
| 100 |
+
train_path = (root / args.train_output).resolve()
|
| 101 |
+
test_path = (root / args.test_output).resolve()
|
| 102 |
+
stats_path = (root / args.stats_output).resolve()
|
| 103 |
+
|
| 104 |
+
items: list[dict[str, Any]] = []
|
| 105 |
+
with input_path.open("r", encoding="utf-8") as file:
|
| 106 |
+
for line in file:
|
| 107 |
+
line = line.strip()
|
| 108 |
+
if not line:
|
| 109 |
+
continue
|
| 110 |
+
items.append(json.loads(line))
|
| 111 |
+
|
| 112 |
+
# 10:1 -> test ratio 1/(10+1)
|
| 113 |
+
test_ratio = 1.0 / 11.0
|
| 114 |
+
train, test, counts = split_stratified(items, test_ratio=test_ratio, seed=args.seed)
|
| 115 |
+
|
| 116 |
+
with train_path.open("w", encoding="utf-8") as file:
|
| 117 |
+
for idx, item in enumerate(train):
|
| 118 |
+
out_item = dict(item)
|
| 119 |
+
out_item["task_id"] = idx
|
| 120 |
+
out_item["split"] = "train"
|
| 121 |
+
out_item["evaluation_type"] = "qa"
|
| 122 |
+
out_item["task_type"] = "COVLA_TASK"
|
| 123 |
+
out_item["sub_dimension"] = "brake_reason"
|
| 124 |
+
file.write(json.dumps(out_item, ensure_ascii=False) + "\n")
|
| 125 |
+
|
| 126 |
+
with test_path.open("w", encoding="utf-8") as file:
|
| 127 |
+
for idx, item in enumerate(test):
|
| 128 |
+
out_item = dict(item)
|
| 129 |
+
out_item["task_id"] = idx
|
| 130 |
+
out_item["split"] = "test"
|
| 131 |
+
out_item["evaluation_type"] = "qa"
|
| 132 |
+
out_item["task_type"] = "COVLA_TASK"
|
| 133 |
+
out_item["sub_dimension"] = "brake_reason"
|
| 134 |
+
file.write(json.dumps(out_item, ensure_ascii=False) + "\n")
|
| 135 |
+
|
| 136 |
+
total = len(items)
|
| 137 |
+
train_n = len(train)
|
| 138 |
+
test_n = len(test)
|
| 139 |
+
stats = {
|
| 140 |
+
"total": total,
|
| 141 |
+
"train": train_n,
|
| 142 |
+
"test": test_n,
|
| 143 |
+
"actual_train_test_ratio": round(train_n / test_n, 4) if test_n else None,
|
| 144 |
+
"class_counts": counts,
|
| 145 |
+
}
|
| 146 |
+
with stats_path.open("w", encoding="utf-8") as file:
|
| 147 |
+
json.dump(stats, file, ensure_ascii=False, indent=2)
|
| 148 |
+
|
| 149 |
+
print("Split done.")
|
| 150 |
+
print(f"total={total} train={train_n} test={test_n}")
|
| 151 |
+
print(f"all -> {ratio_str(counts['all'])}")
|
| 152 |
+
print(f"train -> {ratio_str(counts['train'])}")
|
| 153 |
+
print(f"test -> {ratio_str(counts['test'])}")
|
| 154 |
+
print(f"train file: {train_path}")
|
| 155 |
+
print(f"test file: {test_path}")
|
| 156 |
+
print(f"stats file: {stats_path}")
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
if __name__ == "__main__":
|
| 160 |
+
main()
|
sample/video-timeseries/cuhk_x_har/README.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CUHK-X HAR
|
| 2 |
+
|
| 3 |
+
**Processing code only:** source data and generated task records are not
|
| 4 |
+
included. Complete the upstream data-use agreement and follow its terms.
|
| 5 |
+
See the [shared setup instructions](../../../processing/README.md).
|
| 6 |
+
Run the commands below from the directory containing `MMTA-v1.0/`, keeping
|
| 7 |
+
`local_sources/` and `local_work/` outside the release folder.
|
| 8 |
+
|
| 9 |
+
Download [CUHK-X](https://github.com/openaiotlab/CUHK-X) from its official portal after completing the data-use agreement. Unpack the matching IMU and Skeleton action/user/trial trees. Use --file CUHK-S/HAR/ARCHIVE_NAME with download.py to download a selected archive.
|
| 10 |
+
|
| 11 |
+
```bash
|
| 12 |
+
python -B MMTA-v1.0/sample/video-timeseries/cuhk_x_har/download.py --output local_sources/cuhk_x_har --list-directory CUHK-S/HAR --accept-terms
|
| 13 |
+
python -B MMTA-v1.0/sample/video-timeseries/cuhk_x_har/generate.py \
|
| 14 |
+
--source-root local_sources/cuhk_x_har/data --output-dir local_work/cuhk_x_build
|
| 15 |
+
```
|
| 16 |
+
|
| 17 |
+
Build: Excel/CSV streams -> skeleton videos at 20 fps -> IMU/video trial matching -> up to five observations per second per device -> action prompts and split -> video/CSV conversion.
|
| 18 |
+
|
| 19 |
+
Output: `--output-dir/cuhk_x_har/cuhk_x_har.omnits.jsonl`, plus media and history CSVs. Paths are relative to that output domain directory. Use `--split train` to convert the training split where available.
|
sample/video-timeseries/cuhk_x_har/download.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Download cuhk_x_har from its official source for local processing."""
|
| 3 |
+
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "processing"))
|
| 8 |
+
from download import main
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
if __name__ == "__main__":
|
| 12 |
+
main("cuhk_x_har")
|
sample/video-timeseries/cuhk_x_har/generate.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Generate local CUHK-X records from raw IMU and skeleton trials."""
|
| 3 |
+
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
sys.dont_write_bytecode = True
|
| 8 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "processing" / "common"))
|
| 9 |
+
from local_generation import main
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
if __name__ == "__main__":
|
| 13 |
+
main("cuhk_x_har")
|
sample/video-timeseries/cuhk_x_har/images_to_video.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Adapted from the original dataset construction script."""
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import re
|
| 6 |
+
import shutil
|
| 7 |
+
import sys
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
try:
|
| 11 |
+
import cv2
|
| 12 |
+
import numpy as np
|
| 13 |
+
except ImportError:
|
| 14 |
+
print("Install opencv-python-headless to render skeleton videos.")
|
| 15 |
+
sys.exit(1)
|
| 16 |
+
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff", ".webp"}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def natural_key(path: Path):
|
| 20 |
+
parts = re.split("(\\d+)", path.name)
|
| 21 |
+
return [int(p) if p.isdigit() else p.lower() for p in parts]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def get_images_in_dir(folder: Path):
|
| 25 |
+
images = [
|
| 26 |
+
p for p in folder.iterdir() if p.is_file() and p.suffix.lower() in IMAGE_EXTS
|
| 27 |
+
]
|
| 28 |
+
images.sort(key=natural_key)
|
| 29 |
+
return images
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def find_image_folders(root: Path, only_subdir_name: str | None = None):
|
| 33 |
+
image_dirs = []
|
| 34 |
+
for folder in root.rglob("*"):
|
| 35 |
+
if folder.is_dir():
|
| 36 |
+
if only_subdir_name and folder.name != only_subdir_name:
|
| 37 |
+
continue
|
| 38 |
+
imgs = get_images_in_dir(folder)
|
| 39 |
+
if imgs:
|
| 40 |
+
image_dirs.append((folder, imgs))
|
| 41 |
+
return image_dirs
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def to_bgr(frame):
|
| 45 |
+
if len(frame.shape) == 2:
|
| 46 |
+
return cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
|
| 47 |
+
if frame.shape[2] == 4:
|
| 48 |
+
return cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
|
| 49 |
+
return frame
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def detect_split_x_auto(frame):
|
| 53 |
+
frame = to_bgr(frame)
|
| 54 |
+
height, width = frame.shape[:2]
|
| 55 |
+
if width < 4:
|
| 56 |
+
return max(1, width // 2)
|
| 57 |
+
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
| 58 |
+
col_mean = gray.mean(axis=0)
|
| 59 |
+
grad = np.abs(np.diff(col_mean))
|
| 60 |
+
left = max(1, int(width * 0.3))
|
| 61 |
+
right = min(width - 2, int(width * 0.7))
|
| 62 |
+
if right <= left:
|
| 63 |
+
return max(1, width // 2)
|
| 64 |
+
local = grad[left:right]
|
| 65 |
+
if local.size == 0:
|
| 66 |
+
return max(1, width // 2)
|
| 67 |
+
idx_local = int(np.argmax(local))
|
| 68 |
+
best_x = left + idx_local + 1
|
| 69 |
+
if local[idx_local] < 2.0:
|
| 70 |
+
return max(1, width // 2)
|
| 71 |
+
return max(1, min(width - 1, best_x))
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def get_crop_x(frame, split_mode: str, split_x: int | None):
|
| 75 |
+
width = frame.shape[1]
|
| 76 |
+
if split_mode == "none":
|
| 77 |
+
return None
|
| 78 |
+
if split_mode == "left-half":
|
| 79 |
+
return max(1, width // 2)
|
| 80 |
+
if split_mode == "manual":
|
| 81 |
+
if split_x is None:
|
| 82 |
+
raise ValueError("Manual cropping requires --split-x")
|
| 83 |
+
return max(1, min(width - 1, split_x))
|
| 84 |
+
if split_mode == "auto":
|
| 85 |
+
return detect_split_x_auto(frame)
|
| 86 |
+
raise ValueError(f"Unknown cropping mode: {split_mode}")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def apply_left_crop(frame, crop_x):
|
| 90 |
+
frame = to_bgr(frame)
|
| 91 |
+
if crop_x is None:
|
| 92 |
+
return frame
|
| 93 |
+
return frame[:, :crop_x]
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def build_output_path(output_dir: Path, fps: int, split_mode: str):
|
| 97 |
+
suffix = "" if split_mode == "none" else f"_{split_mode}"
|
| 98 |
+
return output_dir / f"{output_dir.name}_{fps}fps{suffix}.mp4"
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def resolve_output_dir(image_folder: Path, image_subdir_name: str | None):
|
| 102 |
+
if image_subdir_name and image_folder.name == image_subdir_name:
|
| 103 |
+
return image_folder.parent
|
| 104 |
+
return image_folder
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def write_video_from_images(
|
| 108 |
+
image_folder: Path,
|
| 109 |
+
images,
|
| 110 |
+
fps: int,
|
| 111 |
+
overwrite: bool,
|
| 112 |
+
split_mode: str,
|
| 113 |
+
split_x: int | None,
|
| 114 |
+
image_subdir_name: str | None,
|
| 115 |
+
source_root: Path | None = None,
|
| 116 |
+
output_root: Path | None = None,
|
| 117 |
+
):
|
| 118 |
+
output_dir = resolve_output_dir(image_folder, image_subdir_name)
|
| 119 |
+
if output_root is not None:
|
| 120 |
+
output_dir = output_root / output_dir.relative_to(source_root)
|
| 121 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 122 |
+
out_path = build_output_path(output_dir, fps, split_mode)
|
| 123 |
+
if out_path.exists() and (not overwrite):
|
| 124 |
+
print(f"[skip] Already exists: {out_path}")
|
| 125 |
+
return True
|
| 126 |
+
first = cv2.imread(str(images[0]), cv2.IMREAD_UNCHANGED)
|
| 127 |
+
if first is None:
|
| 128 |
+
print(f"[warn] Cannot read first frame: {images[0]}")
|
| 129 |
+
return False
|
| 130 |
+
first = to_bgr(first)
|
| 131 |
+
crop_x = get_crop_x(first, split_mode, split_x)
|
| 132 |
+
first = apply_left_crop(first, crop_x)
|
| 133 |
+
height, width = first.shape[:2]
|
| 134 |
+
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
| 135 |
+
writer = cv2.VideoWriter(str(out_path), fourcc, fps, (width, height))
|
| 136 |
+
if not writer.isOpened():
|
| 137 |
+
print(f"[error] Cannot create video: {out_path}")
|
| 138 |
+
return False
|
| 139 |
+
written = 0
|
| 140 |
+
for img_path in images:
|
| 141 |
+
frame = cv2.imread(str(img_path), cv2.IMREAD_UNCHANGED)
|
| 142 |
+
if frame is None:
|
| 143 |
+
print(f"[warn] Skipping unreadable image: {img_path}")
|
| 144 |
+
continue
|
| 145 |
+
frame = to_bgr(frame)
|
| 146 |
+
frame = apply_left_crop(frame, crop_x)
|
| 147 |
+
if frame.shape[1] != width or frame.shape[0] != height:
|
| 148 |
+
frame = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA)
|
| 149 |
+
writer.write(frame)
|
| 150 |
+
written += 1
|
| 151 |
+
writer.release()
|
| 152 |
+
if written == 0:
|
| 153 |
+
print(f"[error] No frames written: {image_folder}")
|
| 154 |
+
return False
|
| 155 |
+
crop_msg = f", crop_x={crop_x}" if crop_x is not None else ""
|
| 156 |
+
print(f"[ok] {image_folder} -> {out_path} (frames={written}, fps={fps}{crop_msg})")
|
| 157 |
+
return True
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def main():
|
| 161 |
+
parser = argparse.ArgumentParser(
|
| 162 |
+
description="Render ordered skeleton images at a fixed frame rate."
|
| 163 |
+
)
|
| 164 |
+
parser.add_argument("root", help="Skeleton source root.")
|
| 165 |
+
parser.add_argument(
|
| 166 |
+
"--output-root",
|
| 167 |
+
type=Path,
|
| 168 |
+
help="Preserve trial paths in a separate output tree.",
|
| 169 |
+
)
|
| 170 |
+
parser.add_argument("--fps", type=int, default=20, help="Output frame rate.")
|
| 171 |
+
parser.add_argument(
|
| 172 |
+
"--image-subdir-name",
|
| 173 |
+
default="visualizations",
|
| 174 |
+
help="Image folder stored inside each trial.",
|
| 175 |
+
)
|
| 176 |
+
parser.add_argument(
|
| 177 |
+
"--only-image-subdir",
|
| 178 |
+
action="store_true",
|
| 179 |
+
help="Only process the named image subdirectory.",
|
| 180 |
+
)
|
| 181 |
+
parser.add_argument(
|
| 182 |
+
"--split-mode",
|
| 183 |
+
choices=["left-half", "auto", "manual", "none"],
|
| 184 |
+
default="left-half",
|
| 185 |
+
help="Image cropping mode.",
|
| 186 |
+
)
|
| 187 |
+
parser.add_argument(
|
| 188 |
+
"--split-x", type=int, default=None, help="Manual crop boundary."
|
| 189 |
+
)
|
| 190 |
+
parser.add_argument(
|
| 191 |
+
"--overwrite", action="store_true", help="Replace existing output videos."
|
| 192 |
+
)
|
| 193 |
+
args = parser.parse_args()
|
| 194 |
+
root = Path(args.root).resolve()
|
| 195 |
+
if not root.exists() or not root.is_dir():
|
| 196 |
+
print(f"Input directory not found: {root}")
|
| 197 |
+
sys.exit(1)
|
| 198 |
+
if args.fps < 1:
|
| 199 |
+
parser.error("--fps must be positive")
|
| 200 |
+
output_root = args.output_root.resolve() if args.output_root else None
|
| 201 |
+
if output_root is not None and output_root.is_relative_to(root):
|
| 202 |
+
parser.error("--output-root must be outside the skeleton input tree")
|
| 203 |
+
subdir_filter = args.image_subdir_name if args.only_image_subdir else None
|
| 204 |
+
image_folders = find_image_folders(root, only_subdir_name=subdir_filter)
|
| 205 |
+
print(f"Found {len(image_folders)} image directories")
|
| 206 |
+
ok_count = 0
|
| 207 |
+
for image_folder, images in image_folders:
|
| 208 |
+
if write_video_from_images(
|
| 209 |
+
image_folder,
|
| 210 |
+
images,
|
| 211 |
+
args.fps,
|
| 212 |
+
args.overwrite,
|
| 213 |
+
args.split_mode,
|
| 214 |
+
args.split_x,
|
| 215 |
+
args.image_subdir_name,
|
| 216 |
+
root,
|
| 217 |
+
output_root,
|
| 218 |
+
):
|
| 219 |
+
ok_count += 1
|
| 220 |
+
if output_root is not None:
|
| 221 |
+
for path in sorted(root.rglob("*")):
|
| 222 |
+
if not path.is_file() or path.suffix.lower() not in {
|
| 223 |
+
".mp4",
|
| 224 |
+
".avi",
|
| 225 |
+
".mov",
|
| 226 |
+
".mkv",
|
| 227 |
+
}:
|
| 228 |
+
continue
|
| 229 |
+
target = output_root / path.relative_to(root)
|
| 230 |
+
if not target.parent.exists() or not any(target.parent.glob("*.mp4")):
|
| 231 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 232 |
+
shutil.copy2(path, target)
|
| 233 |
+
print(f"Completed {ok_count}/{len(image_folders)} image directories")
|
| 234 |
+
if ok_count < len(image_folders):
|
| 235 |
+
raise RuntimeError("Some skeleton videos could not be generated")
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
if __name__ == "__main__":
|
| 239 |
+
main()
|
sample/video-timeseries/cuhk_x_har/imu_skeleton_to_jsonl.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Adapted from the original dataset construction script."""
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
TIME_COL = "time"
|
| 12 |
+
DEVICE_COL = "device_name"
|
| 13 |
+
ACC_X_COL = "acc_x_g"
|
| 14 |
+
ACC_Y_COL = "acc_y_g"
|
| 15 |
+
ACC_Z_COL = "acc_z_g"
|
| 16 |
+
GYRO_X_COL = "gyro_x_dps"
|
| 17 |
+
GYRO_Y_COL = "gyro_y_dps"
|
| 18 |
+
GYRO_Z_COL = "gyro_z_dps"
|
| 19 |
+
SOURCE_COLUMN_ALIASES = {
|
| 20 |
+
"\u65f6\u95f4": TIME_COL,
|
| 21 |
+
"\u8bbe\u5907\u540d\u79f0": DEVICE_COL,
|
| 22 |
+
"\u52a0\u901f\u5ea6X(g)": ACC_X_COL,
|
| 23 |
+
"\u52a0\u901f\u5ea6Y(g)": ACC_Y_COL,
|
| 24 |
+
"\u52a0\u901f\u5ea6Z(g)": ACC_Z_COL,
|
| 25 |
+
"\u89d2\u901f\u5ea6X(\u00b0/s)": GYRO_X_COL,
|
| 26 |
+
"\u89d2\u901f\u5ea6Y(\u00b0/s)": GYRO_Y_COL,
|
| 27 |
+
"\u89d2\u901f\u5ea6Z(\u00b0/s)": GYRO_Z_COL,
|
| 28 |
+
}
|
| 29 |
+
REQUIRED_COLS = [
|
| 30 |
+
TIME_COL,
|
| 31 |
+
DEVICE_COL,
|
| 32 |
+
ACC_X_COL,
|
| 33 |
+
ACC_Y_COL,
|
| 34 |
+
ACC_Z_COL,
|
| 35 |
+
GYRO_X_COL,
|
| 36 |
+
GYRO_Y_COL,
|
| 37 |
+
GYRO_Z_COL,
|
| 38 |
+
]
|
| 39 |
+
VIDEO_SUFFIXES = {".mp4", ".avi", ".mov", ".mkv", ".MP4", ".AVI", ".MOV", ".MKV"}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def parse_args() -> argparse.Namespace:
|
| 43 |
+
parser = argparse.ArgumentParser(
|
| 44 |
+
description="Convert aligned IMU + Skeleton data to JSONL"
|
| 45 |
+
)
|
| 46 |
+
parser.add_argument("--imu-root", type=Path, default=Path("IMU"))
|
| 47 |
+
parser.add_argument("--skeleton-root", type=Path, default=Path("Skeleton"))
|
| 48 |
+
parser.add_argument(
|
| 49 |
+
"--output", type=Path, default=Path("imu_skeleton_aligned.jsonl")
|
| 50 |
+
)
|
| 51 |
+
parser.add_argument("--max-records", type=int, default=0)
|
| 52 |
+
parser.add_argument("--relative-video-path", action="store_true")
|
| 53 |
+
return parser.parse_args()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def clean_columns(df: pd.DataFrame) -> pd.DataFrame:
|
| 57 |
+
df.columns = [str(col).strip().lstrip("\ufeff") for col in df.columns]
|
| 58 |
+
return df.rename(columns=SOURCE_COLUMN_ALIASES)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def read_imu_pair(csv_files: list[Path]) -> pd.DataFrame:
|
| 62 |
+
frames = []
|
| 63 |
+
for csv_file in csv_files:
|
| 64 |
+
frame = pd.read_csv(csv_file)
|
| 65 |
+
frame = clean_columns(frame)
|
| 66 |
+
missing_cols = [col for col in REQUIRED_COLS if col not in frame.columns]
|
| 67 |
+
if missing_cols:
|
| 68 |
+
raise ValueError(f"Missing columns in {csv_file}: {missing_cols}")
|
| 69 |
+
frames.append(frame[REQUIRED_COLS].copy())
|
| 70 |
+
merged = pd.concat(frames, ignore_index=True)
|
| 71 |
+
merged[TIME_COL] = pd.to_datetime(merged[TIME_COL], errors="coerce")
|
| 72 |
+
merged = (
|
| 73 |
+
merged.dropna(subset=[TIME_COL]).sort_values(TIME_COL).reset_index(drop=True)
|
| 74 |
+
)
|
| 75 |
+
merged[DEVICE_COL] = (
|
| 76 |
+
merged[DEVICE_COL]
|
| 77 |
+
.astype(str)
|
| 78 |
+
.str.split("(", n=1, regex=False)
|
| 79 |
+
.str[0]
|
| 80 |
+
.str.strip()
|
| 81 |
+
)
|
| 82 |
+
for col in [ACC_X_COL, ACC_Y_COL, ACC_Z_COL, GYRO_X_COL, GYRO_Y_COL, GYRO_Z_COL]:
|
| 83 |
+
merged[col] = pd.to_numeric(merged[col], errors="coerce")
|
| 84 |
+
merged = merged.dropna(
|
| 85 |
+
subset=[ACC_X_COL, ACC_Y_COL, ACC_Z_COL, GYRO_X_COL, GYRO_Y_COL, GYRO_Z_COL]
|
| 86 |
+
)
|
| 87 |
+
return merged
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def sample_group(group_df: pd.DataFrame, target_count: int = 5) -> pd.DataFrame:
|
| 91 |
+
n = len(group_df)
|
| 92 |
+
if n <= target_count:
|
| 93 |
+
return group_df
|
| 94 |
+
idx = np.linspace(0, n - 1, target_count, dtype=int)
|
| 95 |
+
return group_df.iloc[idx]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def downsample_per_second_per_device(df: pd.DataFrame) -> pd.DataFrame:
|
| 99 |
+
df = df.copy()
|
| 100 |
+
df["_second"] = df[TIME_COL].dt.floor("s")
|
| 101 |
+
sampled_parts = []
|
| 102 |
+
for _, group_df in df.groupby(["_second", DEVICE_COL], sort=True):
|
| 103 |
+
sampled_parts.append(sample_group(group_df.sort_values(TIME_COL)))
|
| 104 |
+
if sampled_parts:
|
| 105 |
+
sampled = pd.concat(sampled_parts, ignore_index=True)
|
| 106 |
+
else:
|
| 107 |
+
sampled = df.iloc[0:0].copy()
|
| 108 |
+
sampled = sampled.sort_values([TIME_COL, DEVICE_COL]).reset_index(drop=True)
|
| 109 |
+
return sampled
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def to_output_record(
|
| 113 |
+
video_path: Path, sampled_df: pd.DataFrame, relative_root: Path | None
|
| 114 |
+
) -> dict:
|
| 115 |
+
if relative_root is None:
|
| 116 |
+
video_path_str = str(video_path.resolve())
|
| 117 |
+
else:
|
| 118 |
+
video_path_str = os.path.relpath(video_path.resolve(), relative_root.resolve())
|
| 119 |
+
time_strings = (
|
| 120 |
+
sampled_df[TIME_COL].dt.strftime("%Y-%m-%d %H:%M:%S.%f").str[:-3].tolist()
|
| 121 |
+
)
|
| 122 |
+
return {
|
| 123 |
+
"video_path": video_path_str,
|
| 124 |
+
"downsampled_data": {
|
| 125 |
+
"time": time_strings,
|
| 126 |
+
"device_name": sampled_df[DEVICE_COL].tolist(),
|
| 127 |
+
"acc_x_g": sampled_df[ACC_X_COL].tolist(),
|
| 128 |
+
"acc_y_g": sampled_df[ACC_Y_COL].tolist(),
|
| 129 |
+
"acc_z_g": sampled_df[ACC_Z_COL].tolist(),
|
| 130 |
+
"gyro_x_dps": sampled_df[GYRO_X_COL].tolist(),
|
| 131 |
+
"gyro_y_dps": sampled_df[GYRO_Y_COL].tolist(),
|
| 132 |
+
"gyro_z_dps": sampled_df[GYRO_Z_COL].tolist(),
|
| 133 |
+
},
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def get_video_file(skeleton_trial_dir: Path) -> Path | None:
|
| 138 |
+
if not skeleton_trial_dir.exists() or not skeleton_trial_dir.is_dir():
|
| 139 |
+
return None
|
| 140 |
+
video_files = sorted(
|
| 141 |
+
[
|
| 142 |
+
p
|
| 143 |
+
for p in skeleton_trial_dir.iterdir()
|
| 144 |
+
if p.is_file() and p.suffix in VIDEO_SUFFIXES
|
| 145 |
+
]
|
| 146 |
+
)
|
| 147 |
+
if not video_files:
|
| 148 |
+
return None
|
| 149 |
+
return video_files[0]
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def build_jsonl(
|
| 153 |
+
imu_root: Path,
|
| 154 |
+
skeleton_root: Path,
|
| 155 |
+
output: Path,
|
| 156 |
+
max_records: int,
|
| 157 |
+
relative_video_path: bool,
|
| 158 |
+
) -> None:
|
| 159 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 160 |
+
total_written = 0
|
| 161 |
+
skipped = 0
|
| 162 |
+
relative_root = output.parent if relative_video_path else None
|
| 163 |
+
with output.open("w", encoding="utf-8") as f_out:
|
| 164 |
+
for action_dir in sorted([p for p in imu_root.iterdir() if p.is_dir()]):
|
| 165 |
+
for user_dir in sorted([p for p in action_dir.iterdir() if p.is_dir()]):
|
| 166 |
+
for trial_dir in sorted([p for p in user_dir.iterdir() if p.is_dir()]):
|
| 167 |
+
csv_files = sorted(
|
| 168 |
+
[p for p in trial_dir.glob("*.csv") if p.is_file()]
|
| 169 |
+
)
|
| 170 |
+
if len(csv_files) < 2:
|
| 171 |
+
skipped += 1
|
| 172 |
+
continue
|
| 173 |
+
csv_files = csv_files[:2]
|
| 174 |
+
skeleton_trial_dir = (
|
| 175 |
+
skeleton_root / action_dir.name / user_dir.name / trial_dir.name
|
| 176 |
+
)
|
| 177 |
+
video_file = get_video_file(skeleton_trial_dir)
|
| 178 |
+
if video_file is None:
|
| 179 |
+
skipped += 1
|
| 180 |
+
continue
|
| 181 |
+
try:
|
| 182 |
+
merged_df = read_imu_pair(csv_files)
|
| 183 |
+
sampled_df = downsample_per_second_per_device(merged_df)
|
| 184 |
+
if sampled_df.empty:
|
| 185 |
+
raise ValueError("No valid IMU observations")
|
| 186 |
+
except Exception as exc:
|
| 187 |
+
print(f"[skip] {trial_dir} -> {exc}")
|
| 188 |
+
skipped += 1
|
| 189 |
+
continue
|
| 190 |
+
record = to_output_record(video_file, sampled_df, relative_root)
|
| 191 |
+
f_out.write(
|
| 192 |
+
json.dumps(record, ensure_ascii=False, allow_nan=False) + "\n"
|
| 193 |
+
)
|
| 194 |
+
total_written += 1
|
| 195 |
+
if max_records > 0 and total_written >= max_records:
|
| 196 |
+
print(
|
| 197 |
+
f"Done. written={total_written}, skipped={skipped}, output={output}"
|
| 198 |
+
)
|
| 199 |
+
return
|
| 200 |
+
print(f"Done. written={total_written}, skipped={skipped}, output={output}")
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def main() -> None:
|
| 204 |
+
args = parse_args()
|
| 205 |
+
build_jsonl(
|
| 206 |
+
imu_root=args.imu_root,
|
| 207 |
+
skeleton_root=args.skeleton_root,
|
| 208 |
+
output=args.output,
|
| 209 |
+
max_records=args.max_records,
|
| 210 |
+
relative_video_path=args.relative_video_path,
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
if __name__ == "__main__":
|
| 215 |
+
main()
|
sample/video-timeseries/cuhk_x_har/prepare.py
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Build CUHK-X action prompts from an existing aligned IMU/skeleton JSONL."""
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import random
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
DATASET_SOURCE = "https://github.com/openaiotlab/CUHK-X"
|
| 15 |
+
|
| 16 |
+
DEVICE_DESC: dict[str, str] = {
|
| 17 |
+
"WTLA": "Wearable tracker on Left Arm",
|
| 18 |
+
"WTRA": "Wearable tracker on Right Arm",
|
| 19 |
+
"WTC": "Wearable tracker on Chest",
|
| 20 |
+
"WTLL": "Wearable tracker on Left Leg",
|
| 21 |
+
"WTRL": "Wearable tracker on Right Leg",
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
DEVICE_TO_ID: dict[str, int] = {
|
| 25 |
+
"WTC": 0,
|
| 26 |
+
"WTLA": 1,
|
| 27 |
+
"WTLL": 2,
|
| 28 |
+
"WTRA": 3,
|
| 29 |
+
"WTRL": 4,
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
FIELD_DESC: dict[str, str] = {
|
| 33 |
+
"time_s": "Relative timestamp in seconds from the first sampled IMU record.",
|
| 34 |
+
"device_id": "Numeric device identifier. See <device_definitions> for the code mapping.",
|
| 35 |
+
"acc_x_g": "Acceleration on X axis in g.",
|
| 36 |
+
"acc_y_g": "Acceleration on Y axis in g.",
|
| 37 |
+
"acc_z_g": "Acceleration on Z axis in g.",
|
| 38 |
+
"gyro_x_dps": "Angular velocity on X axis in degrees/second.",
|
| 39 |
+
"gyro_y_dps": "Angular velocity on Y axis in degrees/second.",
|
| 40 |
+
"gyro_z_dps": "Angular velocity on Z axis in degrees/second.",
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def parse_args() -> argparse.Namespace:
|
| 45 |
+
parser = argparse.ArgumentParser(
|
| 46 |
+
description="Build prompt-based action-classification JSONL for CUHK-X HAR"
|
| 47 |
+
)
|
| 48 |
+
parser.add_argument(
|
| 49 |
+
"--root",
|
| 50 |
+
type=Path,
|
| 51 |
+
default=Path("."),
|
| 52 |
+
help="Workspace/data root",
|
| 53 |
+
)
|
| 54 |
+
parser.add_argument(
|
| 55 |
+
"--input",
|
| 56 |
+
type=Path,
|
| 57 |
+
default=Path("imu_skeleton_aligned.jsonl"),
|
| 58 |
+
help="Input aligned jsonl from imu_skeleton_to_jsonl.py",
|
| 59 |
+
)
|
| 60 |
+
parser.add_argument(
|
| 61 |
+
"--skeleton-root",
|
| 62 |
+
type=Path,
|
| 63 |
+
default=Path("Skeleton"),
|
| 64 |
+
help="Skeleton root for discovering action space",
|
| 65 |
+
)
|
| 66 |
+
parser.add_argument(
|
| 67 |
+
"--train-output",
|
| 68 |
+
type=Path,
|
| 69 |
+
default=Path("imu_action_classification_prompt_train.jsonl"),
|
| 70 |
+
help="Output train jsonl",
|
| 71 |
+
)
|
| 72 |
+
parser.add_argument(
|
| 73 |
+
"--test-output",
|
| 74 |
+
type=Path,
|
| 75 |
+
default=Path("imu_action_classification_prompt_test.jsonl"),
|
| 76 |
+
help="Output test jsonl",
|
| 77 |
+
)
|
| 78 |
+
parser.add_argument(
|
| 79 |
+
"--train-sample-output",
|
| 80 |
+
type=Path,
|
| 81 |
+
default=Path("imu_action_classification_prompt_train.sample.jsonl"),
|
| 82 |
+
help="Sample output for train split",
|
| 83 |
+
)
|
| 84 |
+
parser.add_argument(
|
| 85 |
+
"--test-sample-output",
|
| 86 |
+
type=Path,
|
| 87 |
+
default=Path("imu_action_classification_prompt_test.sample.jsonl"),
|
| 88 |
+
help="Sample output for test split",
|
| 89 |
+
)
|
| 90 |
+
parser.add_argument(
|
| 91 |
+
"--sample-size",
|
| 92 |
+
type=int,
|
| 93 |
+
default=8,
|
| 94 |
+
help="Number of records to save into each sample output",
|
| 95 |
+
)
|
| 96 |
+
parser.add_argument(
|
| 97 |
+
"--max-records",
|
| 98 |
+
type=int,
|
| 99 |
+
default=0,
|
| 100 |
+
help="If > 0, only process first N records",
|
| 101 |
+
)
|
| 102 |
+
parser.add_argument(
|
| 103 |
+
"--seed",
|
| 104 |
+
type=int,
|
| 105 |
+
default=42,
|
| 106 |
+
help="Random seed for split reproducibility",
|
| 107 |
+
)
|
| 108 |
+
return parser.parse_args()
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def choose_decimals_by_avg_diff(values: list[float]) -> int:
|
| 112 |
+
if len(values) == 0:
|
| 113 |
+
return 0
|
| 114 |
+
if len(values) > 1:
|
| 115 |
+
diffs = [abs(values[i + 1] - values[i]) for i in range(len(values) - 1)]
|
| 116 |
+
avg_diff = float(np.mean(diffs)) if diffs else 0.0
|
| 117 |
+
else:
|
| 118 |
+
avg_diff = abs(values[0]) * 0.01 if values[0] != 0 else 1.0
|
| 119 |
+
|
| 120 |
+
if avg_diff == 0:
|
| 121 |
+
return 0
|
| 122 |
+
if avg_diff >= 10:
|
| 123 |
+
return 0
|
| 124 |
+
if avg_diff >= 1:
|
| 125 |
+
return 1
|
| 126 |
+
if avg_diff >= 0.1:
|
| 127 |
+
return 2
|
| 128 |
+
if avg_diff >= 0.01:
|
| 129 |
+
return 3
|
| 130 |
+
if avg_diff >= 0.001:
|
| 131 |
+
return 4
|
| 132 |
+
return 5
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def discover_actions(skeleton_root: Path) -> list[dict[str, Any]]:
|
| 136 |
+
actions: list[dict[str, Any]] = []
|
| 137 |
+
for action_dir in skeleton_root.iterdir():
|
| 138 |
+
if not action_dir.is_dir():
|
| 139 |
+
continue
|
| 140 |
+
parts = action_dir.name.split("_", 1)
|
| 141 |
+
if len(parts) != 2:
|
| 142 |
+
continue
|
| 143 |
+
try:
|
| 144 |
+
action_id = int(parts[0])
|
| 145 |
+
except ValueError:
|
| 146 |
+
continue
|
| 147 |
+
action_name = parts[1]
|
| 148 |
+
actions.append(
|
| 149 |
+
{
|
| 150 |
+
"action_id": action_id,
|
| 151 |
+
"action_name": action_name,
|
| 152 |
+
"action_dir": action_dir.name,
|
| 153 |
+
}
|
| 154 |
+
)
|
| 155 |
+
actions.sort(key=lambda x: x["action_id"])
|
| 156 |
+
return actions
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def parse_action_from_video_path(video_path: str) -> tuple[int, str, str]:
|
| 160 |
+
p = Path(video_path)
|
| 161 |
+
parts = p.parts
|
| 162 |
+
if "Skeleton" not in parts:
|
| 163 |
+
raise ValueError(f"Cannot locate 'Skeleton' in video_path: {video_path}")
|
| 164 |
+
skeleton_idx = parts.index("Skeleton")
|
| 165 |
+
if skeleton_idx + 1 >= len(parts):
|
| 166 |
+
raise ValueError(f"Cannot locate action directory in video_path: {video_path}")
|
| 167 |
+
action_dir = parts[skeleton_idx + 1]
|
| 168 |
+
pair = action_dir.split("_", 1)
|
| 169 |
+
if len(pair) != 2:
|
| 170 |
+
raise ValueError(f"Invalid action directory format: {action_dir}")
|
| 171 |
+
action_id = int(pair[0])
|
| 172 |
+
action_name = pair[1]
|
| 173 |
+
return action_id, action_name, action_dir
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def fmt_val(v: Any, decimals: int) -> str:
|
| 177 |
+
if v is None:
|
| 178 |
+
return "null"
|
| 179 |
+
try:
|
| 180 |
+
return f"{float(v):.{decimals}f}"
|
| 181 |
+
except (TypeError, ValueError):
|
| 182 |
+
return str(v)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def parse_time_value(value: Any) -> float | datetime | None:
|
| 186 |
+
if value is None:
|
| 187 |
+
return None
|
| 188 |
+
if isinstance(value, (int, float)):
|
| 189 |
+
return float(value)
|
| 190 |
+
|
| 191 |
+
text = str(value).strip()
|
| 192 |
+
if not text:
|
| 193 |
+
return None
|
| 194 |
+
|
| 195 |
+
try:
|
| 196 |
+
return float(text)
|
| 197 |
+
except ValueError:
|
| 198 |
+
pass
|
| 199 |
+
|
| 200 |
+
candidates = [text]
|
| 201 |
+
if text.endswith("Z"):
|
| 202 |
+
candidates.append(text[:-1] + "+00:00")
|
| 203 |
+
for candidate in candidates:
|
| 204 |
+
try:
|
| 205 |
+
return datetime.fromisoformat(candidate)
|
| 206 |
+
except ValueError:
|
| 207 |
+
continue
|
| 208 |
+
return None
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def build_relative_time_seconds(times: list[Any], size: int) -> list[float]:
|
| 212 |
+
parsed = [parse_time_value(times[i]) if i < len(times) else None for i in range(size)]
|
| 213 |
+
first = next((value for value in parsed if value is not None), None)
|
| 214 |
+
if first is None:
|
| 215 |
+
return [float(i) for i in range(size)]
|
| 216 |
+
|
| 217 |
+
rel_times: list[float] = []
|
| 218 |
+
for i, value in enumerate(parsed):
|
| 219 |
+
if value is None:
|
| 220 |
+
rel_times.append(float(i))
|
| 221 |
+
elif isinstance(first, datetime) and isinstance(value, datetime):
|
| 222 |
+
rel_times.append((value - first).total_seconds())
|
| 223 |
+
elif isinstance(first, (int, float)) and isinstance(value, (int, float)):
|
| 224 |
+
rel_times.append(float(value) - float(first))
|
| 225 |
+
else:
|
| 226 |
+
rel_times.append(float(i))
|
| 227 |
+
return rel_times
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def build_timeseries_lines(
|
| 231 |
+
downsampled_data: dict[str, Any],
|
| 232 |
+
) -> tuple[list[str], dict[str, Any], dict[str, int]]:
|
| 233 |
+
times = downsampled_data.get("time") or []
|
| 234 |
+
devices = downsampled_data.get("device_name") or []
|
| 235 |
+
acc_x = downsampled_data.get("acc_x_g") or []
|
| 236 |
+
acc_y = downsampled_data.get("acc_y_g") or []
|
| 237 |
+
acc_z = downsampled_data.get("acc_z_g") or []
|
| 238 |
+
gyro_x = downsampled_data.get("gyro_x_dps") or []
|
| 239 |
+
gyro_y = downsampled_data.get("gyro_y_dps") or []
|
| 240 |
+
gyro_z = downsampled_data.get("gyro_z_dps") or []
|
| 241 |
+
|
| 242 |
+
dec_acc_x = choose_decimals_by_avg_diff([float(v) for v in acc_x if v is not None])
|
| 243 |
+
dec_acc_y = choose_decimals_by_avg_diff([float(v) for v in acc_y if v is not None])
|
| 244 |
+
dec_acc_z = choose_decimals_by_avg_diff([float(v) for v in acc_z if v is not None])
|
| 245 |
+
dec_gyro_x = choose_decimals_by_avg_diff([float(v) for v in gyro_x if v is not None])
|
| 246 |
+
dec_gyro_y = choose_decimals_by_avg_diff([float(v) for v in gyro_y if v is not None])
|
| 247 |
+
dec_gyro_z = choose_decimals_by_avg_diff([float(v) for v in gyro_z if v is not None])
|
| 248 |
+
|
| 249 |
+
precision = {
|
| 250 |
+
"acc_x_g": dec_acc_x,
|
| 251 |
+
"acc_y_g": dec_acc_y,
|
| 252 |
+
"acc_z_g": dec_acc_z,
|
| 253 |
+
"gyro_x_dps": dec_gyro_x,
|
| 254 |
+
"gyro_y_dps": dec_gyro_y,
|
| 255 |
+
"gyro_z_dps": dec_gyro_z,
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
size = min(
|
| 259 |
+
len(times),
|
| 260 |
+
len(devices),
|
| 261 |
+
len(acc_x),
|
| 262 |
+
len(acc_y),
|
| 263 |
+
len(acc_z),
|
| 264 |
+
len(gyro_x),
|
| 265 |
+
len(gyro_y),
|
| 266 |
+
len(gyro_z),
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
time_s = build_relative_time_seconds(times, size)
|
| 270 |
+
lines: list[str] = []
|
| 271 |
+
unique_devices: set[str] = set()
|
| 272 |
+
for i in range(size):
|
| 273 |
+
d = str(devices[i])
|
| 274 |
+
unique_devices.add(d)
|
| 275 |
+
device_id = DEVICE_TO_ID.get(d, -1)
|
| 276 |
+
t_label = fmt_val(time_s[i], 3)
|
| 277 |
+
lines.append(
|
| 278 |
+
f"{t_label}: "
|
| 279 |
+
f"device_id={device_id}, "
|
| 280 |
+
f"acc_x_g={fmt_val(acc_x[i], dec_acc_x)}, "
|
| 281 |
+
f"acc_y_g={fmt_val(acc_y[i], dec_acc_y)}, "
|
| 282 |
+
f"acc_z_g={fmt_val(acc_z[i], dec_acc_z)}, "
|
| 283 |
+
f"gyro_x_dps={fmt_val(gyro_x[i], dec_gyro_x)}, "
|
| 284 |
+
f"gyro_y_dps={fmt_val(gyro_y[i], dec_gyro_y)}, "
|
| 285 |
+
f"gyro_z_dps={fmt_val(gyro_z[i], dec_gyro_z)}"
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
stats = {
|
| 289 |
+
"num_samples": size,
|
| 290 |
+
"num_devices": len(unique_devices),
|
| 291 |
+
"devices": sorted(unique_devices),
|
| 292 |
+
"device_to_id": DEVICE_TO_ID,
|
| 293 |
+
}
|
| 294 |
+
return lines, stats, precision
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def build_prompt(
|
| 298 |
+
video_path: str,
|
| 299 |
+
downsampled_data: dict[str, Any],
|
| 300 |
+
action_space: list[dict[str, Any]],
|
| 301 |
+
) -> str:
|
| 302 |
+
field_block = "\n".join([f"- {k}: {v}" for k, v in FIELD_DESC.items()])
|
| 303 |
+
device_block = "\n".join(
|
| 304 |
+
[
|
| 305 |
+
f"- device_id={DEVICE_TO_ID[k]}: {k} - {DEVICE_DESC[k]}"
|
| 306 |
+
for k in sorted(DEVICE_DESC, key=lambda name: DEVICE_TO_ID[name])
|
| 307 |
+
]
|
| 308 |
+
)
|
| 309 |
+
action_block = "\n".join(
|
| 310 |
+
[f"- {x['action_id']}: {x['action_name']}" for x in action_space]
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
ts_lines, _, _ = build_timeseries_lines(downsampled_data)
|
| 314 |
+
timeseries_block = "\n".join(ts_lines)
|
| 315 |
+
if not timeseries_block:
|
| 316 |
+
timeseries_block = "(empty)"
|
| 317 |
+
|
| 318 |
+
prompt = f"""\
|
| 319 |
+
You are solving an action-classification task for CUHK-X multimodal HAR.
|
| 320 |
+
|
| 321 |
+
The video segment and downsampled IMU samples belong to the same action instance.
|
| 322 |
+
|
| 323 |
+
<field_definitions>
|
| 324 |
+
{field_block}
|
| 325 |
+
</field_definitions>
|
| 326 |
+
|
| 327 |
+
<device_definitions>
|
| 328 |
+
{device_block}
|
| 329 |
+
</device_definitions>
|
| 330 |
+
|
| 331 |
+
<action_space>
|
| 332 |
+
{action_block}
|
| 333 |
+
</action_space>
|
| 334 |
+
|
| 335 |
+
<timeseries>
|
| 336 |
+
Format: time_s: device_id=..., acc_x_g=..., acc_y_g=..., acc_z_g=..., gyro_x_dps=..., gyro_y_dps=..., gyro_z_dps=...
|
| 337 |
+
{timeseries_block}
|
| 338 |
+
</timeseries>
|
| 339 |
+
|
| 340 |
+
Question: Which action category (action_id) best matches this segment?
|
| 341 |
+
Return only one integer action_id from the action_space.
|
| 342 |
+
"""
|
| 343 |
+
|
| 344 |
+
return "\n".join(ln.rstrip() for ln in prompt.splitlines()).strip()
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def build_question() -> str:
|
| 348 |
+
return "Which action category (action_id) best matches this video-sensor segment?"
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def build_options(action_space: list[dict[str, Any]]) -> dict[str, str]:
|
| 352 |
+
return {str(x["action_id"]): x["action_name"] for x in action_space}
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def stratified_split_by_action(
|
| 356 |
+
records: list[dict[str, Any]],
|
| 357 |
+
train_ratio: float,
|
| 358 |
+
seed: int,
|
| 359 |
+
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
| 360 |
+
rng = random.Random(seed)
|
| 361 |
+
groups: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
| 362 |
+
for item in records:
|
| 363 |
+
groups[str(item.get("ground_truth"))].append(item)
|
| 364 |
+
|
| 365 |
+
train_items: list[dict[str, Any]] = []
|
| 366 |
+
test_items: list[dict[str, Any]] = []
|
| 367 |
+
|
| 368 |
+
for label in sorted(groups.keys(), key=lambda x: int(x)):
|
| 369 |
+
bucket = groups[label]
|
| 370 |
+
rng.shuffle(bucket)
|
| 371 |
+
n = len(bucket)
|
| 372 |
+
train_n = int(n * train_ratio)
|
| 373 |
+
if n >= 2:
|
| 374 |
+
train_n = min(max(train_n, 1), n - 1)
|
| 375 |
+
train_bucket = bucket[:train_n]
|
| 376 |
+
test_bucket = bucket[train_n:]
|
| 377 |
+
|
| 378 |
+
for x in train_bucket:
|
| 379 |
+
x["split"] = "train"
|
| 380 |
+
for x in test_bucket:
|
| 381 |
+
x["split"] = "test"
|
| 382 |
+
|
| 383 |
+
train_items.extend(train_bucket)
|
| 384 |
+
test_items.extend(test_bucket)
|
| 385 |
+
|
| 386 |
+
rng.shuffle(train_items)
|
| 387 |
+
rng.shuffle(test_items)
|
| 388 |
+
return train_items, test_items
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def main() -> None:
|
| 392 |
+
args = parse_args()
|
| 393 |
+
root = args.root.resolve()
|
| 394 |
+
input_path = (root / args.input).resolve()
|
| 395 |
+
skeleton_root = (root / args.skeleton_root).resolve()
|
| 396 |
+
train_output_path = (root / args.train_output).resolve()
|
| 397 |
+
test_output_path = (root / args.test_output).resolve()
|
| 398 |
+
train_sample_output_path = (root / args.train_sample_output).resolve()
|
| 399 |
+
test_sample_output_path = (root / args.test_sample_output).resolve()
|
| 400 |
+
|
| 401 |
+
action_space = discover_actions(skeleton_root)
|
| 402 |
+
if not action_space:
|
| 403 |
+
raise RuntimeError(f"No actions found under: {skeleton_root}")
|
| 404 |
+
|
| 405 |
+
options = build_options(action_space)
|
| 406 |
+
|
| 407 |
+
records: list[dict[str, Any]] = []
|
| 408 |
+
with input_path.open("r", encoding="utf-8") as f:
|
| 409 |
+
for idx, line in enumerate(f):
|
| 410 |
+
line = line.strip()
|
| 411 |
+
if not line:
|
| 412 |
+
continue
|
| 413 |
+
raw = json.loads(line)
|
| 414 |
+
|
| 415 |
+
video_path = raw.get("video_path", "")
|
| 416 |
+
downsampled_data = raw.get("downsampled_data") or {}
|
| 417 |
+
|
| 418 |
+
action_id, action_name, action_dir = parse_action_from_video_path(video_path)
|
| 419 |
+
_, sensor_stats, precision = build_timeseries_lines(downsampled_data)
|
| 420 |
+
|
| 421 |
+
out_item: dict[str, Any] = dict(raw)
|
| 422 |
+
out_item["task_id"] = idx
|
| 423 |
+
out_item["evaluation_type"] = "qa"
|
| 424 |
+
out_item["task_type"] = "CUHKX_HAR"
|
| 425 |
+
out_item["sub_dimension"] = "ActionClassification"
|
| 426 |
+
|
| 427 |
+
out_item["action_id"] = action_id
|
| 428 |
+
out_item["action_name"] = action_name
|
| 429 |
+
out_item["action_dir"] = action_dir
|
| 430 |
+
|
| 431 |
+
out_item["prompt"] = build_prompt(video_path, downsampled_data, action_space)
|
| 432 |
+
out_item["question"] = build_question()
|
| 433 |
+
out_item["options"] = options
|
| 434 |
+
out_item["ground_truth"] = str(action_id)
|
| 435 |
+
out_item["value_precision"] = precision
|
| 436 |
+
out_item["device_mapping"] = DEVICE_TO_ID
|
| 437 |
+
|
| 438 |
+
out_item.pop("downsampled_data", None)
|
| 439 |
+
|
| 440 |
+
records.append(out_item)
|
| 441 |
+
|
| 442 |
+
if args.max_records > 0 and len(records) >= args.max_records:
|
| 443 |
+
break
|
| 444 |
+
|
| 445 |
+
train_items, test_items = stratified_split_by_action(
|
| 446 |
+
records=records,
|
| 447 |
+
train_ratio=0.9,
|
| 448 |
+
seed=args.seed,
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
train_output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 452 |
+
test_output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 453 |
+
train_sample_output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 454 |
+
test_sample_output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 455 |
+
|
| 456 |
+
with train_output_path.open("w", encoding="utf-8") as f:
|
| 457 |
+
for item in train_items:
|
| 458 |
+
f.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 459 |
+
|
| 460 |
+
with test_output_path.open("w", encoding="utf-8") as f:
|
| 461 |
+
for item in test_items:
|
| 462 |
+
f.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 463 |
+
|
| 464 |
+
with train_sample_output_path.open("w", encoding="utf-8") as f:
|
| 465 |
+
for item in train_items[: args.sample_size]:
|
| 466 |
+
f.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 467 |
+
|
| 468 |
+
with test_sample_output_path.open("w", encoding="utf-8") as f:
|
| 469 |
+
for item in test_items[: args.sample_size]:
|
| 470 |
+
f.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 471 |
+
|
| 472 |
+
def count_labels(rows: list[dict[str, Any]]) -> dict[str, int]:
|
| 473 |
+
stats: dict[str, int] = {}
|
| 474 |
+
for x in rows:
|
| 475 |
+
gt = x.get("ground_truth")
|
| 476 |
+
stats[gt] = stats.get(gt, 0) + 1
|
| 477 |
+
return stats
|
| 478 |
+
|
| 479 |
+
summary = {
|
| 480 |
+
"input": str(input_path),
|
| 481 |
+
"train_output": str(train_output_path),
|
| 482 |
+
"test_output": str(test_output_path),
|
| 483 |
+
"train_sample_output": str(train_sample_output_path),
|
| 484 |
+
"test_sample_output": str(test_sample_output_path),
|
| 485 |
+
"total": len(records),
|
| 486 |
+
"train_size": len(train_items),
|
| 487 |
+
"test_size": len(test_items),
|
| 488 |
+
"num_actions": len(action_space),
|
| 489 |
+
"action_ids": [x["action_id"] for x in action_space],
|
| 490 |
+
"train_label_stats": count_labels(train_items),
|
| 491 |
+
"test_label_stats": count_labels(test_items),
|
| 492 |
+
"seed": args.seed,
|
| 493 |
+
}
|
| 494 |
+
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
if __name__ == "__main__":
|
| 498 |
+
main()
|
sample/video-timeseries/cuhk_x_har/xlsx_to_csv.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Convert CUHK-X IMU workbooks and copy CSV streams into a local tree."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import shutil
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import pandas as pd
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def convert(input_root: Path, output_root: Path) -> None:
|
| 14 |
+
"""Keep the original workbook conversion and preserve trial directories."""
|
| 15 |
+
if output_root.exists():
|
| 16 |
+
raise ValueError(f"Choose a new IMU output directory: {output_root}")
|
| 17 |
+
output_root.mkdir(parents=True)
|
| 18 |
+
paths = sorted(input_root.rglob("*"))
|
| 19 |
+
for path in paths:
|
| 20 |
+
if path.is_file() and path.suffix.lower() == ".csv":
|
| 21 |
+
target = output_root / path.relative_to(input_root)
|
| 22 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 23 |
+
shutil.copy2(path, target)
|
| 24 |
+
converted = 0
|
| 25 |
+
for path in paths:
|
| 26 |
+
if (
|
| 27 |
+
not path.is_file()
|
| 28 |
+
or path.suffix.lower() not in {".xlsx", ".xls"}
|
| 29 |
+
or path.name.startswith("~$")
|
| 30 |
+
):
|
| 31 |
+
continue
|
| 32 |
+
target = (output_root / path.relative_to(input_root)).with_suffix(".csv")
|
| 33 |
+
if target.exists():
|
| 34 |
+
continue
|
| 35 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 36 |
+
pd.read_excel(path).to_csv(target, index=False, encoding="utf-8-sig")
|
| 37 |
+
converted += 1
|
| 38 |
+
print(f"Converted {converted} workbooks into {output_root}")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def main() -> None:
|
| 42 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 43 |
+
parser.add_argument("--input-root", type=Path, required=True)
|
| 44 |
+
parser.add_argument("--output-root", type=Path, required=True)
|
| 45 |
+
args = parser.parse_args()
|
| 46 |
+
convert(args.input_root.resolve(), args.output_root.resolve())
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
if __name__ == "__main__":
|
| 50 |
+
main()
|