File size: 1,796 Bytes
2d4c453
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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):
      # count the rows in the first file
      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)

#ds = ParsedMultiCharDataset(
#    repo_id="AbstractPhil/human-templated-captions-1b",
#    start_file=0,
#    num_files=10
#)
#for i, ex in enumerate(ds):
#    print(ex)
#    if i > 10:
#        break
#