Datasets:
Download tools/stream_json.py from zixuanlan/VLM_Train: direct link, hf CLI and curl.
- Browser
- Download file 1.3 kB
-
https://huggingface.co/datasets/zixuanlan/VLM_Train/resolve/main/tools/stream_json.py
- Command line
-
hf download hf://datasets/zixuanlan/VLM_Train/tools/stream_json.py
-
curl -L -o stream_json.py https://huggingface.co/datasets/zixuanlan/VLM_Train/resolve/main/tools/stream_json.py
1.3 kB
| import json,codecs | |
| def records(path): | |
| dec=json.JSONDecoder(); utf=codecs.getincrementaldecoder('utf-8')();buf=''; state='start' | |
| with path.open('rb') as f: | |
| while True: | |
| chunk=f.read(1024*1024);buf+=utf.decode(chunk,final=not chunk);pos=0 | |
| while True: | |
| while pos<len(buf) and buf[pos].isspace():pos+=1 | |
| if pos==len(buf):break | |
| if state=='start': | |
| if buf[pos]!='[':raise ValueError('Expected array') | |
| pos+=1;state='first';continue | |
| if state=='end':raise ValueError('Trailing data') | |
| if state=='separator': | |
| if buf[pos]==']':pos+=1;state='end';continue | |
| if buf[pos]!=',':raise ValueError('Expected comma') | |
| pos+=1;state='value';continue | |
| if state=='first' and buf[pos]==']':pos+=1;state='end';continue | |
| try:obj,end=dec.raw_decode(buf,pos) | |
| except json.JSONDecodeError: | |
| if not chunk:raise | |
| break | |
| yield obj;pos=end;state='separator' | |
| buf=buf[pos:] | |
| if not chunk: | |
| if state!='end':raise ValueError('Incomplete JSON') | |
| break | |