Skip to content

Commit

Permalink
添加django的autoreload模块来加速开发。
Browse files Browse the repository at this point in the history
  • Loading branch information
cedricporter committed Jul 18, 2012
1 parent 82ac4a2 commit 6d28fa6
Show file tree
Hide file tree
Showing 4 changed files with 192 additions and 33 deletions.
32 changes: 16 additions & 16 deletions EffectLab/Effect.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,15 @@ def filter(self, img):
antialias = self.antialias
left, top, right, bottom = self.box if self.box else (0, 0, width, height)

for x in range(left, right):
for y in range(top, bottom):
for x in xrange(left, right):
for y in xrange(top, bottom):
found = 0
psum = (0, ) * nband

# anti-alias
for ai in range(antialias):
for ai in xrange(antialias):
_x = x + ai / float(antialias)
for aj in range(antialias):
for aj in xrange(antialias):
_y = y + aj / float(antialias)

u, v = self.formula(_x, _y)
Expand Down Expand Up @@ -116,18 +116,18 @@ def filter(self, img):

nband = len(img.getpixel((0, 0)))
antialias = self.antialias
for x in range(width):
for y in range(height):
for x in xrange(width):
for y in xrange(height):
if sqrt((x - cx) ** 2 + (y - cy) ** 2) > r:
continue

found = 0
psum = (0, ) * nband

# anti-alias
for ai in range(antialias):
for ai in xrange(antialias):
_x = x + ai / float(antialias)
for aj in range(antialias):
for aj in xrange(antialias):
_y = y + aj / float(antialias)

u, v = self.warp(_x, _y, r, (cx, cy), (mx, my))
Expand Down Expand Up @@ -166,15 +166,15 @@ def filter(self, img):
nx, ny = width, height
new_img = img.copy()
nband = len(img.getpixel((0, 0)))
for j in range(height):
for i in range(width):
for j in xrange(height):
for i in xrange(width):
found = 0
psum = (0, ) * nband
new_img.putpixel((i, j), Effect.empty_color)
# antialias
for ai in range(self.antialias):
for ai in xrange(self.antialias):
x = 2 * (i + ai / float(self.antialias)) / width - 1
for aj in range(self.antialias):
for aj in xrange(self.antialias):
y = 2 * (j + aj / float(self.antialias)) / height - 1

# distortion
Expand Down Expand Up @@ -275,9 +275,9 @@ def filter(self, img):
new_img = img.copy()
height_delta = (bottom - top + 1) * self.vertical_delta
width_delta = 2 * math.pi / (right - left + 1) * (self.horizon_delta + 1)
for x in range(left, right):
for x in xrange(left, right):
degree = x * width_delta
for y in range(top, bottom):
for y in xrange(top, bottom):

# distortion
h = sin(degree) * height_delta * ((bottom - top) / 2 - sqrt((y - mid_y) ** 2 + (x - mid_x) ** 2)) / mid_y
Expand Down Expand Up @@ -330,9 +330,9 @@ def filter(self, img):

# draw grid
draw = ImageDraw.Draw(img)
for x in range(0, width, self.width_offset):
for x in xrange(0, width, self.width_offset):
draw.line((x, 0, x, height), self.color)
for y in range(0, height, self.height_offset):
for y in xrange(0, height, self.height_offset):
draw.line((0, y, width, y), self.color)

del draw
Expand Down
54 changes: 37 additions & 17 deletions TestEffectLab.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,18 @@
# website: http://EverET.org
#

import os
import os, time, string, random
import autoreload
from math import sqrt, sin, cos, tan, atan2
from EffectLab.Effect import *

def merge_origin_and_new(img, effect):
'''Merge origin and new Image processed by function effect in one Image
'''
width, height = img.size
grid = GridMaker(20, 20)
old = grid(img)
old = img
# grid = GridMaker(20, 20)
# old = grid(img)
img = effect(old)

# merge origin and new image
Expand All @@ -25,22 +27,40 @@ def merge_origin_and_new(img, effect):

return out

if __name__ == '__main__':
effects = [GlobalWaveEffect(),
RadianSqrtEffect(),
RadianFormulaEffect(lambda r, phi: (r ** 1.5 * math.cos(r), phi)),
LensWarpEffect(lambda x, y: (sin(x * math.pi / 2), sin(y * math.pi / 2))),
LensWarpEffect(lambda x, y: (sign(x) * x ** 2, sign(y) * y ** 2)),
RadianFormulaEffect(lambda r, phi: (r ** 2, phi), 4),
LocalWarpEffect((130, 120), (130, 50), 100),
]

if os.path.exists('z.jpg'):
img = Image.open('z.jpg')
else:
img = Image.new("RGBA", (300, 300), (255, 255, 255, 255))

def main():
print 'Started'

effects = [
RadianFormulaEffect(lambda r, phi: (r ** 2, phi), 4),
LensWarpEffect(lambda x, y: (sin(x * math.pi / 2), sin(y * math.pi / 2))),
RadianFormulaEffect(lambda r, phi: (r ** 1.5 * math.cos(r), phi)),
GlobalWaveEffect(),
RadianSqrtEffect(),
LensWarpEffect(lambda x, y: (sign(x) * x ** 2, sign(y) * y ** 2)),
LocalWarpEffect((130, 120), (130, 50), 100),
]

# if os.path.exists('z.jpg'):
# img = Image.open('z.jpg')
# else:
# img = Image.new("RGBA", (300, 300), (255, 255, 255, 255))

text = ''.join(random.choice(string.letters) for i in xrange(4))

img = Image.new("RGB", (100, 40), (255, 255, 255))
font = ImageFont.truetype("UbuntuMono-R.ttf", 33)
draw = ImageDraw.Draw(img)
draw.setfont(font)

draw.text((10, 0), text, (0, 0, 0))
del draw

for index, effect in enumerate(effects):
merge_origin_and_new(img, effect).save('%d.jpg' % index, quality=90)
print '.',
print 'done'


if __name__ == '__main__':
autoreload.main(main)
Binary file added UbuntuMono-R.ttf
Binary file not shown.
139 changes: 139 additions & 0 deletions autoreload.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
# Autoreloading launcher.
# Borrowed from Peter Hunt and the CherryPy project (http://www.cherrypy.org).
# Some taken from Ian Bicking's Paste (http://pythonpaste.org/).
#
# Portions copyright (c) 2004, CherryPy Team ([email protected])
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of the CherryPy Team nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# 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.

import os, sys, time, signal

try:
import thread
except ImportError:
import dummy_thread as thread

# This import does nothing, but it's necessary to avoid some race conditions
# in the threading module. See http://code.djangoproject.com/ticket/2330 .
try:
import threading
except ImportError:
pass

try:
import termios
except ImportError:
termios = None

RUN_RELOADER = True

_mtimes = {}
_win = (sys.platform == "win32")

def code_changed():
global _mtimes, _win
for filename in filter(lambda v: v, map(lambda m: getattr(m, "__file__", None), sys.modules.values())):
if filename.endswith(".pyc") or filename.endswith(".pyo"):
filename = filename[:-1]
if not os.path.exists(filename):
continue # File might be in an egg, so it can't be reloaded.
stat = os.stat(filename)
mtime = stat.st_mtime
if _win:
mtime -= stat.st_ctime
if filename not in _mtimes:
_mtimes[filename] = mtime
continue
if mtime != _mtimes[filename]:
_mtimes = {}
return True
return False

def ensure_echo_on():
if termios:
fd = sys.stdin
if fd.isatty():
attr_list = termios.tcgetattr(fd)
if not attr_list[3] & termios.ECHO:
attr_list[3] |= termios.ECHO
if hasattr(signal, 'SIGTTOU'):
old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN)
else:
old_handler = None
termios.tcsetattr(fd, termios.TCSANOW, attr_list)
if old_handler is not None:
signal.signal(signal.SIGTTOU, old_handler)

def reloader_thread():
ensure_echo_on()
while RUN_RELOADER:
if code_changed():
sys.exit(3) # force reload
time.sleep(1)

def restart_with_reloader():
while True:
args = [sys.executable] + ['-W%s' % o for o in sys.warnoptions] + sys.argv
if sys.platform == "win32":
args = ['"%s"' % arg for arg in args]
new_environ = os.environ.copy()
new_environ["RUN_MAIN"] = 'true'
exit_code = os.spawnve(os.P_WAIT, sys.executable, args, new_environ)
if exit_code != 3:
return exit_code

def python_reloader(main_func, args, kwargs):
if os.environ.get("RUN_MAIN") == "true":
thread.start_new_thread(main_func, args, kwargs)
try:
reloader_thread()
except KeyboardInterrupt:
pass
else:
try:
sys.exit(restart_with_reloader())
except KeyboardInterrupt:
pass

def jython_reloader(main_func, args, kwargs):
from _systemrestart import SystemRestart
thread.start_new_thread(main_func, args)
while True:
if code_changed():
raise SystemRestart
time.sleep(1)


def main(main_func, args=None, kwargs=None):
if args is None:
args = ()
if kwargs is None:
kwargs = {}
if sys.platform.startswith('java'):
reloader = jython_reloader
else:
reloader = python_reloader
reloader(main_func, args, kwargs)

0 comments on commit 6d28fa6

Please sign in to comment.