Python Library Media
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import logging
  2. import os
  3. from PIL import Image
  4. import media
  5. import subprocess
  6. import time
  7. logger = media.logger
  8. __KEY_CAMERA_VENDOR__ = 'camera_vendor'
  9. __KEY_CAMERA_MODEL__ = 'camera_model'
  10. def get_audio_data(full_path):
  11. conv_key_dict = {}
  12. conv_key_dict['album'] = (str, media.KEY_ALBUM)
  13. conv_key_dict['TAG:album'] = (str, media.KEY_ALBUM)
  14. conv_key_dict['TAG:artist'] = (str, media.KEY_ARTIST)
  15. conv_key_dict['artist'] = (str, media.KEY_ARTIST)
  16. conv_key_dict['bit_rate'] = (__int_conv__, media.KEY_BITRATE)
  17. conv_key_dict['duration'] = (float, media.KEY_DURATION)
  18. conv_key_dict['TAG:genre'] = (str, media.KEY_GENRE)
  19. conv_key_dict['genre'] = (str, media.KEY_GENRE)
  20. conv_key_dict['TAG:title'] = (str, media.KEY_TITLE)
  21. conv_key_dict['title'] = (str, media.KEY_TITLE)
  22. conv_key_dict['TAG:track'] = (__int_conv__, media.KEY_TRACK)
  23. conv_key_dict['track'] = (__int_conv__, media.KEY_TRACK)
  24. conv_key_dict['TAG:date'] = (__int_conv__, media.KEY_YEAR)
  25. conv_key_dict['date'] = (__int_conv__, media.KEY_YEAR)
  26. return __adapt__data__(__get_xxprobe_data__(full_path, conv_key_dict), full_path)
  27. def get_video_data(full_path):
  28. conv_key_dict = {}
  29. conv_key_dict['creation_time'] = (__vid_datetime_conv__, media.KEY_TIME)
  30. conv_key_dict['TAG:creation_time'] = (__vid_datetime_conv__, media.KEY_TIME)
  31. conv_key_dict['bit_rate'] = (__int_conv__, media.KEY_BITRATE)
  32. conv_key_dict['duration'] = (float, media.KEY_DURATION)
  33. conv_key_dict['height'] = (__int_conv__, media.KEY_HEIGHT)
  34. conv_key_dict['width'] = (__int_conv__, media.KEY_WIDTH)
  35. conv_key_dict['display_aspect_ratio'] = (__ratio_conv__, media.KEY_RATIO)
  36. return __adapt__data__(__get_xxprobe_data__(full_path, conv_key_dict), full_path)
  37. def get_image_data(full_path):
  38. return __adapt__data__(__get_exif_data__(full_path), full_path)
  39. def __adapt__data__(data, full_path):
  40. data[media.KEY_SIZE] = os.path.getsize(full_path)
  41. # Join Camera Vendor and Camera Model
  42. if __KEY_CAMERA_MODEL__ in data and __KEY_CAMERA_VENDOR__ in data:
  43. model = data.pop(__KEY_CAMERA_MODEL__)
  44. vendor = data.pop(__KEY_CAMERA_VENDOR__)
  45. data[media.KEY_CAMERA] = '%s: %s' % (vendor, model)
  46. # Add time if not exists
  47. if media.KEY_TIME not in data:
  48. if media.KEY_YEAR in data and media.KEY_TRACK in data:
  49. if data[media.KEY_YEAR] != 0: # ignore year 0 - must be wrong
  50. # Use a date where track 1 is the newest in the given year
  51. minute = int(data[media.KEY_TRACK] / 60)
  52. second = (data[media.KEY_TRACK] - 60 * minute) % 60
  53. #
  54. data[media.KEY_TIME] = int(time.mktime((data[media.KEY_YEAR], 1, 1, 0, 59 - minute, 59 - second, 0, 0, 0)))
  55. data[media.KEY_TIME_IS_SUBSTITUTION] = True
  56. else:
  57. data[media.KEY_TIME] = int(os.path.getmtime(full_path))
  58. data[media.KEY_TIME_IS_SUBSTITUTION] = True
  59. return data
  60. def __get_xxprobe_data__(full_path, conv_key_dict):
  61. def _ffprobe_command(full_path):
  62. return ['ffprobe', '-v', 'quiet', '-show_format', '-show_streams', full_path]
  63. def _avprobe_command(full_path):
  64. return ['avprobe', '-v', 'quiet', '-show_format', '-show_streams', full_path]
  65. try:
  66. xxprobe_text = subprocess.check_output(_avprobe_command(full_path))
  67. except FileNotFoundError:
  68. try:
  69. xxprobe_text = subprocess.check_output(_ffprobe_command(full_path))
  70. except FileNotFoundError:
  71. logger.warning('ffprobe and avprobe seem to be not installed')
  72. return {}
  73. #
  74. rv = {}
  75. for line in xxprobe_text.decode('utf-8').splitlines():
  76. try:
  77. key, val = [snippet.strip() for snippet in line.split('=')]
  78. except ValueError:
  79. continue
  80. else:
  81. if key in conv_key_dict:
  82. tp, name = conv_key_dict[key]
  83. try:
  84. rv[name] = tp(val)
  85. except ValueError:
  86. logger.log(logging.WARNING if val else logger.INFO, 'Can\'t convert %s (%s) for %s', repr(val), name, name)
  87. return rv
  88. def __get_exif_data__(full_path):
  89. rv = {}
  90. im = Image.open(full_path)
  91. try:
  92. exif = dict(im._getexif().items())
  93. except AttributeError:
  94. logger.debug('%s does not have any exif information', full_path)
  95. else:
  96. conv_key_dict = {}
  97. # IMAGE
  98. conv_key_dict[0x9003] = (__datetime_conv__, media.KEY_TIME)
  99. conv_key_dict[0x8822] = (__exposure_program_conv__, media.KEY_EXPOSURE_PROGRAM)
  100. conv_key_dict[0x829A] = (__num_denum_conv__, media.KEY_EXPOSURE_TIME)
  101. conv_key_dict[0x9209] = (__flash_conv__, media.KEY_FLASH)
  102. conv_key_dict[0x829D] = (__num_denum_conv__, media.KEY_APERTURE)
  103. conv_key_dict[0x920A] = (__num_denum_conv__, media.KEY_FOCAL_LENGTH)
  104. conv_key_dict[0x8825] = (__gps_conv__, media.KEY_GPS)
  105. conv_key_dict[0xA003] = (__int_conv__, media.KEY_HEIGHT)
  106. conv_key_dict[0x8827] = (__int_conv__, media.KEY_ISO)
  107. conv_key_dict[0x010F] = (str, __KEY_CAMERA_VENDOR__)
  108. conv_key_dict[0x0110] = (str, __KEY_CAMERA_MODEL__)
  109. conv_key_dict[0x0112] = (__int_conv__, media.KEY_ORIENTATION)
  110. conv_key_dict[0xA002] = (__int_conv__, media.KEY_WIDTH)
  111. for key in conv_key_dict:
  112. if key in exif:
  113. tp, name = conv_key_dict[key]
  114. value = tp(exif[key])
  115. if value is not None:
  116. rv[name] = value
  117. return rv
  118. # TODO: Join datetime converter __datetime_conv__ and __vid_datetime_conv_
  119. def __datetime_conv__(dt):
  120. format_string = "%Y:%m:%d %H:%M:%S"
  121. return int(time.mktime(time.strptime(dt, format_string)))
  122. def __vid_datetime_conv__(dt):
  123. try:
  124. dt = dt[:dt.index('.')]
  125. except ValueError:
  126. pass # time string seems to have no '.'
  127. dt = dt.replace('T', ' ').replace('/', '').replace('\\', '')
  128. if len(dt) == 16:
  129. dt += ':00'
  130. format_string = '%Y-%m-%d %H:%M:%S'
  131. return int(time.mktime(time.strptime(dt, format_string)))
  132. def __exposure_program_conv__(n):
  133. return {
  134. 0: 'Unidentified',
  135. 1: 'Manual',
  136. 2: 'Program Normal',
  137. 3: 'Aperture Priority',
  138. 4: 'Shutter Priority',
  139. 5: 'Program Creative',
  140. 6: 'Program Action',
  141. 7: 'Portrait Mode',
  142. 8: 'Landscape Mode'
  143. }.get(n, None)
  144. def __flash_conv__(n):
  145. return {
  146. 0: 'No',
  147. 1: 'Fired',
  148. 5: 'Fired (?)', # no return sensed
  149. 7: 'Fired (!)', # return sensed
  150. 9: 'Fill Fired',
  151. 13: 'Fill Fired (?)',
  152. 15: 'Fill Fired (!)',
  153. 16: 'Off',
  154. 24: 'Auto Off',
  155. 25: 'Auto Fired',
  156. 29: 'Auto Fired (?)',
  157. 31: 'Auto Fired (!)',
  158. 32: 'Not Available'
  159. }.get(n, None)
  160. def __int_conv__(value):
  161. try:
  162. return int(value)
  163. except ValueError:
  164. for c in ['.', '/', '-']:
  165. p = value.find(c)
  166. if p >= 0:
  167. value = value[:p]
  168. return int(value)
  169. def __num_denum_conv__(data):
  170. num, denum = data
  171. return num / denum
  172. def __gps_conv__(data):
  173. def lat_lon_cal(lon_or_lat):
  174. lon_lat = 0.
  175. fac = 1.
  176. for num, denum in lon_or_lat:
  177. lon_lat += float(num) / float(denum) * fac
  178. fac *= 1. / 60.
  179. return lon_lat
  180. try:
  181. lon = lat_lon_cal(data[0x0004])
  182. lat = lat_lon_cal(data[0x0002])
  183. if lon != 0 or lat != 0: # do not use lon and lat equal 0, caused by motorola gps weakness
  184. return {'lon': lon, 'lat': lat}
  185. except KeyError:
  186. logger.warning('GPS data extraction failed for %s', repr(data))
  187. def __ratio_conv__(ratio):
  188. ratio = ratio.replace('\\', '')
  189. num, denum = ratio.split(':')
  190. return float(num) / float(denum)