1
0
mirror of https://github.com/gryf/pygtktalog.git synced 2025-12-17 19:40:21 +01:00

Several small fixes, mostly for style issues

This commit is contained in:
2019-02-24 18:25:34 +01:00
parent 07690f9c94
commit 6c6f01781a
11 changed files with 69 additions and 65 deletions

View File

@@ -12,11 +12,6 @@ from sqlalchemy.ext.declarative import declarative_base
from pygtktalog.logger import get_logger from pygtktalog.logger import get_logger
# setup SQLAlchemy logging facility
# TODO: Logger("sqlalchemy")
# or maybe it will be better to separate sqlalchemy stuff from application
#get_logger("sqlalchemy", 'INFO')
# Prepare SQLAlchemy objects # Prepare SQLAlchemy objects
Meta = MetaData() Meta = MetaData()
Base = declarative_base(metadata=Meta) Base = declarative_base(metadata=Meta)

View File

@@ -148,8 +148,8 @@ class Thumbnail(Base):
if not os.path.exists(os.path.join(img_path, *new_name)): if not os.path.exists(os.path.join(img_path, *new_name)):
shutil.move(thumb, os.path.join(img_path, *new_name)) shutil.move(thumb, os.path.join(img_path, *new_name))
else: else:
LOG.info("Thumbnail already exists (%s: %s)" % \ LOG.info("Thumbnail already exists (%s: %s)",
(fname, "/".join(new_name))) fname, "/".join(new_name))
os.unlink(thumb) os.unlink(thumb)
def __repr__(self): def __repr__(self):
@@ -202,7 +202,6 @@ class Image(Base):
else: else:
LOG.info("Thumbnail already generated %s" % "/".join(new_name)) LOG.info("Thumbnail already generated %s" % "/".join(new_name))
def get_copy(self): def get_copy(self):
""" """
Create the very same object as self with exception of id field Create the very same object as self with exception of id field

View File

@@ -138,21 +138,30 @@ class MainWindow(object):
def _setup_menu_toolbar(self, vbox): def _setup_menu_toolbar(self, vbox):
"""Create menu/toolbar using uimanager.""" """Create menu/toolbar using uimanager."""
actions = [('File', None, '_File'), actions = [('File', None, '_File'),
('New', gtk.STOCK_NEW, '_New', None, 'Create new catalog', self.on_new), ('New', gtk.STOCK_NEW, '_New', None,
('Open', gtk.STOCK_OPEN, '_Open', None, 'Open catalog file', self.on_open), 'Create new catalog', self.on_new),
('Save', gtk.STOCK_SAVE, '_Save', None, 'Save catalog file', self.on_save), ('Open', gtk.STOCK_OPEN, '_Open', None,
('Save As', gtk.STOCK_SAVE_AS, '_Save As', None, None, self.on_save), 'Open catalog file', self.on_open),
('Save', gtk.STOCK_SAVE, '_Save', None,
'Save catalog file', self.on_save),
('Save As', gtk.STOCK_SAVE_AS,
'_Save As', None, None, self.on_save),
('Import', None, '_Import', None, None, self.on_import), ('Import', None, '_Import', None, None, self.on_import),
('Export', None, '_Export', None, None, self.on_export), ('Export', None, '_Export', None, None, self.on_export),
('Recent', None, '_Recent files'), ('Recent', None, '_Recent files'),
('Quit', gtk.STOCK_QUIT, '_Quit', None, 'Quit the Program', self.on_quit), ('Quit', gtk.STOCK_QUIT, '_Quit', None,
'Quit the Program', self.on_quit),
('Edit', None, '_Edit'), ('Edit', None, '_Edit'),
('Delete', gtk.STOCK_DELETE, '_Delete', None, None, self.on_delete), ('Delete', gtk.STOCK_DELETE, '_Delete', None, None,
('Find', gtk.STOCK_FIND, '_Find', None, 'Find file', self.on_find), self.on_delete),
('Find', gtk.STOCK_FIND, '_Find', None, 'Find file',
self.on_find),
('Preferences', gtk.STOCK_PREFERENCES, '_Preferences'), ('Preferences', gtk.STOCK_PREFERENCES, '_Preferences'),
('Catalog', None, '_Catalog'), ('Catalog', None, '_Catalog'),
('Add_CD', gtk.STOCK_CDROM, '_Add CD', None, 'Add CD/DVD/BR to catalog'), ('Add_CD', gtk.STOCK_CDROM, '_Add CD', None,
('Add_Dir', gtk.STOCK_DIRECTORY, '_Add Dir', None, 'Add directory to catalog'), 'Add CD/DVD/BR to catalog'),
('Add_Dir', gtk.STOCK_DIRECTORY, '_Add Dir', None,
'Add directory to catalog'),
('Delete_all_images', None, '_Delete all images'), ('Delete_all_images', None, '_Delete all images'),
('Delete_all_thumbnails', None, '_Delete all thumbnails'), ('Delete_all_thumbnails', None, '_Delete all thumbnails'),
('Save_all_images', None, '_Save all images…'), ('Save_all_images', None, '_Save all images…'),
@@ -244,5 +253,5 @@ class MainWindow(object):
def run(): def run():
gui = MainWindow() MainWindow()
gtk.mainloop() gtk.mainloop()

View File

@@ -27,6 +27,7 @@ COLORS = {'WARNING': YELLOW,
'CRITICAL': WHITE, 'CRITICAL': WHITE,
'ERROR': RED} 'ERROR': RED}
def cprint(txt, color): def cprint(txt, color):
color_map = {"black": BLACK, color_map = {"black": BLACK,
"red": RED, "red": RED,
@@ -58,13 +59,11 @@ class ColoredFormatter(logging.Formatter):
record.levelname = levelname_color record.levelname = levelname_color
return logging.Formatter.format(self, record) return logging.Formatter.format(self, record)
log_obj = None log_obj = None
#def get_logger(module_name, level='INFO', to_file=False):
#def get_logger(module_name, level='DEBUG', to_file=True):
def get_logger(module_name, level='INFO', to_file=True, to_console=True): def get_logger(module_name, level='INFO', to_file=True, to_console=True):
# def get_logger(module_name, level='DEBUG', to_file=True, to_console=True):
#def get_logger(module_name, level='DEBUG', to_file=False):
""" """
Prepare and return log object. Standard formatting is used for all logs. Prepare and return log object. Standard formatting is used for all logs.
Arguments: Arguments:
@@ -83,8 +82,6 @@ def get_logger(module_name, level='INFO', to_file=True, to_console=True):
log.setLevel(LEVEL[level]) log.setLevel(LEVEL[level])
if to_console: if to_console:
#path = "/dev/null"
console_handler = logging.StreamHandler(sys.stderr) console_handler = logging.StreamHandler(sys.stderr)
console_formatter = ColoredFormatter("%(filename)s:%(lineno)s - " console_formatter = ColoredFormatter("%(filename)s:%(lineno)s - "
"%(levelname)s - %(message)s") "%(levelname)s - %(message)s")

View File

@@ -29,6 +29,7 @@ def float_to_string(float_length):
sec = int(float_length) sec = int(float_length)
return "%02d:%02d:%02d" % (hour, minutes, sec) return "%02d:%02d:%02d" % (hour, minutes, sec)
def calculate_image_path(dbpath=None, create=False): def calculate_image_path(dbpath=None, create=False):
"""Calculate image path out of provided path or using current connection""" """Calculate image path out of provided path or using current connection"""
if not dbpath: if not dbpath:
@@ -58,6 +59,7 @@ def calculate_image_path(dbpath=None, create=False):
return os.path.abspath(images_dir) return os.path.abspath(images_dir)
def mk_paths(fname, img_path): def mk_paths(fname, img_path):
"""Make path for provided pathname by calculating crc32 out of file""" """Make path for provided pathname by calculating crc32 out of file"""
with open(fname, 'r+b') as fobj: with open(fname, 'r+b') as fobj:

View File

@@ -1,11 +1,12 @@
""" """
Project: pyGTKtalog Project: pyGTKtalog
Description: pyGTK common utility functions Description: pyGTK common utility functions
Type: tility Type: utility
Author: Roman 'gryf' Dobosz, gryf73@gmail.com Author: Roman 'gryf' Dobosz, gryf73@gmail.com
Created: 2010-11-07 13:30:37 Created: 2010-11-07 13:30:37
""" """
def get_tv_item_under_cursor(treeview): def get_tv_item_under_cursor(treeview):
""" """
Get item (most probably id of the row) form tree view under cursor. Get item (most probably id of the row) form tree view under cursor.
@@ -22,4 +23,3 @@ def get_tv_item_under_cursor(treeview):
item_id = model.get_value(tm_iter, 0) item_id = model.get_value(tm_iter, 0)
return item_id return item_id
return None return None

View File

@@ -6,7 +6,6 @@
Created: 2011-03-27 Created: 2011-03-27
""" """
import os import os
import sys
import re import re
from datetime import datetime from datetime import datetime
import mimetypes import mimetypes
@@ -26,7 +25,6 @@ RE_FN_START = re.compile(r'(?P<fname_start>'
r'(\[[A-Fa-f0-9]{8}\])\..*') r'(\[[A-Fa-f0-9]{8}\])\..*')
class NoAccessError(Exception): class NoAccessError(Exception):
"""No access exception""" """No access exception"""
pass pass
@@ -114,7 +112,7 @@ class Scan(object):
# number of objects to retrieve at once. Limit is 999. Let's do a # number of objects to retrieve at once. Limit is 999. Let's do a
# little bit below. # little bit below.
num = 900 num = 900
steps = len(all_ids) / num + 1 steps = len(all_ids) // num + 1
for step in range(steps): for step in range(steps):
all_obj.extend(self._session all_obj.extend(self._session
.query(File) .query(File)
@@ -181,8 +179,8 @@ class Scan(object):
# self._session.merge(self._files[0]) # self._session.merge(self._files[0])
LOG.debug("Deleting objects whitout parent: %s", LOG.debug("Deleting objects whitout parent: %s",
str(self._session.query(File) str(self._session.query(File)
.filter(File.parent==None).all())) .filter(File.parent==None).all())) # noqa
self._session.query(File).filter(File.parent==None).delete() self._session.query(File).filter(File.parent==None).delete() # noqa
self._session.commit() self._session.commit()
return self._files return self._files
@@ -207,7 +205,7 @@ class Scan(object):
ext = os.path.splitext(fp)[1] ext = os.path.splitext(fp)[1]
if mimeinfo and mimeinfo in mimedict.keys(): if mimeinfo and mimeinfo in mimedict:
mimedict[mimeinfo](fobj, fp) mimedict[mimeinfo](fobj, fp)
elif ext and ext in extdict: elif ext and ext in extdict:
mimedict[extdict[ext]](fobj, fp) mimedict[extdict[ext]](fobj, fp)
@@ -475,8 +473,8 @@ class Scan(object):
def _set_image_path(self): def _set_image_path(self):
"""Get or calculate the images path""" """Get or calculate the images path"""
image_path = self._session.query(Config) \ image_path = (self._session.query(Config)
.filter(Config.key=="image_path").one() .filter(Config.key=="image_path")).one() # noqa
if image_path.value == ":same_as_db:": if image_path.value == ":same_as_db:":
image_path = pygtktalog.misc.calculate_image_path() image_path = pygtktalog.misc.calculate_image_path()
else: else:
@@ -501,4 +499,3 @@ def _get_dirsize(path):
os.path.join(root, fname)) os.path.join(root, fname))
LOG.debug("_get_dirsize, %s: %d", path, size) LOG.debug("_get_dirsize, %s: %d", path, size)
return size return size

View File

@@ -105,7 +105,7 @@ class ThumbCreator(object):
""" """
try: try:
image_thumb = Image.open(self.filename).convert('RGB') image_thumb = Image.open(self.filename).convert('RGB')
except: except Exception:
return None return None
it_x, it_y = image_thumb.size it_x, it_y = image_thumb.size
if it_x > self.thumb_x or it_y > self.thumb_y: if it_x > self.thumb_x or it_y > self.thumb_y:

View File

@@ -183,9 +183,9 @@ class Video(object):
for dummy in range(1, no_pictures + 1): for dummy in range(1, no_pictures + 1):
current_time += step current_time += step
time = float_to_string(current_time) time = float_to_string(current_time)
cmd = "mplayer \"%s\" -ao null -brightness 0 -hue 0 " \ cmd = ('mplayer "%s" -ao null -brightness 0 -hue 0 '
"-saturation 0 -contrast 0 -mc 0 -vf-clr -vo jpeg:outdir=\"%s\" -ss %s" \ '-saturation 0 -contrast 0 -mc 0 -vf-clr '
" -frames 1 2>/dev/null" '-vo jpeg:outdir="%s" -ss %s -frames 1 2>/dev/null')
os.popen(cmd % (self.filename, directory, time)).readlines() os.popen(cmd % (self.filename, directory, time)).readlines()
try: try:
@@ -217,13 +217,13 @@ class Video(object):
if not (self.tags['width'] * row_length) > self.out_width: if not (self.tags['width'] * row_length) > self.out_width:
for i in [8, 6, 5]: for i in [8, 6, 5]:
if (no_pictures % i) == 0 and \ if ((no_pictures % i) == 0 and
(i * self.tags['width']) <= self.out_width: (i * self.tags['width']) <= self.out_width):
row_length = i row_length = i
break break
coef = float(self.out_width - row_length - 1) / \ coef = (float(self.out_width - row_length - 1) /
(self.tags['width'] * row_length) (self.tags['width'] * row_length))
if coef < 1: if coef < 1:
dim = (int(self.tags['width'] * coef), dim = (int(self.tags['width'] * coef),
int(self.tags['height'] * coef)) int(self.tags['height'] * coef))
@@ -232,7 +232,7 @@ class Video(object):
ifn_list = os.listdir(directory) ifn_list = os.listdir(directory)
ifn_list.sort() ifn_list.sort()
img_list = [Image.open(os.path.join(directory, fn)).resize(dim) \ img_list = [Image.open(os.path.join(directory, fn)).resize(dim)
for fn in ifn_list] for fn in ifn_list]
rows = no_pictures // row_length rows = no_pictures // row_length
@@ -251,7 +251,7 @@ class Video(object):
bbox = (left, upper, right, lower) bbox = (left, upper, right, lower)
try: try:
img = img_list.pop(0) img = img_list.pop(0)
except: except Exception:
break break
inew.paste(img, bbox) inew.paste(img, bbox)
inew.save(image_fn, 'JPEG') inew.save(image_fn, 'JPEG')
@@ -272,7 +272,7 @@ class Video(object):
""" """
try: try:
return int(chain.split(".")[0]) return int(chain.split(".")[0])
except: except Exception:
return 0 return 0
def __str__(self): def __str__(self):

View File

@@ -3,7 +3,6 @@
Fast and ugly CLI interface for pyGTKtalog Fast and ugly CLI interface for pyGTKtalog
""" """
import argparse import argparse
import errno
import os import os
import re import re
import sys import sys
@@ -24,6 +23,7 @@ BOLD_SEQ = '\033[1m'
LOG = logger.get_logger(__name__) LOG = logger.get_logger(__name__)
def colorize(txt, color): def colorize(txt, color):
"""Pretty print with colors to console.""" """Pretty print with colors to console."""
color_map = {'black': BLACK, color_map = {'black': BLACK,
@@ -289,14 +289,13 @@ class Iface(object):
def fsck(self): def fsck(self):
"""Fsck orphaned images/thumbs""" """Fsck orphaned images/thumbs"""
image_path = self.sess.query(dbo.Config).\ image_path = (self.sess.query(dbo.Config)
filter(dbo.Config.key=='image_path').one().value .filter(dbo.Config.key=='image_path')).one().value # noqa
if image_path == ':same_as_db:': if image_path == ':same_as_db:':
image_path = misc.calculate_image_path(None, False) image_path = misc.calculate_image_path(None, False)
files_to_remove = [] files_to_remove = []
obj_to_remove = []
# remove images/thumbnails which doesn't have file relation # remove images/thumbnails which doesn't have file relation
for name, obj in (("images", dbo.Image), for name, obj in (("images", dbo.Image),
@@ -318,20 +317,20 @@ class Iface(object):
fname).lstrip('/') fname).lstrip('/')
if '_t' in fname: if '_t' in fname:
obj = self.sess.query(dbo.Thumbnail)\ obj = (self.sess.query(dbo.Thumbnail)
.filter(dbo.Thumbnail.filename==fname_).all() .filter(dbo.Thumbnail.filename==fname_)).all() # noqa
if obj: if obj:
continue continue
obj = self.sess.query(dbo.Image)\ obj = (self.sess.query(dbo.Image)
.filter(dbo.Image.filename==\ .filter(dbo.Image.filename== # noqa
fname_.replace('_t.', '.')).all() fname_.replace('_t.', '.'))).all()
if obj: if obj:
continue continue
else: else:
obj = self.sess.query(dbo.Image)\ obj = (self.sess.query(dbo.Image)
.filter(dbo.Image.filename==fname_).all() .filter(dbo.Image.filename==fname_)).all() # noqa
if obj: if obj:
continue continue
@@ -417,13 +416,13 @@ def add_dir(args):
obj.close() obj.close()
@asserdb
def create_db(args): def create_db(args):
"""List""" """List"""
obj = Iface(args.db, args.pretend, args.debug) obj = Iface(args.db, args.pretend, args.debug)
obj.create(args.dir_to_add, args.imagedir) obj.create(args.dir_to_add, args.imagedir)
obj.close() obj.close()
@asserdb @asserdb
def search(args): def search(args):
"""Find""" """Find"""
@@ -431,6 +430,7 @@ def search(args):
obj.find(args.search_words) obj.find(args.search_words)
obj.close() obj.close()
@asserdb @asserdb
def cleanup(args): def cleanup(args):
"""Cleanup""" """Cleanup"""
@@ -439,7 +439,6 @@ def cleanup(args):
obj.close() obj.close()
def main(): def main():
"""Main""" """Main"""
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
@@ -472,7 +471,7 @@ def main():
create.add_argument('dir_to_add') create.add_argument('dir_to_add')
create.add_argument('-i', '--imagedir', help="Directory where to put " create.add_argument('-i', '--imagedir', help="Directory where to put "
"images for the database. Popular, but deprecated " "images for the database. Popular, but deprecated "
"choice is `~/.pygtktalog/images'. Currnet default " "choice is `~/.pygtktalog/images'. Current default "
"is special string `:same_as_db:' which will try to " "is special string `:same_as_db:' which will try to "
"create directory with the same name as the db with " "create directory with the same name as the db with "
"data suffix", default=':same_as_db:') "data suffix", default=':same_as_db:')
@@ -510,7 +509,12 @@ def main():
fsck.set_defaults(func=cleanup) fsck.set_defaults(func=cleanup)
args = parser.parse_args() args = parser.parse_args()
if 'func' in args:
args.func(args) args.func(args)
else:
parser.print_help()
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@@ -64,5 +64,6 @@ def main():
app = App(db) app = App(db)
app.run() app.run()
if __name__ == "__main__": if __name__ == "__main__":
main() main()