diff --git a/README b/README index 2e8b63b..2287392 100644 --- a/README +++ b/README @@ -24,9 +24,8 @@ REQUIREMENTS pyGTKtalog is written in python with following dependencies: -- python 2.4 or higher -- pygtk 2.10 or higher -- pysqlite2 (unnecessary, if python 2.5 is used) +- python 2.5 or higher +- pygtk 2.12 or higher Optional modules: diff --git a/pygtktalog.py b/pygtktalog.py index 57bab00..282941d 100644 --- a/pygtktalog.py +++ b/pygtktalog.py @@ -1,110 +1,62 @@ -# This Python file uses the following encoding: utf-8 -# -# Author: Roman 'gryf' Dobosz gryf@elysium.pl -# -# Copyright (C) 2007 by Roman 'gryf' Dobosz -# -# This file is part of pyGTKtalog. -# -# 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 2 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, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -# ------------------------------------------------------------------------- +""" + Project: pyGTKtalog + Description: Application main launch file. + Type: core + Author: Roman 'gryf' Dobosz, gryf73@gmail.com + Created: 2007-05-01 +""" import sys import os -try: - import gtk -except ImportError: - print "You need to install pyGTK v2.10.x or newer." - raise +import locale +import gettext -def setup_path(): - """Sets up the python include paths to include needed directories""" - import os.path +import gtk +import pygtk +pygtk.require("2.0") - from src.lib.globs import TOPDIR - sys.path = [os.path.join(TOPDIR, "src")] + sys.path - return +import gtkmvc +gtkmvc.require("1.2.2") + +from src.lib.globs import TOPDIR +from src.lib.globs import APPL_SHORT_NAME +sys.path = [os.path.join(TOPDIR, "src")] + sys.path +from models.m_config import ConfigModel +from models.m_main import MainModel +from ctrls.c_main import MainController +from views.v_main import MainView def check_requirements(): """Checks versions and other requirements""" - import sys - import gtkmvc - gtkmvc.require("1.2.0") - - try: - from models.m_config import ConfigModel - except ImportError: - print "Some fundamental files are missing.", - print "Try runnig pyGTKtalog in his root directory" - raise conf = ConfigModel() conf.load() - try: - import pygtk - #tell pyGTK, if possible, that we want GTKv2 - pygtk.require("2.0") - except ImportError: - #Some distributions come with GTK2, but not pyGTK - pass - - try: - import sqlite3 as sqlite - except ImportError: - try: - from pysqlite2 import dbapi2 as sqlite - except ImportError: - print "pyGTKtalog uses SQLite DB.\nYou'll need to get it and the", - print "python bindings as well.", - print "http://www.sqlite.org" - print "http://initd.org/tracker/pysqlite" - print "Alternatively install python 2.5 or higher" - raise - - if conf.confd['exportxls']: - try: - import pyExcelerator - except ImportError: - print "WARNING: You'll need pyExcelerator, if you want to export", - print "DB to XLS format." - print "http://sourceforge.net/projects/pyexcelerator" - if conf.confd['thumbs'] and conf.confd['retrive']: try: import Image except ImportError: - print "WARNING: You'll need Python Imaging Library (PIL), if you", - print "want to make\nthumbnails!" + print _("WARNING: You'll need Python Imaging Library (PIL), if " + "you want to make thumbnails!") + raise return -if __name__ == "__main__": +def run(): + """Create model, controller and view and launch it.""" # Directory from where pygtkatalog was invoced. We need it for calculate # path for argument (catalog file) execution_dir = os.path.abspath(os.path.curdir) + # Directory, where this files lies. We need it to setup private source # paths libraries_dir = os.path.dirname(__file__) - os.chdir(libraries_dir) + if libraries_dir: + os.chdir(libraries_dir) - setup_path() - #check_requirements() + # Setup i18n + locale.setlocale(locale.LC_ALL, '') + gettext.install(APPL_SHORT_NAME, 'locale', unicode=True) - from models.m_main import MainModel - from ctrls.c_main import MainController - from views.v_main import MainView + check_requirements() model = MainModel() if len(sys.argv) > 1: @@ -115,6 +67,9 @@ if __name__ == "__main__": try: gtk.main() except KeyboardInterrupt: - #model.config.save() - #model.cleanup() + model.config.save() + model.cleanup() gtk.main_quit + +if __name__ == "__main__": + run() diff --git a/src/ctrls/c_main.py b/src/ctrls/c_main.py index 4fc9ba5..2274f50 100644 --- a/src/ctrls/c_main.py +++ b/src/ctrls/c_main.py @@ -252,7 +252,7 @@ class MainController(Controller): except TypeError: if __debug__: print "c_main.py: on_edit2_activate(): 0", - print "zaznaczonych wierszy" + print "selected rows" return val = self.model.get_file_info(id) @@ -281,11 +281,9 @@ class MainController(Controller): def on_remove_thumb1_activate(self, menu_item): if self.model.config.confd['delwarn']: - title = 'Delete thumbnails' - question = 'Delete thumbnails?' - description = "Thumbnails for selected items will be permanently" - description += " removed from catalog." - obj = Dialogs.Qst(title, question, description) + obj = Dialogs.Qst(_("Delete thumbnails"), _("Delete thumbnails?"), + _("Thumbnails for selected items will be " + "permanently removed from catalog.")) if not obj.run(): return try: @@ -307,11 +305,9 @@ class MainController(Controller): def on_remove_image1_activate(self, menu_item): if self.model.config.confd['delwarn']: - title = 'Delete images' - question = 'Delete all images?' - description = 'All images for selected items will be permanently' - description += ' removed from catalog.' - obj = Dialogs.Qst(title, question, description) + obj = Dialogs.Qst(_("Delete images"), _("Delete all images?"), + _("All images for selected items will be " + "permanently removed from catalog.")) if not obj.run(): return try: @@ -343,8 +339,8 @@ class MainController(Controller): else: ImageView(img) else: - Dialogs.Inf("Image view", "No Image", - "Image file does not exist.") + Dialogs.Inf(_("Image view"), _("No Image"), + _("Image file does not exist.")) def on_rename1_activate(self, widget): model, iter = self.view['discs'].get_selection().get_selected() @@ -492,11 +488,10 @@ class MainController(Controller): # check if any unsaved project is on go. if self.model.unsaved_project and \ self.model.config.confd['confirmquit']: - title = 'Quit application - pyGTKtalog' - question = 'Do you really want to quit?' - description = "Current database is not saved, any changes will " - description += "be lost." - if not Dialogs.Qst(title, question, description).run(): + if not Dialogs.Qst(_("Quit application") + " - pyGTKtalog", + _("Do you really want to quit?"), + _("Current database is not saved, any changes " + "will be lost.")).run(): return self.__store_settings() self.model.cleanup() @@ -506,10 +501,10 @@ class MainController(Controller): def on_new_activate(self, widget): """Create new database file""" if self.model.unsaved_project: - title = 'Unsaved data - pyGTKtalog' - question = "Do you want to abandon changes?" - desc = "Current database is not saved, any changes will be lost." - if not Dialogs.Qst(title, question, desc).run(): + if not Dialogs.Qst(_("Unsaved data") + " - pyGTKtalog", + _("Do you want to abandon changes?"), + _("Current database is not saved, any changes " + "will be lost.")).run(): return self.model.new() @@ -525,8 +520,8 @@ class MainController(Controller): def on_add_cd_activate(self, widget, label=None, current_id=None): """Add directory structure from cd/dvd disc""" - mount = device_helper.volmount(self.model.config.confd['cd']) - if mount == 'ok': + mount, msg = device_helper.volmount(self.model.config.confd['cd']) + if mount: guessed_label = device_helper.volname(self.model.config.confd['cd']) if not label: label = Dialogs.InputDiskLabel(guessed_label).run() @@ -543,10 +538,10 @@ class MainController(Controller): device_helper.volumount(self.model.config.confd['cd']) return True else: - Dialogs.Wrn("Error mounting device - pyGTKtalog", - "Cannot mount device pointed to %s" % + Dialogs.Wrn(_("Error mounting device") + " - pyGTKtalog", + _("Cannot mount device pointed to %s") % self.model.config.confd['cd'], - "Last mount message:\n%s" % mount) + _("Last mount message:\n%s") % msg) return False def on_add_directory_activate(self, widget, path=None, label=None, @@ -599,6 +594,7 @@ class MainController(Controller): def on_save_activate(self, widget): """Save catalog to file""" + # FIXME: Traceback when recent is null if self.model.filename: self.model.save() self.__set_title(filepath=self.model.filename) @@ -618,8 +614,8 @@ class MainController(Controller): self.model.config.add_recent(path) self.__set_title(filepath=path) else: - Dialogs.Err("Error writing file - pyGTKtalog", - "Cannot write file %s." % path, "%s" % err) + Dialogs.Err(_("Error writing file") + " - pyGTKtalog", + _("Cannot write file %s.") % path, "%s" % err) def on_stat1_activate(self, menu_item, selected_id=None): data = self.model.get_stats(selected_id) @@ -640,9 +636,9 @@ class MainController(Controller): """Open catalog file""" confirm = self.model.config.confd['confirmabandon'] if self.model.unsaved_project and confirm: - obj = Dialogs.Qst('Unsaved data - pyGTKtalog', - 'There is not saved database', - 'Pressing "Ok" will abandon catalog.') + obj = Dialogs.Qst(_("Unsaved data") + " - pyGTKtalog", + _("There is not saved database"), + _("Pressing Ok will abandon catalog.")) if not obj.run(): return @@ -666,8 +662,8 @@ class MainController(Controller): if path: if not self.model.open(path): - Dialogs.Err("Error opening file - pyGTKtalog", - "Cannot open file %s." % path) + Dialogs.Err(_("Error opening file") + " - pyGTKtalog", + _("Cannot open file %s.") % path) else: self.__generate_recent_menu() self.__activate_ui(path) @@ -733,13 +729,14 @@ class MainController(Controller): """delete selected images (with thumbnails)""" list_of_paths = self.view['images'].get_selected_items() if not list_of_paths: - Dialogs.Inf("Delete images", "No images selected", - "You have to select at least one image to delete.") + Dialogs.Inf(_("Delete images"), _("No images selected"), + _("You have to select at least one image to delete.")) return if self.model.config.confd['delwarn']: - obj = Dialogs.Qst('Delete images', 'Delete selected images?', - 'Selected images will be permanently removed from catalog.') + obj = Dialogs.Qst(_("Delete images"), _("Delete selected images?"), + _("Selected images will be permanently removed" + " from catalog.")) if not obj.run(): return @@ -768,7 +765,7 @@ class MainController(Controller): def on_img_save_activate(self, menu_item): """export images (not thumbnails) into desired direcotry""" - dialog = Dialogs.SelectDirectory("Choose directory to save images") + dialog = Dialogs.SelectDirectory(_("Choose directory to save images")) filepath = dialog.run() if not filepath: @@ -793,14 +790,13 @@ class MainController(Controller): count += 1 if count > 0: - Dialogs.Inf("Save images", - "%d images was succsefully saved." % count, - "Images are placed in directory:\n%s." % filepath) + Dialogs.Inf(_("Save images"), + _("%d images was succsefully saved.") % count, + _("Images are placed in directory:\n%s.") % filepath) else: - description = "Images probably don't have real images - only" - description += " thumbnails." - Dialogs.Inf("Save images", - "No images was saved.", + description = _("Images probably don't have real images - only" + " thumbnails.") + Dialogs.Inf(_("Save images"), _("No images was saved."), description) return @@ -809,12 +805,12 @@ class MainController(Controller): list_of_paths = self.view['images'].get_selected_items() if not list_of_paths: - Dialogs.Inf("Set thumbnail", "No image selected", - "You have to select one image to set as thumbnail.") + Dialogs.Inf(_("Set thumbnail"), _("No image selected"), + _("You have to select one image to set as thumbnail.")) return if len(list_of_paths) >1: - Dialogs.Inf("Set thumbnail", "To many images selected", - "You have to select one image to set as thumbnail.") + Dialogs.Inf(_("Set thumbnail"), _("To many images selected"), + _("You have to select one image to set as thumbnail.")) return model = self.view['images'].get_model() @@ -872,7 +868,7 @@ class MainController(Controller): def on_export_activate(self, menu_item): """export db file and coressponding images to tar.bz2 archive""" - dialog = Dialogs.ChooseFilename(None, "Choose export file") + dialog = Dialogs.ChooseFilename(None, _("Choose export file")) filepath = dialog.run() if not filepath: @@ -1018,8 +1014,8 @@ class MainController(Controller): def on_delete_tag_activate(self, menu_item): ids = self.__get_tv_selection_ids(self.view['files']) if not ids: - Dialogs.Inf("Remove tags", "No files selected", - "You have to select some files first.") + Dialogs.Inf(_("Remove tags"), _("No files selected"), + _("You have to select some files first.")) return tags = self.model.get_tags_by_file_id(ids) @@ -1027,8 +1023,9 @@ class MainController(Controller): d = Dialogs.TagsRemoveDialog(tags) retcode, retval = d.run() if retcode=="ok" and not retval: - Dialogs.Inf("Remove tags", "No tags selected", - "You have to select any tag to remove from files.") + Dialogs.Inf(_("Remove tags"), _("No tags selected"), + _("You have to select any tag to remove from" + " files.")) return elif retcode == "ok" and retval: self.model.delete_tags(ids, retval) @@ -1053,7 +1050,7 @@ class MainController(Controller): def on_add_image1_activate(self, menu_item): dialog = Dialogs.LoadImageFile(True) - msg = "Don't copy images. Generate only thumbnails." + msg = _("Don't copy images. Generate only thumbnails.") toggle = gtk.CheckButton(msg) toggle.show() dialog.dialog.set_extra_widget(toggle) @@ -1117,15 +1114,15 @@ class MainController(Controller): return if not selected_iter: - Dialogs.Inf("Delete disc", "No disc selected", - "You have to select disc first before you " +\ - "can delete it") + Dialogs.Inf(_("Delete disc"), _("No disc selected"), + _("You have to select disc first before you " + "can delete it")) return if self.model.config.confd['delwarn']: name = model.get_value(selected_iter, 1) - obj = Dialogs.Qst('Delete %s' % name, 'Delete %s?' % name, - 'Object will be permanently removed.') + obj = Dialogs.Qst(_("Delete %s") % name, _("Delete %s?") % name, + _("Object will be permanently removed.")) if not obj.run(): return @@ -1168,14 +1165,14 @@ class MainController(Controller): return if not list_of_paths: - Dialogs.Inf("Delete files", "No files selected", - "You have to select at least one file to delete.") + Dialogs.Inf(_("Delete files"), _("No files selected"), + _("You have to select at least one file to delete.")) return if self.model.config.confd['delwarn']: - description = "Selected files and directories will be " - description += "permanently\n removed from catalog." - obj = Dialogs.Qst("Delete files", "Delete files?", description) + obj = Dialogs.Qst(_("Delete files"), _("Delete files?"), + _("Selected files and directories will be " + "permanently\n removed from catalog.")) if not obj.run(): return @@ -1216,10 +1213,9 @@ class MainController(Controller): def on_th_delete_activate(self, menu_item): if self.model.config.confd['delwarn']: - title = 'Delete thumbnail' - question = 'Delete thumbnail?' - dsc = "Current thumbnail will be permanently removed from catalog." - obj = Dialogs.Qst(title, question, dsc) + obj = Dialogs.Qst(_("Delete thumbnail"), _("Delete thumbnail?"), + _("Current thumbnail will be permanently removed" + " from catalog.")) if not obj.run(): return path, column = self.view['files'].get_cursor() @@ -1366,17 +1362,19 @@ class MainController(Controller): msg = device_helper.eject_cd(ejectapp, self.model.config.confd['cd']) if msg != 'ok': - Dialogs.Wrn("error ejecting device - pyGTKtalog", - "Cannot eject device pointed to %s" % + title = _("Error ejecting device") + Dialogs.Wrn(title + " - pyGTKtalog", + _("Cannot eject device pointed to %s") % self.model.config.confd['cd'], - "Last eject message:\n%s" % msg) + _("Last eject message:\n%s") % msg) else: msg = device_helper.volumount(self.model.config.confd['cd']) if msg != 'ok': - Dialogs.Wrn("error unmounting device - pyGTKtalog", - "Cannot unmount device pointed to %s" % + title = _("Error unmounting device") + Dialogs.Wrn(title + " - pyGTKtalog", + _("Cannot unmount device pointed to %s") % self.model.config.confd['cd'], - "Last umount message:\n%s" % msg) + _("Last umount message:\n%s") % msg) return def property_progress_value_change(self, model, old, new): diff --git a/src/lib/EXIF.py b/src/lib/EXIF.py index d3bd109..ed4192a 100644 --- a/src/lib/EXIF.py +++ b/src/lib/EXIF.py @@ -1,9 +1,35 @@ -# Library to extract EXIF information in digital camera image files +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Library to extract EXIF information from digital camera image files +# http://sourceforge.net/projects/exif-py/ +# +# VERSION 1.1.0 # # To use this library call with: -# f=open(path_name, 'rb') -# tags=EXIF.process_file(f) -# tags will now be a dictionary mapping names of EXIF tags to their +# f = open(path_name, 'rb') +# tags = EXIF.process_file(f) +# +# To ignore MakerNote tags, pass the -q or --quick +# command line arguments, or as +# tags = EXIF.process_file(f, details=False) +# +# To stop processing after a certain tag is retrieved, +# pass the -t TAG or --stop-tag TAG argument, or as +# tags = EXIF.process_file(f, stop_tag='TAG') +# +# where TAG is a valid tag name, ex 'DateTimeOriginal' +# +# These 2 are useful when you are retrieving a large list of images +# +# +# To return an error on invalid tags, +# pass the -s or --strict argument, or as +# tags = EXIF.process_file(f, strict=True) +# +# Otherwise these tags will be ignored +# +# Returned tags will be a dictionary mapping names of EXIF tags to their # values in the file named by path_name. You can process the tags # as you wish. In particular, you can iterate through all the tags with: # for tag in tags.keys(): @@ -17,103 +43,122 @@ # tags, and will also include keys for Makernotes used by some # cameras, for which we have a good specification. # -# Contains code from "exifdump.py" originally written by Thierry Bousch -# and released into the public domain. +# Note that the dictionary keys are the IFD name followed by the +# tag name. For example: +# 'EXIF DateTimeOriginal', 'Image Orientation', 'MakerNote FocusMode' # -# Updated and turned into general-purpose library by Gene Cash -# -# This copyright license is intended to be similar to the FreeBSD license. -# -# Copyright 2002 Gene Cash All rights reserved. +# Copyright (c) 2002-2007 Gene Cash All rights reserved +# Copyright (c) 2007-2008 Ianaré Sévi All rights reserved # # Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: +# modification, are permitted provided that the following conditions +# are met: # -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the -# distribution. +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. # -# THIS SOFTWARE IS PROVIDED BY GENE CASH ``AS IS'' AND ANY EXPRESS OR -# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. # -# This means you may do anything you want with this code, except claim you -# wrote it. Also, if it breaks you get to keep both pieces. +# 3. Neither the name of the authors nor the names of its contributors +# may be used to endorse or promote products derived from this +# software without specific prior written permission. # -# Patch Contributors: -# * Simon J. Gerraty -# s2n fix & orientation decode -# * John T. Riedl -# Added support for newer Nikon type 3 Makernote format for D70 and some -# other Nikon cameras. -# * Joerg Schaefer -# Fixed subtle bug when faking an EXIF header, which affected maker notes -# using relative offsets, and a fix for Nikon D100. +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -# 21-AUG-99 TB Last update by Thierry Bousch to his code. -# 17-JAN-02 CEC Discovered code on web. -# Commented everything. -# Made small code improvements. -# Reformatted for readability. -# 19-JAN-02 CEC Added ability to read TIFFs and JFIF-format JPEGs. -# Added ability to extract JPEG formatted thumbnail. -# Added ability to read GPS IFD (not tested). -# Converted IFD data structure to dictionaries indexed by -# tag name. -# Factored into library returning dictionary of IFDs plus -# thumbnail, if any. -# 20-JAN-02 CEC Added MakerNote processing logic. -# Added Olympus MakerNote. -# Converted data structure to single-level dictionary, avoiding -# tag name collisions by prefixing with IFD name. This makes -# it much easier to use. -# 23-JAN-02 CEC Trimmed nulls from end of string values. -# 25-JAN-02 CEC Discovered JPEG thumbnail in Olympus TIFF MakerNote. -# 26-JAN-02 CEC Added ability to extract TIFF thumbnails. -# Added Nikon, Fujifilm, Casio MakerNotes. -# 30-NOV-03 CEC Fixed problem with canon_decode_tag() not creating an -# IFD_Tag() object. -# 15-FEB-04 CEC Finally fixed bit shift warning by converting Y to 0L. +# +# ----- See 'changes.txt' file for all contributors and changes ----- # # + +# Don't throw an exception when given an out of range character. +def make_string(seq): + str = '' + for c in seq: + # Screen out non-printing characters + if 32 <= c and c < 256: + str += chr(c) + # If no printing chars + if not str: + return seq + return str + +# Special version to deal with the code in the first 8 bytes of a user comment. +# First 8 bytes gives coding system e.g. ASCII vs. JIS vs Unicode +def make_string_uc(seq): + code = seq[0:8] + seq = seq[8:] + # Of course, this is only correct if ASCII, and the standard explicitly + # allows JIS and Unicode. + return make_string(seq) + # field type descriptions as (length, abbreviation, full name) tuples -FIELD_TYPES=( - (0, 'X', 'Proprietary'), # no such type - (1, 'B', 'Byte'), - (1, 'A', 'ASCII'), - (2, 'S', 'Short'), - (4, 'L', 'Long'), - (8, 'R', 'Ratio'), +FIELD_TYPES = ( + (0, 'X', 'Proprietary'), # no such type + (1, 'B', 'Byte'), + (1, 'A', 'ASCII'), + (2, 'S', 'Short'), + (4, 'L', 'Long'), + (8, 'R', 'Ratio'), (1, 'SB', 'Signed Byte'), - (1, 'U', 'Undefined'), + (1, 'U', 'Undefined'), (2, 'SS', 'Signed Short'), (4, 'SL', 'Signed Long'), - (8, 'SR', 'Signed Ratio') -) + (8, 'SR', 'Signed Ratio'), + ) # dictionary of main EXIF tag names # first element of tuple is tag name, optional second element is # another dictionary giving names to values -EXIF_TAGS={ +EXIF_TAGS = { 0x0100: ('ImageWidth', ), 0x0101: ('ImageLength', ), 0x0102: ('BitsPerSample', ), 0x0103: ('Compression', - {1: 'Uncompressed TIFF', - 6: 'JPEG Compressed'}), + {1: 'Uncompressed', + 2: 'CCITT 1D', + 3: 'T4/Group 3 Fax', + 4: 'T6/Group 4 Fax', + 5: 'LZW', + 6: 'JPEG (old-style)', + 7: 'JPEG', + 8: 'Adobe Deflate', + 9: 'JBIG B&W', + 10: 'JBIG Color', + 32766: 'Next', + 32769: 'Epson ERF Compressed', + 32771: 'CCIRLEW', + 32773: 'PackBits', + 32809: 'Thunderscan', + 32895: 'IT8CTPAD', + 32896: 'IT8LW', + 32897: 'IT8MP', + 32898: 'IT8BL', + 32908: 'PixarFilm', + 32909: 'PixarLog', + 32946: 'Deflate', + 32947: 'DCS', + 34661: 'JBIG', + 34676: 'SGILog', + 34677: 'SGILog24', + 34712: 'JPEG 2000', + 34713: 'Nikon NEF Compressed', + 65000: 'Kodak DCR Compressed', + 65535: 'Pentax PEF Compressed'}), 0x0106: ('PhotometricInterpretation', ), + 0x0107: ('Thresholding', ), 0x010A: ('FillOrder', ), 0x010D: ('DocumentName', ), 0x010E: ('ImageDescription', ), @@ -135,6 +180,7 @@ EXIF_TAGS={ 0x011A: ('XResolution', ), 0x011B: ('YResolution', ), 0x011C: ('PlanarConfiguration', ), + 0x011D: ('PageName', make_string), 0x0128: ('ResolutionUnit', {1: 'Not Absolute', 2: 'Pixels/Inch', @@ -151,8 +197,13 @@ EXIF_TAGS={ 0x0202: ('JPEGInterchangeFormatLength', ), 0x0211: ('YCbCrCoefficients', ), 0x0212: ('YCbCrSubSampling', ), - 0x0213: ('YCbCrPositioning', ), + 0x0213: ('YCbCrPositioning', + {1: 'Centered', + 2: 'Co-sited'}), 0x0214: ('ReferenceBlackWhite', ), + + 0x4746: ('Rating', ), + 0x828D: ('CFARepeatPatternDim', ), 0x828E: ('CFAPattern', ), 0x828F: ('BatteryLevel', ), @@ -176,8 +227,7 @@ EXIF_TAGS={ 0x8825: ('GPSInfo', ), 0x8827: ('ISOSpeedRatings', ), 0x8828: ('OECF', ), - # print as string - 0x9000: ('ExifVersion', lambda x: ''.join(map(chr, x))), + 0x9000: ('ExifVersion', make_string), 0x9003: ('DateTimeOriginal', ), 0x9004: ('DateTimeDigitized', ), 0x9101: ('ComponentsConfiguration', @@ -201,83 +251,129 @@ EXIF_TAGS={ 2: 'CenterWeightedAverage', 3: 'Spot', 4: 'MultiSpot', - 5: 'Pattern', - 6: 'Partial', - 255: 'other'}), + 5: 'Pattern'}), 0x9208: ('LightSource', - {0: 'Unknown', - 1: 'Daylight', - 2: 'Fluorescent', - 3: 'Tungsten (incandescent light)', - 4: 'Flash', - 9: 'Fine weather', - 10: 'Cloudy weather', - 11: 'Shade', - 12: 'Daylight fluorescent (D 5700 - 7100K)', - 13: 'Day white fluorescent (N 4600 - 5400K)', - 14: 'Cool white fluorescent (W 3900 - 4500K)', - 15: 'White fluorescent (WW 3200 - 3700K)', - 17: 'Standard light A', - 18: 'Standard light B', - 19: 'Standard light C', - 20: 'D55', - 21: 'D65', - 22: 'D75', - 23: 'D50', - 24: 'ISO studio tungsten', - 255: 'other light source',}), - 0x9209: ('Flash', {0: 'Flash did not fire', - 1: 'Flash fired', - 5: 'Strobe return light not detected', - 7: 'Strobe return light detected', - 9: 'Flash fired, compulsory flash mode', - 13: 'Flash fired, compulsory flash mode, return light not detected', - 15: 'Flash fired, compulsory flash mode, return light detected', - 16: 'Flash did not fire, compulsory flash mode', - 24: 'Flash did not fire, auto mode', - 25: 'Flash fired, auto mode', - 29: 'Flash fired, auto mode, return light not detected', - 31: 'Flash fired, auto mode, return light detected', - 32: 'No flash function', - 65: 'Flash fired, red-eye reduction mode', - 69: 'Flash fired, red-eye reduction mode, return light not detected', - 71: 'Flash fired, red-eye reduction mode, return light detected', - 73: 'Flash fired, compulsory flash mode, red-eye reduction mode', - 77: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected', - 79: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected', - 89: 'Flash fired, auto mode, red-eye reduction mode', - 93: 'Flash fired, auto mode, return light not detected, red-eye reduction mode', - 95: 'Flash fired, auto mode, return light detected, red-eye reduction mode'}), + {0: 'Unknown', + 1: 'Daylight', + 2: 'Fluorescent', + 3: 'Tungsten', + 9: 'Fine Weather', + 10: 'Flash', + 11: 'Shade', + 12: 'Daylight Fluorescent', + 13: 'Day White Fluorescent', + 14: 'Cool White Fluorescent', + 15: 'White Fluorescent', + 17: 'Standard Light A', + 18: 'Standard Light B', + 19: 'Standard Light C', + 20: 'D55', + 21: 'D65', + 22: 'D75', + 255: 'Other'}), + 0x9209: ('Flash', + {0: 'No', + 1: 'Fired', + 5: 'Fired (?)', # no return sensed + 7: 'Fired (!)', # return sensed + 9: 'Fill Fired', + 13: 'Fill Fired (?)', + 15: 'Fill Fired (!)', + 16: 'Off', + 24: 'Auto Off', + 25: 'Auto Fired', + 29: 'Auto Fired (?)', + 31: 'Auto Fired (!)', + 32: 'Not Available'}), 0x920A: ('FocalLength', ), + 0x9214: ('SubjectArea', ), 0x927C: ('MakerNote', ), - # print as string - 0x9286: ('UserComment', lambda x: ''.join(map(chr, x))), + 0x9286: ('UserComment', make_string_uc), 0x9290: ('SubSecTime', ), 0x9291: ('SubSecTimeOriginal', ), 0x9292: ('SubSecTimeDigitized', ), - # print as string - 0xA000: ('FlashPixVersion', lambda x: ''.join(map(chr, x))), - 0xA001: ('ColorSpace', ), + + # used by Windows Explorer + 0x9C9B: ('XPTitle', ), + 0x9C9C: ('XPComment', ), + 0x9C9D: ('XPAuthor', ), #(ignored by Windows Explorer if Artist exists) + 0x9C9E: ('XPKeywords', ), + 0x9C9F: ('XPSubject', ), + + 0xA000: ('FlashPixVersion', make_string), + 0xA001: ('ColorSpace', + {1: 'sRGB', + 2: 'Adobe RGB', + 65535: 'Uncalibrated'}), 0xA002: ('ExifImageWidth', ), 0xA003: ('ExifImageLength', ), 0xA005: ('InteroperabilityOffset', ), 0xA20B: ('FlashEnergy', ), # 0x920B in TIFF/EP - 0xA20C: ('SpatialFrequencyResponse', ), # 0x920C - - - 0xA20E: ('FocalPlaneXResolution', ), # 0x920E - - - 0xA20F: ('FocalPlaneYResolution', ), # 0x920F - - - 0xA210: ('FocalPlaneResolutionUnit', ), # 0x9210 - - - 0xA214: ('SubjectLocation', ), # 0x9214 - - - 0xA215: ('ExposureIndex', ), # 0x9215 - - - 0xA217: ('SensingMethod', ), # 0x9217 - - + 0xA20C: ('SpatialFrequencyResponse', ), # 0x920C + 0xA20E: ('FocalPlaneXResolution', ), # 0x920E + 0xA20F: ('FocalPlaneYResolution', ), # 0x920F + 0xA210: ('FocalPlaneResolutionUnit', ), # 0x9210 + 0xA214: ('SubjectLocation', ), # 0x9214 + 0xA215: ('ExposureIndex', ), # 0x9215 + 0xA217: ('SensingMethod', # 0x9217 + {1: 'Not defined', + 2: 'One-chip color area', + 3: 'Two-chip color area', + 4: 'Three-chip color area', + 5: 'Color sequential area', + 7: 'Trilinear', + 8: 'Color sequential linear'}), 0xA300: ('FileSource', - {3: 'Digital Camera'}), + {1: 'Film Scanner', + 2: 'Reflection Print Scanner', + 3: 'Digital Camera'}), 0xA301: ('SceneType', {1: 'Directly Photographed'}), - 0xA302: ('CVAPattern',), + 0xA302: ('CVAPattern', ), + 0xA401: ('CustomRendered', + {0: 'Normal', + 1: 'Custom'}), + 0xA402: ('ExposureMode', + {0: 'Auto Exposure', + 1: 'Manual Exposure', + 2: 'Auto Bracket'}), + 0xA403: ('WhiteBalance', + {0: 'Auto', + 1: 'Manual'}), + 0xA404: ('DigitalZoomRatio', ), + 0xA405: ('FocalLengthIn35mmFilm', ), + 0xA406: ('SceneCaptureType', + {0: 'Standard', + 1: 'Landscape', + 2: 'Portrait', + 3: 'Night)'}), + 0xA407: ('GainControl', + {0: 'None', + 1: 'Low gain up', + 2: 'High gain up', + 3: 'Low gain down', + 4: 'High gain down'}), + 0xA408: ('Contrast', + {0: 'Normal', + 1: 'Soft', + 2: 'Hard'}), + 0xA409: ('Saturation', + {0: 'Normal', + 1: 'Soft', + 2: 'Hard'}), + 0xA40A: ('Sharpness', + {0: 'Normal', + 1: 'Soft', + 2: 'Hard'}), + 0xA40B: ('DeviceSettingDescription', ), + 0xA40C: ('SubjectDistanceRange', ), + 0xA500: ('Gamma', ), + 0xC4A5: ('PrintIM', ), + 0xEA1C: ('Padding', ), } # interoperability tags -INTR_TAGS={ +INTR_TAGS = { 0x0001: ('InteroperabilityIndex', ), 0x0002: ('InteroperabilityVersion', ), 0x1000: ('RelatedImageFileFormat', ), @@ -286,7 +382,7 @@ INTR_TAGS={ } # GPS tags (not used yet, haven't seen camera with GPS) -GPS_TAGS={ +GPS_TAGS = { 0x0000: ('GPSVersionID', ), 0x0001: ('GPSLatitudeRef', ), 0x0002: ('GPSLatitude', ), @@ -313,13 +409,66 @@ GPS_TAGS={ 0x0017: ('GPSDestBearingRef', ), 0x0018: ('GPSDestBearing', ), 0x0019: ('GPSDestDistanceRef', ), - 0x001A: ('GPSDestDistance', ) + 0x001A: ('GPSDestDistance', ), + 0x001D: ('GPSDate', ), } +# Ignore these tags when quick processing +# 0x927C is MakerNote Tags +# 0x9286 is user comment +IGNORE_TAGS=(0x9286, 0x927C) + +# http://tomtia.plala.jp/DigitalCamera/MakerNote/index.asp +def nikon_ev_bias(seq): + # First digit seems to be in steps of 1/6 EV. + # Does the third value mean the step size? It is usually 6, + # but it is 12 for the ExposureDifference. + # + # Check for an error condition that could cause a crash. + # This only happens if something has gone really wrong in + # reading the Nikon MakerNote. + if len( seq ) < 4 : return "" + # + if seq == [252, 1, 6, 0]: + return "-2/3 EV" + if seq == [253, 1, 6, 0]: + return "-1/2 EV" + if seq == [254, 1, 6, 0]: + return "-1/3 EV" + if seq == [0, 1, 6, 0]: + return "0 EV" + if seq == [2, 1, 6, 0]: + return "+1/3 EV" + if seq == [3, 1, 6, 0]: + return "+1/2 EV" + if seq == [4, 1, 6, 0]: + return "+2/3 EV" + # Handle combinations not in the table. + a = seq[0] + # Causes headaches for the +/- logic, so special case it. + if a == 0: + return "0 EV" + if a > 127: + a = 256 - a + ret_str = "-" + else: + ret_str = "+" + b = seq[2] # Assume third value means the step size + whole = a / b + a = a % b + if whole != 0: + ret_str = ret_str + str(whole) + " " + if a == 0: + ret_str = ret_str + "EV" + else: + r = Ratio(a, b) + ret_str = ret_str + r.__repr__() + " EV" + return ret_str + # Nikon E99x MakerNote Tags -# http://members.tripod.com/~tawba/990exif.htm MAKERNOTE_NIKON_NEWER_TAGS={ - 0x0002: ('ISOSetting', ), + 0x0001: ('MakernoteVersion', make_string), # Sometimes binary + 0x0002: ('ISOSetting', make_string), 0x0003: ('ColorMode', ), 0x0004: ('Quality', ), 0x0005: ('Whitebalance', ), @@ -329,12 +478,27 @@ MAKERNOTE_NIKON_NEWER_TAGS={ 0x0009: ('AutoFlashMode', ), 0x000B: ('WhiteBalanceBias', ), 0x000C: ('WhiteBalanceRBCoeff', ), + 0x000D: ('ProgramShift', nikon_ev_bias), + # Nearly the same as the other EV vals, but step size is 1/12 EV (?) + 0x000E: ('ExposureDifference', nikon_ev_bias), 0x000F: ('ISOSelection', ), - 0x0012: ('FlashCompensation', ), + 0x0011: ('NikonPreview', ), + 0x0012: ('FlashCompensation', nikon_ev_bias), 0x0013: ('ISOSpeedRequested', ), 0x0016: ('PhotoCornerCoordinates', ), - 0x0018: ('FlashBracketCompensationApplied', ), + # 0x0017: Unknown, but most likely an EV value + 0x0018: ('FlashBracketCompensationApplied', nikon_ev_bias), 0x0019: ('AEBracketCompensationApplied', ), + 0x001A: ('ImageProcessing', ), + 0x001B: ('CropHiSpeed', ), + 0x001D: ('SerialNumber', ), # Conflict with 0x00A0 ? + 0x001E: ('ColorSpace', ), + 0x001F: ('VRInfo', ), + 0x0020: ('ImageAuthentication', ), + 0x0022: ('ActiveDLighting', ), + 0x0023: ('PictureControl', ), + 0x0024: ('WorldTime', ), + 0x0025: ('ISOInfo', ), 0x0080: ('ImageAdjustment', ), 0x0081: ('ToneCompensation', ), 0x0082: ('AuxiliaryLens', ), @@ -342,6 +506,12 @@ MAKERNOTE_NIKON_NEWER_TAGS={ 0x0084: ('LensMinMaxFocalMaxAperture', ), 0x0085: ('ManualFocusDistance', ), 0x0086: ('DigitalZoomFactor', ), + 0x0087: ('FlashMode', + {0x00: 'Did Not Fire', + 0x01: 'Fired, Manual', + 0x07: 'Fired, External', + 0x08: 'Fired, Commander Mode ', + 0x09: 'Fired, TTL Mode'}), 0x0088: ('AFFocusPosition', {0x0000: 'Center', 0x0100: 'Top', @@ -358,26 +528,92 @@ MAKERNOTE_NIKON_NEWER_TAGS={ 0x40: 'Single frame, white balance bracketing', 0x41: 'Continuous, white balance bracketing', 0x42: 'Timer, white balance bracketing'}), + 0x008A: ('AutoBracketRelease', ), + 0x008B: ('LensFStops', ), + 0x008C: ('NEFCurve1', ), # ExifTool calls this 'ContrastCurve' 0x008D: ('ColorMode', ), - 0x008F: ('SceneMode?', ), + 0x008F: ('SceneMode', ), 0x0090: ('LightingType', ), + 0x0091: ('ShotInfo', ), # First 4 bytes are a version number in ASCII 0x0092: ('HueAdjustment', ), + # ExifTool calls this 'NEFCompression', should be 1-4 + 0x0093: ('Compression', ), 0x0094: ('Saturation', {-3: 'B&W', -2: '-2', -1: '-1', - 0: '0', - 1: '1', - 2: '2'}), + 0: '0', + 1: '1', + 2: '2'}), 0x0095: ('NoiseReduction', ), + 0x0096: ('NEFCurve2', ), # ExifTool calls this 'LinearizationTable' + 0x0097: ('ColorBalance', ), # First 4 bytes are a version number in ASCII + 0x0098: ('LensData', ), # First 4 bytes are a version number in ASCII + 0x0099: ('RawImageCenter', ), + 0x009A: ('SensorPixelSize', ), + 0x009C: ('Scene Assist', ), + 0x009E: ('RetouchHistory', ), + 0x00A0: ('SerialNumber', ), + 0x00A2: ('ImageDataSize', ), + # 00A3: unknown - a single byte 0 + # 00A4: In NEF, looks like a 4 byte ASCII version number ('0200') + 0x00A5: ('ImageCount', ), + 0x00A6: ('DeletedImageCount', ), 0x00A7: ('TotalShutterReleases', ), + # First 4 bytes are a version number in ASCII, with version specific + # info to follow. Its hard to treat it as a string due to embedded nulls. + 0x00A8: ('FlashInfo', ), 0x00A9: ('ImageOptimization', ), 0x00AA: ('Saturation', ), 0x00AB: ('DigitalVariProgram', ), - 0x0010: ('DataDump', ) + 0x00AC: ('ImageStabilization', ), + 0x00AD: ('Responsive AF', ), # 'AFResponse' + 0x00B0: ('MultiExposure', ), + 0x00B1: ('HighISONoiseReduction', ), + 0x00B7: ('AFInfo', ), + 0x00B8: ('FileInfo', ), + # 00B9: unknown + 0x0100: ('DigitalICE', ), + 0x0103: ('PreviewCompression', + {1: 'Uncompressed', + 2: 'CCITT 1D', + 3: 'T4/Group 3 Fax', + 4: 'T6/Group 4 Fax', + 5: 'LZW', + 6: 'JPEG (old-style)', + 7: 'JPEG', + 8: 'Adobe Deflate', + 9: 'JBIG B&W', + 10: 'JBIG Color', + 32766: 'Next', + 32769: 'Epson ERF Compressed', + 32771: 'CCIRLEW', + 32773: 'PackBits', + 32809: 'Thunderscan', + 32895: 'IT8CTPAD', + 32896: 'IT8LW', + 32897: 'IT8MP', + 32898: 'IT8BL', + 32908: 'PixarFilm', + 32909: 'PixarLog', + 32946: 'Deflate', + 32947: 'DCS', + 34661: 'JBIG', + 34676: 'SGILog', + 34677: 'SGILog24', + 34712: 'JPEG 2000', + 34713: 'Nikon NEF Compressed', + 65000: 'Kodak DCR Compressed', + 65535: 'Pentax PEF Compressed',}), + 0x0201: ('PreviewImageStart', ), + 0x0202: ('PreviewImageLength', ), + 0x0213: ('PreviewYCbCrPositioning', + {1: 'Centered', + 2: 'Co-sited'}), + 0x0010: ('DataDump', ), } -MAKERNOTE_NIKON_OLDER_TAGS={ +MAKERNOTE_NIKON_OLDER_TAGS = { 0x0003: ('Quality', {1: 'VGA Basic', 2: 'VGA Normal', @@ -406,7 +642,7 @@ MAKERNOTE_NIKON_OLDER_TAGS={ 3: 'Incandescent', 4: 'Fluorescent', 5: 'Cloudy', - 6: 'Speed Light'}) + 6: 'Speed Light'}), } # decode Olympus SpecialMode tag in MakerNote @@ -422,8 +658,10 @@ def olympus_special_mode(v): 2: 'Right to left', 3: 'Bottom to top', 4: 'Top to bottom'} + if v[0] not in a or v[2] not in b: + return v return '%s - sequence %d - %s' % (a[v[0]], v[1], b[v[2]]) - + MAKERNOTE_OLYMPUS_TAGS={ # ah HAH! those sneeeeeaky bastids! this is how they get past the fact # that a JPEG thumbnail is not allowed in an uncompressed TIFF file @@ -435,15 +673,235 @@ MAKERNOTE_OLYMPUS_TAGS={ 3: 'SHQ'}), 0x0202: ('Macro', {0: 'Normal', - 1: 'Macro'}), + 1: 'Macro', + 2: 'SuperMacro'}), + 0x0203: ('BWMode', + {0: 'Off', + 1: 'On'}), 0x0204: ('DigitalZoom', ), - 0x0207: ('SoftwareRelease', ), - 0x0208: ('PictureInfo', ), - # print as string - 0x0209: ('CameraID', lambda x: ''.join(map(chr, x))), - 0x0F00: ('DataDump', ) + 0x0205: ('FocalPlaneDiagonal', ), + 0x0206: ('LensDistortionParams', ), + 0x0207: ('SoftwareRelease', ), + 0x0208: ('PictureInfo', ), + 0x0209: ('CameraID', make_string), # print as string + 0x0F00: ('DataDump', ), + 0x0300: ('PreCaptureFrames', ), + 0x0404: ('SerialNumber', ), + 0x1000: ('ShutterSpeedValue', ), + 0x1001: ('ISOValue', ), + 0x1002: ('ApertureValue', ), + 0x1003: ('BrightnessValue', ), + 0x1004: ('FlashMode', ), + 0x1004: ('FlashMode', + {2: 'On', + 3: 'Off'}), + 0x1005: ('FlashDevice', + {0: 'None', + 1: 'Internal', + 4: 'External', + 5: 'Internal + External'}), + 0x1006: ('ExposureCompensation', ), + 0x1007: ('SensorTemperature', ), + 0x1008: ('LensTemperature', ), + 0x100b: ('FocusMode', + {0: 'Auto', + 1: 'Manual'}), + 0x1017: ('RedBalance', ), + 0x1018: ('BlueBalance', ), + 0x101a: ('SerialNumber', ), + 0x1023: ('FlashExposureComp', ), + 0x1026: ('ExternalFlashBounce', + {0: 'No', + 1: 'Yes'}), + 0x1027: ('ExternalFlashZoom', ), + 0x1028: ('ExternalFlashMode', ), + 0x1029: ('Contrast int16u', + {0: 'High', + 1: 'Normal', + 2: 'Low'}), + 0x102a: ('SharpnessFactor', ), + 0x102b: ('ColorControl', ), + 0x102c: ('ValidBits', ), + 0x102d: ('CoringFilter', ), + 0x102e: ('OlympusImageWidth', ), + 0x102f: ('OlympusImageHeight', ), + 0x1034: ('CompressionRatio', ), + 0x1035: ('PreviewImageValid', + {0: 'No', + 1: 'Yes'}), + 0x1036: ('PreviewImageStart', ), + 0x1037: ('PreviewImageLength', ), + 0x1039: ('CCDScanMode', + {0: 'Interlaced', + 1: 'Progressive'}), + 0x103a: ('NoiseReduction', + {0: 'Off', + 1: 'On'}), + 0x103b: ('InfinityLensStep', ), + 0x103c: ('NearLensStep', ), + + # TODO - these need extra definitions + # http://search.cpan.org/src/EXIFTOOL/Image-ExifTool-6.90/html/TagNames/Olympus.html + 0x2010: ('Equipment', ), + 0x2020: ('CameraSettings', ), + 0x2030: ('RawDevelopment', ), + 0x2040: ('ImageProcessing', ), + 0x2050: ('FocusInfo', ), + 0x3000: ('RawInfo ', ), } +# 0x2020 CameraSettings +MAKERNOTE_OLYMPUS_TAG_0x2020={ + 0x0100: ('PreviewImageValid', + {0: 'No', + 1: 'Yes'}), + 0x0101: ('PreviewImageStart', ), + 0x0102: ('PreviewImageLength', ), + 0x0200: ('ExposureMode', + {1: 'Manual', + 2: 'Program', + 3: 'Aperture-priority AE', + 4: 'Shutter speed priority AE', + 5: 'Program-shift'}), + 0x0201: ('AELock', + {0: 'Off', + 1: 'On'}), + 0x0202: ('MeteringMode', + {2: 'Center Weighted', + 3: 'Spot', + 5: 'ESP', + 261: 'Pattern+AF', + 515: 'Spot+Highlight control', + 1027: 'Spot+Shadow control'}), + 0x0300: ('MacroMode', + {0: 'Off', + 1: 'On'}), + 0x0301: ('FocusMode', + {0: 'Single AF', + 1: 'Sequential shooting AF', + 2: 'Continuous AF', + 3: 'Multi AF', + 10: 'MF'}), + 0x0302: ('FocusProcess', + {0: 'AF Not Used', + 1: 'AF Used'}), + 0x0303: ('AFSearch', + {0: 'Not Ready', + 1: 'Ready'}), + 0x0304: ('AFAreas', ), + 0x0401: ('FlashExposureCompensation', ), + 0x0500: ('WhiteBalance2', + {0: 'Auto', + 16: '7500K (Fine Weather with Shade)', + 17: '6000K (Cloudy)', + 18: '5300K (Fine Weather)', + 20: '3000K (Tungsten light)', + 21: '3600K (Tungsten light-like)', + 33: '6600K (Daylight fluorescent)', + 34: '4500K (Neutral white fluorescent)', + 35: '4000K (Cool white fluorescent)', + 48: '3600K (Tungsten light-like)', + 256: 'Custom WB 1', + 257: 'Custom WB 2', + 258: 'Custom WB 3', + 259: 'Custom WB 4', + 512: 'Custom WB 5400K', + 513: 'Custom WB 2900K', + 514: 'Custom WB 8000K', }), + 0x0501: ('WhiteBalanceTemperature', ), + 0x0502: ('WhiteBalanceBracket', ), + 0x0503: ('CustomSaturation', ), # (3 numbers: 1. CS Value, 2. Min, 3. Max) + 0x0504: ('ModifiedSaturation', + {0: 'Off', + 1: 'CM1 (Red Enhance)', + 2: 'CM2 (Green Enhance)', + 3: 'CM3 (Blue Enhance)', + 4: 'CM4 (Skin Tones)'}), + 0x0505: ('ContrastSetting', ), # (3 numbers: 1. Contrast, 2. Min, 3. Max) + 0x0506: ('SharpnessSetting', ), # (3 numbers: 1. Sharpness, 2. Min, 3. Max) + 0x0507: ('ColorSpace', + {0: 'sRGB', + 1: 'Adobe RGB', + 2: 'Pro Photo RGB'}), + 0x0509: ('SceneMode', + {0: 'Standard', + 6: 'Auto', + 7: 'Sport', + 8: 'Portrait', + 9: 'Landscape+Portrait', + 10: 'Landscape', + 11: 'Night scene', + 13: 'Panorama', + 16: 'Landscape+Portrait', + 17: 'Night+Portrait', + 19: 'Fireworks', + 20: 'Sunset', + 22: 'Macro', + 25: 'Documents', + 26: 'Museum', + 28: 'Beach&Snow', + 30: 'Candle', + 35: 'Underwater Wide1', + 36: 'Underwater Macro', + 39: 'High Key', + 40: 'Digital Image Stabilization', + 44: 'Underwater Wide2', + 45: 'Low Key', + 46: 'Children', + 48: 'Nature Macro'}), + 0x050a: ('NoiseReduction', + {0: 'Off', + 1: 'Noise Reduction', + 2: 'Noise Filter', + 3: 'Noise Reduction + Noise Filter', + 4: 'Noise Filter (ISO Boost)', + 5: 'Noise Reduction + Noise Filter (ISO Boost)'}), + 0x050b: ('DistortionCorrection', + {0: 'Off', + 1: 'On'}), + 0x050c: ('ShadingCompensation', + {0: 'Off', + 1: 'On'}), + 0x050d: ('CompressionFactor', ), + 0x050f: ('Gradation', + {'-1 -1 1': 'Low Key', + '0 -1 1': 'Normal', + '1 -1 1': 'High Key'}), + 0x0520: ('PictureMode', + {1: 'Vivid', + 2: 'Natural', + 3: 'Muted', + 256: 'Monotone', + 512: 'Sepia'}), + 0x0521: ('PictureModeSaturation', ), + 0x0522: ('PictureModeHue?', ), + 0x0523: ('PictureModeContrast', ), + 0x0524: ('PictureModeSharpness', ), + 0x0525: ('PictureModeBWFilter', + {0: 'n/a', + 1: 'Neutral', + 2: 'Yellow', + 3: 'Orange', + 4: 'Red', + 5: 'Green'}), + 0x0526: ('PictureModeTone', + {0: 'n/a', + 1: 'Neutral', + 2: 'Sepia', + 3: 'Blue', + 4: 'Purple', + 5: 'Green'}), + 0x0600: ('Sequence', ), # 2 or 3 numbers: 1. Mode, 2. Shot number, 3. Mode bits + 0x0601: ('PanoramaMode', ), # (2 numbers: 1. Mode, 2. Shot number) + 0x0603: ('ImageQuality2', + {1: 'SQ', + 2: 'HQ', + 3: 'SHQ', + 4: 'RAW'}), + 0x0901: ('ManometerReading', ), + } + + MAKERNOTE_CASIO_TAGS={ 0x0001: ('RecordingMode', {1: 'Single Shutter', @@ -471,11 +929,11 @@ MAKERNOTE_CASIO_TAGS={ 15: 'Strong'}), 0x0006: ('Object Distance', ), 0x0007: ('WhiteBalance', - {1: 'Auto', - 2: 'Tungsten', - 3: 'Daylight', - 4: 'Fluorescent', - 5: 'Shade', + {1: 'Auto', + 2: 'Tungsten', + 3: 'Daylight', + 4: 'Fluorescent', + 5: 'Shade', 129: 'Manual'}), 0x000B: ('Sharpness', {0: 'Normal', @@ -490,16 +948,16 @@ MAKERNOTE_CASIO_TAGS={ 1: 'Low', 2: 'High'}), 0x0014: ('CCDSpeed', - {64: 'Normal', - 80: 'Normal', + {64: 'Normal', + 80: 'Normal', 100: 'High', 125: '+1.0', 244: '+3.0', - 250: '+2.0',}) + 250: '+2.0'}), } MAKERNOTE_FUJIFILM_TAGS={ - 0x0000: ('NoteVersion', lambda x: ''.join(map(chr, x))), + 0x0000: ('NoteVersion', make_string), 0x1000: ('Quality', ), 0x1001: ('Sharpness', {1: 'Soft', @@ -508,20 +966,20 @@ MAKERNOTE_FUJIFILM_TAGS={ 4: 'Hard', 5: 'Hard'}), 0x1002: ('WhiteBalance', - {0: 'Auto', - 256: 'Daylight', - 512: 'Cloudy', - 768: 'DaylightColor-Fluorescent', - 769: 'DaywhiteColor-Fluorescent', - 770: 'White-Fluorescent', + {0: 'Auto', + 256: 'Daylight', + 512: 'Cloudy', + 768: 'DaylightColor-Fluorescent', + 769: 'DaywhiteColor-Fluorescent', + 770: 'White-Fluorescent', 1024: 'Incandescent', 3840: 'Custom'}), 0x1003: ('Color', - {0: 'Normal', + {0: 'Normal', 256: 'High', 512: 'Low'}), 0x1004: ('Tone', - {0: 'Normal', + {0: 'Normal', 256: 'High', 512: 'Low'}), 0x1010: ('FlashMode', @@ -540,12 +998,12 @@ MAKERNOTE_FUJIFILM_TAGS={ {0: 'Off', 1: 'On'}), 0x1031: ('PictureMode', - {0: 'Auto', - 1: 'Portrait', - 2: 'Landscape', - 4: 'Sports', - 5: 'Night', - 6: 'Program AE', + {0: 'Auto', + 1: 'Portrait', + 2: 'Landscape', + 4: 'Sports', + 5: 'Night', + 6: 'Program AE', 256: 'Aperture Priority AE', 512: 'Shutter Priority AE', 768: 'Manual Exposure'}), @@ -560,19 +1018,18 @@ MAKERNOTE_FUJIFILM_TAGS={ 1: 'On'}), 0x1302: ('AEWarning', {0: 'Off', - 1: 'On'}) + 1: 'On'}), } -MAKERNOTE_CANON_TAGS={ +MAKERNOTE_CANON_TAGS = { 0x0006: ('ImageType', ), 0x0007: ('FirmwareVersion', ), 0x0008: ('ImageNumber', ), - 0x0009: ('OwnerName', ) + 0x0009: ('OwnerName', ), } -# see http://www.burren.cx/david/canon.html by David Burren # this is in element offset, name, optional value dictionary format -MAKERNOTE_CANON_TAG_0x001={ +MAKERNOTE_CANON_TAG_0x001 = { 1: ('Macromode', {1: 'Macro', 2: 'Normal'}), @@ -677,10 +1134,10 @@ MAKERNOTE_CANON_TAG_0x001={ 4: 'FP Sync Enabled'}), 32: ('FocusMode', {0: 'Single', - 1: 'Continuous'}) + 1: 'Continuous'}), } -MAKERNOTE_CANON_TAG_0x004={ +MAKERNOTE_CANON_TAG_0x004 = { 7: ('WhiteBalance', {0: 'Auto', 1: 'Sunny', @@ -692,54 +1149,54 @@ MAKERNOTE_CANON_TAG_0x004={ 9: ('SequenceNumber', ), 14: ('AFPointUsed', ), 15: ('FlashBias', - {0XFFC0: '-2 EV', - 0XFFCC: '-1.67 EV', - 0XFFD0: '-1.50 EV', - 0XFFD4: '-1.33 EV', - 0XFFE0: '-1 EV', - 0XFFEC: '-0.67 EV', - 0XFFF0: '-0.50 EV', - 0XFFF4: '-0.33 EV', - 0X0000: '0 EV', - 0X000C: '0.33 EV', - 0X0010: '0.50 EV', - 0X0014: '0.67 EV', - 0X0020: '1 EV', - 0X002C: '1.33 EV', - 0X0030: '1.50 EV', - 0X0034: '1.67 EV', - 0X0040: '2 EV'}), - 19: ('SubjectDistance', ) + {0xFFC0: '-2 EV', + 0xFFCC: '-1.67 EV', + 0xFFD0: '-1.50 EV', + 0xFFD4: '-1.33 EV', + 0xFFE0: '-1 EV', + 0xFFEC: '-0.67 EV', + 0xFFF0: '-0.50 EV', + 0xFFF4: '-0.33 EV', + 0x0000: '0 EV', + 0x000C: '0.33 EV', + 0x0010: '0.50 EV', + 0x0014: '0.67 EV', + 0x0020: '1 EV', + 0x002C: '1.33 EV', + 0x0030: '1.50 EV', + 0x0034: '1.67 EV', + 0x0040: '2 EV'}), + 19: ('SubjectDistance', ), } # extract multibyte integer in Motorola format (little endian) def s2n_motorola(str): - x=0 + x = 0 for c in str: - x=(x << 8) | ord(c) + x = (x << 8) | ord(c) return x # extract multibyte integer in Intel format (big endian) def s2n_intel(str): - x=0 - y=0L + x = 0 + y = 0L for c in str: - x=x | (ord(c) << y) - y=y+8 + x = x | (ord(c) << y) + y = y + 8 return x # ratio object that eventually will be able to reduce itself to lowest # common denominator for printing def gcd(a, b): - if b == 0: - return a - else: - return gcd(b, a % b) + if b == 0: + return a + else: + return gcd(b, a % b) class Ratio: def __init__(self, num, den): - self.num=num - self.den=den + self.num = num + self.den = den def __repr__(self): self.reduce() @@ -748,31 +1205,31 @@ class Ratio: return '%d/%d' % (self.num, self.den) def reduce(self): - div=gcd(self.num, self.den) + div = gcd(self.num, self.den) if div > 1: - self.num=self.num/div - self.den=self.den/div + self.num = self.num / div + self.den = self.den / div # for ease of dealing with tags class IFD_Tag: def __init__(self, printable, tag, field_type, values, field_offset, field_length): # printable version of data - self.printable=printable + self.printable = printable # tag ID number - self.tag=tag + self.tag = tag # field type as index into FIELD_TYPES - self.field_type=field_type + self.field_type = field_type # offset of start of field in bytes from beginning of IFD - self.field_offset=field_offset + self.field_offset = field_offset # length of data field in bytes - self.field_length=field_length + self.field_length = field_length # either a string or array of data items - self.values=values - + self.values = values + def __str__(self): return self.printable - + def __repr__(self): return '(0x%04X) %s=%s @ %d' % (self.tag, FIELD_TYPES[self.field_type][2], @@ -781,14 +1238,15 @@ class IFD_Tag: # class that handles an EXIF header class EXIF_header: - def __init__(self, file, endian, offset, fake_exif, debug=0): - self.file=file - self.endian=endian - self.offset=offset - self.fake_exif=fake_exif - self.debug=debug - self.tags={} - + def __init__(self, file, endian, offset, fake_exif, strict, debug=0): + self.file = file + self.endian = endian + self.offset = offset + self.fake_exif = fake_exif + self.strict = strict + self.debug = debug + self.tags = {} + # convert slice to integer, based on sign and endian flags # usually this offset is assumed to be relative to the beginning of the # start of the EXIF information. For some cameras that use relative tags, @@ -809,15 +1267,15 @@ class EXIF_header: # convert offset to string def n2s(self, offset, length): - s='' - for i in range(length): + s = '' + for dummy in range(length): if self.endian == 'I': - s=s+chr(offset & 0xFF) + s = s + chr(offset & 0xFF) else: - s=chr(offset & 0xFF)+s - offset=offset >> 8 + s = chr(offset & 0xFF) + s + offset = offset >> 8 return s - + # return first IFD def first_IFD(self): return self.s2n(4, 4) @@ -837,142 +1295,182 @@ class EXIF_header: return a # return list of entries in this IFD - def dump_IFD(self, ifd, ifd_name, dict=EXIF_TAGS, relative=0): + def dump_IFD(self, ifd, ifd_name, dict=EXIF_TAGS, relative=0, stop_tag='UNDEF'): entries=self.s2n(ifd, 2) for i in range(entries): # entry is index of start of this IFD in the file - entry=ifd+2+12*i - tag=self.s2n(entry, 2) - # get tag name. We do it early to make debugging easier - tag_entry=dict.get(tag) + entry = ifd + 2 + 12 * i + tag = self.s2n(entry, 2) + + # get tag name early to avoid errors, help debug + tag_entry = dict.get(tag) if tag_entry: - tag_name=tag_entry[0] + tag_name = tag_entry[0] else: - tag_name='Tag 0x%04X' % tag - field_type=self.s2n(entry+2, 2) - if not 0 < field_type < len(FIELD_TYPES): + tag_name = 'Tag 0x%04X' % tag + + # ignore certain tags for faster processing + if not (not detailed and tag in IGNORE_TAGS): + field_type = self.s2n(entry + 2, 2) + # unknown field type - raise ValueError, \ - 'unknown type %d in tag 0x%04X' % (field_type, tag) - typelen=FIELD_TYPES[field_type][0] - count=self.s2n(entry+4, 4) - offset=entry+8 - if count*typelen > 4: - # offset is not the value; it's a pointer to the value - # if relative we set things up so s2n will seek to the right - # place when it adds self.offset. Note that this 'relative' - # is for the Nikon type 3 makernote. Other cameras may use - # other relative offsets, which would have to be computed here - # slightly differently. - if relative: - tmp_offset=self.s2n(offset, 4) - offset=tmp_offset+ifd-self.offset+4 - if self.fake_exif: - offset=offset+18 - else: - offset=self.s2n(offset, 4) - field_offset=offset - if field_type == 2: - # special case: null-terminated ASCII string - if count != 0: - self.file.seek(self.offset+offset) - values=self.file.read(count) - values=values.strip().replace('\x00','') - else: - values='' - else: - values=[] - signed=(field_type in [6, 8, 9, 10]) - for j in range(count): - if field_type in (5, 10): - # a ratio - value_j=Ratio(self.s2n(offset, 4, signed), - self.s2n(offset+4, 4, signed)) + if not 0 < field_type < len(FIELD_TYPES): + if not self.strict: + continue else: - value_j=self.s2n(offset, typelen, signed) - values.append(value_j) - offset=offset+typelen - # now "values" is either a string or an array - if count == 1 and field_type != 2: - printable=str(values[0]) - else: - printable=str(values) - # compute printable version of values - if tag_entry: - if len(tag_entry) != 1: - # optional 2nd tag element is present - if callable(tag_entry[1]): - # call mapping function - printable=tag_entry[1](values) + raise ValueError('unknown type %d in tag 0x%04X' % (field_type, tag)) + + typelen = FIELD_TYPES[field_type][0] + count = self.s2n(entry + 4, 4) + # Adjust for tag id/type/count (2+2+4 bytes) + # Now we point at either the data or the 2nd level offset + offset = entry + 8 + + # If the value fits in 4 bytes, it is inlined, else we + # need to jump ahead again. + if count * typelen > 4: + # offset is not the value; it's a pointer to the value + # if relative we set things up so s2n will seek to the right + # place when it adds self.offset. Note that this 'relative' + # is for the Nikon type 3 makernote. Other cameras may use + # other relative offsets, which would have to be computed here + # slightly differently. + if relative: + tmp_offset = self.s2n(offset, 4) + offset = tmp_offset + ifd - 8 + if self.fake_exif: + offset = offset + 18 else: - printable='' - for i in values: - # use lookup table for this tag - printable+=tag_entry[1].get(i, repr(i)) - self.tags[ifd_name+' '+tag_name]=IFD_Tag(printable, tag, - field_type, - values, field_offset, - count*typelen) - if self.debug: - print ' debug: %s: %s' % (tag_name, - repr(self.tags[ifd_name+' '+tag_name])) + offset = self.s2n(offset, 4) + + field_offset = offset + if field_type == 2: + # special case: null-terminated ASCII string + # XXX investigate + # sometimes gets too big to fit in int value + if count != 0 and count < (2**31): + self.file.seek(self.offset + offset) + values = self.file.read(count) + #print values + # Drop any garbage after a null. + values = values.split('\x00', 1)[0] + else: + values = '' + else: + values = [] + signed = (field_type in [6, 8, 9, 10]) + + # XXX investigate + # some entries get too big to handle could be malformed + # file or problem with self.s2n + if count < 1000: + for dummy in range(count): + if field_type in (5, 10): + # a ratio + value = Ratio(self.s2n(offset, 4, signed), + self.s2n(offset + 4, 4, signed)) + else: + value = self.s2n(offset, typelen, signed) + values.append(value) + offset = offset + typelen + # The test above causes problems with tags that are + # supposed to have long values! Fix up one important case. + elif tag_name == 'MakerNote' : + for dummy in range(count): + value = self.s2n(offset, typelen, signed) + values.append(value) + offset = offset + typelen + #else : + # print "Warning: dropping large tag:", tag, tag_name + + # now 'values' is either a string or an array + if count == 1 and field_type != 2: + printable=str(values[0]) + elif count > 50 and len(values) > 20 : + printable=str( values[0:20] )[0:-1] + ", ... ]" + else: + printable=str(values) + + # compute printable version of values + if tag_entry: + if len(tag_entry) != 1: + # optional 2nd tag element is present + if callable(tag_entry[1]): + # call mapping function + printable = tag_entry[1](values) + else: + printable = '' + for i in values: + # use lookup table for this tag + printable += tag_entry[1].get(i, repr(i)) + + self.tags[ifd_name + ' ' + tag_name] = IFD_Tag(printable, tag, + field_type, + values, field_offset, + count * typelen) + if self.debug: + print ' debug: %s: %s' % (tag_name, + repr(self.tags[ifd_name + ' ' + tag_name])) + + if tag_name == stop_tag: + break # extract uncompressed TIFF thumbnail (like pulling teeth) # we take advantage of the pre-existing layout in the thumbnail IFD as # much as possible def extract_TIFF_thumbnail(self, thumb_ifd): - entries=self.s2n(thumb_ifd, 2) + entries = self.s2n(thumb_ifd, 2) # this is header plus offset to IFD ... if self.endian == 'M': - tiff='MM\x00*\x00\x00\x00\x08' + tiff = 'MM\x00*\x00\x00\x00\x08' else: - tiff='II*\x00\x08\x00\x00\x00' + tiff = 'II*\x00\x08\x00\x00\x00' # ... plus thumbnail IFD data plus a null "next IFD" pointer self.file.seek(self.offset+thumb_ifd) - tiff+=self.file.read(entries*12+2)+'\x00\x00\x00\x00' - + tiff += self.file.read(entries*12+2)+'\x00\x00\x00\x00' + # fix up large value offset pointers into data area for i in range(entries): - entry=thumb_ifd+2+12*i - tag=self.s2n(entry, 2) - field_type=self.s2n(entry+2, 2) - typelen=FIELD_TYPES[field_type][0] - count=self.s2n(entry+4, 4) - oldoff=self.s2n(entry+8, 4) + entry = thumb_ifd + 2 + 12 * i + tag = self.s2n(entry, 2) + field_type = self.s2n(entry+2, 2) + typelen = FIELD_TYPES[field_type][0] + count = self.s2n(entry+4, 4) + oldoff = self.s2n(entry+8, 4) # start of the 4-byte pointer area in entry - ptr=i*12+18 + ptr = i * 12 + 18 # remember strip offsets location if tag == 0x0111: - strip_off=ptr - strip_len=count*typelen + strip_off = ptr + strip_len = count * typelen # is it in the data area? - if count*typelen > 4: + if count * typelen > 4: # update offset pointer (nasty "strings are immutable" crap) # should be able to say "tiff[ptr:ptr+4]=newoff" - newoff=len(tiff) - tiff=tiff[:ptr]+self.n2s(newoff, 4)+tiff[ptr+4:] + newoff = len(tiff) + tiff = tiff[:ptr] + self.n2s(newoff, 4) + tiff[ptr+4:] # remember strip offsets location if tag == 0x0111: - strip_off=newoff - strip_len=4 + strip_off = newoff + strip_len = 4 # get original data and store it - self.file.seek(self.offset+oldoff) - tiff+=self.file.read(count*typelen) - + self.file.seek(self.offset + oldoff) + tiff += self.file.read(count * typelen) + # add pixel strips and update strip offset info - old_offsets=self.tags['Thumbnail StripOffsets'].values - old_counts=self.tags['Thumbnail StripByteCounts'].values + old_offsets = self.tags['Thumbnail StripOffsets'].values + old_counts = self.tags['Thumbnail StripByteCounts'].values for i in range(len(old_offsets)): # update offset pointer (more nasty "strings are immutable" crap) - offset=self.n2s(len(tiff), strip_len) - tiff=tiff[:strip_off]+offset+tiff[strip_off+strip_len:] - strip_off+=strip_len + offset = self.n2s(len(tiff), strip_len) + tiff = tiff[:strip_off] + offset + tiff[strip_off + strip_len:] + strip_off += strip_len # add pixel strip to end - self.file.seek(self.offset+old_offsets[i]) - tiff+=self.file.read(old_counts[i]) - - self.tags['TIFFThumbnail']=tiff - + self.file.seek(self.offset + old_offsets[i]) + tiff += self.file.read(old_counts[i]) + + self.tags['TIFFThumbnail'] = tiff + # decode all the camera-specific MakerNote formats # Note is the data that comprises this MakerNote. The MakerNote will @@ -993,26 +1491,33 @@ class EXIF_header: # the offsets should be from the header at the start of all the EXIF info, # or from the header at the start of the makernote.) def decode_maker_note(self): - note=self.tags['EXIF MakerNote'] - make=self.tags['Image Make'].printable - model=self.tags['Image Model'].printable + note = self.tags['EXIF MakerNote'] + + # Some apps use MakerNote tags but do not use a format for which we + # have a description, so just do a raw dump for these. + #if self.tags.has_key('Image Make'): + make = self.tags['Image Make'].printable + #else: + # make = '' + + # model = self.tags['Image Model'].printable # unused # Nikon # The maker note usually starts with the word Nikon, followed by the # type of the makernote (1 or 2, as a short). If the word Nikon is # not at the start of the makernote, it's probably type 2, since some # cameras work that way. - if make in ('NIKON', 'NIKON CORPORATION'): - if note.values[0:7] == [78, 105, 107, 111, 110, 00, 01]: + if 'NIKON' in make: + if note.values[0:7] == [78, 105, 107, 111, 110, 0, 1]: if self.debug: print "Looks like a type 1 Nikon MakerNote." self.dump_IFD(note.field_offset+8, 'MakerNote', dict=MAKERNOTE_NIKON_OLDER_TAGS) - elif note.values[0:7] == [78, 105, 107, 111, 110, 00, 02]: + elif note.values[0:7] == [78, 105, 107, 111, 110, 0, 2]: if self.debug: print "Looks like a labeled type 2 Nikon MakerNote" if note.values[12:14] != [0, 42] and note.values[12:14] != [42L, 0L]: - raise ValueError, "Missing marker tag '42' in MakerNote." + raise ValueError("Missing marker tag '42' in MakerNote.") # skip the Makernote label and the TIFF header self.dump_IFD(note.field_offset+10+8, 'MakerNote', dict=MAKERNOTE_NIKON_NEWER_TAGS, relative=1) @@ -1025,34 +1530,37 @@ class EXIF_header: return # Olympus - if make[:7] == 'OLYMPUS': + if make.startswith('OLYMPUS'): self.dump_IFD(note.field_offset+8, 'MakerNote', dict=MAKERNOTE_OLYMPUS_TAGS) - return + # XXX TODO + #for i in (('MakerNote Tag 0x2020', MAKERNOTE_OLYMPUS_TAG_0x2020),): + # self.decode_olympus_tag(self.tags[i[0]].values, i[1]) + #return # Casio - if make == 'Casio': + if 'CASIO' in make or 'Casio' in make: self.dump_IFD(note.field_offset, 'MakerNote', dict=MAKERNOTE_CASIO_TAGS) return - + # Fujifilm if make == 'FUJIFILM': # bug: everything else is "Motorola" endian, but the MakerNote # is "Intel" endian - endian=self.endian - self.endian='I' + endian = self.endian + self.endian = 'I' # bug: IFD offsets are from beginning of MakerNote, not # beginning of file header - offset=self.offset - self.offset+=note.field_offset + offset = self.offset + self.offset += note.field_offset # process note with bogus values (note is actually at offset 12) self.dump_IFD(12, 'MakerNote', dict=MAKERNOTE_FUJIFILM_TAGS) # reset to correct values - self.endian=endian - self.offset=offset + self.endian = endian + self.offset = offset return - + # Canon if make == 'Canon': self.dump_IFD(note.field_offset, 'MakerNote', @@ -1062,6 +1570,11 @@ class EXIF_header: self.canon_decode_tag(self.tags[i[0]].values, i[1]) return + + # XXX TODO decode Olympus MakerNote tag based on offset within tag + def olympus_decode_tag(self, value, dict): + pass + # decode Canon MakerNote tag based on offset within tag # see http://www.burren.cx/david/canon.html by David Burren def canon_decode_tag(self, value, dict): @@ -1082,29 +1595,34 @@ class EXIF_header: # process an image file (expects an open file object) # this is the function that has to deal with all the arbitrary nasty bits # of the EXIF standard -def process_file(file, debug=0): +def process_file(f, stop_tag='UNDEF', details=True, strict=False, debug=False): + # yah it's cheesy... + global detailed + detailed = details + + # by default do not fake an EXIF beginning + fake_exif = 0 + # determine whether it's a JPEG or TIFF - data=file.read(12) + data = f.read(12) if data[0:4] in ['II*\x00', 'MM\x00*']: # it's a TIFF file - file.seek(0) - endian=file.read(1) - file.read(1) - offset=0 + f.seek(0) + endian = f.read(1) + f.read(1) + offset = 0 elif data[0:2] == '\xFF\xD8': # it's a JPEG file - # skip JFIF style header(s) - fake_exif=0 - while data[2] == '\xFF' and data[6:10] in ('JFIF', 'JFXX', 'OLYM'): - length=ord(data[4])*256+ord(data[5]) - file.read(length-8) + while data[2] == '\xFF' and data[6:10] in ('JFIF', 'JFXX', 'OLYM', 'Phot'): + length = ord(data[4])*256+ord(data[5]) + f.read(length-8) # fake an EXIF beginning of file - data='\xFF\x00'+file.read(10) - fake_exif=1 + data = '\xFF\x00'+f.read(10) + fake_exif = 1 if data[2] == '\xFF' and data[6:10] == 'Exif': # detected EXIF header - offset=file.tell() - endian=file.read(1) + offset = f.tell() + endian = f.read(1) else: # no EXIF information return {} @@ -1115,86 +1633,120 @@ def process_file(file, debug=0): # deal with the EXIF info we found if debug: print {'I': 'Intel', 'M': 'Motorola'}[endian], 'format' - hdr=EXIF_header(file, endian, offset, fake_exif, debug) - ifd_list=hdr.list_IFDs() - ctr=0 + hdr = EXIF_header(f, endian, offset, fake_exif, strict, debug) + ifd_list = hdr.list_IFDs() + ctr = 0 for i in ifd_list: if ctr == 0: - IFD_name='Image' + IFD_name = 'Image' elif ctr == 1: - IFD_name='Thumbnail' - thumb_ifd=i + IFD_name = 'Thumbnail' + thumb_ifd = i else: - IFD_name='IFD %d' % ctr + IFD_name = 'IFD %d' % ctr if debug: print ' IFD %d (%s) at offset %d:' % (ctr, IFD_name, i) - hdr.dump_IFD(i, IFD_name) + hdr.dump_IFD(i, IFD_name, stop_tag=stop_tag) # EXIF IFD - exif_off=hdr.tags.get(IFD_name+' ExifOffset') + exif_off = hdr.tags.get(IFD_name+' ExifOffset') if exif_off: if debug: print ' EXIF SubIFD at offset %d:' % exif_off.values[0] - hdr.dump_IFD(exif_off.values[0], 'EXIF') + hdr.dump_IFD(exif_off.values[0], 'EXIF', stop_tag=stop_tag) # Interoperability IFD contained in EXIF IFD - intr_off=hdr.tags.get('EXIF SubIFD InteroperabilityOffset') + intr_off = hdr.tags.get('EXIF SubIFD InteroperabilityOffset') if intr_off: if debug: print ' EXIF Interoperability SubSubIFD at offset %d:' \ % intr_off.values[0] hdr.dump_IFD(intr_off.values[0], 'EXIF Interoperability', - dict=INTR_TAGS) + dict=INTR_TAGS, stop_tag=stop_tag) # GPS IFD - gps_off=hdr.tags.get(IFD_name+' GPSInfo') + gps_off = hdr.tags.get(IFD_name+' GPSInfo') if gps_off: if debug: print ' GPS SubIFD at offset %d:' % gps_off.values[0] - hdr.dump_IFD(gps_off.values[0], 'GPS', dict=GPS_TAGS) - ctr+=1 + hdr.dump_IFD(gps_off.values[0], 'GPS', dict=GPS_TAGS, stop_tag=stop_tag) + ctr += 1 # extract uncompressed TIFF thumbnail - thumb=hdr.tags.get('Thumbnail Compression') + thumb = hdr.tags.get('Thumbnail Compression') if thumb and thumb.printable == 'Uncompressed TIFF': hdr.extract_TIFF_thumbnail(thumb_ifd) - + # JPEG thumbnail (thankfully the JPEG data is stored as a unit) - thumb_off=hdr.tags.get('Thumbnail JPEGInterchangeFormat') + thumb_off = hdr.tags.get('Thumbnail JPEGInterchangeFormat') if thumb_off: - file.seek(offset+thumb_off.values[0]) - size=hdr.tags['Thumbnail JPEGInterchangeFormatLength'].values[0] - hdr.tags['JPEGThumbnail']=file.read(size) - + f.seek(offset+thumb_off.values[0]) + size = hdr.tags['Thumbnail JPEGInterchangeFormatLength'].values[0] + hdr.tags['JPEGThumbnail'] = f.read(size) + # deal with MakerNote contained in EXIF IFD - if hdr.tags.has_key('EXIF MakerNote'): + # (Some apps use MakerNote tags but do not use a format for which we + # have a description, do not process these). + if 'EXIF MakerNote' in hdr.tags and 'Image Make' in hdr.tags and detailed: hdr.decode_maker_note() # Sometimes in a TIFF file, a JPEG thumbnail is hidden in the MakerNote # since it's not allowed in a uncompressed TIFF IFD - if not hdr.tags.has_key('JPEGThumbnail'): + if 'JPEGThumbnail' not in hdr.tags: thumb_off=hdr.tags.get('MakerNote JPEGThumbnail') if thumb_off: - file.seek(offset+thumb_off.values[0]) + f.seek(offset+thumb_off.values[0]) hdr.tags['JPEGThumbnail']=file.read(thumb_off.field_length) - + return hdr.tags + +# show command line usage +def usage(exit_status): + msg = 'Usage: EXIF.py [OPTIONS] file1 [file2 ...]\n' + msg += 'Extract EXIF information from digital camera image files.\n\nOptions:\n' + msg += '-q --quick Do not process MakerNotes.\n' + msg += '-t TAG --stop-tag TAG Stop processing when this tag is retrieved.\n' + msg += '-s --strict Run in strict mode (stop on errors).\n' + msg += '-d --debug Run in debug mode (display extra info).\n' + print msg + sys.exit(exit_status) + # library test/debug function (dump given files) if __name__ == '__main__': import sys - - if len(sys.argv) < 2: - print 'Usage: %s files...\n' % sys.argv[0] - sys.exit(0) - - for filename in sys.argv[1:]: + import getopt + + # parse command line options/arguments + try: + opts, args = getopt.getopt(sys.argv[1:], "hqsdt:v", ["help", "quick", "strict", "debug", "stop-tag="]) + except getopt.GetoptError: + usage(2) + if args == []: + usage(2) + detailed = True + stop_tag = 'UNDEF' + debug = False + strict = False + for o, a in opts: + if o in ("-h", "--help"): + usage(0) + if o in ("-q", "--quick"): + detailed = False + if o in ("-t", "--stop-tag"): + stop_tag = a + if o in ("-s", "--strict"): + strict = True + if o in ("-d", "--debug"): + debug = True + + # output info for each file + for filename in args: try: file=open(filename, 'rb') except: - print filename, 'unreadable' - print + print "'%s' is unreadable\n"%filename continue - print filename+':' - # data=process_file(file, 1) # with debug info - data=process_file(file) + print filename + ':' + # get the tags + data = process_file(file, stop_tag=stop_tag, details=detailed, strict=strict, debug=debug) if not data: print 'No EXIF information found' continue @@ -1209,6 +1761,7 @@ if __name__ == '__main__': (i, FIELD_TYPES[data[i].field_type][2], data[i].printable) except: print 'error', i, '"', data[i], '"' - if data.has_key('JPEGThumbnail'): + if 'JPEGThumbnail' in data: print 'File has JPEG thumbnail' print + diff --git a/src/lib/device_helper.py b/src/lib/device_helper.py index cf3955a..1435996 100644 --- a/src/lib/device_helper.py +++ b/src/lib/device_helper.py @@ -1,32 +1,23 @@ -# This Python file uses the following encoding: utf-8 -# -# Author: Roman 'gryf' Dobosz gryf@elysium.pl -# -# Copyright (C) 2007 by Roman 'gryf' Dobosz -# -# This file is part of pyGTKtalog. -# -# 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 2 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, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -# ------------------------------------------------------------------------- - +""" + Project: pyGTKtalog + Description: Simple functions for device management. + Type: lib + Author: Roman 'gryf' Dobosz, gryf73@gmail.com + Created: 2008-12-15 +""" import os +import locale +import gettext + +from src.lib.globs import APPL_SHORT_NAME + +locale.setlocale(locale.LC_ALL, '') +gettext.install(APPL_SHORT_NAME, 'locale', unicode=True) def volname(mntp): """read volume name from cd/dvd""" dev = mountpoint_to_dev(mntp) + label = None if dev != None: try: disk = open(dev, "rb") @@ -35,17 +26,20 @@ def volname(mntp): disk.close() except IOError: return None - return label - return None + return label def volmount(mntp): - """mount device, return 'ok' or error message""" + """ + Mount device. + @param mountpoint + @returns tuple with bool status of mount, and string with error message + """ _in, _out, _err = os.popen3("mount %s" % mntp) inf = _err.readlines() if len(inf) > 0: - return inf[0].strip() + return False, inf[0].strip() else: - return 'ok' + return True, '' def volumount(mntp): """mount device, return 'ok' or error message""" @@ -88,5 +82,5 @@ def eject_cd(eject_app, cdrom): return inf[0].strip() return 'ok' - return "Eject program not specified" + return _("Eject program not specified") diff --git a/src/lib/globs.py b/src/lib/globs.py index d879cd4..89e0120 100644 --- a/src/lib/globs.py +++ b/src/lib/globs.py @@ -35,7 +35,7 @@ TOPDIR = top_dir RESOURCES_DIR = os.path.join(TOPDIR, "resources") GLADE_DIR = os.path.join(RESOURCES_DIR, "glade") STYLES_DIR = os.path.join(RESOURCES_DIR, "styles") -APPL_SHORT_NAME = "pygtktalog2" +APPL_SHORT_NAME = "pygtktalog" APPL_VERSION = (1, 0, 2) # ---------------------------------------------------------------------- diff --git a/src/lib/gthumb.py b/src/lib/gthumb.py index 0a6c052..38c5f5e 100644 --- a/src/lib/gthumb.py +++ b/src/lib/gthumb.py @@ -27,7 +27,7 @@ import os from datetime import date class GthumbCommentParser(object): - + """Read and return comments created eith gThumb program""" def __init__(self, image_path, image_filename): self.path = image_path self.filename = image_filename @@ -36,16 +36,16 @@ class GthumbCommentParser(object): """Return dictionary with apropriate fields, or None if no comment available""" try: - gf = gzip.open(os.path.join(self.path, - '.comments', self.filename + '.xml')) + gzf = gzip.open(os.path.join(self.path, '.comments', + self.filename + '.xml')) except: return None try: - xml = gf.read() - gf.close() + xml = gzf.read() + gzf.close() except: - gf.close() + gzf.close() return None if not xml: diff --git a/src/lib/img.py b/src/lib/img.py index 9488d00..014ff60 100644 --- a/src/lib/img.py +++ b/src/lib/img.py @@ -44,7 +44,6 @@ class Img(object): """Save image and asociated thumbnail into specific directory structure returns filename for image""" - image_filename = path.join(self.base, self.sha512) thumbnail = path.join(self.base, self.sha512 + "_t") diff --git a/src/lib/midentify.py b/src/lib/midentify.py index 8fdb488..b054a9d 100644 --- a/src/lib/midentify.py +++ b/src/lib/midentify.py @@ -1,63 +1,61 @@ -# This Python file uses the following encoding: utf-8 - +""" + Project: pyGTKtalog + Description: Gather video file information. Uses external tools. + Type: lib + Author: Roman 'gryf' Dobosz, gryf73@gmail.com + Created: 2008-12-15 +""" from os import popen -from sys import argv, exit +import sys class Midentify(object): """Class for retrive midentify script output and put it in dict. Usually there is no need for such a detailed movie/clip information. Midentify script belongs to mplayer package. """ - + def __init__(self, filename): """Init class instance. Filename of a video file is required.""" self.filename = filename self.tags = {} - + def get_data(self): """return dict with clip information""" - output = popen("midentify \"%s\"" % self.filename).readlines() + output = popen('midentify "%s"' % self.filename).readlines() + + attrs = {'ID_VIDEO_WIDTH': ['width', int], + 'ID_VIDEO_HEIGHT': ['height', int], + 'ID_LENGTH': ['length', lambda x: int(x.split(".")[0])], + # length is in seconds + 'ID_DEMUXER': ['container', str], + 'ID_VIDEO_FORMAT': ['video_format', str], + 'ID_VIDEO_CODEC': ['video_codec', str], + 'ID_AUDIO_CODEC': ['audio_codec', str], + 'ID_AUDIO_FORMAT': ['audio_format', str], + 'ID_AUDIO_NCH': ['audio_no_channels', int],} + for line in output: line = line.strip() - if "ID_VIDEO_WIDTH" in line: - self.tags['width'] = line.replace("ID_VIDEO_WIDTH=", "") - elif "ID_VIDEO_HEIGHT" in line: - self.tags['height'] = line.replace("ID_VIDEO_HEIGHT=", "") - elif "ID_LENGTH" in line: - length = line.replace("ID_LENGTH=", "") - if "." in length: - length = length.split(".")[0] - seconds = int(length) - if seconds > 0: - hours = seconds / 3600 - seconds -= hours * 3600 - minutes = seconds / 60 - seconds -= minutes * 60 - self.tags['length'] = length - length_str = "%02d:%02d:%02d" % (hours, minutes, seconds) - self.tags['duration'] = length_str - elif "ID_DEMUXER" in line: - self.tags['container'] = line.replace("ID_DEMUXER=", "") - elif "ID_VIDEO_FORMAT" in line: - self.tags['video_format'] = line.replace("ID_VIDEO_FORMAT=", "") - elif "ID_VIDEO_CODEC" in line: - self.tags['video_codec'] = line.replace("ID_VIDEO_CODEC=", "") - elif "ID_AUDIO_CODEC" in line: - self.tags['audio_codec'] = line.replace("ID_AUDIO_CODEC=", "") - elif "ID_AUDIO_FORMAT" in line: - self.tags['audio_format'] = line.replace("ID_AUDIO_FORMAT=", "") - elif "ID_AUDIO_NCH" in line: - self.tags['audio_no_channels'] = line.replace("ID_AUDIO_NCH=", - "") + for attr in attrs: + if attr in line: + self.tags[attrs[attr][0]] = \ + attrs[attr][1](line.replace("%s=" % attr, "")) + + if 'length' in self.tags: + if self.tags['length'] > 0: + hours = self.tags['length'] / 3600 + seconds = self.tags['length'] - hours * 3600 + minutes = seconds / 60 + seconds -= minutes * 60 + length_str = "%02d:%02d:%02d" % (hours, minutes, seconds) + self.tags['duration'] = length_str return self.tags - if __name__ == "__main__": - """run as standalone script""" - if len(argv) < 2: - print "usage: %s filename" % argv[0] - exit() - - for arg in argv[1:]: + if len(sys.argv) < 2: + print "usage: %s filename" % sys.argv[0] + sys.exit() + + for arg in sys.argv[1:]: mid = Midentify(arg) print mid.get_data() diff --git a/src/models/m_main.py b/src/models/m_main.py index d94ebf3..8d0e3bb 100644 --- a/src/models/m_main.py +++ b/src/models/m_main.py @@ -27,23 +27,17 @@ import sys import shutil import bz2 import math +import sqlite3 as sqlite from tempfile import mkstemp +from datetime import datetime +import threading as _threading import gtk import gobject from gtkmvc.model_mt import ModelMT - -try: - import sqlite3 as sqlite -except ImportError: - from pysqlite2 import dbapi2 as sqlite - -from datetime import datetime - -import threading as _threading - from m_config import ConfigModel + try: from lib.thumbnail import Thumbnail from lib.img import Img @@ -53,6 +47,7 @@ from lib.parse_exif import ParseExif from lib.gthumb import GthumbCommentParser from lib.no_thumb import no_thumb as no_thumb_img +from lib.video import Video class MainModel(ModelMT): """Create, load, save, manipulate db file which is container for data""" @@ -91,6 +86,7 @@ class MainModel(ModelMT): # images extensions - only for PIL and EXIF IMG = ['jpg', 'jpeg', 'gif', 'png', 'tif', 'tiff', 'tga', 'pcx', 'bmp', 'xbm', 'xpm', 'jp2', 'jpx', 'pnm'] + MOV = ['avi', 'mpg', 'mpeg', 'mkv', 'wmv', 'ogm', 'mov'] def __init__(self): """initialize""" @@ -1753,7 +1749,24 @@ class MainModel(ModelMT): fileid = db_cursor.fetchone()[0] ext = i.split('.')[-1].lower() - + + # Video + if ext in self.MOV: + #import rpdb2; rpdb2.start_embedded_debugger('pass') + v = Video(current_file) + cfn = v.capture() + img = Img(cfn, self.image_path) + th = img.save() + if th: + sql = """INSERT INTO + thumbnails(file_id, filename) + VALUES(?, ?)""" + db_cursor.execute(sql, (fileid, th+"_t")) + sql = """INSERT INTO images(file_id, filename) + VALUES(?, ?)""" + db_cursor.execute(sql, (fileid, th)) + os.unlink(cfn) + # Images - thumbnails and exif data if self.config.confd['thumbs'] and ext in self.IMG: thumb = Thumbnail(current_file, self.image_path) diff --git a/src/test/run_tests.py b/src/test/run_tests.py index 1459d89..b56b1a1 100755 --- a/src/test/run_tests.py +++ b/src/test/run_tests.py @@ -1,53 +1,27 @@ -#!/usr/bin/env python -# This Python file uses the following encoding: utf-8 -# -# Author: Roman 'gryf' Dobosz gryf@elysium.pl -# -# Copyright (C) 2007 by Roman 'gryf' Dobosz -# -# This file is part of pyGTKtalog. -# -# 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 2 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, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -# ------------------------------------------------------------------------- +""" + Project: pyGTKtalog + Description: Test harvester and runner. + Type: exec + Author: Roman 'gryf' Dobosz, gryf73@gmail.com + Created: 2008-12-15 +""" import sys import unittest from os import path, chdir import glob -def my_import(module, name): - """import replacement""" - mod = __import__(module, {}, {}, [name]) - components = name.split('.') - for comp in components[1:]: - mod = getattr(mod, comp) - return mod - def setup_path(): """Sets up the python include paths to include needed directories""" this_path = path.abspath(path.dirname(__file__)) sys.path = [path.join(this_path, "../../src")] + sys.path - sys.path = [path.join(this_path, "../../src/test")] + sys.path sys.path = [path.join(this_path, "../../src/test/unit")] + sys.path return def build_suite(): - """build suite test from files in unit directory""" + """Build suite test from files in unit directory. Filenames with test + suites should always end with "_test.py".""" modules = [] - classes = [] for fname in glob.glob1('unit', '*_test.py'): class_name = fname[:-8] if "_" in class_name: @@ -59,7 +33,6 @@ def build_suite(): class_name = "Test" + class_name.capitalize() modules.append(fname[:-3]) - classes.append(class_name) modules = map(__import__, modules) load = unittest.defaultTestLoader.loadTestsFromModule diff --git a/src/test/unit/dummy_test.py b/src/test/unit/dummy_test.py index c42e90a..c2e3356 100644 --- a/src/test/unit/dummy_test.py +++ b/src/test/unit/dummy_test.py @@ -1,9 +1,15 @@ -# This Python file uses the following encoding: utf-8 +""" + Project: pyGTKtalog + Description: This is simple dummy test for... testing purposes :) + Type: test + Author: Roman 'gryf' Dobosz, gryf73@gmail.com + Created: 2008-12-15 +""" import unittest class TestDummy(unittest.TestCase): """Fake test class""" - def test_dummyMethod(self): + def test_dummy_method(self): """Test simple assertion""" self.assertTrue(True) diff --git a/src/test/unit/foo_bar_test.py b/src/test/unit/foo_bar_test.py index 7c1a8c9..13a8860 100644 --- a/src/test/unit/foo_bar_test.py +++ b/src/test/unit/foo_bar_test.py @@ -1,9 +1,15 @@ -# This Python file uses the following encoding: utf-8 +""" + Project: pyGTKtalog + Description: This is another dummy test. + Type: test + Author: Roman 'gryf' Dobosz, gryf73@gmail.com + Created: 2008-12-15 +""" import unittest class TestFooBar(unittest.TestCase): """Fake test class""" - def test_dummyMethod(self): + def test_dummy_method(self): """Test simple assertion""" self.assertTrue(True) diff --git a/src/test/unit/midentify_test.py b/src/test/unit/midentify_test.py index 3526fbf..7071bbd 100644 --- a/src/test/unit/midentify_test.py +++ b/src/test/unit/midentify_test.py @@ -1,4 +1,10 @@ -# This Python file uses the following encoding: utf-8 +""" + Project: pyGTKtalog + Description: Tests for Midentify class. + Type: test + Author: Roman 'gryf' Dobosz, gryf73@gmail.com + Created: 2008-12-15 +""" import unittest from lib.midentify import Midentify @@ -8,82 +14,82 @@ class TestMidentify(unittest.TestCase): Midentify script belongs to mplayer package. """ - def test_testAvi(self): + def test_avi(self): """test mock avi file, should return dict with expected values""" avi = Midentify("mocks/m.avi") result_dict = avi.get_data() self.assertTrue(len(result_dict) != 0, "result should have lenght > 0") self.assertEqual(result_dict['audio_format'], '85') - self.assertEqual(result_dict['width'], '128') - self.assertEqual(result_dict['audio_no_channels'], '2') - self.assertEqual(result_dict['height'], '96') + self.assertEqual(result_dict['width'], 128) + self.assertEqual(result_dict['audio_no_channels'], 2) + self.assertEqual(result_dict['height'], 96) self.assertEqual(result_dict['video_format'], 'XVID') - self.assertEqual(result_dict['length'], '4') + self.assertEqual(result_dict['length'], 4) self.assertEqual(result_dict['audio_codec'], 'mp3') self.assertEqual(result_dict['video_codec'], 'ffodivx') self.assertEqual(result_dict['duration'], '00:00:04') self.assertEqual(result_dict['container'], 'avi') - def test_testAvi2(self): + def test_avi2(self): """test another mock avi file, should return dict with expected values""" avi = Midentify("mocks/m1.avi") result_dict = avi.get_data() self.assertTrue(len(result_dict) != 0, "result should have lenght > 0") self.assertEqual(result_dict['audio_format'], '85') - self.assertEqual(result_dict['width'], '128') - self.assertEqual(result_dict['audio_no_channels'], '2') - self.assertEqual(result_dict['height'], '96') + self.assertEqual(result_dict['width'], 128) + self.assertEqual(result_dict['audio_no_channels'], 2) + self.assertEqual(result_dict['height'], 96) self.assertEqual(result_dict['video_format'], 'H264') - self.assertEqual(result_dict['length'], '4') + self.assertEqual(result_dict['length'], 4) self.assertEqual(result_dict['audio_codec'], 'mp3') self.assertEqual(result_dict['video_codec'], 'ffh264') self.assertEqual(result_dict['duration'], '00:00:04') self.assertEqual(result_dict['container'], 'avi') - def test_testMkv(self): + def test_mkv(self): """test mock mkv file, should return dict with expected values""" avi = Midentify("mocks/m.mkv") result_dict = avi.get_data() self.assertTrue(len(result_dict) != 0, "result should have lenght > 0") self.assertEqual(result_dict['audio_format'], '8192') - self.assertEqual(result_dict['width'], '128') - self.assertEqual(result_dict['audio_no_channels'], '2') - self.assertEqual(result_dict['height'], '96') + self.assertEqual(result_dict['width'], 128) + self.assertEqual(result_dict['audio_no_channels'], 2) + self.assertEqual(result_dict['height'], 96) self.assertEqual(result_dict['video_format'], 'mp4v') - self.assertEqual(result_dict['length'], '4') + self.assertEqual(result_dict['length'], 4) self.assertEqual(result_dict['audio_codec'], 'a52') self.assertEqual(result_dict['video_codec'], 'ffodivx') self.assertEqual(result_dict['duration'], '00:00:04') self.assertEqual(result_dict['container'], 'mkv') - def test_testMpg(self): + def test_mpg(self): """test mock mpg file, should return dict with expected values""" avi = Midentify("mocks/m.mpg") result_dict = avi.get_data() self.assertTrue(len(result_dict) != 0, "result should have lenght > 0") self.assertFalse(result_dict.has_key('audio_format')) - self.assertEqual(result_dict['width'], '128') + self.assertEqual(result_dict['width'], 128) self.assertFalse(result_dict.has_key('audio_no_channels')) - self.assertEqual(result_dict['height'], '96') + self.assertEqual(result_dict['height'], 96) self.assertEqual(result_dict['video_format'], '0x10000001') self.assertFalse(result_dict.has_key('lenght')) self.assertFalse(result_dict.has_key('audio_codec')) - self.assertEqual(result_dict['video_codec'], 'mpegpes') + self.assertEqual(result_dict['video_codec'], 'ffmpeg1') self.assertFalse(result_dict.has_key('duration')) self.assertEqual(result_dict['container'], 'mpeges') - def test_testOgm(self): + def test_ogm(self): """test mock ogm file, should return dict with expected values""" avi = Midentify("mocks/m.ogm") result_dict = avi.get_data() self.assertTrue(len(result_dict) != 0, "result should have lenght > 0") self.assertEqual(result_dict['audio_format'], '8192') - self.assertEqual(result_dict['width'], '160') - self.assertEqual(result_dict['audio_no_channels'], '2') - self.assertEqual(result_dict['height'], '120') + self.assertEqual(result_dict['width'], 160) + self.assertEqual(result_dict['audio_no_channels'], 2) + self.assertEqual(result_dict['height'], 120) self.assertEqual(result_dict['video_format'], 'H264') - self.assertEqual(result_dict['length'], '4') + self.assertEqual(result_dict['length'], 4) self.assertEqual(result_dict['audio_codec'], 'a52') self.assertEqual(result_dict['video_codec'], 'ffh264') self.assertEqual(result_dict['duration'], '00:00:04')