aboutsummaryrefslogtreecommitdiffstats
path: root/bsie/extractor/image/photometrics.py
blob: ae0a5413eb99bfb97d3dc44bac9b2337252dafec (plain)
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
"""

Part of the bsie module.
A copy of the license is provided with the project.
Author: Matthias Baumgartner, 2022
"""
# standard imports
from fractions import Fraction
import typing

# bsie imports
from bsie.utils import bsfs, node, ns

# inner-module imports
from .. import base

# exports
__all__: typing.Sequence[str] = (
    'Exif',
    )


## code ##

def _gps_to_dec(coords: typing.Tuple[float, float, float]) -> float:
    """Convert GPS coordinates from exif to float."""
    # unpack args
    deg, min, sec = coords
    # convert to float
    deg = float(Fraction(deg))
    min = float(Fraction(min))
    sec = float(Fraction(sec))

    if float(sec) > 0:
        # format is deg+min+sec
        return (float(deg) * 3600 + float(min) * 60 + float(sec)) / 3600
    else:
        # format is deg+min
        return float(deg) + float(min) / 60


class Exif(base.Extractor):
    """Extract information from EXIF/IPTC tags of an image file."""

    CONTENT_READER = 'bsie.reader.exif.Exif'

    def __init__(self):
        super().__init__(bsfs.schema.from_string(base.SCHEMA_PREAMBLE + '''
            #bse:t_capture rdfs:subClassOf bsfs:Predicate ;
            #    rdfs:domain bsfs:File ;
            #    rdfs:range xsd:float ;
            #    bsfs:unique "true"^^xsd:boolean .
            bse:exposure rdfs:subClassOf bsfs:Predicate ;
                rdfs:domain bsfs:File ;
                rdfs:range xsd:float ;
                bsfs:unique "true"^^xsd:boolean .
            bse:aperture rdfs:subClassOf bsfs:Predicate ;
                rdfs:domain bsfs:File ;
                rdfs:range xsd:float ;
                bsfs:unique "true"^^xsd:boolean .
            bse:iso rdfs:subClassOf bsfs:Predicate ;
                rdfs:domain bsfs:File ;
                rdfs:range xsd:integer ;
                bsfs:unique "true"^^xsd:boolean .
            bse:focal_length rdfs:subClassOf bsfs:Predicate ;
                rdfs:domain bsfs:File ;
                rdfs:range xsd:float ;
                bsfs:unique "true"^^xsd:boolean .
            bse:width rdfs:subClassOf bsfs:Predicate ;
                rdfs:domain bsfs:File ;
                rdfs:range xsd:integer ;
                bsfs:unique "true"^^xsd:boolean .
            bse:height rdfs:subClassOf bsfs:Predicate ;
                rdfs:domain bsfs:File ;
                rdfs:range xsd:integer ;
                bsfs:unique "true"^^xsd:boolean .
            bse:orientation rdfs:subClassOf bsfs:Predicate ;
                rdfs:domain bsfs:File ;
                rdfs:range xsd:integer ;
                bsfs:unique "true"^^xsd:boolean .
            bse:orientation_label rdfs:subClassOf bsfs:Predicate ;
                rdfs:domain bsfs:File ;
                rdfs:range xsd:string ;
                bsfs:unique "true"^^xsd:boolean .
            bse:altitude rdfs:subClassOf bsfs:Predicate ;
                rdfs:domain bsfs:File ;
                rdfs:range xsd:float ;
                bsfs:unique "true"^^xsd:boolean .
            bse:latitude rdfs:subClassOf bsfs:Predicate ;
                rdfs:domain bsfs:File ;
                rdfs:range xsd:float ;
                bsfs:unique "true"^^xsd:boolean .
            bse:longitude rdfs:subClassOf bsfs:Predicate ;
                rdfs:domain bsfs:File ;
                rdfs:range xsd:float ;
                bsfs:unique "true"^^xsd:boolean .
            '''))
        # initialize mapping from predicate to callback
        self._callmap = {
            #self.schema.predicate(ns.bse.t_capture):         self._date,
            self.schema.predicate(ns.bse.exposure):          self._exposure,
            self.schema.predicate(ns.bse.aperture):          self._aperture,
            self.schema.predicate(ns.bse.iso):               self._iso,
            self.schema.predicate(ns.bse.focal_length):      self._focal_length,
            self.schema.predicate(ns.bse.width):             self._width,
            self.schema.predicate(ns.bse.height):            self._height,
            self.schema.predicate(ns.bse.orientation):       self._orientation,
            self.schema.predicate(ns.bse.orientation_label): self._orientation_label,
            self.schema.predicate(ns.bse.altitude):          self._altitude,
            self.schema.predicate(ns.bse.latitude):          self._latitude,
            self.schema.predicate(ns.bse.longitude):         self._longitude,
            }

    def extract(
            self,
            subject: node.Node,
            content: dict,
            principals: typing.Iterable[bsfs.schema.Predicate],
            ) -> typing.Iterator[typing.Tuple[node.Node, bsfs.schema.Predicate, typing.Any]]:
        for pred in principals:
            # find callback
            clbk = self._callmap.get(pred)
            if clbk is None:
                continue
            # get value
            value = clbk(content)
            if value is None:
                continue
            # produce triple
            yield subject, pred, value

    def _date(self, content: dict): # FIXME: Return type annotation
        raise NotImplementedError()
        #date_keys = (
        #    'Exif.Photo.DateTimeOriginal',
        #    'Exif.Photo.DateTimeDigitized',
        #    'Exif.Image.DateTime',
        #    )
        #for key in date_keys:
        #    if key in content:
        #        dt = content[key].value
        #        if dt.tzinfo is None:
        #            dt = dt.replace(tzinfo=ttime.NoTimeZone)
        #        return dt
        #return None


    ## photometrics

    def _exposure(self, content: dict) -> typing.Optional[float]:
        if 'Exif.Photo.ExposureTime' in content:
            return 1.0 / float(Fraction(content['Exif.Photo.ExposureTime']))
        return None

    def _aperture(self, content: dict) -> typing.Optional[float]:
        if 'Exif.Photo.FNumber' in content:
            return float(Fraction(content['Exif.Photo.FNumber']))
        return None

    def _iso(self, content: dict) -> typing.Optional[int]:
        if 'Exif.Photo.ISOSpeedRatings' in content:
            return int(content['Exif.Photo.ISOSpeedRatings'])
        return None

    def _focal_length(self, content: dict) -> typing.Optional[float]:
        if 'Exif.Photo.FocalLength' in content:
            return float(Fraction(content['Exif.Photo.FocalLength']))
        return None


    ## image dimensions

    def _width(self, content: dict) -> typing.Optional[int]:
        # FIXME: consider orientation!
        if 'Exif.Photo.PixelXDimension' in content:
            return int(content['Exif.Photo.PixelXDimension'])
        return None

    def _height(self, content: dict) -> typing.Optional[int]:
        # FIXME: consider orientation!
        if 'Exif.Photo.PixelYDimension' in content:
            return int(content['Exif.Photo.PixelYDimension'])
        return None

    def _orientation(self, content: dict) -> typing.Optional[int]:
        if 'Exif.Image.Orientation' in content:
            return int(content['Exif.Image.Orientation'])
        return None

    def _orientation_label(self, content: dict) -> typing.Optional[str]:
        width = self._width(content)
        height = self._height(content)
        ori = self._orientation(content)
        if width is not None and height is not None and ori is not None:
            if ori <= 4:
                return 'landscape' if width >= height else 'portrait'
            else:
                return 'portrait' if width >= height else 'landscape'
        return None


    ## location

    def _altitude(self, content: dict) -> typing.Optional[float]:
        if 'Exif.GPSInfo.GPSAltitude' in content:
            return float(Fraction(content['Exif.GPSInfo.GPSAltitude']))
        return None

    def _latitude(self, content: dict) -> typing.Optional[float]:
        if 'Exif.GPSInfo.GPSLatitude' in content:
            return _gps_to_dec(content['Exif.GPSInfo.GPSLatitude'].split())
        return None

    def _longitude(self, content: dict) -> typing.Optional[float]:
        if 'Exif.GPSInfo.GPSLongitude' in content:
            return _gps_to_dec(content['Exif.GPSInfo.GPSLongitude'].split())
        return None

## EOF ##