/usr/share/phatch/phatch/lib/metadata.py is in phatch-cli 0.2.7.1-3.1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 | # -*- coding: UTF-8 -*-
# Phatch - Photo Batch Processor
# Copyright (C) 2007-2008 www.stani.be
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses/
#
# Phatch recommends SPE (http://pythonide.stani.be) for python editing.
# Follows PEP8
# import rpdb2; rpdb2.start_embedded_debugger('x')
#TODO: PROVIDE THESE AS EXTRACT METHOD, exif rotation
#synchronize between exif automatically? pil manual
#sphinx doc everything
import datetime
import os
import re
import time
try:
import pyexiv2
import _pyexiv2
except ImportError:
pyexiv2 = None
_pyexiv2 = None
import imtools
import odict
import unicoding
from desktop import DESKTOP_FOLDER
from metadataTest import DateTime, INFO_TEST, is_string, MONTHS, now, WEEKDAYS
from reverse_translation import _t
RE_VAR = re.compile('<.+?>')
DATETIME_KEYS = ['year', 'month', 'day', 'hour', 'minute', 'second']
RE_DATETIME_KEYS = re.compile('(%s)$' % ('|'.join(['[.]' + key
for key in DATETIME_KEYS])))
RE_PYEXIV2_TAG = re.compile('^(Exif|Iptc)_.+')
RE_PYEXIV2_TAG_EDITABLE = re.compile('^(Exif|Iptc)_\w+$')
ORIENTATION_TAGS = ['orientation', 'Pexif_Orientation', 'Zexif_Orientation']
WRITABLE_TAGS = ['dpi', 'transparency'] + ORIENTATION_TAGS
def is_editable_tag(tag):
if RE_PYEXIV2_TAG_EDITABLE.match(tag):
value = INFO_TEST.get(tag, 1)
return type(value) in (str, unicode, int, float) \
or isinstance(value, DateTime)
return False
def is_writable_tag(tag):
return tag in WRITABLE_TAGS or \
(RE_PYEXIV2_TAG_EDITABLE.match(tag) and not(tag in (
'Exif_Photo_PixelXDimension',
'Exif_Photo_PixelYDimension',
'Exif_Image_Software')))
def is_writeable_not_exif_tag(tag, mode):
return tag in ('dpi', 'orientation') \
or (mode == 'P' and tag == 'transparency')
RE_DATETIME_COLON = \
re.compile('[0-9]{4,4}:[0-9]{2,2}:[0-9]{2,2} [0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2}')
class InfoProvideError(Exception):
"""When the variable can't be provided by the current info
instances.
"""
pass
# Keep this outside _InfoCache to avoid self reference
def _update_static_source(self):
"""Update static cache does not do anything. This is just
a dummy function which can be assigned to
:method:``_update_source`` if the source is not callable."""
pass
def _update_callable_source(self):
"""Update dynamic cache updates ``self._source`` with
``self._get_source_dynamic``. This can be assigned to
:method:``_update_source`` if the source is callable.
.. see also: :method:`_set_source`
"""
self._set_source(self._get_source_dynamic())
class _InfoCache(object):
def __init__(self, source=None, vars=None):
"""Creates a cached info. The base is the source from which
all variables are extracted on demand. When all variables
have to be extracted use the :method:``extract_all`` method.
The source can be a static object or a callable for cases
where the object is manipulated and the variables remain
valid (e.g. when resizing an image the mode stays valid)
The difference between ``get`` and ``extract`` is that ``get``
returns a value, while ``extract`` extracts it and places it in
``dict``. ``extract`` allows for multiple, related values to
be extracted simultaneously.
``__getitem__``is installed by :method:`enable_cache` or
:method:`disable_cache`
:param source: retrieve source from which to extract data
:type source: object or callable
"""
if not (source is None):
if is_string(source):
source = self.get_source_from_file(source)
self.set_source(source)
else:
self.dict = self.empty_dict.copy()
self.set_vars(vars)
def _set_extract_methods(self):
"""To be overwritten if the info has preknown variables."""
self._extract_methods = {}
def dump(self, source=None):
if source:
self.set_source(source)
self.extract_vars()
return self.dict.copy()
@classmethod
def provides(cls, var):
"""Wether this info (might) provide the ``var`` variable.
:returns: if this info should handle this variable
:rtype: bool
"""
return var in cls.possible_vars or var[:cls._prefix_n] == cls.prefix
def set_source(self, source):
"""Sets the source of this info. This allows reuse of the same
info if needed.
:param source: retrieve source from which to extract data
:type source: object or callable
.. see also: :method:`_set_source`
"""
if is_string(source):
#source is a filename
source = self.get_source_from_file(source)
if callable(source):
self._get_source_dynamic = source
self._update_source = _update_callable_source
source = None
else:
self._get_source_dynamic = None
self._update_source = _update_static_source
self._set_source(source)
self.disable_cache()
self.dict = self.empty_dict.copy()
def _set_source(self, source):
"""Sets the source at the lowest level. Helper method for
:method:`set_source` and :method:`_update_callable_source`.
:param source: retrieve source from which to extract data
:type source: object or callable
"""
self._source = source
def set_vars(self, vars):
self.vars = vars
def enable_cache(self):
"""Enable the static cache so that the expensive
:method:``_get_source_dynamic`` does not get called for
every var access.
This makes only sense for callable sources.
"""
self._update_source(self)
type(self).__getitem__ = type(self)._get_var_from_source_without_update
def disable_cache(self):
"""Turn off static caching.
This makes only sense for callable sources.
"""
type(self).__getitem__ = type(self)._get_var_from_source_with_update
def _get_var_from_source_with_update(self, var):
"""If the variable ``var`` is not present in the ``dict``,
this method updates the ``source`` first and afterwards
extracts the variable ``var`` from source.
:param var: variable
:type var: string
"""
try:
return self.dict[var]
except KeyError:
self._update_source(self)
return self._get_var_from_source(var)
def _get_var_from_source_without_update(self, var):
"""If the variable ``var`` is not present in the ``dict``,
this extracts the variable ``var`` from source without updating
the ``source`` (as it is static).
:param var: variable
:type var: string
"""
try:
return self.dict[var]
except KeyError:
return self._get_var_from_source(var)
def _get_var_from_source(self, var):
"""
:param var: variable
:type var: string
"""
self._extract_var_with_method_or_other(var)
return self.dict[var]
def _extract_var_with_method_or_other(self, var):
"""Extract var and store it in a dictionary.
:param var: variable
:type var: string
"""
if var in self._extract_methods:
self._extract_methods[var](self)
else:
self._extract_other_method(var)
def _extract_other_method(self, var):
"""Extract only one var"""
if var[:self._prefix_n] == self.prefix:
self.dict[var] = self._get_other(var[self._prefix_n:])
else:
raise KeyError(var)
def _extract_other(self, var):
"""Extract only one other ``var`` into ``dict``. This raises a
``KeyError`` by default. Helper function for
:method:`_extract_other_method`. (to be overwritten)
:param var: variable
:type var: string
"""
raise KeyError(self.prefix + var)
def _extract_others(self):
"""Extract all other vars. Does nothing by default.
(to be overwritten)"""
def extract_vars(self, vars=None):
if vars is None:
vars = self.vars
self.enable_cache()
for var in self.vars:
self[var]
self.disable_cache()
def extract_all(self):
"""Extract all values, which is usefull for inspector."""
for var, extract in self._extract_methods.items():
if not(var in self.dict):
extract(self)
self._extract_others()
@classmethod
def load_module(cls):
"""Load module lazily on demand and redirect
:method:`get_source_from_file`
from :method:`_get_source_from_file_and_module` to
:method:`_get_source_from_file`.
"""
cls._load_module()
cls.get_source_from_file = cls._get_source_from_file
def load_filename(self, filename):
"""Load source from filename.
:param filename: filename of the source file
:type filename: string
"""
self.set_source(self.get_source_from_file(filename))
def _get_source_from_file_and_module(self, filename):
"""Loads module and get source from file. Normally this is only
called the first time as :method:`get_source_from_file`. Afterwards
:method:`_get_source_from_file` is called.
:param filename: filename of the source file
:type filename: string
.. see also:: :method:`load_module`
"""
self.load_module()
return self._get_source_from_file(filename)
@classmethod
def _load_module(cls):
"""Code to load the dependent module. (To be overwritten.)"""
def _get_source_from_file(self, filename):
"""If the source can be loaded from a file, specify the load
method here. (To be overwritten.)
:param filename: filename of the source file
:type filename: string
"""
return filename
@classmethod
def needs_orientation(cls, vars):
"""Whether this info needs orientation"""
return False
get_source_from_file = _get_source_from_file_and_module
empty_dict = {}
type = 'cache'
_extract_methods = {}
prefix = type + '_'
_prefix_n = len(prefix)
possible_vars = sorted(_extract_methods.keys())
class UnknownTypeError(Exception):
pass
class InfoFile(_InfoCache):
"""Wraps a lazy file path access around an image filename.
>>> info = InfoFile('/home/phatch/test.png')
>>> info['foldername']
u'phatch'
>>> sorted(info.dict.keys())
['foldername', 'root']
>>> info['type']
u'png'
>>> sorted(info.dict.keys())
['filename', 'foldername', 'root', 'type']
>>> info.set_source('/home/gimp/world.jpg')
>>> info['type']
u'jpg'
>>> sorted(info.dict.keys())
['filename', 'type']
"""
def _set_source(self, source):
if is_string(source):
self._source_path = source
self._source_parent = os.path.dirname(self._source_path)
else:
self._source_path, self._source_parent = source
self._source_path = unicoding.ensure_unicode(self._source_path)
self._source_parent = unicoding.ensure_unicode(self._source_parent)
self._source_parent = self._source_parent.rstrip(os.path.sep)
def _extract_path(self):
"""Extracts the full path from the source."""
self.dict['path'] = self._source_path
def _extract_folder(self):
"""Extracts the parent folder from the source."""
self.dict['folder'] = self._source_parent
def _extract_root(self):
"""Extracts the root folder from the source. The root folder
is the parent of the parent folder."""
self.dict['root'], self.dict['foldername'] = \
os.path.split(self._source_parent)
def _extract_filename(self):
"""Extracts the filename (without type) and type from the source."""
filename = os.path.basename(self._source_path)
self.dict['filename'], typ = \
os.path.splitext(filename)
self.dict['type'] = typ[1:]
def _extract_stat(self):
"""Extracts the file size and date information from the source."""
try:
file_stat = os.stat(self._source_path)
self.dict['filesize'] = file_stat.st_size
st_mtime = time.localtime(file_stat.st_mtime)[:7]
except:
self.dict['filesize'] = 0
st_mtime = (0, ) * 7
self.dict['year'], self.dict['month'], self.dict['day'], \
self.dict['hour'], self.dict['minute'], self.dict['second'], \
self.dict['weekday'] = st_mtime
self.dict['weekdayname'] = WEEKDAYS[self.dict['weekday']]
self.dict['monthname'] = MONTHS[self.dict['month'] - 1]
def _extract_subfolder(self):
"""Extracts the ``subfolder`` from the source. ``subfolder`` is the
child folder from ``folder``.
"""
self.dict['subfolder'] = \
os.path.dirname(self._source_path)[len(self._source_parent) + 1:]
def _extract_desktop(self):
self.dict['desktop'] = DESKTOP_FOLDER
@classmethod
def split_vars(cls, vars):
vars = set(vars)
#known, unknown
return (vars.intersection(cls.possible_vars),
vars.difference(cls.possible_vars))
type = 'File'
_extract_methods = {
_t('day'): _extract_stat,
_t('desktop'): _extract_desktop,
_t('foldername'): _extract_root,
_t('filename'): _extract_filename,
_t('filesize'): _extract_stat,
_t('folder'): _extract_folder,
_t('hour'): _extract_stat,
_t('minute'): _extract_stat,
_t('month'): _extract_stat,
_t('monthname'): _extract_stat,
_t('path'): _extract_path,
_t('root'): _extract_root,
_t('second'): _extract_stat,
_t('subfolder'): _extract_subfolder,
_t('type'): _extract_filename,
_t('weekday'): _extract_stat,
_t('weekdayname'): _extract_stat,
_t('year'): _extract_stat,
}
prefix = type + '_'
_prefix_n = len(prefix)
possible_vars = sorted(_extract_methods.keys())
class _InfoPil(_InfoCache):
@classmethod
def _load_module(cls):
"""Code to load the PIL Image module."""
try:
import openImage
cls.Image = openImage
except ImportError:
import Image
cls.Image = Image
@classmethod
def _get_source_from_file(cls, filename):
"""Load the PIL source from a file.
:param filename: filename of the source file
:type filename: string
"""
return cls.Image.open(filename)
class InfoPil(_InfoPil):
"""Wraps a lazy PIL var access to an image.
:param image: Pil.Image or callable to retrieve it
:type image: Pil.Image/function
>>> import pprint
>>> import Image
>>> image = Image.new('L',(1,2))
>>> info = InfoPil(image)
>>> info['format']
>>> info.provides('formatdescription')
True
>>> pprint.pprint(info.possible_vars)
['aspect',
'compression',
'dpi',
'format',
'formatdescription',
'gamma',
'height',
'interlace',
'mode',
'size',
'transparency',
'width']
>>> sorted(info.dict.keys())
['format', 'orientation']
>>> info['mode']
'L'
>>> info['height']
2
>>> info['format']
>>> info['dpi']
72
>>> sorted(info.dict.keys())
['dpi', 'format', 'height', 'mode', 'orientation', 'size', 'width']
>>> info.reset_geometry()
>>> sorted(info.dict.keys())
['dpi', 'format', 'mode', 'orientation']
>>> info.extract_all()
>>> pprint.pprint(sorted(info.dict.keys()))
['aspect',
'compression',
'dpi',
'format',
'formatdescription',
'gamma',
'height',
'interlace',
'mode',
'orientation',
'size',
'transparency',
'width']
"""
def _extract_aspect(self):
self.dict['aspect'] = self._source.info.get('aspect', None)
def _extract_compression(self):
self.dict['compression'] = \
self._source.info.get('compression', 'none')
def _extract_dpi(self):
self.dict['dpi'] = \
self._source.info.get('dpi', (72, ))[0]
def _extract_format(self):
self.dict['format'] = self._source.format
def _extract_formatdescription(self):
self.dict['formatdescription'] = \
self._source.format_description
def _extract_gamma(self):
self.dict['gamma'] = self._source.info.get('gamma', None)
def _extract_interlace(self):
self.dict['interlace'] = \
self._source.info.get('interlace', None)
def _extract_mode(self):
self.dict['mode'] = self._source.mode
def _extract_size(self):
"""Extract size of image with PIL"""
#we don't translate dotted attributes
size = self._source.size
if self.dict['orientation'] > 4:
size = (size[1], size[0])
self.dict['width'], self.dict['height'] = \
self.dict['size'] = size
def _extract_transparency(self):
self.dict['transparency'] = \
self._source.info.get('transparency', None)
def _get_other(self, var):
"""Get only one variable which is not defined in
:method:`_extract_methods`.
:param var: name of the variable
:type var: string
"""
try:
return self._source.info[var]
except KeyError:
raise KeyError(self.prefix + var)
def _extract_others(self):
"""Extract all other possible vars"""
for key, value in self._source.info.items():
if not(key in self.vars_skip):
self.dict[self.prefix + key] = value
def reset_geometry(self):
for var in ('width', 'height', 'size'):
if var in self.dict:
del self.dict[var]
def set_orientation(self, orientation):
self.dict['orientation'] = orientation
self.reset_geometry()
@classmethod
def needs_orientation(cls, vars):
"""InfoPil always needs to know the orientation.
:returns: True
:rtype: bool
"""
return True
read_only = ('aspect', 'dpi', 'gamma', 'interlace', 'transparency')
empty_dict = {'orientation': 1}
type = 'Pil'
_extract_methods = {
_t('aspect'): _extract_aspect,
_t('compression'): _extract_compression,
_t('dpi'): _extract_dpi,
_t('gamma'): _extract_gamma,
_t('height'): _extract_size,
_t('interlace'): _extract_interlace,
_t('mode'): _extract_mode,
_t('width'): _extract_size,
_t('format'): _extract_format,
_t('formatdescription'): _extract_formatdescription,
_t('size'): _extract_size,
_t('transparency'): _extract_transparency}
prefix = type + '_'
_prefix_n = len(prefix)
possible_vars = sorted(_extract_methods.keys())
vars_skip = possible_vars + ['exif'] # skip for writing png metadata
#Initialize PIL metadata
#This can't be lazily loaded as it is needed by the provide method.
try:
from ExifTags import TAGS, GPSTAGS
EXIFTAGS = {}
EXIFTAGS.update(TAGS)
EXIFTAGS.update(GPSTAGS)
del TAGS
del GPSTAGS
except:
#older versions of PIL
EXIFTAGS = {'Orientation': 'Orientation'}
EXIFTAGS_REVERSE = {}
for key, item in EXIFTAGS.items():
EXIFTAGS_REVERSE[item] = key
def convert_from_string(value):
"""If value is recongized as a datetime string, convert value
into :class:`DateTime` instance.
:param value: any value
:type value: string
:returns: same value or converted in date
:rtype: string/:class:`DateTime`
"""
if is_string(value) and RE_DATETIME_COLON.match(value):
return DateTime(value)
return value
class _InfoPilMetadata(_InfoPil):
def _extract_orientation(self):
"""Extract orientation from source image as integer."""
self.dict['orientation'] = self._source.get(self.orientation, 1)
def _set_source(self, source):
"""Sets the source at the lowest level. Helper method for
:method:`set_source` and :method:`_update_callable_source`.
:param source: retrieve source from which to extract data
:type source: object or callable
"""
try:
self._source = source._getexif()
except:
self._source = {}
return
if not self._source:
self._source = {}
orientation = EXIFTAGS_REVERSE['Orientation']
_extract_methods = {
_t('orientation'): _extract_orientation}
possible_vars = sorted(_extract_methods.keys())
class InfoPexif(_InfoPilMetadata):
"""Wraps a lazy PIL exif var access to an image.
>>> import pprint
>>> filename = '../tests/input/exĩf ïptç.jpg'
>>> info = InfoPexif(filename)
>>> info['orientation']
8
>>> info['Pexif_DateTimeOriginal']
DateTime('2010:03:03 11:03:08')
>>> pprint.pprint(info.dict.keys())
['Pexif_DateTimeOriginal', 'orientation']
>>> import Image
>>> image = Image.open(filename)
>>> info = InfoPexif(image)
>>> info['Pexif_DateTimeOriginal']
DateTime('2010:03:03 11:03:08')
>>> pprint.pprint(info.dict.keys())
['Pexif_DateTimeOriginal']
>>> info.extract_all()
>>> info['Pexif_DateTimeOriginal']
DateTime('2010:03:03 11:03:08')
>>> pprint.pprint(info.dict.keys())
['orientation',
'Pexif_Make',
'Pexif_Flash',
'Pexif_YResolution',
'Pexif_DateTimeDigitized',
'Pexif_ExifImageWidth',
'Pexif_FocalPlaneYResolution',
'Pexif_MaxApertureValue',
'Pexif_MeteringMode',
'Pexif_ExifVersion',
'Pexif_MakerNote',
'Pexif_FNumber',
'Pexif_FocalPlaneResolutionUnit',
'Pexif_SensingMethod',
'Pexif_Orientation',
'Pexif_FocalLength',
'Pexif_XResolution',
'Pexif_ExifOffset',
'Pexif_FileSource',
'Pexif_CompressedBitsPerPixel',
'Pexif_ExifImageHeight',
'Pexif_ResolutionUnit',
'Pexif_ExifInteroperabilityOffset',
'Pexif_ApertureValue',
'Pexif_ExposureTime',
'Pexif_ColorSpace',
'Pexif_YCbCrPositioning',
'Pexif_Model',
'Pexif_DateTime',
'Pexif_ComponentsConfiguration',
'Pexif_FlashPixVersion',
'Pexif_FocalPlaneXResolution',
'Pexif_DateTimeOriginal',
'Pexif_UserComment']
"""
@classmethod
def provides(cls, var):
return var == 'orientation' or \
(var[:cls._prefix_n] == cls.prefix and
var[cls._prefix_n:] in EXIFTAGS_REVERSE)
def _get_other(self, var):
"""Get only one variable which is not defined in
:method:`_extract_methods`.
:param var: name of the variable
:type var: string
"""
try:
key = EXIFTAGS_REVERSE[var]
except KeyError:
# re raise: give full name to key error
raise KeyError(self.prefix + var)
return convert_from_string(self._source[key])
def _extract_others(self):
"""Extract all other possible vars"""
for key, value in self._source.items():
if key in EXIFTAGS:
self.dict['Pexif_' + EXIFTAGS[key]] = \
convert_from_string(value)
type = 'Pexif'
prefix = type + '_'
_prefix_n = len(prefix)
class InfoZexif(_InfoPilMetadata):
"""Wraps a lazy PIL exif var access to an image.
>>> import pprint
>>> filename = '../tests/input/exĩf ïptç.jpg'
>>> info = InfoZexif(filename)
>>> info['Zexif_0x9202']
(128, 32)
>>> import Image
>>> image = Image.open(filename)
>>> info = InfoZexif(image)
>>> info['Zexif_0x9202']
(128, 32)
>>> pprint.pprint(info.dict.keys())
['Zexif_0x9202']
>>> info.extract_all()
>>> pprint.pprint(info.dict.keys())
['Zexif_0x9202',
'Zexif_0x0128',
'orientation',
'Zexif_0x9205',
'Zexif_0x9101',
'Zexif_0xa001',
'Zexif_0xa002',
'Zexif_0x9209',
'Zexif_0xa20f',
'Zexif_0xa005',
'Zexif_0xa20e',
'Zexif_0x9000',
'Zexif_0xa217',
'Zexif_0x9003',
'Zexif_0x9004',
'Zexif_0xa210',
'Zexif_0x011b',
'Zexif_0x9286',
'Zexif_0x9207',
'Zexif_0x829d',
'Zexif_0x829a',
'Zexif_0xa404',
'Zexif_0xa406',
'Zexif_0xa401',
'Zexif_0xa402',
'Zexif_0xa403',
'Zexif_0xa000',
'Zexif_0x9102',
'Zexif_0x0110',
'Zexif_0x0112',
'Zexif_0x0132',
'Zexif_0x920a',
'Zexif_0x8769',
'Zexif_0x010f',
'Zexif_0x927c',
'Zexif_0xa300',
'Zexif_0x0213',
'Zexif_0x011a',
'Zexif_0xa003']
"""
@classmethod
def provides(cls, var):
return var == 'orientation' or \
(var[:cls._prefix_n] == cls.prefix and
cls.regex.match(var[cls._prefix_n:]))
def _get_other(self, var):
"""Get only one variable which is not defined in
:method:`_extract_methods`.
:param var: name of the variable
:type var: string
"""
return convert_from_string(self._source[eval(var)])
def _extract_others(self):
"""Extract all other vars"""
for key, value in self._source.items():
self.dict['Zexif_0x%04x' % key] = convert_from_string(value)
type = 'Zexif'
regex = re.compile('0x[a-f0-9]{4,4}')
prefix = type + '_'
_prefix_n = len(prefix)
class _InfoPyexiv2(_InfoCache):
@classmethod
def provides(cls, var):
return cls.regex.search(var)
def convert(self, value):
if value.__class__ == datetime.datetime:
value = DateTime(value)
return value
def _get_other(self, var):
"""Get only one variable which is not defined in
:method:`_extract_methods`.
:param var: name of the variable
:type var: string
"""
return self.convert(self._source['%s.%s' \
% (self.type, var.replace('_', '.'))].value)
def _extract_others_from_keys(self, exif_keys):
"""Extract all other vars"""
for var in exif_keys:
_var = var.replace('.', '_')
if not(_var in self.dict):
try:
value = self._source[var].value
except:
continue
self.dict[_var] = self.convert(value)
@classmethod
def _load_module(cls):
"""Code to load the pyexiv2 module."""
import pyexiv2
import _pyexiv2
cls.pyexiv2 = pyexiv2
cls._pyexiv2 = _pyexiv2
@classmethod
def _get_source_from_file(cls, filename):
"""Load the pyexiv2 source from a file.
:param filename: filename of the source file
:type filename: string
"""
format = imtools.get_format(os.path.splitext(filename)[-1][1:])
if cls._pyexiv2.is_readable_format(format):
source = cls.pyexiv2.ImageMetadata(filename)
source.read()
return source
else:
return {}
class InfoExif(_InfoPyexiv2):
"""
>>> import pprint
>>> filename = '../tests/input/exĩf ïptç.jpg'
>>> info = InfoExif(filename)
>>> info['Exif_Image_DateTime']
DateTime('2010:03:03 11:03:08')
>>> import pyexiv2
>>> exif = pyexiv2.ImageMetadata(filename)
>>> exif.read()
>>> info = InfoExif(exif)
>>> info['Exif_Image_DateTime']
DateTime('2010:03:03 11:03:08')
>>> print info['Exif_Image_DateTime']
2010:03:03 11:03:08
>>> info['Exif_Image_Orientation']
8
>>> info['Exif_Photo_MaxApertureValue'].__class__ == pyexiv2.Rational
True
>>> print info['Exif_Photo_MaxApertureValue']
128/32
>>> info.extract_all()
>>> pprint.pprint(sorted(info.dict.keys()))
['Exif_CanonCs_0x0000',
'Exif_CanonCs_0x0006',
'Exif_CanonCs_0x0008',
'Exif_CanonCs_0x0009',
'Exif_CanonCs_0x0015',
'Exif_CanonCs_0x001e',
'Exif_CanonCs_0x001f',
'Exif_CanonCs_0x0026',
'Exif_CanonCs_0x0027',
'Exif_CanonCs_0x0029',
'Exif_CanonCs_0x002b',
'Exif_CanonCs_0x002c',
'Exif_CanonCs_0x002d',
'Exif_CanonCs_AESetting',
'Exif_CanonCs_AFPoint',
'Exif_CanonCs_ColorTone',
'Exif_CanonCs_Contrast',
'Exif_CanonCs_DigitalZoom',
'Exif_CanonCs_DisplayAperture',
'Exif_CanonCs_DriveMode',
'Exif_CanonCs_EasyMode',
'Exif_CanonCs_ExposureProgram',
'Exif_CanonCs_FlashActivity',
'Exif_CanonCs_FlashDetails',
'Exif_CanonCs_FlashMode',
'Exif_CanonCs_FocusContinuous',
'Exif_CanonCs_FocusMode',
'Exif_CanonCs_FocusType',
'Exif_CanonCs_ISOSpeed',
'Exif_CanonCs_ImageSize',
'Exif_CanonCs_ImageStabilization',
'Exif_CanonCs_Lens',
'Exif_CanonCs_LensType',
'Exif_CanonCs_Macro',
'Exif_CanonCs_MaxAperture',
'Exif_CanonCs_MeteringMode',
'Exif_CanonCs_MinAperture',
'Exif_CanonCs_PhotoEffect',
'Exif_CanonCs_Quality',
'Exif_CanonCs_Saturation',
'Exif_CanonCs_Selftimer',
'Exif_CanonCs_Sharpness',
'Exif_CanonCs_ZoomSourceWidth',
'Exif_CanonCs_ZoomTargetWidth',
'Exif_CanonSi_0x0000',
'Exif_CanonSi_0x0001',
'Exif_CanonSi_0x0003',
'Exif_CanonSi_0x0006',
'Exif_CanonSi_0x0008',
'Exif_CanonSi_0x000a',
'Exif_CanonSi_0x000b',
'Exif_CanonSi_0x000c',
'Exif_CanonSi_0x000d',
'Exif_CanonSi_0x0010',
'Exif_CanonSi_0x0011',
'Exif_CanonSi_0x0012',
'Exif_CanonSi_0x0014',
'Exif_CanonSi_0x0017',
'Exif_CanonSi_0x0018',
'Exif_CanonSi_0x0019',
'Exif_CanonSi_0x001a',
'Exif_CanonSi_0x001b',
'Exif_CanonSi_0x001c',
'Exif_CanonSi_0x001d',
'Exif_CanonSi_0x001e',
'Exif_CanonSi_0x001f',
'Exif_CanonSi_0x0020',
'Exif_CanonSi_0x0021',
'Exif_CanonSi_AFPointUsed',
'Exif_CanonSi_ApertureValue',
'Exif_CanonSi_FlashBias',
'Exif_CanonSi_ISOSpeed',
'Exif_CanonSi_Sequence',
'Exif_CanonSi_ShutterSpeedValue',
'Exif_CanonSi_SubjectDistance',
'Exif_CanonSi_TargetAperture',
'Exif_CanonSi_TargetShutterSpeed',
'Exif_CanonSi_WhiteBalance',
'Exif_Canon_0x0000',
'Exif_Canon_0x0003',
'Exif_Canon_0x000d',
'Exif_Canon_0x0013',
'Exif_Canon_0x0018',
'Exif_Canon_0x0019',
'Exif_Canon_0x001c',
'Exif_Canon_0x001d',
'Exif_Canon_0x001e',
'Exif_Canon_0x001f',
'Exif_Canon_0x0022',
'Exif_Canon_0x0023',
'Exif_Canon_0x0024',
'Exif_Canon_0x0025',
'Exif_Canon_0x0026',
'Exif_Canon_0x0027',
'Exif_Canon_0x0028',
'Exif_Canon_FirmwareVersion',
'Exif_Canon_FocalLength',
'Exif_Canon_ImageNumber',
'Exif_Canon_ImageType',
'Exif_Canon_ModelID',
'Exif_Canon_OwnerName',
'Exif_Image_DateTime',
'Exif_Image_ExifTag',
'Exif_Image_Make',
'Exif_Image_Model',
'Exif_Image_Orientation',
'Exif_Image_ResolutionUnit',
'Exif_Image_XResolution',
'Exif_Image_YCbCrPositioning',
'Exif_Image_YResolution',
'Exif_Iop_InteroperabilityIndex',
'Exif_Iop_InteroperabilityVersion',
'Exif_Iop_RelatedImageLength',
'Exif_Iop_RelatedImageWidth',
'Exif_MakerNote_ByteOrder',
'Exif_MakerNote_Offset',
'Exif_Photo_ApertureValue',
'Exif_Photo_ColorSpace',
'Exif_Photo_ComponentsConfiguration',
'Exif_Photo_CompressedBitsPerPixel',
'Exif_Photo_CustomRendered',
'Exif_Photo_DateTimeDigitized',
'Exif_Photo_DateTimeOriginal',
'Exif_Photo_DigitalZoomRatio',
'Exif_Photo_ExifVersion',
'Exif_Photo_ExposureBiasValue',
'Exif_Photo_ExposureMode',
'Exif_Photo_ExposureTime',
'Exif_Photo_FNumber',
'Exif_Photo_FileSource',
'Exif_Photo_Flash',
'Exif_Photo_FlashpixVersion',
'Exif_Photo_FocalLength',
'Exif_Photo_FocalPlaneResolutionUnit',
'Exif_Photo_FocalPlaneXResolution',
'Exif_Photo_FocalPlaneYResolution',
'Exif_Photo_InteroperabilityTag',
'Exif_Photo_MakerNote',
'Exif_Photo_MaxApertureValue',
'Exif_Photo_MeteringMode',
'Exif_Photo_PixelXDimension',
'Exif_Photo_PixelYDimension',
'Exif_Photo_SceneCaptureType',
'Exif_Photo_SensingMethod',
'Exif_Photo_ShutterSpeedValue',
'Exif_Photo_UserComment',
'Exif_Photo_WhiteBalance',
'Exif_Thumbnail_Compression',
'Exif_Thumbnail_JPEGInterchangeFormat',
'Exif_Thumbnail_JPEGInterchangeFormatLength',
'Exif_Thumbnail_ResolutionUnit',
'Exif_Thumbnail_XResolution',
'Exif_Thumbnail_YResolution',
'orientation']
"""
def _extract_orientation(self):
"""Extract orientation from source image as integer."""
try:
#be careful to use dots here instead of _
self.dict['orientation'] = self._source['Exif.Image.Orientation'].value
except KeyError:
self.dict['orientation'] = 1
def _extract_others(self):
"""Extract all other vars"""
self._extract_others_from_keys(self._source.exif_keys)
regex = re.compile('^Exif|^orientation$')
type = 'Exif'
_extract_methods = {
_t('orientation'): _extract_orientation}
prefix = type + '_'
_prefix_n = len(prefix)
possible_vars = sorted(_extract_methods.keys())
class InfoIptc(_InfoPyexiv2):
"""
>>> import pprint
>>> filename = '../tests/input/exĩf ïptç.jpg'
>>> info = InfoIptc(filename)
>>> info['Iptc_Application2_RecordVersion']
0
>>> import pyexiv2
>>> exif = pyexiv2.ImageMetadata(filename)
>>> exif.read()
>>> info = InfoIptc(exif)
>>> info['Iptc_Application2_RecordVersion']
0
>>> info['Iptc_Application2_Copyright']
'Copyright 2010, www.stani.be'
>>> pprint.pprint(sorted(info.dict.keys()))
['Iptc_Application2_Copyright', 'Iptc_Application2_RecordVersion']
>>> info.extract_all()
>>> pprint.pprint(sorted(info.dict.keys()))
['Iptc_Application2_Byline',
'Iptc_Application2_Caption',
'Iptc_Application2_Copyright',
'Iptc_Application2_ObjectName',
'Iptc_Application2_RecordVersion']
"""
def _extract_others(self):
"""Extract all other vars"""
self._extract_others_from_keys(self._source.iptc_keys)
type = 'Iptc'
regex = re.compile('^Iptc_')
prefix = type + '_'
_prefix_n = len(prefix)
class InfoEXIF(_InfoCache):
"""
>>> import pprint
>>> filename = '../tests/input/exĩf ïptç.jpg'
>>> info = InfoEXIF(filename)
>>> pprint.pprint(sorted(info.dict.keys()))
[]
>>> info['EXIF_Thumbnail_Compression']
(0x0103) Short=JPEG (old-style) @ 3402
>>> pprint.pprint(sorted(info.dict.keys()))
['EXIF_Thumbnail_Compression']
>>> import pyexiv2
>>> from other import EXIF
>>> exif = EXIF.process_file(open(filename, 'rb'))
>>> info = InfoEXIF(exif)
>>> info['orientation']
8
>>> str(info['EXIF_Image_Orientation'])
'Rotated 90 CCW'
>>> info['EXIF_Thumbnail_Compression']
(0x0103) Short=JPEG (old-style) @ 3402
>>> pprint.pprint(sorted(info.dict.keys()))
['EXIF_Image_Orientation', 'EXIF_Thumbnail_Compression', 'orientation']
>>> info.extract_all()
>>> pprint.pprint(sorted(info.dict.keys()))
['EXIF_ApertureValue',
'EXIF_ColorSpace',
'EXIF_ComponentsConfiguration',
'EXIF_CompressedBitsPerPixel',
'EXIF_CustomRendered',
'EXIF_DateTimeDigitized',
'EXIF_DateTimeOriginal',
'EXIF_DigitalZoomRatio',
'EXIF_ExifImageLength',
'EXIF_ExifImageWidth',
'EXIF_ExifVersion',
'EXIF_ExposureBiasValue',
'EXIF_ExposureMode',
'EXIF_ExposureTime',
'EXIF_FNumber',
'EXIF_FileSource',
'EXIF_Flash',
'EXIF_FlashPixVersion',
'EXIF_FocalLength',
'EXIF_FocalPlaneResolutionUnit',
'EXIF_FocalPlaneXResolution',
'EXIF_FocalPlaneYResolution',
'EXIF_Image_DateTime',
'EXIF_Image_ExifOffset',
'EXIF_Image_Make',
'EXIF_Image_Model',
'EXIF_Image_Orientation',
'EXIF_Image_ResolutionUnit',
'EXIF_Image_XResolution',
'EXIF_Image_YCbCrPositioning',
'EXIF_Image_YResolution',
'EXIF_InteroperabilityOffset',
'EXIF_JPEGThumbnail',
'EXIF_MakerNote',
'EXIF_MakerNote_AFPointSelected',
'EXIF_MakerNote_AFPointUsed',
'EXIF_MakerNote_ContinuousDriveMode',
'EXIF_MakerNote_Contrast',
'EXIF_MakerNote_DigitalZoom',
'EXIF_MakerNote_EasyShootingMode',
'EXIF_MakerNote_ExposureMode',
'EXIF_MakerNote_FirmwareVersion',
'EXIF_MakerNote_FlashActivity',
'EXIF_MakerNote_FlashBias',
'EXIF_MakerNote_FlashDetails',
'EXIF_MakerNote_FlashMode',
'EXIF_MakerNote_FocalUnitsPerMM',
'EXIF_MakerNote_FocusMode',
'EXIF_MakerNote_FocusType',
'EXIF_MakerNote_ISO',
'EXIF_MakerNote_ImageNumber',
'EXIF_MakerNote_ImageSize',
'EXIF_MakerNote_ImageType',
'EXIF_MakerNote_LongFocalLengthOfLensInFocalUnits',
'EXIF_MakerNote_Macromode',
'EXIF_MakerNote_MeteringMode',
'EXIF_MakerNote_OwnerName',
'EXIF_MakerNote_Quality',
'EXIF_MakerNote_Saturation',
'EXIF_MakerNote_SelfTimer',
'EXIF_MakerNote_SequenceNumber',
'EXIF_MakerNote_Sharpness',
'EXIF_MakerNote_ShortFocalLengthOfLensInFocalUnits',
'EXIF_MakerNote_SubjectDistance',
'EXIF_MakerNote_Tag_0x0000',
'EXIF_MakerNote_Tag_0x0001',
'EXIF_MakerNote_Tag_0x0002',
'EXIF_MakerNote_Tag_0x0003',
'EXIF_MakerNote_Tag_0x0004',
'EXIF_MakerNote_Tag_0x000D',
'EXIF_MakerNote_Tag_0x0010',
'EXIF_MakerNote_Tag_0x0013',
'EXIF_MakerNote_Tag_0x0018',
'EXIF_MakerNote_Tag_0x0019',
'EXIF_MakerNote_Tag_0x001C',
'EXIF_MakerNote_Tag_0x001D',
'EXIF_MakerNote_Tag_0x001E',
'EXIF_MakerNote_Tag_0x001F',
'EXIF_MakerNote_Tag_0x0022',
'EXIF_MakerNote_Tag_0x0023',
'EXIF_MakerNote_Tag_0x0024',
'EXIF_MakerNote_Tag_0x0025',
'EXIF_MakerNote_Tag_0x0026',
'EXIF_MakerNote_Tag_0x0027',
'EXIF_MakerNote_Tag_0x0028',
'EXIF_MakerNote_Unknown',
'EXIF_MakerNote_WhiteBalance',
'EXIF_MaxApertureValue',
'EXIF_MeteringMode',
'EXIF_SceneCaptureType',
'EXIF_SensingMethod',
'EXIF_ShutterSpeedValue',
'EXIF_Thumbnail_Compression',
'EXIF_Thumbnail_JPEGInterchangeFormat',
'EXIF_Thumbnail_JPEGInterchangeFormatLength',
'EXIF_Thumbnail_ResolutionUnit',
'EXIF_Thumbnail_XResolution',
'EXIF_Thumbnail_YResolution',
'EXIF_UserComment',
'EXIF_WhiteBalance',
'orientation']
"""
def _extract_orientation(self):
"""Extract orientation from source image as integer.
.. note::
This translates the EXIF orientation string back to a
number.
"""
try:
orientation = self._orientation_dict[
str(self._source['Image Orientation'])]
except KeyError:
orientation = 1
self.dict['orientation'] = orientation
def _get_other(self, var):
"""Get a variable which is not defined in
:method:`_extract_methods`.
:param var: name of the variable
:type var: string
"""
var = var.replace('_', ' ')
try:
return self._source['EXIF ' + var]
except KeyError:
return self._source[var]
def _extract_others(self):
"""Extract all other vars"""
for tag, value in self._source.items():
tag = tag.replace(' ', '_')
if not tag.startswith('EXIF'):
tag = 'EXIF_' + tag
self.dict[tag] = value
@classmethod
def _load_module(cls):
"""Code to load the EXIF module."""
from other import EXIF
cls.EXIF = EXIF
@classmethod
def _get_source_from_file(cls, filename):
"""Load the EXIF source from a file.
:param filename: filename of the source file
:type filename: string
"""
return cls.EXIF.process_file(open(filename, 'rb'))
type = 'EXIF'
_extract_methods = {
_t('orientation'): _extract_orientation}
_orientation_dict = {
'Horizontal (normal)': 1,
'Mirrored horizontal': 2,
'Rotated 180': 3,
'Mirrored vertical': 4,
'Mirrored horizontal then rotated 90 CCW': 5,
'Rotated 90 CW': 6,
'Mirrored horizontal then rotated 90 CW': 7,
'Rotated 90 CCW': 8}
prefix = type + '_'
_prefix_n = len(prefix)
possible_vars = sorted(_extract_methods.keys())
INFOS = [InfoFile]
if pyexiv2:
INFOS.extend([InfoExif, InfoIptc])
INFOS.extend([InfoPil, InfoPexif, InfoZexif])
#, InfoEXIF] #EXIF disabled for now as it crashes
INFOS_WITH_ORIENTATION = [Info for Info in INFOS
if 'orientation' in Info.possible_vars]
VARS_BY_INFO_EXIF = {}
for info in INFOS:
#set to None so it defaults to all variables
VARS_BY_INFO_EXIF[info] = None
VARS_BY_INFO = {InfoFile: None, InfoPil: None}
def get_vars_by_info(filename):
format = imtools.get_format_filename(filename)
if (_pyexiv2 and _pyexiv2.is_readable_format(format)) or format == 'JPEG':
return VARS_BY_INFO_EXIF.copy()
else:
return VARS_BY_INFO.copy()
class InfoTest:
def __getitem__(self, var):
if self.provides(var):
if '_DateTime' in var:
return now()
else:
return INFO_TEST.get(var, '2')
raise KeyError(var)
def __contains__(self, var):
return self.provides(var)
@classmethod
def provides(cls, var):
if var in ('desktop', 'index', 'folderindex'):
return True
for Info in INFOS:
if Info.provides(var):
return True
return False
class InfoExtract:
"""Create an info like dictionary which uses a collection of several
info instances and can evaluate Python expressions.
>>> import Image
>>> import pprint
>>> list(InfoExtract.get_vars_by_info(['mode'])[0].values())
[['mode', 'orientation']]
>>> list(InfoExtract.get_vars_by_info(['width'])[0].values())
[['width', 'orientation']]
>>> vars = ['format', 'width', 'subfolder', 'orientation', 'crazy']
>>> filename = '../tests/input/exĩf ïptç.jpg'
>>> image = Image.open(filename)
>>> info = InfoExtract(filename, vars + ['Pexif_DateTimeOriginal'])
>>> info.types()
['File', 'Exif', 'Pil', 'Pexif']
>>> info.vars_unknown
['crazy']
>>> info['format']
'JPEG'
>>> pprint.pprint(sorted(info.dump(expand=False).items()))
[('Pexif_DateTimeOriginal', DateTime('2010:03:03 11:03:08')),
('format', 'JPEG'),
('height', 640),
('orientation', 8),
('size', (480, 640)),
('subfolder', u''),
('width', 480)]
>>> info['size'] # uses orientation
(480, 640)
>>> image.size # ignores orientation
(640, 480)
>>> info['Pexif_DateTimeOriginal']
DateTime('2010:03:03 11:03:08')
>>> pprint.pprint(sorted(info.dump(expand=True).items()))
[('Pexif_DateTimeOriginal', DateTime('2010:03:03 11:03:08')),
('Pexif_DateTimeOriginal.day', 3),
('Pexif_DateTimeOriginal.hour', 11),
('Pexif_DateTimeOriginal.microsecond', 0),
('Pexif_DateTimeOriginal.minute', 3),
('Pexif_DateTimeOriginal.month', 3),
('Pexif_DateTimeOriginal.monthname', 'March'),
('Pexif_DateTimeOriginal.second', 8),
('Pexif_DateTimeOriginal.weekday', 2),
('Pexif_DateTimeOriginal.weekdayname', 'Wednesday'),
('Pexif_DateTimeOriginal.year', 2010),
('format', 'JPEG'),
('height', 640),
('orientation', 8),
('size', (480, 640)),
('size[0]', 480),
('size[1]', 640),
('subfolder', u''),
('width', 480)]
>>> info.extract_all()
>>> pprint.pprint(sorted(info.dump(expand=False).keys()))
['Exif_CanonCs_0x0000',
'Exif_CanonCs_0x0006',
'Exif_CanonCs_0x0008',
'Exif_CanonCs_0x0009',
'Exif_CanonCs_0x0015',
'Exif_CanonCs_0x001e',
'Exif_CanonCs_0x001f',
'Exif_CanonCs_0x0026',
'Exif_CanonCs_0x0027',
'Exif_CanonCs_0x0029',
'Exif_CanonCs_0x002b',
'Exif_CanonCs_0x002c',
'Exif_CanonCs_0x002d',
'Exif_CanonCs_AESetting',
'Exif_CanonCs_AFPoint',
'Exif_CanonCs_ColorTone',
'Exif_CanonCs_Contrast',
'Exif_CanonCs_DigitalZoom',
'Exif_CanonCs_DisplayAperture',
'Exif_CanonCs_DriveMode',
'Exif_CanonCs_EasyMode',
'Exif_CanonCs_ExposureProgram',
'Exif_CanonCs_FlashActivity',
'Exif_CanonCs_FlashDetails',
'Exif_CanonCs_FlashMode',
'Exif_CanonCs_FocusContinuous',
'Exif_CanonCs_FocusMode',
'Exif_CanonCs_FocusType',
'Exif_CanonCs_ISOSpeed',
'Exif_CanonCs_ImageSize',
'Exif_CanonCs_ImageStabilization',
'Exif_CanonCs_Lens',
'Exif_CanonCs_LensType',
'Exif_CanonCs_Macro',
'Exif_CanonCs_MaxAperture',
'Exif_CanonCs_MeteringMode',
'Exif_CanonCs_MinAperture',
'Exif_CanonCs_PhotoEffect',
'Exif_CanonCs_Quality',
'Exif_CanonCs_Saturation',
'Exif_CanonCs_Selftimer',
'Exif_CanonCs_Sharpness',
'Exif_CanonCs_ZoomSourceWidth',
'Exif_CanonCs_ZoomTargetWidth',
'Exif_CanonSi_0x0000',
'Exif_CanonSi_0x0001',
'Exif_CanonSi_0x0003',
'Exif_CanonSi_0x0006',
'Exif_CanonSi_0x0008',
'Exif_CanonSi_0x000a',
'Exif_CanonSi_0x000b',
'Exif_CanonSi_0x000c',
'Exif_CanonSi_0x000d',
'Exif_CanonSi_0x0010',
'Exif_CanonSi_0x0011',
'Exif_CanonSi_0x0012',
'Exif_CanonSi_0x0014',
'Exif_CanonSi_0x0017',
'Exif_CanonSi_0x0018',
'Exif_CanonSi_0x0019',
'Exif_CanonSi_0x001a',
'Exif_CanonSi_0x001b',
'Exif_CanonSi_0x001c',
'Exif_CanonSi_0x001d',
'Exif_CanonSi_0x001e',
'Exif_CanonSi_0x001f',
'Exif_CanonSi_0x0020',
'Exif_CanonSi_0x0021',
'Exif_CanonSi_AFPointUsed',
'Exif_CanonSi_ApertureValue',
'Exif_CanonSi_FlashBias',
'Exif_CanonSi_ISOSpeed',
'Exif_CanonSi_Sequence',
'Exif_CanonSi_ShutterSpeedValue',
'Exif_CanonSi_SubjectDistance',
'Exif_CanonSi_TargetAperture',
'Exif_CanonSi_TargetShutterSpeed',
'Exif_CanonSi_WhiteBalance',
'Exif_Canon_0x0000',
'Exif_Canon_0x0003',
'Exif_Canon_0x000d',
'Exif_Canon_0x0013',
'Exif_Canon_0x0018',
'Exif_Canon_0x0019',
'Exif_Canon_0x001c',
'Exif_Canon_0x001d',
'Exif_Canon_0x001e',
'Exif_Canon_0x001f',
'Exif_Canon_0x0022',
'Exif_Canon_0x0023',
'Exif_Canon_0x0024',
'Exif_Canon_0x0025',
'Exif_Canon_0x0026',
'Exif_Canon_0x0027',
'Exif_Canon_0x0028',
'Exif_Canon_FirmwareVersion',
'Exif_Canon_FocalLength',
'Exif_Canon_ImageNumber',
'Exif_Canon_ImageType',
'Exif_Canon_ModelID',
'Exif_Canon_OwnerName',
'Exif_Image_DateTime',
'Exif_Image_ExifTag',
'Exif_Image_Make',
'Exif_Image_Model',
'Exif_Image_Orientation',
'Exif_Image_ResolutionUnit',
'Exif_Image_XResolution',
'Exif_Image_YCbCrPositioning',
'Exif_Image_YResolution',
'Exif_Iop_InteroperabilityIndex',
'Exif_Iop_InteroperabilityVersion',
'Exif_Iop_RelatedImageLength',
'Exif_Iop_RelatedImageWidth',
'Exif_MakerNote_ByteOrder',
'Exif_MakerNote_Offset',
'Exif_Photo_ApertureValue',
'Exif_Photo_ColorSpace',
'Exif_Photo_ComponentsConfiguration',
'Exif_Photo_CompressedBitsPerPixel',
'Exif_Photo_CustomRendered',
'Exif_Photo_DateTimeDigitized',
'Exif_Photo_DateTimeOriginal',
'Exif_Photo_DigitalZoomRatio',
'Exif_Photo_ExifVersion',
'Exif_Photo_ExposureBiasValue',
'Exif_Photo_ExposureMode',
'Exif_Photo_ExposureTime',
'Exif_Photo_FNumber',
'Exif_Photo_FileSource',
'Exif_Photo_Flash',
'Exif_Photo_FlashpixVersion',
'Exif_Photo_FocalLength',
'Exif_Photo_FocalPlaneResolutionUnit',
'Exif_Photo_FocalPlaneXResolution',
'Exif_Photo_FocalPlaneYResolution',
'Exif_Photo_InteroperabilityTag',
'Exif_Photo_MakerNote',
'Exif_Photo_MaxApertureValue',
'Exif_Photo_MeteringMode',
'Exif_Photo_PixelXDimension',
'Exif_Photo_PixelYDimension',
'Exif_Photo_SceneCaptureType',
'Exif_Photo_SensingMethod',
'Exif_Photo_ShutterSpeedValue',
'Exif_Photo_UserComment',
'Exif_Photo_WhiteBalance',
'Exif_Thumbnail_Compression',
'Exif_Thumbnail_JPEGInterchangeFormat',
'Exif_Thumbnail_JPEGInterchangeFormatLength',
'Exif_Thumbnail_ResolutionUnit',
'Exif_Thumbnail_XResolution',
'Exif_Thumbnail_YResolution',
'Pexif_ApertureValue',
'Pexif_ColorSpace',
'Pexif_ComponentsConfiguration',
'Pexif_CompressedBitsPerPixel',
'Pexif_DateTime',
'Pexif_DateTimeDigitized',
'Pexif_DateTimeOriginal',
'Pexif_ExifImageHeight',
'Pexif_ExifImageWidth',
'Pexif_ExifInteroperabilityOffset',
'Pexif_ExifOffset',
'Pexif_ExifVersion',
'Pexif_ExposureTime',
'Pexif_FNumber',
'Pexif_FileSource',
'Pexif_Flash',
'Pexif_FlashPixVersion',
'Pexif_FocalLength',
'Pexif_FocalPlaneResolutionUnit',
'Pexif_FocalPlaneXResolution',
'Pexif_FocalPlaneYResolution',
'Pexif_Make',
'Pexif_MakerNote',
'Pexif_MaxApertureValue',
'Pexif_MeteringMode',
'Pexif_Model',
'Pexif_Orientation',
'Pexif_ResolutionUnit',
'Pexif_SensingMethod',
'Pexif_UserComment',
'Pexif_XResolution',
'Pexif_YCbCrPositioning',
'Pexif_YResolution',
'aspect',
'compression',
'day',
'desktop',
'dpi',
'filename',
'filesize',
'folder',
'foldername',
'format',
'formatdescription',
'gamma',
'height',
'hour',
'interlace',
'minute',
'mode',
'month',
'monthname',
'orientation',
'path',
'root',
'second',
'size',
'subfolder',
'transparency',
'type',
'weekday',
'weekdayname',
'width',
'year']
>>> info.set(filename='../tests/input/exĩf ïptç.jpg',
... vars=vars) #exclude Pexif.* vars
>>> pprint.pprint(sorted(info.dump(expand=False).items()))
[('format', 'JPEG'),
('height', 640),
('orientation', 8),
('size', (480, 640)),
('subfolder', u''),
('width', 480)]
>>> info['root']
u'../tests'
>>> d = info.dump(expand=False)
>>> pprint.pprint(sorted(d.items()))
[('foldername', u'input'),
('format', 'JPEG'),
('height', 640),
('orientation', 8),
('root', u'../tests'),
('size', (480, 640)),
('subfolder', u''),
('width', 480)]
>>> type(d) == dict
True
>>> info.set(vars=vars + ['Iptc_Application2_Copyright'])
>>> info.extract_all()
>>> pprint.pprint(sorted(info.dump(expand=False).keys()))
['Exif_CanonCs_0x0000',
'Exif_CanonCs_0x0006',
'Exif_CanonCs_0x0008',
'Exif_CanonCs_0x0009',
'Exif_CanonCs_0x0015',
'Exif_CanonCs_0x001e',
'Exif_CanonCs_0x001f',
'Exif_CanonCs_0x0026',
'Exif_CanonCs_0x0027',
'Exif_CanonCs_0x0029',
'Exif_CanonCs_0x002b',
'Exif_CanonCs_0x002c',
'Exif_CanonCs_0x002d',
'Exif_CanonCs_AESetting',
'Exif_CanonCs_AFPoint',
'Exif_CanonCs_ColorTone',
'Exif_CanonCs_Contrast',
'Exif_CanonCs_DigitalZoom',
'Exif_CanonCs_DisplayAperture',
'Exif_CanonCs_DriveMode',
'Exif_CanonCs_EasyMode',
'Exif_CanonCs_ExposureProgram',
'Exif_CanonCs_FlashActivity',
'Exif_CanonCs_FlashDetails',
'Exif_CanonCs_FlashMode',
'Exif_CanonCs_FocusContinuous',
'Exif_CanonCs_FocusMode',
'Exif_CanonCs_FocusType',
'Exif_CanonCs_ISOSpeed',
'Exif_CanonCs_ImageSize',
'Exif_CanonCs_ImageStabilization',
'Exif_CanonCs_Lens',
'Exif_CanonCs_LensType',
'Exif_CanonCs_Macro',
'Exif_CanonCs_MaxAperture',
'Exif_CanonCs_MeteringMode',
'Exif_CanonCs_MinAperture',
'Exif_CanonCs_PhotoEffect',
'Exif_CanonCs_Quality',
'Exif_CanonCs_Saturation',
'Exif_CanonCs_Selftimer',
'Exif_CanonCs_Sharpness',
'Exif_CanonCs_ZoomSourceWidth',
'Exif_CanonCs_ZoomTargetWidth',
'Exif_CanonSi_0x0000',
'Exif_CanonSi_0x0001',
'Exif_CanonSi_0x0003',
'Exif_CanonSi_0x0006',
'Exif_CanonSi_0x0008',
'Exif_CanonSi_0x000a',
'Exif_CanonSi_0x000b',
'Exif_CanonSi_0x000c',
'Exif_CanonSi_0x000d',
'Exif_CanonSi_0x0010',
'Exif_CanonSi_0x0011',
'Exif_CanonSi_0x0012',
'Exif_CanonSi_0x0014',
'Exif_CanonSi_0x0017',
'Exif_CanonSi_0x0018',
'Exif_CanonSi_0x0019',
'Exif_CanonSi_0x001a',
'Exif_CanonSi_0x001b',
'Exif_CanonSi_0x001c',
'Exif_CanonSi_0x001d',
'Exif_CanonSi_0x001e',
'Exif_CanonSi_0x001f',
'Exif_CanonSi_0x0020',
'Exif_CanonSi_0x0021',
'Exif_CanonSi_AFPointUsed',
'Exif_CanonSi_ApertureValue',
'Exif_CanonSi_FlashBias',
'Exif_CanonSi_ISOSpeed',
'Exif_CanonSi_Sequence',
'Exif_CanonSi_ShutterSpeedValue',
'Exif_CanonSi_SubjectDistance',
'Exif_CanonSi_TargetAperture',
'Exif_CanonSi_TargetShutterSpeed',
'Exif_CanonSi_WhiteBalance',
'Exif_Canon_0x0000',
'Exif_Canon_0x0003',
'Exif_Canon_0x000d',
'Exif_Canon_0x0013',
'Exif_Canon_0x0018',
'Exif_Canon_0x0019',
'Exif_Canon_0x001c',
'Exif_Canon_0x001d',
'Exif_Canon_0x001e',
'Exif_Canon_0x001f',
'Exif_Canon_0x0022',
'Exif_Canon_0x0023',
'Exif_Canon_0x0024',
'Exif_Canon_0x0025',
'Exif_Canon_0x0026',
'Exif_Canon_0x0027',
'Exif_Canon_0x0028',
'Exif_Canon_FirmwareVersion',
'Exif_Canon_FocalLength',
'Exif_Canon_ImageNumber',
'Exif_Canon_ImageType',
'Exif_Canon_ModelID',
'Exif_Canon_OwnerName',
'Exif_Image_DateTime',
'Exif_Image_ExifTag',
'Exif_Image_Make',
'Exif_Image_Model',
'Exif_Image_Orientation',
'Exif_Image_ResolutionUnit',
'Exif_Image_XResolution',
'Exif_Image_YCbCrPositioning',
'Exif_Image_YResolution',
'Exif_Iop_InteroperabilityIndex',
'Exif_Iop_InteroperabilityVersion',
'Exif_Iop_RelatedImageLength',
'Exif_Iop_RelatedImageWidth',
'Exif_MakerNote_ByteOrder',
'Exif_MakerNote_Offset',
'Exif_Photo_ApertureValue',
'Exif_Photo_ColorSpace',
'Exif_Photo_ComponentsConfiguration',
'Exif_Photo_CompressedBitsPerPixel',
'Exif_Photo_CustomRendered',
'Exif_Photo_DateTimeDigitized',
'Exif_Photo_DateTimeOriginal',
'Exif_Photo_DigitalZoomRatio',
'Exif_Photo_ExifVersion',
'Exif_Photo_ExposureBiasValue',
'Exif_Photo_ExposureMode',
'Exif_Photo_ExposureTime',
'Exif_Photo_FNumber',
'Exif_Photo_FileSource',
'Exif_Photo_Flash',
'Exif_Photo_FlashpixVersion',
'Exif_Photo_FocalLength',
'Exif_Photo_FocalPlaneResolutionUnit',
'Exif_Photo_FocalPlaneXResolution',
'Exif_Photo_FocalPlaneYResolution',
'Exif_Photo_InteroperabilityTag',
'Exif_Photo_MakerNote',
'Exif_Photo_MaxApertureValue',
'Exif_Photo_MeteringMode',
'Exif_Photo_PixelXDimension',
'Exif_Photo_PixelYDimension',
'Exif_Photo_SceneCaptureType',
'Exif_Photo_SensingMethod',
'Exif_Photo_ShutterSpeedValue',
'Exif_Photo_UserComment',
'Exif_Photo_WhiteBalance',
'Exif_Thumbnail_Compression',
'Exif_Thumbnail_JPEGInterchangeFormat',
'Exif_Thumbnail_JPEGInterchangeFormatLength',
'Exif_Thumbnail_ResolutionUnit',
'Exif_Thumbnail_XResolution',
'Exif_Thumbnail_YResolution',
'Iptc_Application2_Byline',
'Iptc_Application2_Caption',
'Iptc_Application2_Copyright',
'Iptc_Application2_ObjectName',
'Iptc_Application2_RecordVersion',
'aspect',
'compression',
'day',
'desktop',
'dpi',
'filename',
'filesize',
'folder',
'foldername',
'format',
'formatdescription',
'gamma',
'height',
'hour',
'interlace',
'minute',
'mode',
'month',
'monthname',
'orientation',
'path',
'root',
'second',
'size',
'subfolder',
'transparency',
'type',
'weekday',
'weekdayname',
'width',
'year']
"""
def __init__(self, filename=None, vars=None, sources=None):
"""Create an InfoExtract instance.
:param filename: filename of the source file
:type filename: string
:param vars: variables that have to be extracted (e.g. orientation)
:type vars: list
"""
if vars is None:
vars = []
self.list = []
self._vars = None # list of possible vars which can occur
self._vars_by_info = None
self.set_vars(vars, filename)
if filename:
self.open(filename, sources)
def __getitem__(self, var):
# force var as string, otherwise py2exiv fails (eg with unicode)
# eg u'Exif_Photo_DateTimeOriginal'
var = str(var)
for info in self.list:
if info.provides(var):
return info[var]
raise KeyError(var)
def set(self, filename=None, vars=None, sources=None):
"""Set new parameters for the info.
:param filename: filename of the source file
:type filename: string
:param vars: variables that have to be extracted (e.g. orientation)
:type vars: list
"""
if not(vars is None):
self.set_vars(vars)
self.open(filename)
elif not(filename is None):
self.open(filename, sources)
def open(self, filename, sources=None):
"""Feeds a new file as source for all info types.
:param filename: filename of the source file
:type filename: string
.. note:: This will clear the cache.
"""
if filename:
self.filename = filename.replace('file://', '')
if not self._vars:
# ->all variables, which are image dependent
self._vars_by_info = get_vars_by_info(filename)
self.clear_cache()
# ensure sources is a dict
if not sources:
sources = {}
# load files
self.list = [
Info(sources.get(Info, self.filename), self._vars_by_info[Info])
for Info in self._vars_by_info.keys()] # use keys to respect order
self.set_orientation()
return self
def clear_cache(self):
"""Clears the look up cache."""
self._cache = {}
@classmethod
def get_vars_by_info(cls, vars, old_vars=None, filename='test.png'):
"""Organizes vars in a dictionary by Info class (e.g.
:class:`InfoPil`, :class:`InfoExif`, ...).
As this is a class method, ``old_vars`` has to be passed explicitly
instead of being obtained from the instance.
:param vars: variables
:type vars: list of strings
:param old_vars: previous variables
:type old_vars: list of strings
"""
# collect all requested infos
if vars:
vars_by_info, vars_unknown = cls.scan_infos(vars)
else:
vars_by_info = get_vars_by_info(filename)
vars_unknown = []
# check orientation
set_vars_by_info = set(vars_by_info)
if not set_vars_by_info.intersection(INFOS_WITH_ORIENTATION):
needs_orientation = [Info
for Info in set_vars_by_info.difference(INFOS_WITH_ORIENTATION)
if Info.needs_orientation(vars_by_info[Info])]
if needs_orientation:
if not(vars_by_info[InfoPil] is None):
# orientation is included in None already
vars_by_info[InfoPil] += ['orientation']
return vars_by_info, vars_unknown
def set_vars(self, vars, filename='test.png'):
"""Limit the range of the possible variables which might
be looked up.
:param vars: variables that have to be extracted (e.g. orientation)
:type vars: list
"""
# collect all requested infos
if vars != self._vars:
self._vars_by_info, self.vars_unknown = \
self.get_vars_by_info(vars, self._vars, filename)
# update vars (needs to be after previous collect)
if not vars:
vars = []
self._vars = list(set(vars).difference(self.vars_unknown))
def set_orientation(self, orientation=None):
if orientation is None:
try:
orientation = self['orientation']
except:
# no orientation needed
return
for info in self.list:
if info.needs_orientation(info.vars):
info.set_orientation(orientation)
@classmethod
def scan_infos(cls, vars):
"""Scan which info types the variables ``vars`` require.
:param vars: variables which have to be provided
:type vars: list
:returns: variables by required info types
:rtype: dict of lists
"""
Infos = odict.odict()
todo = vars[:] # we don't want to change the orignal vars
todo_temp = vars[:]
# loop first over Infos so that the info order is kept
for Info in INFOS:
for var in todo:
if Info.provides(var):
if Info in Infos:
Infos[Info].append(var)
else:
Infos[Info] = [var]
# var is provided, so don't look for it anymore
todo_temp.remove(var)
# make a copy as we can't modify an looping iterable
if todo_temp:
todo = todo_temp[:]
else:
break
# return vars by info, unknown vars
return Infos, todo_temp
def provides(self, var):
"""Whether this info provides this variable.
:param var: name of the variable
:type var: string
:returns: if ``var`` is provided
:rtype: bool
"""
for info in self.list:
if info.provides(var):
return True
return False
def types(self):
"""Which info types are used by this instance.
:returns: info types
:rtype: list
"""
return [info.type for info in self.list]
def clear(self):
"""Clear alfl info types."""
self.list = []
def dump(self, filename=None, expand=False, free=False):
"""Dump as a dictionary.
:param vars: list of variables as arguments
:type vars: list
"""
if filename:
self.open(filename)
if self._vars:
#load vars
for info in self.list:
info.enable_cache()
for var in self._vars:
self[var]
for info in self.list:
info.disable_cache()
else:
self.extract_all()
d = {}
for info in self.list:
d.update(info.dict)
if expand:
self.expand(d)
if free:
self.list = []
return d
@classmethod
def expand(cls, d):
for key, value in d.items():
cls.expand_var(d, key, value)
@classmethod
def expand_var(cls, d, key, value):
if isinstance(value, DateTime):
for attr in DateTime.attrs:
d['%s.%s' % (key, attr)] = getattr(value, attr)
elif isinstance(value, list) and len(value) < 10:
# IPTC values (always a list)
if len(value) == 1:
d[key] = value[0]
else:
for index, value_index in enumerate(value):
d['%s[%d]' % (key, index)] = value[index]
# Delete extra values if needed:
index = len(value)
while True:
try:
del d['%s[%d]' % (key, index)]
except KeyError:
break
else:
index = index + 1
elif hasattr(value, 'denominator') and value.denominator != 1:
d['%s.denominator' % key] = value.denominator
d['%s.numerator' % key] = value.numerator
def set_source(self, d):
"""Set source of an info from the collection. Raises an
``UnknownTypeError`` in case an unknown type is given.
:param d: dictionary {type: source} or type
:type d: dict/str
"""
for info in self.list:
if info.type in d:
info.set_source(d[info.type])
def extract_all(self):
"""Extract all variables provided by the info types."""
for info in self.list:
info.extract_all()
class DumpInfo(dict):
"""Dictionary like object which tracks changes.
>>> d = DumpInfo({'hello': 'world'})
>>> d['foo'] = 'bar'
>>> d.changed
['foo']
"""
def __init__(self, d=None):
""":param d: initial dictionary or None
:type d: dict/None"""
if d:
self.update(d)
self.changed = []
def __setitem__(self, var, value):
"""Sets the item of the dictionary and add var to the ``changed``
list
:param var: variable
:type var: string
:param value: any kind of value
"""
super(DumpInfo, self).__setitem__(var, value)
self.changed.append(var)
|