File size: 6,173 Bytes
6eece70
 
 
 
 
 
 
 
 
 
844a51a
6eece70
 
 
844a51a
6eece70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e30c694
6eece70
 
 
 
 
 
 
 
 
 
 
 
c1586cb
6eece70
 
fcc1085
c1586cb
6eece70
 
 
 
 
 
 
 
 
 
e30c694
6eece70
e30c694
6eece70
 
e30c694
6eece70
 
 
e30c694
 
6eece70
 
 
 
e30c694
c1586cb
6eece70
 
c1586cb
6eece70
c1586cb
e30c694
c1586cb
6eece70
 
 
e30c694
 
 
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
import os
import warnings
from shutil import unpack_archive
from typing import Union, List
from urllib.request import urlretrieve

import pandas as pd
import sqlite3
import datasets

_CITATION = """@article{zanca2023contrastive,

  title={Contrastive Language-Image Pretrained Models are Zero-Shot Human Scanpath Predictors},

  author={Zanca, Dario and Zugarini, Andrea and Dietz, Simon and Altstidl, Thomas R and Ndjeuha, Mark A Turban and Schwinn, Leo and Eskofier, Bjoern},

  journal={arXiv preprint arXiv:2305.12380},

  year={2023}

}"""

_DESCRIPTION = """CapMIT1003 is a dataset of captions and click-contingent image explorations collected during captioning tasks. 

CapMIT1003 is based on the same stimuli from the well-known MIT1003 benchmark, for which eye-tracking data

under free-viewing conditions is available, which offers a promising opportunity to concurrently study human attention under both tasks.

"""

_HOMEPAGE = "https://github.com/mad-lab-fau/CapMIT1003/"
MIT1003_URL = "http://people.csail.mit.edu/tjudd/WherePeopleLook/ALLSTIMULI.zip"
_VERSION = "1.0.0"

logger = datasets.logging.get_logger(__name__)


class CapMIT1003DB:
    """

    Lightweight wrapper around CapMIT1003 SQLite3 database.



    It provides utility functions for loading labeled images with captions and their associated click paths. To use it,

    you first need to download the database from https://redacted.com/scanpath.db.

    """

    def __init__(self, db_path: Union[str, bytes, os.PathLike] = 'capmit1003.db',

                 img_path: Union[str, bytes, os.PathLike] = os.path.join('mit1003', 'ALLSTIMULI')):
        """



        Parameters

        ----------

        db_path: str or bytes or os.PathLike

            Path pointing to the location of the `scanpath.db` SQLite3 database.

        img_path: str or bytes or os.PathLike

            Path pointing to the location of the MIT1003 stimuli images.

        """
        self.db_path = db_path
        self.img_path = os.path.join(img_path, '')
        if not os.path.exists(db_path) and not os.path.isfile(db_path):
            warnings.warn('Could not find database at {}'.format(db_path))
        if not os.path.exists(img_path) and not os.path.isdir(img_path):
            warnings.warn('Could not find images at {}'.format(img_path))

    def __enter__(self):
        self.cnx = sqlite3.connect(self.db_path)
        return self

    def __exit__(self, type, value, traceback):
        self.cnx.close()

    def get_captions(self) -> pd.DataFrame:
        """ Retrieve image-caption pairs of CapMIT1003 database.



        Returns

        -------

        pd.DataFrame

            Data frame with columns `obs_uid`, `usr_uid`, `start_time`, `caption`, `img_uid`, and `img_path`. See

            accompanying readme for full documentation of columns.

        """
        captions = pd.read_sql_query('SELECT * FROM captions o LEFT JOIN images i USING(img_uid)', self.cnx)
        captions['img_path'] = self.img_path + captions['img_path']
        return captions

    def get_click_path(self, obs_uid: str) -> pd.DataFrame:
        """ Retrieve click path for a specific image-caption pair.



        Parameters

        ----------

        obs_uid: str

            The unique id of the image-caption pair for which to retrieve the click path.



        Returns

        -------

        pd.DataFrame

            Data frame with columns `click_id`, `obs_uid`, `x`, `y`, and `click_time`. See accompanying readme for full

            documentation of columns.

        """
        return pd.read_sql_query('SELECT x, y, click_time AS time FROM clicks WHERE obs_uid = ?', self.cnx,
                                 params=[obs_uid])


class CapMIT1003(datasets.GeneratorBasedBuilder):
    _URLS = [MIT1003_URL]

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    "obs_uid": datasets.Value("string"),
                    "usr_uid": datasets.Value("string"),
                    "caption": datasets.Value("string"),
                    "image": datasets.Image(),
                    "clicks_path": datasets.Sequence(datasets.Sequence(datasets.Value("int32"), length=2)),
                    "clicks_time": datasets.Sequence(datasets.Value("timestamp[s]"))
                }
            ),
            # No default supervised_keys (as we have to pass both question
            # and context as input).
            supervised_keys=None,
            homepage=_HOMEPAGE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
        urls_to_download = {"mit1003": self._URLS}
        downloaded_files = dl_manager.download_and_extract(urls_to_download)
        downloaded_db = dl_manager.download({"cap1003": ["./capmit1003.db"]})

        return [
            datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"mit1003_path": downloaded_files["mit1003"], "capmit1003_db_path": downloaded_db["cap1003"]}),
        ]


    def _generate_examples(self, mit1003_path, capmit1003_db_path):
        with CapMIT1003DB(os.path.join(capmit1003_db_path[0]), os.path.join(mit1003_path[0], "ALLSTIMULI")) as db:
            image_captions = db.get_captions()
            for pair in image_captions.itertuples(index=False):
                obs_uid = pair.obs_uid
                click_path = db.get_click_path(obs_uid)
                xy_coordinates = click_path[['x', 'y']].values
                clicks_time = click_path["time"].values
                example = {
                    "obs_uid": obs_uid,
                    "usr_uid": pair.usr_uid,
                    "image": pair.img_path,
                    "caption": pair.caption,
                    "clicks_path": xy_coordinates,
                    "clicks_time": clicks_time
                }

                yield obs_uid, example


#datasets-cli test CapMIT1003/CAPMIT1003.py --save_info --all_configs