#!/usr/bin/env python from typing import TypeVar, Tuple from dataclasses import dataclass, field import math import json from argaze import DataStructures from argaze.AreaOfInterest import AOIFeatures import numpy import pandas import cv2 as cv @dataclass(frozen=True) class GazePosition(): """Define gaze position as a tuple of coordinates with accuracy.""" value: tuple[int | float] = field(default=(0, 0)) """Position's value.""" accuracy: float = field(default=0., kw_only=True) """Position's accuracy.""" def __getitem__(self, axis: int) -> int | float: """Get position value along a particular axis.""" return self.value[axis] def __iter__(self) -> iter: """Iterate over each position value axis.""" return iter(self.value) def __len__(self) -> int: """Number of axis in position value.""" return len(self.value) def __repr__(self): """String representation""" return json.dumps(self, ensure_ascii = False, default=vars) def __array__(self): """Cast as numpy array.""" return numpy.array(self.value) @property def valid(self) -> bool: """Is the accuracy not None?""" return self.accuracy is not None def draw(self, frame, color=(0, 255, 255)): """Draw gaze position point and accuracy circle.""" if self.valid: # Draw point at position cv.circle(frame, self.value, 2, color, -1) # Draw accuracy circle if self.accuracy > 0: cv.circle(frame, self.value, round(self.accuracy), color, 1) class UnvalidGazePosition(GazePosition): """Unvalid gaze position.""" def __init__(self): super().__init__((None, None), accuracy=None) class TimeStampedGazePositions(DataStructures.TimeStampedBuffer): """Define timestamped buffer to store gaze positions.""" def __setitem__(self, key, value: GazePosition|dict): """Force GazePosition storage.""" # Convert dict into GazePosition if type(value) == dict: assert(set(["value", "accuracy"]).issubset(value.keys())) value = GazePosition(value["value"], accuracy=value["accuracy"]) assert(type(value) == GazePosition or type(value) == UnvalidGazePosition) super().__setitem__(key, value) GazeMovementType = TypeVar('GazeMovement', bound="GazeMovement") # Type definition for type annotation convenience @dataclass(frozen=True) class GazeMovement(): """Define abstract gaze movement class as a buffer of timestamped positions.""" positions: TimeStampedGazePositions """All timestamp gaze positions.""" duration: float = field(init=False) """Inferred duration from first and last timestamps.""" def __post_init__(self): start_position_ts, start_position = self.positions.first end_position_ts, end_position = self.positions.last # Update frozen duration attribute object.__setattr__(self, 'duration', end_position_ts - start_position_ts) def __str__(self) -> str: """String display""" output = f'{type(self)}:\n\tduration={self.duration}\n\tsize={len(self.positions)}' for ts, position in self.positions.items(): output += f'\n\t{ts}:\n\t\tvalue={position.value},\n\t\taccurracy={position.accuracy}' return output class Fixation(GazeMovement): """Define abstract fixation as gaze movement.""" def __post_init__(self): super().__post_init__() class Saccade(GazeMovement): """Define abstract saccade as gaze movement.""" def __post_init__(self): super().__post_init__() TimeStampedGazeMovementsType = TypeVar('TimeStampedGazeMovements', bound="TimeStampedGazeMovements") # Type definition for type annotation convenience class TimeStampedGazeMovements(DataStructures.TimeStampedBuffer): """Define timestamped buffer to store gaze movements.""" def __setitem__(self, key, value: GazeMovement): """Force value to inherit from GazeMovement.""" assert(type(value).__bases__[0] == Fixation or type(value).__bases__[0] == Saccade) super().__setitem__(key, value) def __str__(self): output = '' for ts, item in self.items(): output += f'\n{item}' return output GazeStatusType = TypeVar('GazeStatus', bound="GazeStatus") # Type definition for type annotation convenience @dataclass(frozen=True) class GazeStatus(GazePosition): """Define gaze status as a gaze position belonging to an identified and indexed gaze movement.""" movement_type: str = field(kw_only=True) """GazeMovement type to which gaze position belongs.""" movement_index: int = field(kw_only=True) """GazeMovement index to which gaze positon belongs.""" @classmethod def from_position(cls, gaze_position: GazePosition, movement_type: str, movement_index: int) -> GazeStatusType: """Initialize from a gaze position instance.""" return cls(gaze_position.value, accuracy=gaze_position.accuracy, movement_type=movement_type, movement_index=movement_index) TimeStampedGazeStatusType = TypeVar('TimeStampedGazeStatus', bound="TimeStampedGazeStatus") # Type definition for type annotation convenience class TimeStampedGazeStatus(DataStructures.TimeStampedBuffer): """Define timestamped buffer to store gaze status.""" def __setitem__(self, key, value: GazeStatus): super().__setitem__(key, value) class GazeMovementIdentifier(): """Abstract class to define what should provide a gaze movement identifier.""" def __iter__(self) -> GazeMovementType: raise NotImplementedError('__iter__() method not implemented') def __next__(self): raise NotImplementedError('__next__() method not implemented') def __call__(self, ts_gaze_positions: TimeStampedGazePositions): assert(type(ts_gaze_positions) == TimeStampedGazePositions) # process identification on a copy self.__ts_gaze_positions = ts_gaze_positions.copy() return self def identify(self, ts_gaze_positions: TimeStampedGazePositions) -> Tuple[TimeStampedGazeMovementsType, TimeStampedGazeMovementsType, TimeStampedGazeStatusType]: """Identifiy fixations and saccades from timestamped gaze positions.""" assert(type(ts_gaze_positions) == TimeStampedGazePositions) ts_fixations = TimeStampedGazeMovements() ts_saccades = TimeStampedGazeMovements() ts_status = TimeStampedGazeStatus() for gaze_movement in self(ts_gaze_positions): if isinstance(gaze_movement, Fixation): start_ts, start_position = gaze_movement.positions.first ts_fixations[start_ts] = gaze_movement for ts, position in gaze_movement.positions.items(): ts_status[ts] = GazeStatus.from_position(position, 'Fixation', len(ts_fixations)) elif isinstance(gaze_movement, Saccade): start_ts, start_position = gaze_movement.positions.first end_ts, end_position = gaze_movement.positions.last ts_saccades[start_ts] = gaze_movement ts_status[start_ts] = GazeStatus.from_position(start_position, 'Saccade', len(ts_saccades)) ts_status[end_ts] = GazeStatus.from_position(end_position, 'Saccade', len(ts_saccades)) else: continue return ts_fixations, ts_saccades, ts_status @dataclass class VisualScanStep(): """Define a visual scan step as a start timestamp, duration, the name of the area of interest and where gaze looked at in each frame during the step.""" timestamp: int duration: float area: str look_at: DataStructures.TimeStampedBuffer class VisualScanGenerator(): """Abstract class to define when an aoi starts to be looked and when it stops.""" visual_scan_steps: list def __init__(self, ts_aoi_scenes: AOIFeatures.TimeStampedAOIScenes): if type(ts_aoi_scenes) != AOIFeatures.TimeStampedAOIScenes: raise ValueError('argument must be a TimeStampedAOIScenes') self.visual_scan_steps = [] for step in self: if step == None: continue self.visual_scan_steps.append(step) def __iter__(self): raise NotImplementedError('__iter__() method not implemented') def steps(self) -> list: """Get visual scan steps.""" return self.visual_scan_steps def as_dataframe(self) -> pandas.DataFrame: """Convert buffer as pandas dataframe.""" df = pandas.DataFrame.from_dict(self.visual_scan_steps) df.set_index('timestamp', inplace=True) df.sort_values(by=['timestamp'], inplace=True) return df def save_as_csv(self, filepath): """Write buffer content into a csv file.""" try: self.as_dataframe().to_csv(filepath, index=True) except: raise RuntimeError(f'Can\' write {filepath}') class PointerBasedVisualScan(VisualScanGenerator): """Build visual scan on the basis of which AOI are looked.""" def __init__(self, ts_aoi_scenes: AOIFeatures.TimeStampedAOIScenes, ts_gaze_positions: TimeStampedGazePositions): # process identification on a copy self.__ts_aoi_scenes = ts_aoi_scenes.copy() self.__ts_gaze_positions = ts_gaze_positions.copy() # a dictionary to store when an aoi starts to be looked self.__step_dict = {} # build visual scan super().__init__(ts_aoi_scenes) def __iter__(self): """Visual scan generator function.""" # while there is aoi scene to process while len(self.__ts_aoi_scenes) > 0: (ts_current, aoi_scene_current) = self.__ts_aoi_scenes.pop_first() # is aoi scene a missing exception ? try: raise aoi_scene_current # when aoi scene is missing except AOIFeatures.AOISceneMissing as e: pass # when aoi scene is not missing except: try: gaze_position = self.__ts_gaze_positions[ts_current] # is aoi scene a missing exception ? raise gaze_position # when gaze position is missing except GazePositionMissing as e: pass # when there is no gaze position at current time except KeyError as e: pass # when gaze position is not missing except: for name, aoi in aoi_scene_current.items(): looked = aoi.contains_point(gaze_position) if looked: if not name in self.__step_dict.keys(): # aoi starts to be looked self.__step_dict[name] = { 'start': ts_current, 'look_at': DataStructures.TimeStampedBuffer() } # store where the aoi is looked for 4 corners aoi if len(aoi) == 4: self.__step_dict[name]['look_at'][round(ts_current)] = aoi.inner_axis(gaze_position) elif name in self.__step_dict.keys(): ts_start = self.__step_dict[name]['start'] # aoi stops to be looked yield VisualScanStep(round(ts_start), round(ts_current - ts_start), name, self.__step_dict[name]['look_at']) # forget the aoi del self.__step_dict[name] # close started steps for name, step in self.__step_dict.items(): ts_start = step['start'] # aoi stops to be looked yield VisualScanStep(round(ts_start), round(ts_current - ts_start), name, step['look_at']) class FixationBasedVisualScan(VisualScanGenerator): """Build visual scan on the basis of timestamped fixations.""" def __init__(self, ts_aoi_scenes: AOIFeatures.TimeStampedAOIScenes, ts_fixations: TimeStampedGazeMovements): super().__init__(ts_aoi_scenes) if type(ts_fixations) != TimeStampedGazeMovements: raise ValueError('second argument must be a GazeFeatures.TimeStampedGazeMovements') # process identification on a copy self.__ts_aoi_scenes = ts_aoi_scenes.copy() self.__ts_fixations = ts_fixations.copy() def __iter__(self): """Visual scan generator function.""" yield -1, None