Create dataset.py
Browse files- dataset.py +50 -0
dataset.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv
|
| 2 |
+
from torch.utils.data import IterableDataset
|
| 3 |
+
from huggingface_hub import hf_hub_download
|
| 4 |
+
|
| 5 |
+
class ParsedMultiCharDataset(IterableDataset):
|
| 6 |
+
def __init__(self,
|
| 7 |
+
repo_id: str,
|
| 8 |
+
delimiter: str = ".,|,.",
|
| 9 |
+
start_file: int = 0,
|
| 10 |
+
num_files: int = 190,
|
| 11 |
+
guess_total_count = True):
|
| 12 |
+
self.repo_id = repo_id
|
| 13 |
+
self.files = [f"captions/caption_{i+start_file:03d}.csv" for i in range(num_files)]
|
| 14 |
+
self.delimiter = ".,|,."
|
| 15 |
+
self.total_rows = -1
|
| 16 |
+
if guess_total_count:
|
| 17 |
+
self.total_rows = self.guess_total_rows()
|
| 18 |
+
print(f"Total rows: {self.total_rows} totaling {len(self.files) * self.total_rows}")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def guess_total_rows(self):
|
| 22 |
+
# count the rows in the first file
|
| 23 |
+
path = hf_hub_download(self.repo_id, self.files[0], repo_type="dataset")
|
| 24 |
+
with open(path, encoding="utf-8") as f:
|
| 25 |
+
reader = csv.DictReader(f)
|
| 26 |
+
return sum(1 for _ in reader)
|
| 27 |
+
|
| 28 |
+
def __iter__(self):
|
| 29 |
+
for rel_path in self.files:
|
| 30 |
+
path = hf_hub_download(self.repo_id, rel_path, repo_type="dataset")
|
| 31 |
+
with open(path, encoding="utf-8") as f:
|
| 32 |
+
reader = csv.DictReader(f)
|
| 33 |
+
for row in reader:
|
| 34 |
+
id_ = row.get("id", "").strip()
|
| 35 |
+
text_field = row.get("text", "")
|
| 36 |
+
for caption in text_field.split(self.delimiter):
|
| 37 |
+
caption = caption.strip()
|
| 38 |
+
if caption:
|
| 39 |
+
yield (id_, caption)
|
| 40 |
+
|
| 41 |
+
#ds = ParsedMultiCharDataset(
|
| 42 |
+
# repo_id="AbstractPhil/human-templated-captions-1b",
|
| 43 |
+
# start_file=0,
|
| 44 |
+
# num_files=10
|
| 45 |
+
#)
|
| 46 |
+
#for i, ex in enumerate(ds):
|
| 47 |
+
# print(ex)
|
| 48 |
+
# if i > 10:
|
| 49 |
+
# break
|
| 50 |
+
#
|