Skip to content

Commit

Permalink
Merge pull request #1 from umyuu/version-0.0.2
Browse files Browse the repository at this point in the history
Version 0 0 2
  • Loading branch information
umyuu authored Mar 22, 2017
2 parents af214c2 + 2285c0e commit 7a353e4
Show file tree
Hide file tree
Showing 4 changed files with 186 additions and 78 deletions.
9 changes: 6 additions & 3 deletions plug-ins/guetzli_export_plugin.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
{
"COMMENT": "",
"COMMAND": {
"NEW_SHELL" : "FALSE",
"NEW_SHELL": "True",
"FILE": {
"DOWNLOAD": {
"LINK": "https://github.com/google/guetzli/releases"
},
"PREFIX": "guetzli*",
"LOWER_LIMIT": 500000
"LOWER_LIMIT": 232960
},
"SUFFIX": [".png", ".jpg", ".jpeg"],
"PARAMS": {
"-verbose": "True"
"--quality": "95"
}
}
}
127 changes: 89 additions & 38 deletions plug-ins/guetzli_export_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import subprocess
from collections import OrderedDict
import threading
from decimal import Decimal

try:
from gimpfu import *
Expand All @@ -17,14 +18,27 @@


class ProgressBar(object):
def __init__(self):
self.value = 0
self.step = 0.04
self.minimum = 0
self.maximum = 1
def __init__(self, step=0.01):
"""
self.step calcation
"""
self.value = Decimal(0)
self._step = Decimal(step)
# <blockquote cite="https://developer.gimp.org/api/2.0/libgimp/libgimp-gimpprogress.html">
# gimp_progress_update
# percentage :Percentage of progress completed (in the range from 0.0 to 1.0).
# </blockquote>
self.minimum = Decimal(0)
self.maximum = Decimal(1)
# todo model&view split
if isGIMP:
gimp.progress_init("Save guetzli ...")

@property
def step(self):
return self._step
@step.setter
def step(self, value):
self._step = value
def perform_step(self):
"""
value increment
Expand All @@ -33,35 +47,66 @@ def perform_step(self):
self.value += self.step
if isGIMP:
gimp.progress_update(self.value)
else:
print(self.value)
if self.value >= self.maximum:
self.value = self.minimum

class Canvas(object):
"""
Image Wrapper Class
"""
def __init__(self):
if isGIMP:
self.image = gimp.image_list()[0]
else:
self.image = None
@property
def filename(self):
if self.image is not None:
return self.image.filename
return '.\\test.png'
@property
def width(self):
if self.image is not None:
return self.image.width
return 800
@property
def height(self):
if self.image is not None:
return self.image.height
return 617
@property
def size(self):
return self.width * self.height
class Plugin(object):
JSON = None

def __init__(self):
self.base_dir = os.path.dirname(__file__)
Plugin.load_setting()
node = Plugin.JSON['COMMAND']
self.cmd = self.search_command(node['FILE']['PREFIX'], node['FILE']['LOWER_LIMIT'])
self.params = OrderedDict()
self.is_verbose = node['PARAMS']['-verbose'].upper() == 'TRUE'
self.cmd = self.search_command(node['FILE'])
self.params = OrderedDict(node['PARAMS'])
self.is_new_shell = node['NEW_SHELL'].upper() == 'TRUE'
self.output_extension = '.jpeg'
self.canvas = Canvas()
self.input_file = None
self.output_file = None
def search_command(self, target, lower_limit):
def search_command(self, node):
""" search guetzli
:param target:
:param lower_limit:
:param node:
:return:file name
order by find first
"""
for file in glob.glob(os.path.join(self.base_dir, target)):
target = node['PREFIX']
lower_limit = int(node['LOWER_LIMIT'])
link = node['DOWNLOAD']['LINK']
for exe_file in glob.glob(os.path.join(self.base_dir, target)):
# skip plugin file
if os.path.getsize(file) >= int(lower_limit):
return file
raise Exception('File Not Found\n{0}\n{1}'.format(self.base_dir, target[:-1]))
if os.path.getsize(exe_file) > lower_limit:
return exe_file
raise Exception('File Not Found\n{0}\nPlease download {1}\n{2}'.format(self.base_dir, target[:-1], link))

@staticmethod
def load_setting():
Expand All @@ -76,36 +121,45 @@ def load_setting():
with open(file_name, 'r') as infile:
Plugin.JSON = json.load(infile)
except:
# file open error Wrapping
raise Exception('File Not Found\n{0}'.format(file_name))
return Plugin.JSON

@staticmethod
def with_suffix(file_name, suffix):
return os.path.splitext(file_name)[0] + suffix

def set_quality(self, quality):
self.params['-quality'] = int(quality)
self.params['--quality'] = int(quality)
return self
def set_extension(self, extension):
self.output_extension = extension
return self
def get_args(self):
"""
guetzli | params | in | out
guetzli , params , in , out
:return:
"""
args = [self.cmd]
# add command line parameter
for k in self.params.keys():
args.append(k)
args.append(str(self.params[k]))
if self.is_verbose:
args.append('-verbose')
self.set_filename()
args.append(self.input_file)
args.append(self.output_file)
return args

def calc_best_step(self):
"""
ProgressBar step calc
<blockquote cite="https://github.com/google/guetzli">
Guetzli uses a significant amount of CPU time. You should count on using about 1 minute of CPU per 1 MPix of input image.
</blockquote>
:return:
"""
minute = Decimal(self.canvas.size) / Decimal(1000000)
# Thread#join timeout elapsed
step = minute / Decimal(60)
return step
def run(self):
cmd = self.get_args()
if not isGIMP:
Expand All @@ -115,7 +169,7 @@ def run(self):
# http://stackoverflow.com/questions/9941064/subprocess-popen-with-a-unicode-path
cmd = cmd.encode(locale.getpreferredencoding())
try:
progress = ProgressBar()
progress = ProgressBar(self.calc_best_step())
lock = threading.RLock()
in_params = [cmd, self.is_new_shell]
out_params = [None, '']
Expand All @@ -125,19 +179,19 @@ def run(self):
t.join(timeout=1)
progress.perform_step()
with lock:
# not Success
if out_params[0] != 0:
raise Exception(out_params[1])
except Exception as ex:
raise
@staticmethod
def run_thread(in_params, lock, out_params):
"""
:param in_params: cmd | is_new_shell
:param in_params: cmd , is_new_shell
:param lock:
:param out_params: return code | message
:param out_params: return code , message
:return:None
"""
return_code = 0
exception = None
try:
return_code = subprocess.call(in_params[0], shell=in_params[1])
Expand All @@ -151,27 +205,24 @@ def run_thread(in_params, lock, out_params):

def set_filename(self):
"""
set input, output file
"""
name = ''
if isGIMP:
image = gimp.image_list()[0]
name = image.filename
else:
name = '.\\test.png'
name = self.canvas.filename
# suffix check
supported = tuple(Plugin.JSON['COMMAND']['SUFFIX'])
if not name.endswith(supported):
raise Exception('UnSupported File Type\n{0}'.format(name))
if isGIMP:
name = '{0}'.format(name)
else:
name = '{0}'.format(name)
self.input_file = '"{0}"'.format(name)
self.output_file = '"{0}"'.format(Plugin.with_suffix(name, self.output_extension))

@staticmethod
def main(ext, quality):
"""
plugin entry point
:param ext: output file extension
:param quality:
:return:
"""
plugin = Plugin()
plugin.set_extension(ext)
plugin.set_quality(quality)
Expand All @@ -185,7 +236,7 @@ def main(ext, quality):
help="",
author="umyu",
copyright="umyu",
date="2017/3/20",
date="2017/3/22",
label="Save guetzli ...",
imagetypes="*",
params=[
Expand Down
9 changes: 6 additions & 3 deletions src/guetzli_export_plugin.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
{
"COMMENT": "",
"COMMAND": {
"NEW_SHELL" : "True",
"NEW_SHELL": "True",
"FILE": {
"DOWNLOAD": {
"LINK": "https://github.com/google/guetzli/releases"
},
"PREFIX": "guetzli*",
"LOWER_LIMIT": 500000
"LOWER_LIMIT": 232960
},
"SUFFIX": [".png", ".jpg", ".jpeg"],
"PARAMS": {
"-verbose": "True"
"--quality": "95"
}
}
}
Loading

0 comments on commit 7a353e4

Please sign in to comment.