archiver.py 5.6 KB
Newer Older
Rayyyyy's avatar
Rayyyyy committed
1
import datetime
Rayyyyy's avatar
Rayyyyy committed
2
3
import io
import json
Rayyyyy's avatar
Rayyyyy committed
4
import mmap
Rayyyyy's avatar
Rayyyyy committed
5
import os
Rayyyyy's avatar
Rayyyyy committed
6
from pathlib import Path
Rayyyyy's avatar
Rayyyyy committed
7
8
9
10
11
from typing import Any

import jsonlines
import tqdm
import zstandard
Rayyyyy's avatar
Rayyyyy committed
12
13


Rayyyyy's avatar
Rayyyyy committed
14
def json_serial(obj: Any) -> str:
Rayyyyy's avatar
Rayyyyy committed
15
16
17
18
19
20
21
22
23
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, (datetime.datetime,)):
        return obj.isoformat()
    raise TypeError("Type %s not serializable" % type(obj))


# Modified version of lm_dataformat Archive for single file.
class Archive:
Rayyyyy's avatar
Rayyyyy committed
24
    def __init__(self, file_path: str, compression_level: int = 3) -> None:
Rayyyyy's avatar
Rayyyyy committed
25
26
27
28
29
30
31
32
        self.file_path = file_path
        dir_name = os.path.dirname(file_path)
        if dir_name:
            os.makedirs(dir_name, exist_ok=True)
        self.fh = open(self.file_path, "wb")
        self.cctx = zstandard.ZstdCompressor(level=compression_level)
        self.compressor = self.cctx.stream_writer(self.fh)

Rayyyyy's avatar
Rayyyyy committed
33
34
35
    def add_data(self, data, meta=None) -> None:
        if meta is None:
            meta = {}
Rayyyyy's avatar
Rayyyyy committed
36
37
38
39
40
41
42
        self.compressor.write(
            json.dumps({"text": data, "meta": meta}, default=json_serial).encode(
                "UTF-8"
            )
            + b"\n"
        )

Rayyyyy's avatar
Rayyyyy committed
43
    def commit(self) -> None:
Rayyyyy's avatar
Rayyyyy committed
44
45
46
47
48
49
50
        self.compressor.flush(zstandard.FLUSH_FRAME)
        self.fh.flush()
        self.fh.close()


# Modified version of lm_dataformat Reader with self.fh set, allowing peeking for tqdm.
class Reader:
Rayyyyy's avatar
Rayyyyy committed
51
    def __init__(self) -> None:
Rayyyyy's avatar
Rayyyyy committed
52
53
        pass

Rayyyyy's avatar
Rayyyyy committed
54
55
56
57
58
59
60
    def read(
        self,
        file,
        get_meta: bool = False,
        autojoin_paragraphs: bool = True,
        para_joiner: str = "\n\n",
    ):
Rayyyyy's avatar
Rayyyyy committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
        with open(file, "rb") as fh:
            self.fh = fh
            cctx = zstandard.ZstdDecompressor()
            reader = io.BufferedReader(cctx.stream_reader(fh))
            rdr = jsonlines.Reader(reader)
            for ob in rdr:
                # naive jsonl where each object is just the string itself, with no meta. For legacy compatibility.
                if isinstance(ob, str):
                    assert not get_meta
                    yield ob
                    continue

                text = ob["text"]

                if autojoin_paragraphs and isinstance(text, list):
                    text = para_joiner.join(text)

                if get_meta:
                    yield text, (ob["meta"] if "meta" in ob else {})
                else:
                    yield text


class TextArchive:
Rayyyyy's avatar
Rayyyyy committed
85
    def __init__(self, file_path, mode: str = "rb+") -> None:
Rayyyyy's avatar
Rayyyyy committed
86
87
88
89
90
91
92
93
94
95
        self.file_path = file_path
        dir_name = os.path.dirname(file_path)
        if dir_name:
            os.makedirs(dir_name, exist_ok=True)

        if not os.path.exists(file_path):
            Path(file_path).touch()

        self.fh = open(self.file_path, mode)

Rayyyyy's avatar
Rayyyyy committed
96
    def add_data(self, data) -> None:
Rayyyyy's avatar
Rayyyyy committed
97
98
        self.fh.write(data.encode("UTF-8") + b"\n")

Rayyyyy's avatar
Rayyyyy committed
99
    def commit(self) -> None:
Rayyyyy's avatar
Rayyyyy committed
100
101
102
103
104
        self.fh.flush()
        self.fh.close()


class TextReader:
Rayyyyy's avatar
Rayyyyy committed
105
    def __init__(self, file_path) -> None:
Rayyyyy's avatar
Rayyyyy committed
106
107
108
109
        self.file_path = file_path

    # Optimized mmap read with infrequent tqdm updates to maintain speed
    # Tested up to 250MB/s.
Rayyyyy's avatar
Rayyyyy committed
110
    def read_tqdm(self, update_frequency: int = 10000):
Rayyyyy's avatar
Rayyyyy committed
111
112
        current_file_position = 0
        line_counter = 0
Rayyyyy's avatar
Rayyyyy committed
113
        with open(self.file_path, "r", encoding="utf-8") as fh, tqdm.tqdm(
Rayyyyy's avatar
Rayyyyy committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
            total=os.path.getsize(self.file_path),
            dynamic_ncols=True,
            unit="byte",
            unit_scale=1,
        ) as progress:
            with mmap.mmap(fh.fileno(), length=0, access=mmap.ACCESS_READ) as mmap_obj:
                for line in iter(mmap_obj.readline, b""):
                    line = line.decode("utf-8")
                    line_counter += 1
                    if line_counter == update_frequency:
                        new_file_pos = mmap_obj.tell()
                        bytes_read = new_file_pos - current_file_position
                        current_file_position = new_file_pos
                        progress.update(bytes_read)
                        line_counter = 0
                    yield line[:-1]

    def read_and_tell(self):
        current_file_position = 0
        with open(self.file_path, "r", encoding="utf8") as fh:
            with mmap.mmap(fh.fileno(), length=0, access=mmap.ACCESS_READ) as mmap_obj:
                for line in iter(mmap_obj.readline, b""):
                    line = line.decode("utf-8")
                    new_file_pos = mmap_obj.tell()
                    raw_bytes_read = new_file_pos - current_file_position
                    current_file_position = new_file_pos
                    yield line[:-1], raw_bytes_read

    def read(self):
        with open(self.file_path, "r", encoding="utf8") as fh:
            with mmap.mmap(fh.fileno(), length=0, access=mmap.ACCESS_READ) as mmap_obj:
                for line in iter(mmap_obj.readline, b""):
                    line = line.decode("utf-8")
                    yield line[:-1]

    def read_slow(self):
        with open(self.file_path, "r", encoding="utf8") as fh:
            while True:
                line = fh.readline()
                if line == -1 or line == "":
                    break
                else:
                    yield line[:-1]


# Optimized for speed. Decompresses the archive in shell before
# using the mmap'd TextReader.
class ZStdTextReader:
Rayyyyy's avatar
Rayyyyy committed
162
    def __init__(self, file) -> None:
Rayyyyy's avatar
Rayyyyy committed
163
164
165
166
167
168
169
170
171
        self.file = file

    def read_tqdm(self):
        decompressed_file = self.file[:-4]
        print("Decompressing file, please wait...")
        os.system(f"zstd -d {self.file}")  # linux decompress is faster
        reader = TextReader(decompressed_file)
        yield from reader.read_tqdm()
        os.remove(decompressed_file)