| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import io |
| 4 |
from functools import partial |
| 5 |
|
| 6 |
from fsspec.core import open_files |
| 7 |
from tlz import concat |
| 8 |
|
| 9 |
from dask.bag.core import from_delayed |
| 10 |
from dask.bytes import read_bytes |
| 11 |
from dask.delayed import delayed |
| 12 |
from dask.utils import parse_bytes, system_encoding |
| 13 |
|
| 14 |
delayed = delayed(pure=True) |
| 15 |
|
| 16 |
|
| 17 |
def read_text( |
| 18 |
urlpath, |
| 19 |
blocksize=None, |
| 20 |
compression="infer", |
| 21 |
encoding=system_encoding, |
| 22 |
errors="strict", |
| 23 |
linedelimiter=None, |
| 24 |
collection=True, |
| 25 |
storage_options=None, |
| 26 |
files_per_partition=None, |
| 27 |
include_path=False, |
| 28 |
): |
| 29 |
"""Read lines from text files |
| 30 |
|
| 31 |
Parameters |
| 32 |
---------- |
| 33 |
urlpath : string or list |
| 34 |
Absolute or relative filepath(s). Prefix with a protocol like ``s3://`` |
| 35 |
to read from alternative filesystems. To read from multiple files you |
| 36 |
can pass a globstring or a list of paths, with the caveat that they |
| 37 |
must all have the same protocol. |
| 38 |
blocksize: None, int, or str |
| 39 |
Size (in bytes) to cut up larger files. Streams by default. |
| 40 |
Can be ``None`` for streaming, an integer number of bytes, or a string |
| 41 |
like "128MiB" |
| 42 |
compression: string |
| 43 |
Compression format like 'gzip' or 'xz'. Defaults to 'infer' |
| 44 |
encoding: string |
| 45 |
errors: string |
| 46 |
linedelimiter: string or None |
| 47 |
collection: bool, optional |
| 48 |
Return dask.bag if True, or list of delayed values if false |
| 49 |
storage_options: dict |
| 50 |
Extra options that make sense to a particular storage connection, e.g. |
| 51 |
host, port, username, password, etc. |
| 52 |
files_per_partition: None or int |
| 53 |
If set, group input files into partitions of the requested size, |
| 54 |
instead of one partition per file. Mutually exclusive with blocksize. |
| 55 |
include_path: bool |
| 56 |
Whether or not to include the path in the bag. |
| 57 |
If true, elements are tuples of (line, path). |
| 58 |
Default is False. |
| 59 |
|
| 60 |
Examples |
| 61 |
-------- |
| 62 |
>>> b = read_text('myfiles.1.txt') # doctest: +SKIP |
| 63 |
>>> b = read_text('myfiles.*.txt') # doctest: +SKIP |
| 64 |
>>> b = read_text('myfiles.*.txt.gz') # doctest: +SKIP |
| 65 |
>>> b = read_text('s3://bucket/myfiles.*.txt') # doctest: +SKIP |
| 66 |
>>> b = read_text('s3://key:secret@bucket/myfiles.*.txt') # doctest: +SKIP |
| 67 |
>>> b = read_text('hdfs://namenode.example.com/myfiles.*.txt') # doctest: +SKIP |
| 68 |
|
| 69 |
Parallelize a large file by providing the number of uncompressed bytes to |
| 70 |
load into each partition. |
| 71 |
|
| 72 |
>>> b = read_text('largefile.txt', blocksize='10MB') # doctest: +SKIP |
| 73 |
|
| 74 |
Get file paths of the bag by setting include_path=True |
| 75 |
|
| 76 |
>>> b = read_text('myfiles.*.txt', include_path=True) # doctest: +SKIP |
| 77 |
>>> b.take(1) # doctest: +SKIP |
| 78 |
(('first line of the first file', '/home/dask/myfiles.0.txt'),) |
| 79 |
|
| 80 |
Returns |
| 81 |
------- |
| 82 |
dask.bag.Bag or list |
| 83 |
dask.bag.Bag if collection is True or list of Delayed lists otherwise. |
| 84 |
|
| 85 |
See Also |
| 86 |
-------- |
| 87 |
from_sequence: Build bag from Python sequence |
| 88 |
""" |
| 89 |
if blocksize is not None and files_per_partition is not None: |
| 90 |
raise ValueError("Only one of blocksize or files_per_partition can be set") |
| 91 |
if isinstance(blocksize, str): |
| 92 |
blocksize = parse_bytes(blocksize) |
| 93 |
|
| 94 |
if blocksize is None: |
| 95 |
if linedelimiter in [None, "", "\n", "\r", "\r\n"]: |
| 96 |
newline = linedelimiter |
| 97 |
linedelimiter = None |
| 98 |
else: |
| 99 |
newline = "" |
| 100 |
files = open_files( |
| 101 |
urlpath, |
| 102 |
mode="rt", |
| 103 |
encoding=encoding, |
| 104 |
errors=errors, |
| 105 |
compression=compression, |
| 106 |
newline=newline, |
| 107 |
**(storage_options or {}), |
| 108 |
) |
| 109 |
if files_per_partition is None: |
| 110 |
blocks = [ |
| 111 |
delayed(list)( |
| 112 |
delayed( |
| 113 |
partial(file_to_blocks, include_path, delimiter=linedelimiter) |
| 114 |
)(fil) |
| 115 |
) |
| 116 |
for fil in files |
| 117 |
] |
| 118 |
else: |
| 119 |
blocks = [] |
| 120 |
for start in range(0, len(files), files_per_partition): |
| 121 |
block_files = files[start : (start + files_per_partition)] |
| 122 |
block_lines = delayed(concat)( |
| 123 |
delayed(map)( |
| 124 |
partial(file_to_blocks, include_path, delimiter=linedelimiter), |
| 125 |
block_files, |
| 126 |
) |
| 127 |
) |
| 128 |
blocks.append(block_lines) |
| 129 |
else: |
| 130 |
# special case for linedelimiter=None: we will need to split on an actual bytestring |
| 131 |
# and the line reader will then use "universal" mode. Just as well that \r\n and \n |
| 132 |
# will both work (thankfully \r for MacOS is no longer a thing) |
| 133 |
o = read_bytes( |
| 134 |
urlpath, |
| 135 |
delimiter=linedelimiter.encode() if linedelimiter is not None else b"\n", |
| 136 |
blocksize=blocksize, |
| 137 |
sample=False, |
| 138 |
compression=compression, |
| 139 |
include_path=include_path, |
| 140 |
**(storage_options or {}), |
| 141 |
) |
| 142 |
raw_blocks = o[1] |
| 143 |
blocks = [ |
| 144 |
delayed(decode)(b, encoding, errors, linedelimiter) |
| 145 |
for b in concat(raw_blocks) |
| 146 |
] |
| 147 |
if include_path: |
| 148 |
paths = list( |
| 149 |
concat([[path] * len(raw_blocks[i]) for i, path in enumerate(o[2])]) |
| 150 |
) |
| 151 |
blocks = [ |
| 152 |
delayed(attach_path)(entry, path) for entry, path in zip(blocks, paths) |
| 153 |
] |
| 154 |
|
| 155 |
if not blocks: |
| 156 |
raise ValueError("No files found", urlpath) |
| 157 |
|
| 158 |
if collection: |
| 159 |
blocks = from_delayed(blocks) |
| 160 |
|
| 161 |
return blocks |
| 162 |
|
| 163 |
|
| 164 |
def file_to_blocks(include_path, lazy_file, delimiter=None): |
| 165 |
# blocksize is None branch |
| 166 |
with lazy_file as f: |
| 167 |
if delimiter is not None: |
| 168 |
text = f.read() |
| 169 |
if not text: |
| 170 |
return [] |
| 171 |
parts = text.split(delimiter) |
| 172 |
yield from ( |
| 173 |
(line, lazy_file.path) if include_path else line |
| 174 |
for line in [line + delimiter for line in parts[:-1]] + parts[-1:] |
| 175 |
) |
| 176 |
else: |
| 177 |
for line in f: |
| 178 |
yield (line, lazy_file.path) if include_path else line |
| 179 |
|
| 180 |
|
| 181 |
def attach_path(block, path): |
| 182 |
for p in block: |
| 183 |
yield (p, path) |
| 184 |
|
| 185 |
|
| 186 |
def decode(block, encoding, errors, line_delimiter): |
| 187 |
# blocksize is not None branch |
| 188 |
text = block.decode(encoding, errors) |
| 189 |
if line_delimiter in [None, "", "\n", "\r", "\r\n"]: |
| 190 |
lines = io.StringIO(text, newline=line_delimiter) |
| 191 |
return list(lines) |
| 192 |
else: |
| 193 |
if not text: |
| 194 |
return [] |
| 195 |
parts = text.split(line_delimiter) |
| 196 |
out = [t + line_delimiter for t in parts[:-1]] + ( |
| 197 |
parts[-1:] if not text.endswith(line_delimiter) else [] |
| 198 |
) |
| 199 |
return out |