Download MTLCC/code/tfrecord_io.py from Dhruv1000/TSRDA: direct link, hf CLI and curl.
- Browser
- Download file 2.92 kB
-
https://huggingface.co/Dhruv1000/TSRDA/resolve/main/MTLCC/code/tfrecord_io.py
- Command line
-
hf download hf://Dhruv1000/TSRDA/MTLCC/code/tfrecord_io.py
-
curl -L -o tfrecord_io.py https://huggingface.co/Dhruv1000/TSRDA/resolve/main/MTLCC/code/tfrecord_io.py
2.92 kB
| """Dependency-free reader for the MTLCC (data_IJGI18) *.tfrecord.gz tiles. | |
| Each file holds ONE tf.Example whose features are: | |
| x10/data (T,48,48,4) x20/data (T,24,24,6) x60/data (T,8,8,3) raw bytes | |
| labels/data (T,48,48) dates/doy, dates/year raw bytes (+ */shape int64) | |
| Parsed with a tiny protobuf wire decoder so DataLoader workers do not import | |
| TensorFlow. | |
| """ | |
| import gzip | |
| import struct | |
| import numpy as np | |
| def _varint(b, p): | |
| r = s = 0 | |
| while True: | |
| c = b[p]; p += 1 | |
| r |= (c & 0x7F) << s | |
| if c < 0x80: | |
| return r, p | |
| s += 7 | |
| def _fields(b): | |
| p, n = 0, len(b) | |
| while p < n: | |
| key, p = _varint(b, p) | |
| f, w = key >> 3, key & 7 | |
| if w == 0: | |
| v, p = _varint(b, p) | |
| elif w == 2: | |
| l, p = _varint(b, p); v = b[p:p + l]; p += l | |
| elif w == 1: | |
| v = b[p:p + 8]; p += 8 | |
| elif w == 5: | |
| v = b[p:p + 4]; p += 4 | |
| else: | |
| raise ValueError("bad wire type") | |
| yield f, v | |
| def parse_example(buf): | |
| out = {} | |
| for f, features in _fields(buf): # Example.features = 1 | |
| if f != 1: | |
| continue | |
| for f2, entry in _fields(features): # Features.feature (map) = 1 | |
| key = val = None | |
| for f3, v in _fields(entry): | |
| if f3 == 1: | |
| key = bytes(v).decode() | |
| elif f3 == 2: | |
| val = v | |
| for kind, lst in _fields(val): # Feature: 1 bytes,2 float,3 int64 | |
| if kind == 1: | |
| out[key] = [bytes(v) for _, v in _fields(lst)][0] | |
| elif kind == 3: | |
| ints = [] | |
| for _, v in _fields(lst): | |
| if isinstance(v, int): | |
| ints.append(v) | |
| else: # packed varints | |
| p = 0 | |
| while p < len(v): | |
| x, p = _varint(v, p); ints.append(x) | |
| out[key] = ints | |
| return out | |
| def read_first_record(path): | |
| with gzip.open(path, "rb") as f: | |
| raw = f.read() | |
| (length,) = struct.unpack("<Q", raw[:8]) | |
| return raw[12:12 + length] | |
| def _arr(ex, name, dtype): | |
| shape = ex[name.replace("data", "shape")] | |
| return np.frombuffer(ex[name], dtype=dtype).reshape(shape) | |
| def load_tile(path, dtype=None): | |
| """Returns dict(x10,x20,x60,labels,doy,year) as numpy arrays (T leading).""" | |
| ex = parse_example(read_first_record(path)) | |
| d = dtype or np.int64 | |
| return dict(x10=_arr(ex, "x10/data", d), x20=_arr(ex, "x20/data", d), | |
| x60=_arr(ex, "x60/data", d), labels=_arr(ex, "labels/data", np.int64), | |
| doy=np.frombuffer(ex["dates/doy"], dtype=np.int64), | |
| year=np.frombuffer(ex["dates/year"], dtype=np.int64)) | |