VLM_Train / tools /stream_json.py
zixuanlan's picture
Upload verified dataset file: tools/stream_json.py
841ca3c verified
Raw History Blame Contribute Delete
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