<commit_before>import cStringIO
import framework.util as util
from framework.log import log
from framework.controller import *
from PIL import Image, ImageOps

class ImageServer(Controller):
    
    # edit eholda 2011-01-28
    # added thumbnail option
    @classmethod
    def add(cls, db, data, app, max_size=None, grayscale=False, mirror=True, thumb_max_size=None):
        log.info("ImageServer.add")
        try:
            id = db.insert('images', app=app)
        except Exception, e:
            log.error(e)
            return None
        path = ImageServer.path(app, id)        
        try:            
            f = open(path, "wb")
            f.write(data)        
            f.close()
            image = Image.open(path)
        except Exception, e:
            log.error(e)
            try:
                db.query("DELETE FROM images WHERE id=$id", {'id': id})
                os.remove(path)
            except Exception, e:
                log.error(e)
            log.warning("--> removed id %s" % id)
            return None
        if image.format != "PNG":
            log.info("--> converting %s to PNG" % image.format)
        if max_size and (image.size[0] > max_size[0] or image.size[1] > max_size[1]):
            image = ImageServer.resizeToFit(image, max_size)
        if grayscale:
            image = ImageOps.grayscale(image)                
        if thumb_max_size:    
            thumbImage = ImageServer.resizeToFit(image, thumb_max_size)
            thumbPath = ''.join([path[:-4], "_thumb.png"]) 
        try:
            image.save(path, "PNG")  
            if thumb_max_size:
                thumbImage.save(thumbPath, "PNG")
        except Exception, e:
            log.error(e)
            return None
        log.info("--> saved %s" % path)  
        # eholda temporarily comment out mirror stuff
        #if Config.get('mirror')['active'] and mirror:
        #    Tasks().add(tube=Config.get('mirror')['tube'], data={'image_id': id, 'app': app}, timeout=120)  
        return id
        
    # old resize method    
    @classmethod
    def resizeToMax(cls, image, max_size):
        ratio = float(max_size[0]) / float(image.size[0]) if image.size[0] > max_size[0] else float(max_size[1]) / float(image.size[1])
        new_size = int(ratio * image.size[0]), int(ratio * image.size[1])
        log.info("--> resizing to %sx%s" % new_size)
        image = image.resize(new_size, Image.ANTIALIAS)     
        return image

    # new resize method, eholda 2011-02-12
    @classmethod
    def resizeToFit(cls, image, box):
        if (image.size[0] > box[0] or image.size[1] > box[1]):
            xratio = float(box[0]) / float(image.size[0])
            yratio = float(box[1]) / float(image.size[1])
        
            ratio = xratio if xratio < yratio else yratio
            
            #print "--> xratio = %s, yratio = %s, ratio = %s" % (xratio, yratio, ratio)
            
            newsize = [int(ratio * image.size[0]), int(ratio * image.size[1])]
        
            log.info("*** RESIZING from %s to %s" % ([image.size[0], image.size[1]], newsize))
            
            return image.resize(newsize, Image.ANTIALIAS)
        else:
            print "--> no resize"
            return image     

    @classmethod<commit_msg>Added proper thumbnail cropping.<commit_after>import cStringIO
import framework.util as util
from framework.log import log
from framework.controller import *
from PIL import Image, ImageOps

class ImageServer(Controller):
    
    # edit eholda 2011-01-28
    # added thumbnail option
    @classmethod
    def add(cls, db, data, app, max_size=None, grayscale=False, mirror=True, thumb_max_size=None):
        log.info("ImageServer.add")
        try:
            id = db.insert('images', app=app)
        except Exception, e:
            log.error(e)
            return None
        path = ImageServer.path(app, id)        
        try:            
            f = open(path, "wb")
            f.write(data)        
            f.close()
            image = Image.open(path)
        except Exception, e:
            log.error(e)
            try:
                db.query("DELETE FROM images WHERE id=$id", {'id': id})
                os.remove(path)
            except Exception, e:
                log.error(e)
            log.warning("--> removed id %s" % id)
            return None
        if image.format != "PNG":
            log.info("--> converting %s to PNG" % image.format)
        if max_size and (image.size[0] > max_size[0] or image.size[1] > max_size[1]):
            #image = ImageServer.resizeToFit(image, max_size)
            image = ImageServer.resizeToMax(image, max_size)
            image = ImageServer.cropToBox(image, max_size[0])
        
        if grayscale:
            image = ImageOps.grayscale(image)                
        if thumb_max_size:    
            thumbImage = ImageServer.resizeToFit(image, thumb_max_size)
            thumbPath = ''.join([path[:-4], "_thumb.png"]) 
        try:
            image.save(path, "PNG")  
            if thumb_max_size:
                thumbImage.save(thumbPath, "PNG")
        except Exception, e:
            log.error(e)
            return None
        log.info("--> saved %s" % path)  
        # eholda temporarily comment out mirror stuff
        #if Config.get('mirror')['active'] and mirror:
        #    Tasks().add(tube=Config.get('mirror')['tube'], data={'image_id': id, 'app': app}, timeout=120)  
        return id
        
    #
    @classmethod
    def cropToBox(cls, image, max_length):
        if (image.size[0] > image.size[1]):
            top = 0
            left = int(float(image.size[0] - max_length)/float(2))
        else:
            top = int(float(image.size[1] - max_length)/float(2))
            left = 0
            
        box = (left, top, left + max_length, top + max_length)
        
        return image.crop(box)
         
        
    # old resize method    
    @classmethod
    def resizeToMax(cls, image, max_size):
        ratio = float(max_size[0]) / float(image.size[0]) if image.size[0] > max_size[0] else float(max_size[1]) / float(image.size[1])
        new_size = int(ratio * image.size[0]), int(ratio * image.size[1])
        log.info("--> resizing to %sx%s" % new_size)
        image = image.resize(new_size, Image.ANTIALIAS)     
        return image

    # new resize method, eholda 2011-02-12
    @classmethod
    def resizeToFit(cls, image, box):
        if (image.size[0] > box[0] or image.size[1] > box[1]):
            xratio = float(box[0]) / float(image.size[0])
            yratio = float(box[1]) / float(image.size[1])
        
            ratio = xratio if xratio < yratio else yratio
            
            #print "--> xratio = %s, yratio = %s, ratio = %s" % (xratio, yratio, ratio)
            
            newsize = [int(ratio * image.size[0]), int(ratio * image.size[1])]
        
            log.info("*** RESIZING from %s to %s" % ([image.size[0], image.size[1]], newsize))
            
            return image.resize(newsize, Image.ANTIALIAS)
        else:
            print "--> no resize"
            return image     

    @classmethod
{'fraction_non_alphanumeric': 0.12856943864047918, 'fraction_numerical': 0.01351163114639922, 'mean_word_length': 1.7948618139353834, 'pattern_counts': {'":': 2, '<': 5, '<?xml version=': 0, '>': 26, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2991593', 'n_tokens_mistral': 2276, 'n_tokens_neox': 2188, 'n_words': 524}