|
import csv |
|
from torch.utils.data import IterableDataset |
|
from huggingface_hub import hf_hub_download |
|
|
|
class ParsedMultiCharDataset(IterableDataset): |
|
def __init__(self, |
|
repo_id: str, |
|
delimiter: str = ".,|,.", |
|
start_file: int = 0, |
|
num_files: int = 190, |
|
guess_total_count = True): |
|
self.repo_id = repo_id |
|
self.files = [f"captions/caption_{i+start_file:03d}.csv" for i in range(num_files)] |
|
self.delimiter = ".,|,." |
|
self.total_rows = -1 |
|
if guess_total_count: |
|
self.total_rows = self.guess_total_rows() |
|
print(f"Total rows: {self.total_rows} totaling {len(self.files) * self.total_rows}") |
|
|
|
|
|
def guess_total_rows(self): |
|
|
|
path = hf_hub_download(self.repo_id, self.files[0], repo_type="dataset") |
|
with open(path, encoding="utf-8") as f: |
|
reader = csv.DictReader(f) |
|
return sum(1 for _ in reader) |
|
|
|
def __iter__(self): |
|
for rel_path in self.files: |
|
path = hf_hub_download(self.repo_id, rel_path, repo_type="dataset") |
|
with open(path, encoding="utf-8") as f: |
|
reader = csv.DictReader(f) |
|
for row in reader: |
|
id_ = row.get("id", "").strip() |
|
text_field = row.get("text", "") |
|
for caption in text_field.split(self.delimiter): |
|
caption = caption.strip() |
|
if caption: |
|
yield (id_, caption) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|