File size: 7,731 Bytes
217de99
 
f35912b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217de99
 
 
 
 
 
f35912b
 
 
217de99
 
 
f35912b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217de99
 
f35912b
217de99
f35912b
 
 
 
 
 
 
 
217de99
 
 
f35912b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
806a21e
f35912b
 
 
 
 
 
 
 
806a21e
f35912b
 
 
217de99
f35912b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217de99
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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
162
163
164
165
166
167
168
import json
import tarfile
from datasets import DatasetInfo, DatasetBuilder, DownloadManager,BuilderConfig, SplitGenerator, Split, Version
import datasets
import os
import requests
import re


###GEt list of files 
DATASET_URL="https://huggingface.co/datasets/dell-research-harvard/AmericanStories/blob/main/"
def get_list_of_files(url):
    page = requests.get(url).text
    links=re.findall(r'href=[\'"]?([^\'" >]+)', page)
    ###Get only links containing faro_
    links=[link for link in links if link.startswith('faro_')]
    return links

###Arrange into splits by year - files follow the format faro_YYYY.tar.gz
def get_splits(links):
    splits={}
    years=[]
    for link in links:
        year=link.split('_')[1].split('.')[0]
        if year not in splits:
            splits[year]=[]
        splits[year].append(link)
        years.append(year)
    return splits,years

####data dir
DATA_DIR="."

def make_year_file_splits(data_dir):
    ###Get list of files
    data_files=os.listdir(data_dir)
    ###Get only files containing faro_
    data_files=[file for file in data_files if file.startswith('faro_')]

    ###Arrange into splits by year - files follow the format faro_YYYY.tar.gz
    splits={}
    years=[]
    for file in data_files:
        year=file.split('_')[1].split('.')[0]
        if year not in splits:
            splits[year]=[]
        splits[year].append(file)
        years.append(year)
    return splits, years





_CITATION = """\
Coming Soon
"""

_DESCRIPTION = """\
American Stories offers high-quality structured data from historical newspapers suitable for pre-training large language models to enhance the understanding of historical English and world knowledge. It can also be integrated into external databases of retrieval-augmented language models, enabling broader access to historical information, including interpretations of political events and intricate details about people's ancestors. Additionally, the structured article texts facilitate the application of transformer-based methods for popular tasks like detecting reproduced content, significantly improving accuracy compared to traditional OCR methods. American Stories serves as a substantial and valuable dataset for advancing multimodal layout analysis models and other multimodal applications. """

_FILE_DICT,_YEARS=make_year_file_splits(DATA_DIR)




class AmericanStories(datasets.GeneratorBasedBuilder):
    """TODO: Short description of my dataset."""

    VERSION = datasets.Version("0.0.1")

    # This is an example of a dataset with multiple configurations.
    # If you don't want/need to define several sub-sets in your dataset,
    # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.

    # If you need to make complex sub-parts in the datasets with configurable options
    # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
    # BUILDER_CONFIG_CLASS = MyBuilderConfig

    # You will be able to load one or the other configurations in the following list with
    # data = datasets.load_dataset('my_dataset', 'first_domain')
    # data = datasets.load_dataset('my_dataset', 'second_domain')
    BUILDER_CONFIGS = [datasets.BuilderConfig(name="american_stories", version="0.0.1", description="This part of my dataset covers a first domain")]


    def _info(self):
        # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
        features = datasets.Features(
            {   "newspaper_name": datasets.Value("string"),
                "edition": datasets.Value("string"),
                "date": datasets.Value("string"),
                "page": datasets.Value("string"),
                "headline": datasets.Value("string"),
                "byline": datasets.Value("string"),
                "article": datasets.Value("string")
                # These are the features of your dataset like images, labels ...
            }
        )

        return datasets.DatasetInfo(
            # This is the description that will appear on the datasets page.
            description=_DESCRIPTION,
            # This defines the different columns of the dataset and their types
            features=features,  # Here we define them above because they are different between the two configurations
            # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
            # specify them. They'll be used if as_supervised=True in builder.as_dataset.
            # supervised_keys=("sentence", "label"),
            # Homepage of the dataset for documentation
            # License for the dataset if available
            # Citation for the dataset
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager,online=False):
        # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
        # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name

        # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
        # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
        # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
        if not online:
            urls = _FILE_DICT
        else:
            _URL_DICT,year_list=get_splits(get_list_of_files(DATASET_URL))
            urls = _URL_DICT
        year_list=_YEARS
        data_dir = dl_manager.download_and_extract(urls)

        ###REturn a list of splits - but each split is for a year!
        return [
            datasets.SplitGenerator(
            name=year,
            # These kwargs will be passed to _generate_examples
            gen_kwargs={
                "year_dir": os.path.join(data_dir[year][0], "mnt/122a7683-fa4b-45dd-9f13-b18cc4f4a187/ca_rule_based_fa_clean/faro_"+year),
                "split": year,
            },
        ) for year in year_list
        ]
    



    # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
    def _generate_examples(self, year_dir, split):
        # TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
        # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
        for filepath in os.listdir(year_dir):
            with open(os.path.join(year_dir,filepath), encoding="utf-8") as f:
                    data = json.load(f)
                    scan_id=filepath.split('.')[0]
                    scan_date=filepath.split("_")[0]
                    scan_page=filepath.split("_")[1]
                    scan_edition=filepath.split("_")[-2][8:]
                    newspaper_name=data["lccn"]["title"]
                    full_articles_in_data=data["full articles"]
                    for article in full_articles_in_data:
                        article_id=str(article["full_article_id"]) +"_" +scan_id
                        yield article_id,  {
                            "newspaper_name": newspaper_name,
                            "edition": scan_edition,
                            "date": scan_date,
                            "page": scan_page,
                            "headline": article["headline"],
                            "byline": article["byline"],
                            "article": article["article"]
                            }