Example #1
0
 def post(self):
      img = Image(self.request.get('file'))
               
      img.vertical_flip()
      vertical = img.execute_transforms()
      
      self.render(image=vertical)
Example #2
0
 def process_image(self, image_data, width, height, quality):
     img = Image(image_data=image_data)
     try:
         img.resize(width=width)
         return img.execute_transforms(output_encoding=JPEG, quality=quality)
     except NotImageError:
         return image_data
Example #3
0
    def post(self):
        try:
            spoonNumber = int(self.request.get('spoonNumber'))
        except ValueError:
            context = {
                'error':
                self.request.get('spoonNumber') +
                " is not a valid SpoonNumber !"
            }
            self.render_response('error.html', **context)
            return

        spoon = Spoon.get_by_id(spoonNumber)

        #Creating spoonStep
        spoonStep = SpoonStep()
        spoonStep.comment = self.request.get('comment')
        spoonStep.place = self.request.get('place')
        spoonStep.currentOwner = self.request.get('currentOwner')
        if self.request.get('email'):
            spoonStep.email = self.request.get('email')
        spoonStep.spoon = spoon
        picture = self.request.get('img')
        if picture:
            resizedPicture = picture
            if Image(picture).width > 620 or Image(picture).height > 400:
                resizedPicture = images.resize(picture, 620, 400)
            spoonStep.image_blob = db.Blob(resizedPicture)
        spoonStep.put()

        # Add the task to the default queue.
        taskqueue.add(url='/sendMail', params={'spoonNumber': spoonNumber})

        self.redirect("/spoon/%s" % spoonNumber)
Example #4
0
 def post(self):
     img = Image(self.request.get('file'))
     json = self.request.get('json', False)
     height = int(self.request.get('height', default_value='1'))
     width = int(self.request.get('width', default_value='1'))
     img.resize(width, height)
     resized = img.execute_transforms()
     self.render(image=resized, data={'height':height, 'width':width})
Example #5
0
 def process_image(self, image_data, width, height, quality):
     img = Image(image_data = image_data)
     image_ops = crop_ops(img.width, img.height, width, height)
     if image_ops:
         for op, kwargs in image_ops:
             getattr(img, op)(**kwargs)
         return img.execute_transforms(output_encoding = JPEG, quality=quality)
     return image_data
Example #6
0
 def post(self):
      img = Image(self.request.get('file'))
      left_x = float(self.request.get('left_x', '90'))
      top_y = float(self.request.get('top_y', '90'))
      right_x = float(self.request.get('right_x', '90'))
      bottom_y = float(self.request.get('bottom_y', '90'))
      
      img.crop(left_x, top_y, right_x, bottom_y)
      cropped = img.execute_transforms()
      self.render(image=cropped)
	def post(self):
		key = int(self.request.get('key'))

		photo = Photo.get_by_id(key)
		raw_image = Image(blob_key=photo.photo_blob_key)
		raw_image.resize(128, 128)
		thumbnail = raw_image.execute_transforms()

		photo.thumbnail = thumbnail
		photo.thumbnailed = True

		photo.put()
Example #8
0
def make_reduced_image(data):
    img = Image(data)
    if not (img.width > settings.FEATURE_MAX_W and img.height > settings.FEATURE_MAX_H):
        return data
    w_pct = settings.FEATURE_MAX_W / float(img.width)
    h_pct = settings.FEATURE_MAX_H / float(img.height)
    if h_pct < w_pct:
        pct = h_pct
    else:
        pct = w_pct
    img.resize(int(pct * img.width), int(pct * img.height))
    return img.execute_transforms(JPEG)
Example #9
0
    def post(self):
        key = int(self.request.get('key'))

        photo = Photo.get_by_id(key)
        raw_image = Image(blob_key=photo.photo_blob_key)
        raw_image.resize(128, 128)
        thumbnail = raw_image.execute_transforms()

        photo.thumbnail = thumbnail
        photo.thumbnailed = True

        photo.put()
def create_meme(top, bottom, meme, template_uid):
    """Create a meme object in the datastore"""
    m = Image(meme)
    thumb = Image(meme)
    width, height = m.width, m.height
    
    if m.width != 500:
        m.resize(width=500)
        m = m.execute_transforms(output_encoding=JPEG)
        
        moar_img_data = Image(m)
        width, height = moar_img_data.width, moar_img_data.height

        meme = db.Blob(m)
    else:
        logging.info("There")
        meme = db.Blob(meme)

    thumb.resize(height=125)
    thumb = thumb.execute_transforms(quality=85,output_encoding=JPEG)
    thumb = db.Blob(thumb)

    meme = Meme(uid=str(get_meme_url()),
                top=top,
                bottom=bottom,
                meme=meme,
                meme_width=width,
                meme_height=height,
                thumb=thumb,
                template_uid=template_uid)
    meme.put()
    return meme
def create_template(name, img):
    """Adds this template to the datastore along with a generated
       thumbnail and accompanied dimension metadata"""
    
    thumb = Image(img)
    template_data = Image(img)
    t_img = db.Blob(img)
    width, height = template_data.width, template_data.height

    if width != 500:
        template_data.resize(width=500)
        template_data = template_data.execute_transforms()
        t_data = Image(template_data)
        width, height = t_data.width, t_data.height
        t_img = db.Blob(template_data)

    thumb.resize(height=125)
    thumb = thumb.execute_transforms(quality=75,output_encoding=JPEG)

    t = Template(uid=generate_uuid(16),
                 name=name,
                 img=t_img,
                 thumb=db.Blob(thumb),
                 real_width=width,
                 real_height=height)
    t.put()
Example #12
0
def fiximage(data):
    """Take an uploaded image, call I'm feeling lucky
  and put it back out to the user.
  """
    logging.info("Transforming image...")
    logging.info("In data size: %d" % (len(data), ))

    image_in = Image(str(data))
    image_in.im_feeling_lucky()

    image_out = ByteArray()
    image_out.write(image_in.execute_transforms())

    logging.info("Out data size: %d" % (len(image_out), ))
    return image_out
Example #13
0
    def store_picture_from_content(cls, blob_key):
        """ Resize picture and upload to Cloud Storage bucket. Return the GCS key """
        data = blobstore.BlobReader(blob_key).read()
        img = Image(data)
        img.resize(width=800, height=600)
        # img.im_feeling_lucky()
        img = img.execute_transforms(output_encoding=JPEG)

        new_gcs_key = cls.upload_blob_to_gcs(img, content_type='img/jpeg')

        # delete original blob
        delete_serving_url(blob_key)
        blobstore.delete(blob_key)

        return new_gcs_key
Example #14
0
    def store_picture_from_content(cls, blob_key):
        """ Resize picture and upload to Cloud Storage bucket. Return the GCS key """
        data = blobstore.BlobReader(blob_key).read()
        img = Image(data)
        img.resize(width=800, height=600)
        # img.im_feeling_lucky()
        img = img.execute_transforms(output_encoding=JPEG)

        new_gcs_key = cls.upload_blob_to_gcs(img, content_type='img/jpeg')

        # delete original blob
        delete_serving_url(blob_key)
        blobstore.delete(blob_key)

        return new_gcs_key
    def trans(image):
        changed_properties = []
        user_profile = get_user_profile(app_user)
        if name is not MISSING:
            if user_profile.name != name:
                changed_properties.append(u"name")
            user_profile.name = name

        # has_birthdate and has_gender are used starting from 1.0.999.A and 1.0.137.i
        if has_birthdate is not MISSING and has_gender is not MISSING:
            if has_birthdate is True:
                user_profile.birthdate = birthdate
                user_profile.birth_day = UserProfile.get_birth_day_int(birthdate)
            if has_gender is True:
                user_profile.gender = gender
        else:
            # birthdate and gender are only used without has_gender and has_birthdate in 1.0.998.A
            if birthdate is not MISSING and gender is not MISSING:
                if birthdate == 0 and gender == 0:
                    pass  # user pressed save in 1.0.998.A without setting gender and birthdate
                else:
                    user_profile.birthdate = birthdate
                    user_profile.birth_day = UserProfile.get_birth_day_int(birthdate)
                    if gender != 0:
                        user_profile.gender = gender

        if image:
            avatar = get_avatar_by_id(user_profile.avatarId)
            if not avatar:
                avatar = Avatar(user=user_profile.user)

            image = base64.b64decode(str(image))
            img = Image(image)
            if img.width > 150 or img.height > 150:
                logging.info('Resizing avatar from %sx%s to 150x150', img.width, img.height)
                img.resize(150, 150)
                image = img.execute_transforms(img.format, 100)

            update_avatar_profile(user_profile, avatar, image)
            changed_properties.append(u"avatar")
        user_profile.version += 1
        user_profile.put()

        from rogerthat.bizz.profile import update_mobiles, update_friends
        update_mobiles(user_profile.user, user_profile, current_mobile)  # update myIdentity
        schedule_re_index(app_user)
        if changed_properties:  # Not necessary when only birth date or gender were updated.
            update_friends(user_profile)  # notify my friends.
Example #16
0
    def post(self):
        #Creating spoon
        spoon = Spoon()
        spoon.comment = self.request.get('comment')
        spoon.initialOwner = self.request.get('initialOwner')
        picture = self.request.get('img')
        if picture:
            resizedPicture = picture
            if Image(picture).width > 620 or Image(picture).height > 400:
                resizedPicture = images.resize(picture, 620, 400)
            spoon.image_blob = db.Blob(resizedPicture)
        spoon.put()

        #Responding
        context = {'spoonNumber': spoon.spoonNumber()}
        self.render_response('newSpoonAdded.html', **context)
Example #17
0
 def get(self, key):
   try:
     photo = ndb.Key(urlsafe=key).get()
     if photo:
       self.response.headers['Content-Type'] = 'image/png'
       self.response.out.write(photo.get_thumb())
     else:
       default_thumb = memcache.get('DEFAULT-THUMB')
       if not default_thumb:
         default_thumb = Image()
         default_thumb.resize(65,55)
         self.response.headers['Content-Type'] = 'image/png'
         self.response.out.write(default_thumb)
         memcache.set('DEFAULT-THUMB', default_thumb)
   except Exception:
     logging_ext.error('ThumbHandler '+key, exc_info=True)
Example #18
0
def get_image_from_url(url):
    if not url:
        raise ndb.Return(None)

    # logger.info('Downloading image %s', url)
    ctx = ndb.get_context()

    url = unicode(url)
    if url and url.startswith('//'):
        url = 'http:' + url

    image = None

    try:
        resp = yield ctx.urlfetch(url, deadline=60)
        image = Image(image_data=resp.content)
        image.width  # Try
    except NotImageError:
        # logger.info('Image at url isnt an image: %s', url)
        pass
    except InvalidURLError:
        pass
    except Exception, e:
        logger.exception(e)
        raise ndb.Return(None)
Example #19
0
 def _to_base_type(self, value):
     """
     Transforming the image and saving it to blobstore
     """
     img = Image(self._img_data)
     if self._width > 0 or self._height > 0:
         img.resize(width=self._width, height=self._height)
     img.im_feeling_lucky()
     return img.execute_transforms(output_encoding=images.JPEG)
Example #20
0
    def _pre_transform(self, image_data):
        """Apply image pre-transformation.

        Attributes:
            image_data (str) -- Original image content.

        Return:
            (image width, image height, transformed image content,
            content type).

        """
        img = Image(image_data=image_data)
        return img.width, img.height, None, None
  def AddImage(self, image_data, width, height, img_type, instance = None):
    """ Handle adding an image of the application.

    Args:
      image_data: binary blob from an HTTP request.
      width: the image maximum width in pixels.
      height: the image maximum height in pixels.
      img_type: the type of the image (screenshot or thumbnail)
      instance: a previously stored image for this app, if one exists. """

    from google.appengine.api.images import Image

    imageContent = Image(image_data)
    imageContent.resize(width, height)

    if instance is None:
      image = ApplicationImage()
    else:
      image = instance
    image.application = self
    image.img_type = img_type
    image.content = imageContent.execute_transforms()
    image.put()
    def AddImage(self, image_data, width, height, img_type, instance=None):
        """ Handle adding an image of the application.

    Args:
      image_data: binary blob from an HTTP request.
      width: the image maximum width in pixels.
      height: the image maximum height in pixels.
      img_type: the type of the image (screenshot or thumbnail)
      instance: a previously stored image for this app, if one exists. """

        from google.appengine.api.images import Image

        imageContent = Image(image_data)
        imageContent.resize(width, height)

        if instance is None:
            image = ApplicationImage()
        else:
            image = instance
        image.application = self
        image.img_type = img_type
        image.content = imageContent.execute_transforms()
        image.put()
Example #23
0
 def _to_base_type(self, value):
     """
     Transforming the image and saving it to blobstore
     """
     img = Image(self._img_data)
     if self._width > 0 or self._height > 0:
         img.resize(width=self._width, height=self._height)
     img.im_feeling_lucky()
     return img.execute_transforms(output_encoding=images.JPEG)
Example #24
0
    def testImage(self):
        """Creates an image object from blob data."""

        from google.appengine.api.images import Image
        query = blobstore.BlobInfo.all()
        key = str(query.fetch(1).pop().key())
        img = Image(blob_key=key)
        img.resize(width=200)
        data = img.execute_transforms()
        thumbnail = Image(data)
        self.assertEqual(200, thumbnail.width)
Example #25
0
def make_image_thumbnail(data):
    img = Image(data)
    if img.width > img.height:
        size = img.height
    else:
        size = img.width
    left = ((img.width - float(size)) / img.width) / 2
    top = ((img.height - float(size)) / img.height) / 2

    #raise Exception('left %f top %f' % (left, top))
    img.crop(left, top, 1.0 - left, 1.0 - top)
    img.resize(settings.THUMBNAIL_SIZE, settings.THUMBNAIL_SIZE)
    return img.execute_transforms(JPEG)
def store_picture_from_content(content, mime_type='application/octet-stream'):
    img = Image(content)
    img.resize(width=800, height=800)
    img.im_feeling_lucky()
    img_type = PNG if 'png' in mime_type else JPEG
    img = img.execute_transforms(output_encoding=img_type)

    # create file
    file_name = files.blobstore.create(mime_type=mime_type)
    with files.open(file_name, 'a') as f:
        f.write(img)

    # Finalize the file
    files.finalize(file_name)

    # Get the file's blob key
    blob_key = files.blobstore.get_blob_key(file_name)
    return get_serving_url(blob_key), blob_key
Example #27
0
def image_resolver(node):
    fname = find_resource_path(str(node.getAttribute('file')), RESOURCE_DIRS)
    from google.appengine.api.images import Image
    from template2pdf.t2p.utils import as_pt
    img = Image(file(fname, 'rb').read())
    sx, sy = img.width, img.height
    args = {}
    for tag in ('width', 'height', 'x', 'y'):
        if node.hasAttribute(tag):
            args[tag] = as_pt(node.getAttribute(tag))
    if ('width' in args) and (not 'height' in args):
        args['height'] = sy * args['width'] / sx
    elif ('height' in args) and (not 'width' in args):
        args['width'] = sx * args['height'] / sy
    elif ('width' in args) and ('height' in args):
        if (float(args['width']) / args['height']) > (float(sx) > sy):
            args['width'] = sx * args['height'] / sy
        else:
            args['height'] = sy * args['width'] / sx
    return fname, args
Example #28
0
def blob_exif(blob_key):
    '''Extract EXIF data from the blob data.'''
    keys = (
        ('make', 'Make', '?'),
        ('model', 'Model', '?'),
        ('datetime', 'DateTimeDigitized', '1990:01:01 00:00:00'),
        ('iso', 'ISOSpeedRatings', 0),
        ('focal_length', 'FocalLength', 0),
        ('lens', 'Lens', '?'),
        ('exposure_time', 'ExposureTime', 1),
        ('exposure_time1', 'ExposureTime', 1.0),
        ('aperture', ['ApertureValue', 'MaxApertureValue'], 0.0),
        ('copyright', 'Copyright', '')
    )
    data = {}
    im = Image(blob_key=blob_key)
    im.rotate(0)
    im.execute_transforms(parse_source_metadata=True)
    exif = im.get_original_metadata()
    logging.info(exif)
    for key, key_exif, default in keys:
        if key == 'datetime':
            dt = exif.get(key_exif, default)
            data[key] = datetime.datetime.strptime(dt, '%Y:%m:%d %H:%M:%S')
        elif key == 'focal_length':
            data[key] = int(exif.get(key_exif, default))
        elif key == 'exposure_time':
            t = exif.get(key_exif, default)
            if t == 0:
                data[key] = t
            else:
                data[key] = int(round(1 / t))
        elif key == 'aperture':
            app, max_app = key_exif
            aperture = exif.get(app, None)
            aperture = exif.get(max_app, default) if not aperture else aperture
            data[key] = aperture
        else:
            data[key] = exif.get(key_exif, default)
    return data
Example #29
0
 def post(self):
      img = Image(self.request.get('file'))
      degrees = int(self.request.get('degrees', '90'))
      img.rotate(degrees)
      rotated = img.execute_transforms()
      self.render(image=rotated)
Example #30
0
    def get(self,
            flip_horizontal,
            width,
            flip_vertical,
            height,
            halign,
            valign,
            url):
        if not url:
            self._error(400, 'The url argument is mandatory!')
            return

        if not width and not height:
            self._error(400, 'Either width or height are mandatory!')

        url = join('http://', url)

        if not self._verify_allowed_domains():
            self._error(404, 'Your domain is not allowed!')
            return

        if not self._verify_allowed_sources(url):
            self._error(404, 'Your image source is not allowed!')
            return

        width = width and int(width) or 0
        height = height and int(height) or 0

        if width > MAX_WIDTH:
            width = MAX_WIDTH
        if height > MAX_HEIGHT:
            height = MAX_HEIGHT

        if not halign:
            halign = "center"
        if not valign:
            valign = "middle"

        key = "%d_%d_%s_%s_%s" % (
                width,
                height,
                halign,
                valign,
                url
        )

        extension = splitext(url)[-1]
        image_format = extension in ('.jpg', '.jpeg') and JPEG or PNG

        data = memcache.get(key)

        self.response.headers['Cache-Key'] = key
        if data is not None:
            results = data
            self.response.headers['Cache-Hit'] = 'True'
        else:
            query = "SELECT * FROM Picture WHERE url = :1 LIMIT 1"
            pictures = db.GqlQuery(query, url).fetch(1)
            
            try:
                if len(pictures) > 0: 
                    picture = pictures[0]
                    if picture.is_expired():
                        img = picture.fetch_image()
                        picture.put()
                    else:
                        img = Image(picture.picture)
                else:
                    picture = Picture()
                    picture.url = url
                    img = picture.fetch_image()
                    picture.put()
            except ImageNotFoundError:
                self._error(404, 'Your image source is not found!')
                return

            if float(width) / float(img.width) > float(height) / float(img.height):
                img.resize(width=width)
                image_width = width
                image_height = float(width) / float(img.width) * float(img.height)
            else:
                img.resize(height=height)
                image_width = float(height) / float(img.height) * float(img.width)
                image_height = height

            rect = BoundingRect(height=image_height, width=image_width)
            rect.set_size(height=height, width=width, halign=halign, valign=valign)

            if not width:
                width = rect.target_width
            if not height:
                height = rect.target_height

            img.crop(left_x=rect.left,
                     top_y=rect.top,
                     right_x=rect.right,
                     bottom_y=rect.bottom)

            if flip_horizontal:
                img.horizontal_flip()
            if flip_vertical:
                img.vertical_flip()

            results = img.execute_transforms(output_encoding=image_format, quality=QUALITY)

            memcache.set(key=key,
                     value=results,
                     time=EXPIRATION) # ONE MONTH


            self.response.headers['Cache-Hit'] = 'False'

        self.response.headers['Content-Type'] = image_format == JPEG and 'image/jpeg' or 'image/png'
        self.response.out.write(results)
Example #31
0
    def calculate_user_values(self, username):
        memcache_data_key = '!data!{}'.format(username)
        values = json.loads(memcache.get(memcache_data_key) or '{}')
        if values:
            return values

        try:
            github_user = User.get(username)
        except pyresto.Error:
            self.response.set_status(404)  # not 100% sure but good enough
            self.render('errors/404')
            return
        except Exception as err:
            self.response.set_status(500)
            logging.error(err)
            return

        languages = User.sort_languages(github_user.language_stats)
        fork_count = sum(1 for repo in github_user.repos if repo.fork)

        today = datetime.datetime.today()
        recent_than = today - datetime.timedelta(days=conf.RECENT_DAYS)
        own_commits = github_user.get_latest_commits(recent_than)

        commits_by_repo = reduce(self.reduce_commits_by_repo,
                                 own_commits, dict())
        if commits_by_repo:
            last_project = max(commits_by_repo, key=commits_by_repo.get)
        else:
            last_project = ''
        logging.info(commits_by_repo)
        if last_project:
            last_project_url = [repo.html_url for repo in github_user.repos
                                if repo.name == last_project][0]
        else:
            last_project_url = None

        commits_by_date = reduce(self.reduce_commits_by_date,
                                 own_commits, dict())
        range = daterange(recent_than, today)
        for d in range:
            key = unicode(d.date())
            if key not in commits_by_date:
                commits_by_date[key] = 0

        commit_data = [commits_by_date[d] for d in sorted(commits_by_date)]
        max_commits = max(commit_data)
        logging.debug('Commit data %s', str(commit_data))
        commit_sparkline = data_uri(sparklines.impulse(commit_data,
                                                       below_color='SlateGray',
                                                       width=3,
                                                       dmin=0,
                                                       dmax=max(commit_data)))

        try:  # try to embed the scaled-down user avatar
            avatar = Image(urllib2.urlopen(github_user.avatar_url).read())
            avatar.resize(24, 24)
            github_user.avatar_url = data_uri(avatar.execute_transforms())
        except (AttributeError, ValueError, urllib2.URLError):
            pass

        user_info = dict((k, v) for k, v in github_user.__dict__.iteritems()
                         if k[0] != '_')

        values = {'user': user_info,
                  'own_repos': len(github_user.repos) - fork_count,
                  'fork_repos': fork_count,
                  'languages': languages,
                  'project_followers': github_user.project_followers -
                  len(github_user.self_watched),
                  'commit_sparkline': commit_sparkline,
                  'max_commits': max_commits,
                  'last_project': last_project,
                  'last_project_url': last_project_url,
                  'days': conf.RECENT_DAYS
                  }

        if not memcache.set(memcache_data_key, json.dumps(values),
                            conf.MEMCACHE_EXPIRATION):
            logging.error('Memcache set failed for user data %s', username)

        return values
Example #32
0
    def calculate_user_values(self, username):
        memcache_data_key = '!data!{}'.format(username)
        values = json.loads(memcache.get(memcache_data_key) or '{}')
        if values:
            return values

        try:
            github_user = User.get(username)
        except pyresto.PyrestoException:
            self.response.set_status(404)  # not 100% sure but good enough
            self.render('errors/404')
            return
        except Exception as err:
            self.response.set_status(500)
            logging.error(err)
            return

        languages = User.sort_languages(github_user.language_stats)
        fork_count = sum(1 for repo in github_user.repos if repo.fork)

        today = datetime.datetime.today()
        days_to_go_back = self.app.config['RECENT_DAYS']

        recent_than = today - datetime.timedelta(days=days_to_go_back)
        own_commits = github_user.get_latest_commits(recent_than)

        commits_by_repo = reduce(self.reduce_commits_by_repo, own_commits,
                                 dict())
        if commits_by_repo:
            last_project_id = max(commits_by_repo, key=commits_by_repo.get)
        else:
            last_project_id = None
        logging.info(commits_by_repo)
        if last_project_id:
            last_project = [
                repo for repo in github_user.repos
                if repo.full_name == last_project_id
            ][0]

            last_project_name = last_project.name
            last_project_url = last_project.html_url
        else:
            last_project_name = ''
            last_project_url = ''

        commits_by_date = reduce(self.reduce_commits_by_date, own_commits,
                                 dict())
        range = daterange(recent_than, today)
        for d in range:
            key = unicode(d.date())
            if key not in commits_by_date:
                commits_by_date[key] = 0

        commit_data = [commits_by_date[d] for d in sorted(commits_by_date)]
        max_commits = max(commit_data)
        logging.debug('Commit data %s', str(commit_data))
        commit_sparkline = data_uri(
            sparklines.impulse(commit_data,
                               below_color='SlateGray',
                               width=3,
                               dmin=0,
                               dmax=max(commit_data)))

        try:  # try to embed the scaled-down user avatar
            avatar = Image(urllib2.urlopen(github_user.avatar_url).read())
            avatar.resize(24, 24)
            github_user.avatar_url = data_uri(avatar.execute_transforms())
        except (AttributeError, ValueError, urllib2.URLError):
            pass

        user_info = dict(
            (k, v) for k, v in github_user.__dict__.iteritems() if k[0] != '_')

        values = {
            'user':
            user_info,
            'own_repos':
            len(github_user.repos) - fork_count,
            'fork_repos':
            fork_count,
            'languages':
            languages,
            'project_followers':
            github_user.project_followers - len(github_user.self_watched),
            'commit_sparkline':
            commit_sparkline,
            'max_commits':
            max_commits,
            'last_project':
            last_project_name,
            'last_project_url':
            last_project_url,
            'days':
            conf.RECENT_DAYS
        }

        if not memcache.set(memcache_data_key, json.dumps(values),
                            self.app.config['MEMCACHE_EXPIRATION']):
            logging.error('Memcache set failed for user data %s', username)

        return values
Example #33
0
    def calculate_user_values(self, username):
        memcache_data_key = "!data!{}".format(username)
        values = json.loads(memcache.get(memcache_data_key) or "{}")
        if values:
            return values

        try:
            github_user = User.get(username)
        except pyresto.PyrestoException:
            self.response.set_status(404)  # not 100% sure but good enough
            self.render("errors/404")
            return
        except Exception as err:
            self.response.set_status(500)
            logging.error(err)
            return

        languages = User.sort_languages(github_user.language_stats)
        fork_count = sum(1 for repo in github_user.repos if repo.fork)

        today = datetime.datetime.today()
        days_to_go_back = self.app.config["RECENT_DAYS"]

        recent_than = today - datetime.timedelta(days=days_to_go_back)
        own_commits = github_user.get_latest_commits(recent_than)

        commits_by_repo = reduce(self.reduce_commits_by_repo, own_commits, dict())
        if commits_by_repo:
            last_project_id = max(commits_by_repo, key=commits_by_repo.get)
        else:
            last_project_id = None
        logging.info(commits_by_repo)
        if last_project_id:
            last_project = [repo for repo in github_user.repos if repo.full_name == last_project_id][0]

            last_project_name = last_project.name
            last_project_url = last_project.html_url
        else:
            last_project_name = ""
            last_project_url = ""

        commits_by_date = reduce(self.reduce_commits_by_date, own_commits, dict())
        range = daterange(recent_than, today)
        for d in range:
            key = unicode(d.date())
            if key not in commits_by_date:
                commits_by_date[key] = 0

        commit_data = [commits_by_date[d] for d in sorted(commits_by_date)]
        max_commits = max(commit_data)
        logging.debug("Commit data %s", str(commit_data))
        commit_sparkline = data_uri(
            sparklines.impulse(commit_data, below_color="SlateGray", width=3, dmin=0, dmax=max(commit_data))
        )

        try:  # try to embed the scaled-down user avatar
            avatar = Image(urllib2.urlopen(github_user.avatar_url).read())
            avatar.resize(24, 24)
            github_user.avatar_url = data_uri(avatar.execute_transforms())
        except (AttributeError, ValueError, urllib2.URLError):
            pass

        user_info = dict((k, v) for k, v in github_user.__dict__.iteritems() if k[0] != "_")

        values = {
            "user": user_info,
            "own_repos": len(github_user.repos) - fork_count,
            "fork_repos": fork_count,
            "languages": languages,
            "project_followers": github_user.project_followers - len(github_user.self_watched),
            "commit_sparkline": commit_sparkline,
            "max_commits": max_commits,
            "last_project": last_project_name,
            "last_project_url": last_project_url,
            "days": conf.RECENT_DAYS,
        }

        if not memcache.set(memcache_data_key, json.dumps(values), self.app.config["MEMCACHE_EXPIRATION"]):
            logging.error("Memcache set failed for user data %s", username)

        return values
Example #34
0
    def get(self, *groups):
        id = int(groups[0])
        level = int(groups[1])
        column = int(groups[2])
        row = int(groups[3])

        try:
            gigapan = get_gigapan(id)
        except:
            self.error(404)
            return

        self.width = gigapan.width
        self.height = gigapan.height
        self.tile_overlap = 0
        self.tile_size = 256
        self._num_levels = None

        tileserver = str(int(math.floor(id / 1000.0))).zfill(2)
        url = API_GIGAPAN_TILE_URL%{"tileserver": tileserver, "id": id}
        name = "r"
        z = max(0, level - 8)
        bit = (1 << z) >> 1
        x = column
        y = row

        while bit > 0:
            name += str((1 if (x & bit) else 0) + (2 if (y & bit) else 0))
            bit = bit >> 1

        i = 0
        while i < (len(name) - 3):
            url = url + "/" + name[i:i+3]
            i = i + 3

        tile_url = url + "/" + name + ".jpg"
        tile_request = fetch(tile_url)
        image_data = tile_request.content
        image = Image(image_data)
        w, h = self.get_dimensions(level)

        modified = False
        if level < 8:
            d = 2**level
            image.resize(d, d)
            image.crop(0.0, 0.0, min(w / float(d), 1.0), h / float(d))
            modified = True
        else:
            tile_x = column * self.tile_size
            tile_y = row * self.tile_size
            tile_right = tile_x + self.tile_size
            tile_bottom = tile_y + self.tile_size
            if tile_right > w or tile_bottom > h:
                factor = float(self.tile_size)
                tile_width = min(w - tile_x, self.tile_size)
                tile_height = min(h - tile_y, self.tile_size)
                image.crop(0.0, 0.0, tile_width / factor, tile_height / factor)
                modified = True

        if modified:
            image_data = image.execute_transforms(output_encoding=google.appengine.api.images.JPEG)

        self.response.headers["Content-Type"] = "image/jpeg"
        self.response.out.write(image_data)
Example #35
0
def upload():
    """
    Endpoint after GCS upload
    :return: JSON --> filelink, filename, thumb
    """
    if request.method == 'POST':
        request_file = request.files['file']

        # Creates the options for the file
        header = request_file.headers['Content-Type']
        parsed_header = parse_options_header(header)

        # IF everything is OK, save the file
        if request_file:
            try:
                blob_key = parsed_header[1]['blob-key']
                blob_info = blobstore.get(blob_key)
                blob_key_object = blob_info._BlobInfo__key
                img_url = '/admin/file_serve/' + blob_key
                img_gallery = img_url

                # Check if is image and save a reference
                if blob_info.content_type in IMAGES_MIME:
                    img = Image(image_data=blob_info.open().read())

                    if img.height > 1600 or img.width > 1600:
                        img_gallery = get_serving_url(blob_key_object,
                                                      size=1600)

                        # Landscape
                        if img.height < img.width:
                            img_height = (img.height * 1600) / img.width
                            img_width = 1600

                        # Portrait
                        else:
                            img_width = (img.width * 1600) / img.height
                            img_height = 1600
                    else:
                        img_height = img.height
                        img_width = img.width

                    img_ref = ImageReference(filename=blob_info.filename,
                                             blob=blob_key_object,
                                             url=img_url,
                                             thumb=get_serving_url(
                                                 blob_key_object,
                                                 crop=True,
                                                 size=200),
                                             gallery=img_gallery,
                                             height=img_height,
                                             width=img_width)
                    img_ref.put()

                return jsonify({
                    "filelink": "/admin/file_serve/" + blob_key,
                    "filegallery": img_gallery,
                    "filename": "" + blob_info.filename
                })
            except Exception as e:
                logging.exception(e)
                return jsonify({"error": e})
Example #36
0
    def get(self):
        url = "http://eatingstats.tumblr.com/tagged/beer/rss"

        d = feedparser.parse(url)
        
        articles = []
        lastbeer = None
        lastbeerPic = ""
        beers = []
        promile = 0
        
        self.response.out.write("<!--")
        for row in d.entries:		
            article = row['description'].encode('utf-8');
            pictureUrl = re.search("(?P<url>https?://[^\s\"]+)", article).group("url")
            result = urlfetch.fetch(pictureUrl)
            if result.status_code == 200:
                img = Image(image_data=result.content);
                img.rotate(0)
                img.execute_transforms(parse_source_metadata=True)
                meta = img.get_original_metadata()
                self.response.out.write(meta)
                if 'DateCreated' in meta:
                    #date like 2012:07:18 17:35:56
                    date = time.strptime(meta['DateCreated'], "%Y:%m:%d %H:%M:%S")
                else:
                    #fetching the tiem from the image metadata failed. so we take the published
                    #date from the rss feed
                    date = row.published_parsed
                    
                self.response.out.write(date)
                if lastbeer == None:
                    lastbeer = date
                    lastbeerPic = pictureUrl
                    promile += alcoholBeer / (0.7*weightPhil)
                else:
                    delta = abs(time.mktime(lastbeer) - time.mktime(date))
                    self.response.out.write("since the last beer: "+str(delta))
                    if delta > 12 * 60 * 60:
                        break;
                    promile += alcoholBeer / (0.7*weightPhil)
                    if delta > 2 * 60 * 60:
                        timeToReduceAlcohol = (delta - 2 * 60 * 60) #for two hours there will be no reduction of blood alcohol content
                        reducedAlcoholByHourInGram = 0.1 * weightPhil
                        reducedAlcoholSinceLastBeer = delta/3600 * reducedAlcoholByHourInGram * 0.08
                        if reducedAlcoholSinceLastBeer <  alcoholBeer / (0.7*weightPhil):
                            promile += alcoholBeer / (0.7*weightPhil) - reducedAlcoholSinceLastBeer
                    
                self.response.out.write("current promille: "+str(promile))
                beers.append(date)
            articles.append(pictureUrl)	
        
        self.response.out.write("-->")

        word = ""
        for k,v in sorted(promilToWords.items()):
            if k > promile * 10 :
                word = v
                break
        
        self.response.out.write("<center><h1>Phil "+word+"!</h1>")
        self.response.out.write("<p>"+time.strftime('At the %d, %b %Y',beers[0])+" with "+str(round(promile/10, 4))+" percent <a href=\"http://en.wikipedia.org/wiki/Blood_alcohol_content\">blood alcohol content.</a></p>")
        self.response.out.write("<br /><img src=\""+lastbeerPic+"\" alt=\"last beer of phil\" /></center>")
        self.response.out.write("<a href=\"https://github.com/leobuettiker/whenwasphildrunk\"><img style=\"position: absolute; top: 0; right: 0; border: 0;\" src=\"https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png\" alt=\"Fork me on GitHub\"></a>")
Example #37
0
def fetchAndProcessImage(imgurl):
    logging.info('Image URL: %s', imgurl)
    imgurl = imgurl.replace('dynamic', 'archive').replace('e.jpg', 'a.jpg')
    logging.info('Image URL enhanced: %s', imgurl)
    imgdata = urllib2.urlopen(imgurl).read()
    im = Image(imgdata)
    dimx = im.width
    dimy = im.height
    logging.info('Width: %s, Height: %s', dimx, dimy)

    im.vertical_flip()
    im.vertical_flip()
    temporary = im.execute_transforms(output_encoding=PNG, quality=100)
    test = png.Reader(file=StringIO.StringIO(temporary))
    img = list(test.asRGBA()[2])

    length = 15

    # Confirm the right and bottom boundaries
    rightmost = 0
    for x in range(0, dimx):
        clr = getpixel(img, x, 5)
        clr = quantizecolor(clr)
        if clr != 255:
            rightmost = x

    logging.info('Rightmost non-white pixel %s', rightmost)
    dimx = rightmost

    bottommost = 0
    for y in range(0, dimx):
        clr = getpixel(img, 5, y)
        clr = quantizecolor(clr)
        if clr != 255:
            bottommost = y

    logging.info('Bottommost non-white pixel %s', bottommost)
    dimy = bottommost

    logging.info('---------------')

    boxx = dimx*1.0 / length
    boxy = dimy*1.0 / length

    arr = {}
    across = {}
    down = {}
    startlist = {}
    for i in range(0, length):
        arr[i] = {}
        across[i] = {}
        down[i] = {}

    for i in range(0, length):
        for j in range(0, length):
            x = boxx * (i + 0.5) + 0.5
            y = boxy * (j + 0.5) + 0.5
            r = getpixel(img, x, y)
            clr = quantizecolor(r)
            if (clr == 255):
                arr[j][i] = 1
            else:
                arr[j][i] = 0

    matrix = []
    for i in range(0, length):
        matrix.append([])
        for j in range(0, length):
            down[i][j] = across[i][j] = 0
            if arr[i][j] == 1:
                down[i][j] = across[i][j] = 1
                matrix[i].append(1)
                if i > 0:
                    down[i][j] = down[i-1][j] + 1
                    if down[i][j] == 2:
                        if startlist.get((i-1, j)):
                            startlist[(i-1, j)] += 1
                        else:
                            startlist[(i-1, j)] = 1
                if j > 0:
                    across[i][j] = across[i][j-1] + 1
                    if across[i][j] == 2:
                        if startlist.get((i, j-1)):
                            startlist[(i, j-1)] += 2
                        else:
                            startlist[(i, j-1)] = 2
            else:
                matrix[i].append(0)

    starts = startlist.keys()
    starts.sort()
    startpos = []

    for startposn in starts:
        startpos.append([startposn[0], startposn[1], startlist[startposn]])

    return matrix, startpos
Example #38
0
def resize_image(image_data, width, height):
    image = Image(image_data=image_data)
    if (image.width / float(width)) > (image.height / float(height)):
        image.resize(height=height)
        image = Image(image_data=image.execute_transforms())
        x_crop_ratio = (image.width - width) / float(image.width * 2)
        image.crop(x_crop_ratio, 0.0, 1 - x_crop_ratio, 1.0)
    else:
        image.resize(width=width)
        image = Image(image_data=image.execute_transforms())
        y_crop_ratio = (image.height - height) / float(image.height * 2)
        image.crop(0.0, y_crop_ratio, 1.0, 1 - y_crop_ratio)
    return image.execute_transforms()
Example #39
0
 def post(self):
      img = Image(self.request.get('file'))
      
      img.im_feeling_lucky()
      lucky = img.execute_transforms()
      self.render(image=lucky)
Example #40
0
 def post(self):
      img = Image(self.request.get('file'))
      img.horizontal_flip()
      horizontal = img.execute_transforms()
      self.render(image=horizontal)
Example #41
0
def fetchAndProcessImage(imgurl):
    logging.info('Image URL: %s', imgurl)
    imgurl = imgurl.replace('dynamic', 'archive').replace('e.jpg', 'a.jpg')
    logging.info('Image URL enhanced: %s', imgurl)
    imgdata = urllib2.urlopen(imgurl).read()
    im = Image(imgdata)
    dimx = im.width
    dimy = im.height
    logging.info('Width: %s, Height: %s', dimx, dimy)

    im.vertical_flip()
    im.vertical_flip()
    temporary = im.execute_transforms(output_encoding=PNG, quality=100)
    test = png.Reader(file=StringIO.StringIO(temporary))
    img = list(test.asRGBA()[2])

    length = 15

    # Confirm the right and bottom boundaries
    rightmost = 0
    for x in range(0, dimx):
        clr = getpixel(img, x, 5)
        clr = quantizecolor(clr)
        if clr != 255:
            rightmost = x

    logging.info('Rightmost non-white pixel %s', rightmost)
    dimx = rightmost

    bottommost = 0
    for y in range(0, dimx):
        clr = getpixel(img, 5, y)
        clr = quantizecolor(clr)
        if clr != 255:
            bottommost = y

    logging.info('Bottommost non-white pixel %s', bottommost)
    dimy = bottommost

    logging.info('---------------')

    boxx = dimx * 1.0 / length
    boxy = dimy * 1.0 / length

    arr = {}
    across = {}
    down = {}
    startlist = {}
    for i in range(0, length):
        arr[i] = {}
        across[i] = {}
        down[i] = {}

    for i in range(0, length):
        for j in range(0, length):
            x = boxx * (i + 0.5) + 0.5
            y = boxy * (j + 0.5) + 0.5
            r = getpixel(img, x, y)
            clr = quantizecolor(r)
            if (clr == 255):
                arr[j][i] = 1
            else:
                arr[j][i] = 0

    matrix = []
    for i in range(0, length):
        matrix.append([])
        for j in range(0, length):
            down[i][j] = across[i][j] = 0
            if arr[i][j] == 1:
                down[i][j] = across[i][j] = 1
                matrix[i].append(1)
                if i > 0:
                    down[i][j] = down[i - 1][j] + 1
                    if down[i][j] == 2:
                        if startlist.get((i - 1, j)):
                            startlist[(i - 1, j)] += 1
                        else:
                            startlist[(i - 1, j)] = 1
                if j > 0:
                    across[i][j] = across[i][j - 1] + 1
                    if across[i][j] == 2:
                        if startlist.get((i, j - 1)):
                            startlist[(i, j - 1)] += 2
                        else:
                            startlist[(i, j - 1)] = 2
            else:
                matrix[i].append(0)

    starts = startlist.keys()
    starts.sort()
    startpos = []

    for startposn in starts:
        startpos.append([startposn[0], startposn[1], startlist[startposn]])

    return matrix, startpos