1
0
mirror of https://github.com/gryf/pygtktalog.git synced 2025-12-17 11:30:19 +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
# 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
Meta = MetaData()
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)):
shutil.move(thumb, os.path.join(img_path, *new_name))
else:
LOG.info("Thumbnail already exists (%s: %s)" % \
(fname, "/".join(new_name)))
LOG.info("Thumbnail already exists (%s: %s)",
fname, "/".join(new_name))
os.unlink(thumb)
def __repr__(self):
@@ -202,7 +202,6 @@ class Image(Base):
else:
LOG.info("Thumbnail already generated %s" % "/".join(new_name))
def get_copy(self):
"""
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):
"""Create menu/toolbar using uimanager."""
actions = [('File', None, '_File'),
('New', gtk.STOCK_NEW, '_New', None, 'Create new catalog', self.on_new),
('Open', gtk.STOCK_OPEN, '_Open', None, '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),
('New', gtk.STOCK_NEW, '_New', None,
'Create new catalog', self.on_new),
('Open', gtk.STOCK_OPEN, '_Open', None,
'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),
('Export', None, '_Export', None, None, self.on_export),
('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'),
('Delete', gtk.STOCK_DELETE, '_Delete', None, None, self.on_delete),
('Find', gtk.STOCK_FIND, '_Find', None, 'Find file', self.on_find),
('Delete', gtk.STOCK_DELETE, '_Delete', None, None,
self.on_delete),
('Find', gtk.STOCK_FIND, '_Find', None, 'Find file',
self.on_find),
('Preferences', gtk.STOCK_PREFERENCES, '_Preferences'),
('Catalog', None, '_Catalog'),
('Add_CD', gtk.STOCK_CDROM, '_Add CD', None, 'Add CD/DVD/BR to catalog'),
('Add_Dir', gtk.STOCK_DIRECTORY, '_Add Dir', None, 'Add directory to catalog'),
('Add_CD', gtk.STOCK_CDROM, '_Add CD', None,
'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_thumbnails', None, '_Delete all thumbnails'),
('Save_all_images', None, '_Save all images…'),
@@ -244,5 +253,5 @@ class MainWindow(object):
def run():
gui = MainWindow()
MainWindow()
gtk.mainloop()

View File

@@ -27,6 +27,7 @@ COLORS = {'WARNING': YELLOW,
'CRITICAL': WHITE,
'ERROR': RED}
def cprint(txt, color):
color_map = {"black": BLACK,
"red": RED,
@@ -58,13 +59,11 @@ class ColoredFormatter(logging.Formatter):
record.levelname = levelname_color
return logging.Formatter.format(self, record)
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='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.
Arguments:
@@ -83,11 +82,9 @@ def get_logger(module_name, level='INFO', to_file=True, to_console=True):
log.setLevel(LEVEL[level])
if to_console:
#path = "/dev/null"
console_handler = logging.StreamHandler(sys.stderr)
console_formatter = ColoredFormatter("%(filename)s:%(lineno)s - "
"%(levelname)s - %(message)s")
"%(levelname)s - %(message)s")
console_handler.setFormatter(console_formatter)
log.addHandler(console_handler)

View File

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

View File

@@ -1,11 +1,12 @@
"""
Project: pyGTKtalog
Description: pyGTK common utility functions
Type: tility
Type: utility
Author: Roman 'gryf' Dobosz, gryf73@gmail.com
Created: 2010-11-07 13:30:37
"""
def get_tv_item_under_cursor(treeview):
"""
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)
return item_id
return None

View File

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

View File

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

View File

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

View File

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

View File

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