"""
Reading and writing data.
- Eyelink EDF files: :func:`read_eyelink` (usually used through
:meth:`~pypillometry.EyeData.from_eyelink`)
- data exports of Tobii Pro Lab (Tobii Pro Glasses):
:func:`read_tobii_prolab` (usually used through
:meth:`~pypillometry.HeadMountedEyeData.from_tobii_prolab`)
- GazePoint recordings (Open Gaze API): :func:`read_gazepoint` (usually
used through :meth:`~pypillometry.EyeData.from_gazepoint`)
- saved objects: :func:`write_file` and :func:`read_file` (pickle or
HDF5 files; usually used through :meth:`~pypillometry.EyeData.write_file`
and :meth:`~pypillometry.EyeData.from_file`)
- files from URLs (HTTP(S), SSH, OSF) and the download cache:
:func:`fetch_url`, :func:`local_copy`, :func:`download`,
:func:`osf_authenticate`, :func:`get_osf_project_files`
- files from figshare items (public, or private with a token):
:func:`get_figshare_files`, :func:`fetch_figshare_file`,
:func:`figshare_session`
See the user guide (Loading and saving data) for an overview.
"""
import gzip
import pickle
import os
from contextlib import contextmanager
from typing import TYPE_CHECKING, Any, Generator, Optional
if TYPE_CHECKING: # imported where used (slow)
import eyelinkio
import pandas as pd
import requests
from loguru import logger
from .convenience import is_url, suppress_all_output, requires_package
from .logging import logging_get_level, _show_progress
from . import state
from . import hdf5
try:
from compression import zstd # Python >= 3.14
except ImportError:
from backports import zstd
#: zstd compression level used by :func:`write_file`
ZSTD_LEVEL = 3
_ZSTD_MAGIC = b"\x28\xb5\x2f\xfd"
_GZIP_MAGIC = b"\x1f\x8b"
_HDF5_EXTENSIONS = (".h5", ".hdf5")
__all__ = [
"osf_authenticate", "download", "fetch_url", "local_copy", "write_file",
"read_file", "read_eyelink", "read_tobii_prolab", "get_osf_project_files",
"get_figshare_files", "fetch_figshare_file", "figshare_session",
]
[docs]
def osf_authenticate(
access_token: str,
validate: bool = True,
session: Optional["requests.Session"] = None,
timeout: float = 10.0,
) -> "requests.Session":
"""
Authenticate against the OSF API using a personal access token.
Parameters
----------
access_token : str
Personal access token generated on OSF.
validate : bool, optional
If True (default), verify the token by calling ``/v2/users/me/``.
session : requests.Session, optional
Existing session to configure. If None, a new session is created.
timeout : float, optional
Timeout (in seconds) for the validation request when ``validate`` is True.
Returns
-------
requests.Session
Session configured with the OSF bearer token.
Raises
------
ValueError
If no access token is provided or validation fails.
"""
import requests
if not access_token or not isinstance(access_token, str):
raise ValueError("A non-empty OSF access token string is required.")
token = access_token.strip()
if not token:
raise ValueError("Access token cannot be empty or whitespace.")
session = session or requests.Session()
session.headers.update(
{
"Authorization": f"Bearer {token}",
"Accept": "application/json",
}
)
if validate:
try:
response = session.get("https://api.osf.io/v2/users/me/", timeout=timeout)
response.raise_for_status()
except requests.exceptions.HTTPError as exc:
status = exc.response.status_code if exc.response is not None else "unknown"
raise ValueError(f"OSF token validation failed (status {status}).") from exc
except requests.exceptions.RequestException as exc:
raise ValueError("OSF token validation request failed.") from exc
else:
logger.info("OSF token validation succeeded.")
return session
def _osf_client_url_to_download_url(url: str, session: Optional["requests.Session"] = None) -> str:
"""
Convert an OSF client URL to a download URL.
Parameters
----------
url : str
OSF client URL
session : requests.Session, optional
requests session to use for the download. If None, a new session is created.
Returns
-------
str
Download URL
"""
import requests
# is it an OSF client URL?
if not url.startswith("https://osf.io/"):
logger.debug(f"URL is not an OSF client URL: {url!r}")
return url
# Check if it's already a download URL
if "/download/" in url:
logger.debug(f"URL is already a download URL: {url!r}")
return url
# get the project ID
from urllib.parse import urlsplit
parts = [segment for segment in urlsplit(url).path.split('/') if segment]
if not parts:
logger.error(f"No OSF identifier found in {url!r}")
return url
file_id = parts[0]
logger.debug(f"File ID: {file_id}")
# make a get request to https://api.osf.io/v2/files/{file_id}/
if session is not None:
response = session.get(f"https://api.osf.io/v2/files/{file_id}/")
else:
response = requests.get(f"https://api.osf.io/v2/files/{file_id}/")
download_url = response.json()["data"]["links"]["move"].replace("/move", "/download")
logger.debug(f"Download URL: {download_url}")
return download_url
[docs]
def download(url: str, fname: str = None, chunk_size: int = 1024, session: Optional["requests.Session"] = None) -> str:
"""Download a file from a URL to a local file.
See https://gist.github.com/yanqd0/c13ed29e29432e3cf3e7c38467f42f51.
Parameters
----------
url : str
URL of the file to download.
fname : str, optional
Local filename to save the file to. If None, create a temporary file.
chunk_size : int, optional
Size of the chunks to download the file in. Default is 1024.
session : requests.Session, optional
requests session to use for the download. If None, a new session is created.
Returns
-------
str
Local filename of the downloaded file.
"""
import requests
from tqdm import tqdm
import tempfile
# Create temporary file if fname is None
if fname is None:
# Extract file extension from URL if possible
from urllib.parse import urlparse
parsed_url = urlparse(url)
path = parsed_url.path
if path and "." in os.path.basename(path):
suffix = os.path.splitext(path)[1]
else:
suffix = ""
# Create temporary file
fd, fname = tempfile.mkstemp(suffix=suffix)
os.close(fd) # Close the file descriptor, we'll open it again below
# convert the URL to a download URL if it is an OSF client URL
url = _osf_client_url_to_download_url(url, session=session)
own_session = session is None
session = session or requests.Session()
try:
with session.get(url, stream=True) as resp:
resp.raise_for_status()
# unknown size (no content-length): progress bar without total
total = int(resp.headers.get("content-length", 0)) or None
# fetch_url() downloads to "<name>.part"
name = os.path.basename(fname)
if name.endswith(".part"):
name = name[:-len(".part")]
with open(fname, "wb") as file, tqdm(
desc=name,
total=total,
unit="iB",
unit_scale=True,
unit_divisor=1024,
disable=not _show_progress(),
) as bar:
for data in resp.iter_content(chunk_size=chunk_size):
size = file.write(data)
bar.update(size)
finally:
if own_session:
session.close()
return fname
def is_ssh_url(source) -> bool:
"""Check if `source` is an SSH URL (``ssh://[user@]host[:port]/path``).
Parameters
----------
source : str
string to check
Returns
-------
bool
True if `source` starts with ``ssh://``
"""
return isinstance(source, str) and source.startswith("ssh://")
def _parse_ssh_url(url: str):
"""Split an SSH URL into (host, port, remote path).
`host` may contain a user (``user@host``). The path is absolute
(``ssh://host/data/f.edf`` -> ``/data/f.edf``) unless it starts with
``~/``; then it is relative to the home directory on the server
(``ssh://host/~/data/f.edf`` -> ``data/f.edf``).
"""
from urllib.parse import urlsplit, unquote
parts = urlsplit(url)
if parts.scheme != "ssh" or not parts.hostname:
raise ValueError(f"Not a valid SSH URL: '{url}' (expected ssh://host/path)")
host = parts.hostname
if parts.username:
host = f"{parts.username}@{host}"
path = unquote(parts.path)
if path in ("", "/"):
raise ValueError(f"SSH URL '{url}' has no path")
if path.startswith("/~/"):
path = path[3:]
elif path == "/~":
raise ValueError(f"SSH URL '{url}' has no path")
return host, parts.port, path
def _cache_path(url: str, cache_dir: str, layout: str = "flat") -> str:
"""Local path in `cache_dir` for a URL.
With ``layout="flat"``, the file (or folder) name only:
``cache_dir/<name>``. With ``layout="mirror"``, the full remote path:
``cache_dir/<host>/<path>``; for SSH URLs with a path relative to the
home directory, ``~`` is inserted after the host.
"""
from urllib.parse import urlsplit, unquote
if layout not in ("flat", "mirror"):
raise ValueError(f"cache_layout must be 'flat' or 'mirror', not '{layout}'")
if is_ssh_url(url):
host, port, path = _parse_ssh_url(url)
rel = path.strip("/").split("/")
if not path.startswith("/"):
rel = ["~"] + rel # relative to home on the server
else:
parts = urlsplit(url)
host, port = parts.hostname, parts.port
rel = [p for p in unquote(parts.path).split("/") if p] or ["index"]
if layout == "flat":
return os.path.join(cache_dir, rel[-1])
host_dir = host if port is None else f"{host}_{port}"
return os.path.join(cache_dir, host_dir, *rel)
def _ssh_remote_size(host: str, port, path: str) -> Optional[int]:
"""Size in bytes of a file (or folder, if `path` ends with ``/``) on an SSH server.
Uses ``wc -c`` for files and ``du -sk`` for folders (approximate).
Returns None if the size cannot be determined.
"""
import shlex
import shutil
import subprocess
if shutil.which("ssh") is None:
return None
is_dir = path.endswith("/")
qpath = shlex.quote(path.rstrip("/") if is_dir else path)
remote = f"du -sk {qpath}" if is_dir else f"wc -c < {qpath}"
cmd = ["ssh", "-o", "BatchMode=yes"]
if port is not None:
cmd += ["-p", str(port)]
cmd += [host, remote]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
size = int(result.stdout.split()[0]) if result.returncode == 0 else None
except (OSError, subprocess.TimeoutExpired, ValueError, IndexError):
size = None
if size is None:
logger.debug(f"Could not get the size of '{host}:{path}'")
return None
return size * 1024 if is_dir else size
def _local_size(path: str) -> int:
"""Size in bytes of a local file or folder (0 if it does not exist)."""
if os.path.isfile(path):
return os.path.getsize(path)
total = 0
for root, _, fnames in os.walk(path):
for fname in fnames:
try:
total += os.path.getsize(os.path.join(root, fname))
except OSError: # file removed while walking
pass
return total
def _scp(url: str, target: str) -> None:
"""Copy the file (or folder, if `url` ends with ``/``) at an SSH URL to `target`.
Shows a progress bar that follows the size of `target` while ``scp``
is running.
"""
from tqdm import tqdm
import subprocess
import shutil
import threading
if shutil.which("scp") is None:
raise RuntimeError("Downloading from SSH URLs requires the 'scp' command")
host, port, path = _parse_ssh_url(url)
is_dir = path.endswith("/")
cmd = ["scp", "-q", "-o", "BatchMode=yes"]
if port is not None:
cmd += ["-P", str(port)]
if is_dir:
cmd.append("-r")
cmd += [f"{host}:{path.rstrip('/') if is_dir else path}", target]
total = _ssh_remote_size(host, port, path)
# run scp in a thread and follow the size of the local copy
out = {}
def run() -> None:
try:
out["result"] = subprocess.run(cmd, capture_output=True, text=True)
except BaseException as e:
out["error"] = e
worker = threading.Thread(target=run, daemon=True)
worker.start()
with tqdm(desc=os.path.basename(path.rstrip("/")), total=total,
unit="iB", unit_scale=True, unit_divisor=1024,
disable=not _show_progress()) as bar:
while worker.is_alive():
worker.join(0.2)
bar.update(_local_size(target) - bar.n)
# final size (also if scp finished before the first update)
bar.update(_local_size(target) - bar.n)
if "error" in out:
raise out["error"]
result = out["result"]
if result.returncode != 0:
msg = result.stderr.strip()
raise RuntimeError(
f"Could not download '{url}' via SSH (scp exit code "
f"{result.returncode}): {msg}\n"
"Note: only key-based SSH login is supported (no passwords)."
)
[docs]
def fetch_url(
url: str,
cache_file: Optional[str] = None,
cache_dir: Optional[str] = None,
force_download: bool = False,
session: Optional["requests.Session"] = None,
cache_layout: str = "flat") -> str:
"""Download an HTTP(S) or SSH URL to a local file, with caching.
HTTP(S) URLs are downloaded with :func:`download` (OSF client URLs
such as ``https://osf.io/<id>`` are converted to download URLs).
SSH URLs have the form ``ssh://[user@]host[:port]/path`` and are
downloaded with the system's ``scp``, which uses ``~/.ssh/config``
(host aliases, users, keys). Only key-based login is supported: password
prompts are disabled (``BatchMode=yes``). The path is absolute on the
server; use ``ssh://host/~/path`` for a path relative to the home
directory. An SSH URL ending in ``/`` downloads the whole folder.
Parameters
----------
url : str
HTTP(S) or SSH URL
cache_file : str, optional
local filename to store the download in
cache_dir : str, optional
directory to store the download in (used if `cache_file` is None);
see `cache_layout`. If both are None, a new temporary directory is
used. The location is logged.
force_download : bool, optional
if False (default), an existing local copy is reused; if True, the
file is downloaded again
session : requests.Session, optional
requests session for HTTP(S) downloads (e.g., from
:func:`osf_authenticate` for private OSF projects)
cache_layout : str, optional
where in `cache_dir` the download is stored: ``"flat"`` (default)
uses the file name only (``cache_dir/<file>``), ``"mirror"`` the
full remote path (``cache_dir/<host>/<path>``). With ``"flat"``,
files with the same name from different URLs share one local copy,
so the first one would be reused; use ``"mirror"`` (or
`force_download`) in that case.
Returns
-------
str
local path of the downloaded file (or folder)
"""
import shutil
import tempfile
if not is_url(url): # also true for SSH URLs
raise ValueError(f"Not a URL: '{url}'")
if cache_file is None:
if cache_dir is None:
cache_dir = tempfile.mkdtemp(prefix="pypillometry_")
cache_file = _cache_path(url, cache_dir, cache_layout)
if os.path.exists(cache_file) and not force_download:
logger.info(f"Using cached copy of '{url}': {cache_file}")
return cache_file
parent = os.path.dirname(cache_file)
if parent:
os.makedirs(parent, exist_ok=True)
# download to a temporary name, so that an interrupted download
# is not used as a cached copy later
part = cache_file + ".part"
if os.path.isdir(part):
shutil.rmtree(part)
elif os.path.exists(part):
os.remove(part)
logger.info(f"Downloading '{url}' to {cache_file}")
if is_ssh_url(url):
_scp(url, part)
else:
download(url, part, session=session)
if os.path.isdir(cache_file):
shutil.rmtree(cache_file)
os.replace(part, cache_file)
return cache_file
[docs]
def get_osf_project_files(osf_id: str, session: Optional["requests.Session"] = None
) -> dict[str, dict[str, Any]]:
"""
Get all file IDs from an OSF project.
Parameters
----------
osf_id : str
The OSF project ID
session : requests.Session, optional
Authenticated session for accessing private projects. If None, uses unauthenticated requests.
Returns
-------
dict
Dictionary mapping file paths to their IDs, download URLs, file sizes
and checksums (``md5``, ``sha256``; empty if OSF does not provide them)
"""
from tqdm import tqdm
files = {}
estimated_files = 100 # Start with estimate of 100 files
def process_files(url: str, current_path: str = "", pbar=None) -> None:
"""
Recursively process files and folders from an OSF API URL.
Parameters
----------
url : str
The OSF API URL to process
current_path : str
Current path in the project structure
pbar : tqdm
Progress bar instance
"""
import requests
nonlocal estimated_files
if session is not None:
response = session.get(url)
else:
response = requests.get(url)
if response.status_code != 200:
raise ValueError(f"Could not access project files: {response.status_code}")
data = response.json()
if 'data' not in data:
raise ValueError(f"Unexpected API response structure: {data}")
for item in data['data']:
if 'attributes' not in item or 'links' not in item:
continue
attrs = item['attributes']
if 'name' not in attrs or 'kind' not in attrs:
continue
name = attrs['name']
full_path = os.path.join(current_path, name)
if attrs['kind'] == 'file':
if 'download' in item['links']:
# Get file size from attributes
size = attrs.get('size', 0)
hashes = (attrs.get('extra') or {}).get('hashes') or {}
files[full_path] = {
'id': item.get('id', ''),
'download_url': item['links']['download'],
'size': size,
'md5': hashes.get('md5') or '',
'sha256': hashes.get('sha256') or '',
}
pbar.update(1)
# If we're close to the estimate, increase it
if len(files) >= estimated_files * 0.8:
estimated_files *= 2
pbar.total = estimated_files
pbar.set_description(f"Processing: {full_path}")
elif attrs['kind'] == 'folder':
# Use the 'upload' link and replace query params to list folder contents
# The 'new_folder' link requires write permissions (403 for public access)
if 'upload' in item['links']:
# upload link looks like: .../folder_id/?kind=file
# we need: .../folder_id/ (without query params)
folder_url = item['links']['upload'].split('?')[0]
process_files(folder_url, full_path, pbar)
if isinstance(data.get('links'), dict) and data['links'].get('next'):
process_files(data['links']['next'], current_path, pbar)
# Process files with progress bar starting at estimated count
root_url = f"https://api.osf.io/v2/nodes/{osf_id}/files/osfstorage/"
with tqdm(total=estimated_files, desc="Processing files",
disable=not _show_progress()) as pbar:
process_files(root_url, "", pbar)
return files
_FIGSHARE_API = "https://api.figshare.com/v2"
def _figshare_article(article) -> tuple[str, int | None]:
"""(item ID, version or None) from an item ID, a figshare URL or a DOI."""
import re
s = str(article).strip()
if s.isdigit():
return s, None
if "figshare" in s:
# DOI: 10.6084/m9.figshare.<id>[.v<version>]
m = re.search(r"figshare\.(\d+)(?:\.v(\d+))?/?$", s)
# URL: https://figshare.com/articles/<type>/<title>/<id>[/<version>]
m = m or re.search(r"/(\d+)(?:/(\d+))?/?(?:[?#].*)?$", s)
if m:
return m.group(1), int(m.group(2)) if m.group(2) else None
raise ValueError(f"Not a figshare item ID, URL or DOI: '{article}'")
[docs]
def figshare_session(token: str) -> "requests.Session":
"""A requests session with a figshare personal token.
For private figshare items (see :func:`get_figshare_files` and
:func:`fetch_figshare_file`, which also take the token directly).
Parameters
----------
token : str
personal token (figshare: Account -> Integrations -> Personal tokens)
Returns
-------
requests.Session
"""
import requests
token = (token or "").strip()
if not token:
raise ValueError("A non-empty figshare token is required.")
session = requests.Session()
session.headers["Authorization"] = f"token {token}"
return session
[docs]
def get_figshare_files(article, version: Optional[int] = None,
token: Optional[str] = None) -> dict[str, dict[str, Any]]:
"""List the files of a figshare item (public, or private with a token).
Parameters
----------
article : int or str
figshare item ID (e.g., ``28776617``), the item's URL
(``https://figshare.com/articles/dataset/<title>/28776617``) or its
DOI (``10.6084/m9.figshare.28776617``)
version : int, optional
version of the item; default the latest one (or the version in the
URL or DOI, if it contains one)
token : str, optional
figshare personal token, for a private item of your account (or one
shared with you). Without `version`, the files of the item as it is
now in the account (including changes that are not published yet);
an item that is not in the account is listed as a public one.
Returns
-------
dict
file name -> dict with the file's ``id``, ``download_url``, ``size``
(bytes) and ``md5`` checksum
Examples
--------
>>> files = get_figshare_files(28776617) # doctest: +SKIP
>>> files["sub-001_ses-1.pypil"]["size"] # doctest: +SKIP
30879440
"""
import requests
article_id, url_version = _figshare_article(article)
if version is None:
version = url_version
url = f"{_FIGSHARE_API}/articles/{article_id}"
if version is not None:
url += f"/versions/{version}"
url += "/files"
session = figshare_session(token) if token else requests.Session()
with session:
if token and version is None:
# the item in the account (private or with unpublished changes)
account_url = f"{_FIGSHARE_API}/account/articles/{article_id}/files"
try:
return _figshare_list(session, account_url)
except FileNotFoundError:
pass # not in the account: public item
try:
return _figshare_list(session, url)
except FileNotFoundError:
which = f"item {article_id}" + (f", version {version}," if version else "")
hint = ("private items need a token" if not token else
"check the token and that the item is in your account")
raise ValueError(f"figshare {which} not found ({hint})") from None
def _figshare_list(session, url) -> dict[str, dict[str, Any]]:
"""All files of a figshare listing URL (FileNotFoundError: 404/403)."""
files = {}
page, page_size = 1, 1000
while True:
resp = session.get(url, params={"page": page, "page_size": page_size},
timeout=30)
if resp.status_code in (403, 404):
raise FileNotFoundError(url)
resp.raise_for_status()
batch = resp.json()
for f in batch:
files[f["name"]] = {
"id": f["id"],
"download_url": f["download_url"],
"size": f.get("size", 0),
"md5": f.get("computed_md5") or f.get("supplied_md5") or "",
}
if len(batch) < page_size:
return files
page += 1
def _md5(fname: str) -> str:
import hashlib
h = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
[docs]
def fetch_figshare_file(
article,
name: str,
version: Optional[int] = None,
cache_dir: Optional[str] = None,
force_download: bool = False,
cache_layout: str = "flat",
token: Optional[str] = None) -> str:
"""Download a file from a figshare item, with caching.
The download is checked against the MD5 checksum that figshare provides.
Parameters
----------
article : int or str
figshare item ID, URL or DOI (see :func:`get_figshare_files`)
name : str
name of the file in the item (see :func:`get_figshare_files`)
version : int, optional
version of the item; default the latest one (or the version in the
URL or DOI, if it contains one)
cache_dir : str, optional
directory to store the download in; if None, a new temporary
directory is used
force_download : bool, optional
if False (default), an existing local copy is reused (without
contacting figshare); if True, the file is downloaded again
cache_layout : str, optional
``"flat"`` (default) stores the file as ``cache_dir/<name>``,
``"mirror"`` as ``cache_dir/figshare.com/<id>/<version>/<name>``
(``latest`` if no version is given), so that files with the same
name from different items do not share a local copy
token : str, optional
figshare personal token, for a private item (see
:func:`get_figshare_files`)
Returns
-------
str
local path of the downloaded file
Examples
--------
>>> fname = fetch_figshare_file(28776617, "sub-001_ses-1.pypil",
... cache_dir="data") # doctest: +SKIP
>>> d = EyeData.from_file(fname) # doctest: +SKIP
"""
import tempfile
article_id, url_version = _figshare_article(article)
if version is None:
version = url_version
if os.path.basename(name) != name or name in ("", ".", ".."):
raise ValueError(f"Not a file name: '{name}'")
if cache_dir is None:
cache_dir = tempfile.mkdtemp(prefix="pypillometry_")
if cache_layout == "flat":
cache_file = os.path.join(cache_dir, name)
elif cache_layout == "mirror":
cache_file = os.path.join(cache_dir, "figshare.com", article_id,
f"v{version}" if version else "latest", name)
else:
raise ValueError(f"cache_layout must be 'flat' or 'mirror', not '{cache_layout}'")
if os.path.exists(cache_file) and not force_download:
logger.info(f"Using cached copy of '{name}' (figshare {article_id}): {cache_file}")
return cache_file
files = get_figshare_files(article_id, version, token=token)
if name not in files:
raise ValueError(f"File '{name}' not found in figshare item {article_id}; "
f"available: {', '.join(files)}")
info = files[name]
session = figshare_session(token) if token else None
try:
fetch_url(info["download_url"], cache_file=cache_file, force_download=True,
session=session)
finally:
if session is not None:
session.close()
if info["md5"] and _md5(cache_file) != info["md5"]:
os.remove(cache_file)
raise ValueError(f"Download of '{name}' (figshare {article_id}) is "
"corrupted (MD5 checksum does not match); try again")
return cache_file
[docs]
@contextmanager
def local_copy(
source: str,
cache_file: Optional[str] = None,
cache_dir: Optional[str] = None,
autodelete: Optional[bool] = None,
force_download: bool = False,
session: Optional["requests.Session"] = None,
cache_layout: str = "flat") -> Generator[str, None, None]:
"""Context manager that gives a local filename for `source`.
HTTP(S) and SSH URLs are downloaded with :func:`fetch_url`; local
paths are passed through unchanged (and never deleted).
Parameters
----------
source : str
local path, HTTP(S) URL or SSH URL
cache_file, cache_dir, force_download, session, cache_layout
see :func:`fetch_url`
autodelete : bool or None, optional
if True, the downloaded copy (also in `cache_file`/`cache_dir`) is
deleted when the context is left, i.e. after the file was read; a
temporary directory is removed completely. If None (default), only
a temporary directory (no `cache_file`/`cache_dir`) is removed.
Yields
------
str
local filename
"""
import shutil
import tempfile
if not is_url(source): # also true for SSH URLs
yield source
return
tmpdir = None
if cache_file is None and cache_dir is None:
tmpdir = tempfile.mkdtemp(prefix="pypillometry_")
cache_dir = tmpdir
if autodelete is None:
autodelete = tmpdir is not None
fname = fetch_url(source, cache_file=cache_file, cache_dir=cache_dir,
force_download=force_download, session=session,
cache_layout=cache_layout)
try:
yield fname
finally:
if autodelete:
target = tmpdir or fname
logger.info(f"Deleting downloaded copy: {target}")
if os.path.isdir(target):
shutil.rmtree(target, ignore_errors=True)
elif os.path.exists(target):
os.remove(target)
def _is_hdf5_name(fname) -> bool:
"""True if `fname` has an HDF5 extension (``.h5`` or ``.hdf5``)."""
return str(fname).lower().endswith(_HDF5_EXTENSIONS)
[docs]
def write_file(obj, fname, compress: bool = True) -> None:
"""
Store any Python object in a file using :mod:`pickle` (or HDF5).
By default, the file is compressed with zstd (about 13 times smaller
for eyedata objects). :func:`read_file` detects the compression
automatically.
If `fname` ends with ``.h5`` or ``.hdf5``, the object is stored in an
HDF5 file instead (see :mod:`pypillometry.hdf5`); this works for
eyedata and segmented objects only.
Parameters
----------
obj : object
object to save
fname : str
filename to save to
compress : bool, optional
if True (default), compress the file with zstd (HDF5: larger arrays
with gzip); if False, write an uncompressed file
Raises
------
TypeError
if `fname` is an HDF5 file and `obj` is not an eyedata or segmented
object
"""
if _is_hdf5_name(fname):
hdf5.write_state(state.to_state(obj), fname, compress=compress)
return
if compress:
f = zstd.open(fname, "wb", level=ZSTD_LEVEL)
else:
f = open(fname, "wb")
with f:
pickle.dump(obj, f, protocol=pickle.HIGHEST_PROTOCOL)
def _open_maybe_compressed(fname):
"""Open `fname` for reading, decompressing zstd or gzip files."""
with open(fname, "rb") as f:
magic = f.read(4)
if magic.startswith(_ZSTD_MAGIC):
return zstd.open(fname, "rb")
if magic.startswith(_GZIP_MAGIC):
return gzip.open(fname, "rb")
return open(fname, "rb")
[docs]
def read_file(
fname: str,
cache_file: Optional[str] = None,
force_download: bool = False,
session: Optional["requests.Session"] = None,
cache_dir: Optional[str] = None,
autodelete: Optional[bool] = None,
cache_layout: str = "flat") -> Any:
"""
Read a Python object from a file using :mod:`pickle` (or HDF5).
Plain, zstd- and gzip-compressed pickle files and HDF5 files written
by :func:`write_file` are supported (the format is detected from the
file content). Objects saved with an older version of pypillometry are
upgraded to the current version.
URLs are downloaded with :func:`~pypillometry.io.fetch_url`, in the
same way as in :func:`~pypillometry.io.read_eyelink`.
Parameters
----------
fname : str
filename, HTTP(S) URL or SSH URL (``ssh://server/folder/file.pd``)
cache_file : str, optional
local filename to store a downloaded file in
cache_dir : str, optional
directory to store a downloaded file in (as ``cache_dir/<file>``,
see `cache_layout`), used if `cache_file` is None. If both are
None, a temporary directory is used.
force_download : bool, optional
if True, download again even if a local copy exists in
`cache_file`/`cache_dir`
session : requests.Session, optional
requests session for HTTP(S) downloads (e.g., from
:func:`~pypillometry.io.osf_authenticate` for private projects)
autodelete : bool or None, optional
if True, the downloaded copy is deleted after it was read (also in
`cache_file`/`cache_dir`). If None (default), only a temporary
download (no `cache_file`/`cache_dir`) is deleted. Local files are
never deleted.
cache_layout : str, optional
``"flat"`` (default) or ``"mirror"`` (``cache_dir/<host>/<path>``),
see :func:`~pypillometry.io.fetch_url`
Returns
-------
object
loaded object
Warnings
--------
Pickle files can run arbitrary code when they are read. Only read pickle
files from sources you trust; HDF5 files do not run code.
"""
with local_copy(fname, cache_file=cache_file, cache_dir=cache_dir,
autodelete=autodelete, force_download=force_download,
session=session, cache_layout=cache_layout) as local:
if hdf5.is_hdf5(local):
return state.from_state(hdf5.read_state(local))
with _open_maybe_compressed(local) as f:
# maps classes that moved to their new location
return state._Unpickler(f).load()
[docs]
@requires_package("eyelinkio")
def read_eyelink(
source: str,
cache_file: Optional[str] = None,
force_download: bool = False,
session: Optional["requests.Session"] = None,
cache_dir: Optional[str] = None,
autodelete: Optional[bool] = None,
cache_layout: str = "flat") -> "eyelinkio.EDF":
"""
Read an Eyelink file/URL and return the object returned by the "eyelinkio" package.
Requires the optional package `eyelinkio`. Its console output is only
shown when the log level is "DEBUG". URLs are downloaded with
:func:`~pypillometry.io.fetch_url`.
Parameters
----------
source : str
filename of the Eyelink EDF file, HTTP(S) URL (OSF client URLs such
as ``https://osf.io/<id>`` are converted to download URLs) or SSH URL
(``ssh://server/folder/file.edf``)
cache_file : str, optional
local filename to store a downloaded file in
cache_dir : str, optional
directory to store a downloaded file in (as ``cache_dir/<file>``,
see `cache_layout`), used if `cache_file` is None. If both are
None, a temporary directory is used.
force_download : bool, optional
if True, download again even if a local copy exists in
`cache_file`/`cache_dir`
session : requests.Session, optional
requests session for HTTP(S) downloads (e.g., from
:func:`~pypillometry.io.osf_authenticate` for private projects)
autodelete : bool or None, optional
if True, the downloaded copy is deleted after it was read (also in
`cache_file`/`cache_dir`). If None (default), only a temporary
download (no `cache_file`/`cache_dir`) is deleted. Local files are
never deleted.
cache_layout : str, optional
``"flat"`` (default) or ``"mirror"`` (``cache_dir/<host>/<path>``),
see :func:`~pypillometry.io.fetch_url`
Returns
-------
eyelinkio.EDF
object returned by :func:`eyelinkio.read_edf`
Notes
-----
Reading EDF files is slow (about a minute for a 90 MB file, mostly in
`eyelinkio`). Convert them once and work with the saved files, which
are read in well under a second: with the command-line program
``edf2pypil`` or with :meth:`~pypillometry.EyeData.write_file`.
See Also
--------
pypillometry.EyeData.from_eyelink : create an eyedata object from an EDF file
"""
with local_copy(source, cache_file=cache_file, cache_dir=cache_dir,
autodelete=autodelete, force_download=force_download,
session=session, cache_layout=cache_layout) as fname:
return _read_edf(fname)
def _read_edf(fname: str) -> "eyelinkio.EDF":
"""Read a local EDF file with eyelinkio (its output only shown at DEBUG level)."""
import eyelinkio
# Check if DEBUG logging is enabled
current_level = logging_get_level()
show_eyelinkio_output = (current_level == "DEBUG")
if show_eyelinkio_output:
logger.debug(f"Loading EDF file: {fname}")
logger.debug("eyelinkio output will be displayed below:")
with _c_time_locale():
edf = eyelinkio.read_edf(fname)
else:
logger.info(f"Loading EDF file: {fname} (current log level: {current_level}, set to DEBUG to see eyelinkio output)")
with suppress_all_output(), _c_time_locale():
edf = eyelinkio.read_edf(fname)
return edf
#: columns of a Tobii Pro Lab data export that describe the recording
_TOBII_INFO_COLUMNS = {
"Project name": "project", "Participant name": "participant",
"Recording name": "recording", "Recording date": "date",
"Recording start time": "start_time", "Recording duration": "duration_ms",
"Recording Fixation filter name": "fixation_filter", "Export date": "export_date",
"Recording media name": "media_name", "Recording media width": "media_width",
"Recording media height": "media_height",
}
#: the sensors in the export: key in the result -> (name in the column
#: "Sensor", prefix of its data columns)
_TOBII_IMU = {"gyro": ("Gyroscope", "Gyro"), "acc": ("Accelerometer", "Accelerometer"),
"mag": ("Magnetometer", "Magnetometer")}
@requires_package("openpyxl")
def _read_excel(fname: str) -> "pd.DataFrame":
"""Read the first sheet of an Excel file as a pandas.DataFrame."""
import pandas as pd
return pd.read_excel(fname)
[docs]
def read_tobii_prolab(fname: str) -> dict[str, Any]:
"""
Read a data export of Tobii Pro Lab (recordings of Tobii Pro Glasses).
The export ("Data Export" in Tobii Pro Lab) is one table with one row
per sample of one of the sensors (eye tracker, gyroscope,
accelerometer, magnetometer) or per event. This function splits it
into one table per sensor.
Reading Excel files requires the optional package `openpyxl` and is
slow (about half a minute for a three-minute recording); exports as
tab-separated text (``.tsv``) are read much faster.
Parameters
----------
fname : str
filename of the export: an Excel file (``.xlsx``) or a
tab-separated text file (any other extension)
Returns
-------
dict
- ``"eye"``: :class:`pandas.DataFrame` with the samples of the eye
tracker: ``time`` (ms) and the gaze and pupil columns of the
export under their original names (e.g., ``"Gaze point X"``,
``"Pupil diameter left"``)
- ``"gyro"``, ``"acc"``, ``"mag"``: DataFrames with the samples of
the gyroscope (deg/s), accelerometer (m/s²) and magnetometer
(µT): ``time`` (ms), ``x``, ``y``, ``z``; empty if the export
has no such data
- ``"events"``: DataFrame with ``time`` (ms) and ``label``
- ``"info"``: dict that describes the recording (e.g.,
``"participant"``, ``"recording"``, ``"date"``)
See Also
--------
pypillometry.HeadMountedEyeData.from_tobii_prolab : create a data object from the export
"""
import pandas as pd
if str(fname).lower().endswith((".xlsx", ".xlsm")):
tab = _read_excel(fname)
else:
tab = pd.read_csv(fname, sep="\t", low_memory=False)
for col in ("Recording timestamp", "Sensor"):
if col not in tab.columns:
raise ValueError(f"'{fname}' is not a Tobii Pro Lab data export: "
f"no column '{col}'")
tab = tab.rename(columns={"Recording timestamp": "time"})
# recordings exported with a decimal comma are read as text
skip = set(_TOBII_INFO_COLUMNS) | {"Sensor", "Event", "Validity left", "Validity right",
"Eye movement type"}
for col in tab.columns:
if col not in skip and not pd.api.types.is_numeric_dtype(tab[col]):
tab[col] = pd.to_numeric(tab[col].astype(str).str.replace(",", "."),
errors="coerce")
info = {key: tab[col].iloc[0] for col, key in _TOBII_INFO_COLUMNS.items()
if col in tab.columns and len(tab) > 0}
info = {k: (v.item() if hasattr(v, "item") else v) for k, v in info.items()}
eye = tab[tab["Sensor"] == "Eye Tracker"]
eye_cols = [c for c in tab.columns
if c.startswith(("Gaze ", "Pupil ", "Validity ", "Eye movement", "Fixation point"))]
res = {"eye": eye[["time"] + eye_cols].reset_index(drop=True)}
for key, (sensor, prefix) in _TOBII_IMU.items():
cols = [f"{prefix} {ax}" for ax in "XYZ"]
if all(c in tab.columns for c in cols):
imu = tab.loc[tab["Sensor"] == sensor, ["time"] + cols]
else:
imu = pd.DataFrame(columns=["time"] + cols)
res[key] = imu.set_axis(["time", "x", "y", "z"], axis=1).reset_index(drop=True)
if "Event" in tab.columns:
events = tab.loc[tab["Event"].notna(), ["time", "Event"]]
else:
events = pd.DataFrame(columns=["time", "Event"])
res["events"] = events.rename(columns={"Event": "label"}).reset_index(drop=True)
res["info"] = info
return res
[docs]
def read_gazepoint(fname: str, keep_initial_label: bool = False) -> dict[str, Any]:
"""
Read a recording of a GazePoint eye tracker (e.g., GP3).
The file is a table (tab- or comma-separated) with one row per sample
and the columns of the GazePoint Open Gaze API, as written by programs
that record the data stream of the eye tracker: ``CNT``, ``TIME`` (s),
``LPOGX``, ..., ``LPD``, ``LPV``, ``LEYEZ``, ``LPUPILD``,
``LPUPILV``, ..., ``USER``.
The column ``USER`` holds the last label that the experiment sent to
the eye tracker (e.g., ``"TRIAL 3"``). It is repeated on every sample
until the next label; each change of the label is an event at that
sample.
The time of the samples is taken from the sample counter ``CNT`` of the
eye tracker: ``TIME`` is the time at which the recording program
received the sample, which jitters by several ms (and is rounded to
steps of 7.8 ms on some computers), so that it looks as if samples were
missing. The time is the straight line in ``CNT`` that fits ``TIME``
best; samples that are really missing are gaps in ``CNT``. Files
without ``CNT`` (or with repeated values of it) use ``TIME``.
Parameters
----------
fname : str
filename of the recording
keep_initial_label : bool, optional
if False (default), the label of the first sample is not an event:
it was sent before the recording started (often left over from an
earlier recording)
Returns
-------
dict
- ``"samples"``: :class:`pandas.DataFrame` with ``time`` (ms) and
the columns of the file under their original names, sorted by
``CNT`` (or by time; then samples with the time of an earlier
sample are dropped)
- ``"events"``: DataFrame with ``time`` (ms) and ``label``
- ``"info"``: dict with ``"format"``, ``"source"``, ``"time_base"``
(``"CNT"`` or ``"TIME"``), ``"sampling_rate"`` (Hz, from the time
of the samples), ``"lost_samples"`` (gaps in ``CNT``) and
``"duplicate_times"`` (number of dropped samples)
See Also
--------
pypillometry.EyeData.from_gazepoint : create an eyedata object from the file
"""
import numpy as np
import pandas as pd
with open(fname) as f:
header = f.readline()
sep = "\t" if "\t" in header else ","
tab = pd.read_csv(fname, sep=sep, dtype={"USER": str}, low_memory=False)
tab.columns = [str(c).strip() for c in tab.columns]
if "TIME" not in tab.columns:
raise ValueError(f"'{fname}' is not a GazePoint recording: no column 'TIME'")
ndup, lost = 0, 0
use_cnt = "CNT" in tab.columns and len(tab) > 1 and not tab["CNT"].duplicated().any()
if use_cnt:
tab = tab.sort_values("CNT", kind="stable").reset_index(drop=True)
cnt = tab["CNT"].to_numpy(dtype=float)
step, offset = np.polyfit(cnt - cnt[0], tab["TIME"].to_numpy(dtype=float) * 1000., 1)
if not step > 0:
raise ValueError(f"{fname}: TIME does not increase with CNT")
time = offset + step * (cnt - cnt[0])
lost = int(cnt[-1] - cnt[0] + 1 - len(cnt))
if lost:
logger.info(f"{fname}: {lost} samples are missing (gaps in CNT)")
else:
if "CNT" in tab.columns:
logger.warning(f"{fname}: CNT has repeated values; the time is taken from TIME")
tab = tab.sort_values("TIME", kind="stable")
ndup = int(tab["TIME"].duplicated().sum())
if ndup:
logger.warning(f"{fname}: {ndup} samples with the time of an earlier sample "
"are dropped")
tab = tab.drop_duplicates("TIME").reset_index(drop=True)
time = tab["TIME"].to_numpy(dtype=float) * 1000.
step = np.median(np.diff(time)) if len(time) > 1 else np.nan
tab.insert(0, "time", time)
events = pd.DataFrame({"time": np.array([], dtype=float), "label": np.array([], dtype=str)})
if "USER" in tab.columns and len(tab) > 0:
user = tab["USER"].fillna("").astype(str).str.strip()
change = (user != user.shift()).to_numpy(copy=True)
change[0] = keep_initial_label
events = pd.DataFrame({"time": time[change], "label": user[change].to_numpy(dtype=str)})
events = events[events["label"] != ""].reset_index(drop=True)
info = dict(format="GazePoint (Open Gaze API)", source=str(fname),
time_base="CNT" if use_cnt else "TIME", sampling_rate=float(1000. / step),
lost_samples=lost, duplicate_times=ndup)
return {"samples": tab, "events": events, "info": info}
@contextmanager
def _c_time_locale() -> Generator[None, None, None]:
"""Use the "C" locale for times while reading an EDF file.
eyelinkio parses the English date in the file header ("Fri Feb 14
...") with ``strptime``, which fails if a program activated a locale
with other names of days and months (e.g., Norwegian).
"""
import locale
old = locale.setlocale(locale.LC_TIME)
try:
locale.setlocale(locale.LC_TIME, "C")
yield
finally:
locale.setlocale(locale.LC_TIME, old)