# -*- coding: utf-8 -*-
import wx
import os
import datetime
import time
import random
import string
from PIL import Image
from PIL.ExifTags import TAGS
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY,
u'Organizador de fotografías',
size=(450,400))
panel = wx.Panel(self, wx.ID_ANY)
self.btAbre = wx.Button(panel, label="1.- Selecciona directorio con fotos a organizar")
self.btAbre.Bind(wx.EVT_BUTTON, self.directorio)
self.lblPrefijo = wx.StaticText(panel, wx.ID_ANY, u'2.- Introduce un prefijo (opcional)')
self.txtPrefijo = wx.TextCtrl(panel, size=(200, -1))
self.txtRuta = wx.TextCtrl(panel, size=(400,27))
self.txtRuta.SetForegroundColour('darkblue')
self.btOrganiza = wx.Button(panel, label=u'3.- ¡Organiza fotos!')
self.btOrganiza.Bind(wx.EVT_BUTTON, organiza)
self.ctInfo = wx.TextCtrl(panel, size=(400,170), style= wx.TE_MULTILINE)
self.txtRuta.SetEditable(False)
self.ctInfo.SetEditable(False)
self.btOrganiza.Disable()
self.btAyuda = wx.Button(panel, label='?')
self.btAyuda.Bind(wx.EVT_BUTTON, self.ayuda)
self.separador = wx.StaticText(panel, label=' ')
self.btSalir = wx.Button(panel, label='Salir')
self.btSalir.Bind(wx.EVT_BUTTON, self.salir)
sizerPrefijo = wx.BoxSizer(wx.HORIZONTAL)
sizerPrefijo.Add(self.lblPrefijo, 0, wx.ALL|wx.LEFT, 5)
sizerPrefijo.Add(self.txtPrefijo, 1, wx.EXPAND|wx.ALL|wx.LEFT, 5)
sizerInferior = wx.BoxSizer(wx.HORIZONTAL)
sizerInferior.Add(self.btAyuda, 0, wx.ALL|wx.LEFT, 5)
sizerInferior.Add(self.separador, 1, wx.EXPAND|wx.ALL|wx.LEFT, 5)
sizerInferior.Add(self.btSalir, 1, wx.ALL|wx.RIGHT, 5)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.btAbre, 0, wx.ALL|wx.CENTER, 5)
sizer.Add(self.txtRuta, 0, wx.ALL|wx.CENTER, 10)
sizer.Add(sizerPrefijo, 0, wx.EXPAND|wx.ALL|wx.CENTER, 5)
sizer.Add(self.btOrganiza, 0, wx.ALL|wx.CENTER, 5)
sizer.Add(self.ctInfo, 1, wx.ALL|wx.CENTER, 10)
sizer.Add(sizerInferior, 0, wx.EXPAND|wx.ALL|wx.CENTER, 5)
panel.SetSizer(sizer)
self.Centre()
def directorio(self, event):
carpeta = None
self.txtRuta.Clear()
self.ctInfo.Clear()
dlg = wx.DirDialog(self, u'Escoge un directorio:',
style=wx.DD_DEFAULT_STYLE
| wx.DD_NEW_DIR_BUTTON)
if dlg.ShowModal() == wx.ID_OK:
carpeta = dlg.GetPath()
# self.ct.WriteText("Directorio seleccionado: %s" % carpeta)
self.txtRuta.WriteText(carpeta)
self.btOrganiza.Enable()
else:
self.txtRuta.WriteText(u'Operación Cancelada')
dlg.Destroy()
return carpeta
def ayuda(self, event):
texto = 'FotoClas\n\n'
texto += u'¿Has vuelto de tus vacaciones con un montón de fotos de distintas cámaras y teléfonos, cada uno con su propia nomenclatura? Menudo follón para organizarlas...\n\n'
texto += u'Esta es una pequeña aplicación que renombra las fotografías de una determinada carpeta, usando su fecha de creación, en formato (Prefijo)-YYYYMMDDHHMMSS\n\n'
texto += u'Para ello, intenta usar los datos EXIF de la fotografía. En este caso, la fecha será la de la cámara que la tomó.\n\n'
texto += u'Si esos datos no están disponibles, se usa la fecha del fichero en el disco.\n\n'
texto += u'Además, se añaden dos letras aleatorias al final, para evitar colisiones de nombres.'
wx.MessageBox(texto, 'Ayuda')
def salir(self, event):
self.Destroy()
# http://stackoverflow.com/questions/765396/exif-manipulation-library-for-python
def get_exif(fn):
ret = {}
i = Image.open(fn)
info = i._getexif()
if info is not None:
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
if tag=='DateTime':
print tag
ret[decoded] = value
print ret
return ret
def organiza(self):
ruta = frame.txtRuta.GetValue() + os.sep
if len(frame.txtPrefijo.GetValue()):
prefijo = frame.txtPrefijo.GetValue() + '-'
else:
prefijo = ''
print prefijo, ruta
ficheros = os.listdir(ruta)
for fichero in ficheros:
if os.path.isfile(ruta+fichero):
if fichero.lower()[-4:]=='.jpg':
nombreOld = ruta + fichero
rnd = ''.join(random.choice(string.ascii_lowercase) for _ in range(2))
try:
fecha = get_exif(nombreOld)['DateTimeOriginal'].replace(':', '').replace(' ','')
except KeyError:
fecha = time.strftime('%Y%m%d%H%M%S', time.localtime(os.path.getmtime(nombreOld)))
nombreNuevo = ruta + prefijo + fecha + rnd + '.jpg'
linea = nombreOld.replace(ruta, '') + ' -> ' + nombreNuevo.replace(ruta, '')
frame.ctInfo.WriteText(linea + '\n')
os.rename(nombreOld, nombreNuevo)
frame.btOrganiza.Disable()
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm()
frame.Show()
app.MainLoop()
Comentarios sobre la versión: 1.0 (3)
http://www.wxpython.org/