File size: 6,176 Bytes
8d095fd
3a0359a
8d095fd
3a0359a
9c0daeb
be61c57
eab141c
 
 
 
 
 
 
 
 
 
 
 
 
 
e203fb8
9c0daeb
 
1ab64c5
8d095fd
1ab64c5
 
e203fb8
 
1ab64c5
 
 
 
 
41d397a
 
24bb688
41d397a
1ab64c5
 
 
be61c57
f1658c0
1ab64c5
7b9e4ff
0aaa4e0
e203fb8
 
0aaa4e0
e203fb8
be61c57
 
 
 
0aaa4e0
8d095fd
be61c57
 
 
 
0aaa4e0
b2620a8
59ea6c7
8d095fd
0aaa4e0
8d095fd
9c0daeb
 
 
8d095fd
e203fb8
4fad638
 
e203fb8
 
8d095fd
 
59ea6c7
9c0daeb
 
 
 
 
 
 
 
 
b2620a8
 
 
a15365e
 
 
9c0daeb
 
a15365e
9c0daeb
e203fb8
9c0daeb
 
8d095fd
 
 
 
0aaa4e0
 
 
 
8d095fd
 
0aaa4e0
8d095fd
0aaa4e0
 
 
 
 
 
 
 
 
8d095fd
 
b2620a8
 
 
 
 
 
a15365e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import tarfile
import datasets
from collections import defaultdict

_DESCRIPTION = """\
Dataset for extracting notations from chess scoresheets, integrating both image and text data.
"""

_CITATION = """\
@InProceedings{huggingface:dataset,
title = {A great new dataset},
author={huggingface, Inc.},
year={2024}
}
"""

_LICENSE = "Creative Commons Attribution 3.0"

class ChessImageTextDataset(datasets.GeneratorBasedBuilder):
    """Dataset for linking chess scoresheet images with multiple ground truth texts."""
    
    def _info(self):
        # Define the features of your dataset (images + text)
        features = datasets.Features(
            {
                "image": datasets.Image(),  # Image feature for chess scoresheets
                "text": datasets.Value("string"),  # Text feature for chess notations
            }
        )
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage={
                "text_dataset_homepage": "https://huggingface.co/datasets/Chesscorner/jsonl-chess-dataset",
                "image_dataset_homepage": "https://huggingface.co/datasets/Chesscorner/chess-images"
            },
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        """Define the splits of the dataset."""
        image_dataset_url = "https://huggingface.co/datasets/Chesscorner/chess-images/resolve/main/flat_images.tar.gz"
        extracted_image_path = dl_manager.download(image_dataset_url)

        text_dataset_url = "https://huggingface.co/datasets/Chesscorner/jsonl-chess-dataset/resolve/main/train.jsonl/train.jsonl"
        text_filepath = dl_manager.download(text_dataset_url)

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "image_tar_path": extracted_image_path,  # Path to the tar.gz file
                    "text_filepath": text_filepath,  # Path to the text dataset
                },
            ),
        ]

    def _generate_examples(self, image_tar_path, text_filepath):
        """Generate examples by linking images with multiple related texts and clean up the text data."""
        idx = 0
        # Extract and map text IDs to their corresponding images
        image_mapping = self._extract_images_from_tar(image_tar_path)

        # Dictionary to hold multiple texts for each image ID
        grouped_texts = defaultdict(list)

        # Load the text dataset (ground truths) from the JSONL file
        with open(text_filepath, encoding="utf-8") as fp:
            for line in fp:
                obj = json.loads(line)
                text = obj["text"]
                
                # Extract the text ID (assuming text ID matches image filename)
                text_id = text[:5]  # Adjust this based on the actual pattern of text IDs
                
                # Group texts by their text_id (which corresponds to the image)
                grouped_texts[text_id].append(text)

        # Now generate examples, linking each image to its grouped texts
        for text_id, texts in grouped_texts.items():
            image_file = image_mapping.get(f"{text_id}.png")  # Adjust file extension if necessary
            
            # Ensure the image exists and yield the example
            if image_file:
                # Clean the text to keep only chess notation
                cleaned_texts = [self._extract_chess_notation(text) for text in texts]
                
                # Add numbering to the moves in pairs
                numbered_text = self._add_numeration(cleaned_texts)
                
                yield idx, {
                    "image": image_file,
                    "text": numbered_text,  # Link all related cleaned notations together with numeration
                }
                idx += 1
            else:
                print(f"Image not found for ID: {text_id}")

    def _extract_images_from_tar(self, tar_path):
        """Extracts the images from the tar.gz archive and returns a mapping of image filenames to file paths."""
        image_mapping = {}
        extraction_directory = "images_extracted"  # Temporary directory to store extracted images
        os.makedirs(extraction_directory, exist_ok=True)

        # Open the tar file and extract only files (skip directories)
        with tarfile.open(tar_path, "r:gz") as tar:
            for member in tar.getmembers():
                if member.isfile():  # Only process files, skip directories
                    image_filename = os.path.basename(member.name)
                    extracted_image_path = os.path.join(extraction_directory, image_filename)

                    # Extract the image file individually
                    with tar.extractfile(member) as extracted_file:
                        with open(extracted_image_path, "wb") as out_file:
                            out_file.write(extracted_file.read())

                    # Map the image file to its path
                    image_mapping[image_filename] = extracted_image_path
        
        return image_mapping

    def _extract_chess_notation(self, text):
        """Extracts the chess notation from the full text string."""
        # Assuming the chess notation comes after the filename and space, e.g., '001_0_30_white.png Rxc6'
        notation = text.split(" ", 1)[-1]  # Extract everything after the first space
        return notation.strip()

    def _add_numeration(self, notations):
        """Adds numeration to chess notations, pairing moves and numbering them."""
        numbered_text = []
        counter = 1

        # Pair every two moves and add numeration
        for i in range(0, len(notations), 2):
            # Grab two moves if available, otherwise just take the remaining one
            move_pair = notations[i:i+2]
            numbered_move = f"{counter}. " + " ".join(move_pair)
            numbered_text.append(numbered_move)
            counter += 1

        # Join all numbered moves into a single text
        return " ".join(numbered_text)