
from datetime import datetime

import PIL.ExifTags
import PIL.Image

from vacker.analyser.geolocation import GeolocationAnalyser


class ImageAnalyser(GeolocationAnalyser):


    @staticmethod
    def check_match(file_obj):

        return file_obj.mime_type and file_obj.mime_type.split('/')[0] == 'image'

    @classmethod
    def get_file_properties(cls, file_obj):
        try:
            pil_image = PIL.Image.open(file_obj.path)
        except OSError as exc:
            print(str(exc))
            return

        file_obj.properties['pv_date_taken'] = None
        file_obj.properties['pv_orientation'] = None
        gps_info = {}
        if hasattr(pil_image, '_getexif'):
            exif_data = {
                PIL.ExifTags.TAGS[k]: v
                for k, v in pil_image._getexif().items()
                if k in PIL.ExifTags.TAGS
            } if pil_image._getexif() else None

            if exif_data:
                if 'Orientation' in exif_data:
                    file_obj.properties['pv_orientation'] = exif_data['Orientation']

                if 'GPSInfo' in exif_data:
                    for key in exif_data['GPSInfo'].keys():
                        decode = PIL.ExifTags.GPSTAGS.get(key,key)
                        gps_info[decode] = exif_data['GPSInfo'][key]

                    long_lat = cls._convert_gps_to_lang_lat(gps_info)

                    if 'longitude' in long_lat and 'latitude' in long_lat:
                        file_obj.properties['l_lat'] = float(long_lat['latitude'])
                        file_obj.properties['l_lng'] = float(long_lat['longitude'])

                for datetime_tag in ['DateTime',
                                     'DateTimeOriginal',
                                     'DateTimeDigitized']:
                    if datetime_tag in exif_data:
                        try:
                            file_obj.properties['pv_date_taken'] = datetime.strptime(exif_data[datetime_tag], '%Y:%m:%d %H:%M:%S')
                            break
                        except:
                            pass

        file_obj.properties['pv_width'], file_obj.properties['pv_height'] = pil_image.size
        pil_image.close()

        # If the datetime has been obtained from the meta information,
        # split the year, month and day out for easier searching/indexing
        #if 'pv_date_taken' in file_obj.properties and file_obj.properties['pv_date_taken']:
            #file_obj.properties['pv_date_y'] = file_obj.properties['pv_date_taken'].year
            #file_obj.properties['pv_date_m'] = file_obj.properties['pv_date_taken'].month
            #file_obj.properties['pv_date_d'] = file_obj.properties['pv_date_taken'].day

@@ -635,16 +635,41 @@
 nfo = %7B%7D
+%0A%0A        raw_exif = None
 %0A       
@@ -716,16 +716,174 @@
         
+raw_exif = pil_image._getexif()%0A        file_obj.properties%5B'pv_width'%5D, file_obj.properties%5B'pv_height'%5D = pil_image.size%0A        pil_image.close()%0A%0A        
 exif_dat
@@ -888,20 +888,16 @@
 ata = %7B%0A
-    
         
@@ -932,28 +932,24 @@
             
-    
 for k, v in 
@@ -948,36 +948,24 @@
 k, v in 
-pil_image._get
+raw_
 exif
-()
 .items()
@@ -965,20 +965,16 @@
 items()%0A
-    
         
@@ -1015,37 +1015,21 @@
     
-    
 %7D if 
-pil_image._get
+raw_
 exif
-()
  els
@@ -1036,20 +1036,16 @@
 e None%0A%0A
-    
         
@@ -1066,28 +1066,24 @@
             
- 
-   
 if 'Orientat
@@ -1093,36 +1093,32 @@
 ' in exif_data:%0A
-    
                 
@@ -1191,28 +1191,24 @@
             
-    
 if 'GPSInfo'
@@ -1214,36 +1214,32 @@
 ' in exif_data:%0A
-    
                 
@@ -1298,20 +1298,16 @@
         
-    
 decode =
@@ -1336,16 +1336,17 @@
 get(key,
+ 
 key)%0A   
@@ -1358,28 +1358,24 @@
             
-  
-  
 gps_info%5Bdec
@@ -1408,20 +1408,16 @@
 %5D%5Bkey%5D%0A%0A
-    
         
@@ -1487,28 +1487,24 @@
             
- 
-   
 if 'longitud
@@ -1546,20 +1546,16 @@
 ng_lat:%0A
-    
         
@@ -1637,36 +1637,32 @@
                 
- 
-   
 file_obj.propert
@@ -1706,20 +1706,16 @@
 ude'%5D)%0A%0A
-    
         
@@ -1776,36 +1776,32 @@
                 
-    
 'DateTimeOrigina
@@ -1804,20 +1804,16 @@
 ginal',%0A
-    
         
@@ -1875,20 +1875,16 @@
         
-    
 if datet
@@ -1921,37 +1921,29 @@
             
-   
- 
 try:%0A
-    
             
@@ -2015,32 +2015,89 @@
 ime(
-exif_data%5Bdatetime_tag%5D,
+%0A                            exif_data%5Bdatetime_tag%5D,%0A                           
  '%25Y
@@ -2114,20 +2114,16 @@
 %25M:%25S')%0A
-    
         
@@ -2168,24 +2168,33 @@
     
-    
 except
-:%0A    
+ Exception as exc:%0A
     
@@ -2223,126 +2223,8 @@
 ss%0A%0A
-        file_obj.properties%5B'pv_width'%5D, file_obj.properties%5B'pv_height'%5D = pil_image.size%0A        pil_image.close()%0A%0A
     

improve handler of duration pil_image is kept open