Пример #1
0
def screen_to_imgur(filename, link, select, sound, notify, quality, delay,
                    optipng):
    """Take a screenshot and upload to imgur"""
    # Default link argument
    if not link:
        link = 'original'
    # Take the screenshot
    screen = screenshot.grab(filename, select, sound, quality, delay, optipng)
    #    print 'Uploading image to imgur...'
    data = imgur.upload(screen)
    screen.close()
    # Get the links of the uploaded screenshot
    if link == 'html_clikeable_thumbail':
        thumb = data['upload']['links']['large_thumbnail']
        original = data['upload']['links']['original']
        url = '<a href="%s"><img src=%s/></a>' % (original, thumb)
    elif link == 'IM':
        original = data['upload']['links']['original']
        url = '[IMG]%s[/IMG]' % (original, thumb)
    else:
        url = data['upload']['links'][link]
    notify_im = data['upload']['links']['small_square']  #thumb image
    # Copy to the clipboard the url of the uploaded screenshot
    clipboard.copy(url)
    if notify:
        # Notify when done
        complete(notify_im, notify)
#    print link.upper() + ': ' + url
    print url
    return url
Пример #2
0
def meme(path):
    app.logger.info('New request for meme: "%s"', path)
    meme_name, top, bottom, ext = parse_meme_url(path)
    meme_image = guess_meme_image(meme_name)

    app.logger.info('Meme: "%s" / "%s" / "%s" . "%s"',
                    meme_image, top, bottom, ext)
    if ext == 'json':
        app.logger.info('Serving JSON')
        return json.dumps({'image': meme_image, 'top': top, 'bottom': bottom})
    elif ext in IMAGE_EXTENSIONS:
        image_path = meme_image_path(meme_image, top, bottom, ext)

        host = request.args.get('host', None)
        if host == 'imgur':
            try:
                imgur_url = imgur.upload(image_path)
                app.logger.info('Uploaded: "%s" as "%s"',
                                image_path, imgur_url)
                app.logger.info('Redirecting to: "%s"', imgur_url)
                return redirect(imgur_url, code=301)
            except imgur.ImgurException as e:
                return error_image_response('Error uploading "%s" to Imgur:', image_path, e.message)

        app.logger.info('Serving: "%s"', image_path)
        return send_file(image_path)
Пример #3
0
def createHorizontalDoubleBarGraph(name, x, y1, y2, x_axis, y_axis, title):

    fig, ax1 = plt.subplots()

    color = 'tab:red'
    y_pos = np.arange(len(x))
    ax1.set_ylabel('time (s)')
    ax1.set_xlabel('exp', color=color)
    ax1.barh(y_pos, y1, align='center', color=color)
    ax1.tick_params(axis='y', labelcolor=color)

    ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

    color = 'tab:blue'
    ax2.set_xlabel('sin',
                   color=color)  # we already handled the x-label with ax1
    ax2.barh(y_pos, y2, align='center', color=color)
    ax2.tick_params(axis='y', labelcolor=color)

    fig.tight_layout()  # otherwise the right y-label is slightly clipped
    plt.show()

    # plt.savefig(path + name + '.pdf')
    html = imgur.upload(plt, photoName)
    return html
Пример #4
0
def makeHistogram(name, data, x_axis, y_axis, title):
    # fig, ax = plt.subplots()

    plt.clf()
    plt.figure(figsize=(12, 9))
    ax = plt.subplot(111)
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()
    plt.xticks(fontsize=14)
    plt.yticks(fontsize=14)
    plt.xlabel(x_axis, fontsize=16)
    plt.ylabel(y_axis, fontsize=16)
    plt.title(title, fontsize=22)
    bins = 50

    arr = plt.hist(list(data), alpha=0.5, bins=50)
    ymin, ymax = ax.get_ylim()
    for i in range(bins):
        if arr[0][i] != 0:
            plt.text(arr[1][i],
                     arr[0][i] + ymax / 90,
                     str("{:,}".format(int(arr[0][i]))),
                     fontweight='bold')

    plt.text(0, -1 * ymax / 10, "Data source: www.twitter.com", fontsize=10)
    plt.tight_layout()
    box_inches = "tight"  #removes all the extra whitespace on the edges of your plot.
    # print(path + screen_name + "_" + name + '.pdf')

    # plt.savefig(name + '.pdf')
    html = imgur.upload(plt.gcf(), title)
    return html
Пример #5
0
def createImagePallete(colors):
    # fig, ax = plt.subplots()
    rows = int(len(colors) / 100) if len(colors) > 100 else 8
    pallete = sorted(colors, key=lambda rgb: step(rgb, rows))

    # rows = int(len(pallete)/100) if len(pallete) > 100 else 8
    pallete = pallete[:len(pallete) - len(pallete) % rows]

    palette = np.array(chunkIt(pallete, rows))
    # indices = np.random.randint(0, len(palette), size=(4, 6))
    # print(palette)
    plt.imshow(palette)

    ax = plt.subplot(111)
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.spines["bottom"].set_visible(False)
    ax.spines["left"].set_visible(False)
    plt.title("Color Pallete for " + screen_name, fontsize=18)
    ymin, ymax = ax.get_ylim()
    print(ymax)
    plt.text(0, -1 * ymax / 10, "Data source: www.twitter.com", fontsize=10)
    plt.axis('off')
    plt.tight_layout()
    # plt.colorbar()
    photoName = screen_name + "_pallete" + '.pdf'
    # plt.savefig(photoName)
    html = imgur.upload(plt.gcf(), photoName)
    return photoName
Пример #6
0
 def _thread_handler(self):
     blogs2update = set()
     while 1:
         try:
             image = self.Q.get(block=True, timeout=10)
             logger.debug("queue get " + str(image))
             try:
                 if image.status != "uploaded":
                     img_url, thumb_url = upload(image.img.read())
                     # use update specified fields to avoid concurrency issue
                     Image.objects.filter(idx=image.idx).update(
                         _img_url=img_url, _thumb_url=thumb_url, status="uploaded"
                     )
                 # make sure we got a newest copy
                 new_image = Image.objects.get(idx=image.idx)
                 if new_image.blog_id:
                     blogs2update.add(new_image.blog_id)
             except:
                 logger.exception("image[%s] upload fail" % image.idx)
         except Queue.Empty:
             for blog_id in blogs2update:
                 try:
                     blog = Blog.objects.get(pk=blog_id)
                     blog.save()
                     blog.image_set.filter(status="uploaded").update(status="updated")
                 except:
                     logger.exception("blog[%s] update fail" % blog_id)
             break
Пример #7
0
def create_user(username, password, profile_picture_binary, email):
#    profile_picture_url = ""
    profile_picture_url = imgur.upload(file_body=profile_picture_binary)
    s = Session()
    user = s.query(User).filter_by(username=username).first()
    if user is not None:
        raise Exception("Account already exists")
    else: 
        user = User(password=password, username=username, profile_picture=profile_picture_url, email=email)
        s.add(user)
        s.commit()
        s.flush()
Пример #8
0
def index(request):    
    if request.method == 'POST':        
        tmpName = sha_constructor(str(random.random())).hexdigest()
        tipo = request.POST['type']
        svg = request.POST['svg']
        filename = request.POST['filename']
        width = request.POST['width']

        if tipo == 'image/png':
            typeString = 'image/png'
            ext = '.png'
        elif tipo == 'image/jpeg':
            typeString = 'image/jpg'
            ext = '.jpg'
        elif tipo == 'application/pdf':
            typeString = 'application/pdf'
            ext = '.pdf'	    
        else:
            typeString = 'image/svg+xml'
            ext = '.svg'
    else:
        return HttpResponse('<h1>GTFO!!</h1>', mimetype='text/html')

    outfile = MEDIA_ROOT + tmpName + ext
    #return the url not the image
    try:    
        img_url = request.POST['img_url']
    except:
        img_url = None
            
    try:
        f = open('%s%s%s' % (MEDIA_ROOT,tmpName,'.svg'), 'w')
        svgObj = File(f)
        svgObj.write(svg.encode('utf-8'))
        svgObj.close()
        string = 'java -jar '+ str(BATIK_PATH) + ' -m ' + str(tipo) +' -d '+ str(outfile) +' -w '+ str(width) + ' ' + str(svgObj.name)        
        convert = commands.getoutput(string)
        salida = open(outfile)
        
        #only url not the image        
        if img_url:                             
            return HttpResponse(imgur.upload(salida)['upload']['links']['original'])
        
        response = HttpResponse(salida, mimetype=tipo)
        response['Content-Disposition'] = 'attachment; filename=grafico'+ext
        return response
    except Exception:
        return HttpResponse(str(Exception))
    def post(self):
        username = self.get_argument('username')
        game_id = self.get_argument('game_id')
        shot_picture = None
        target_username = self.get_argument('target_username')
        mission_id = self.get_argument('mission_id', None)
        session = Session()
        try:
            target_user = get_user(username=target_username)
            assassin_user = get_user(username=username)
            game = get_game(game_id)
            mission = get_mission(game_id=game_id, assassin_username=username, target_id=target_user.id)
            
            picture_binary = self.request.files['shot_picture'][0]['body']
            shot_picture_url = imgur.upload(file_body=picture_binary)

            player_shooting_target = Shot(assassin_id=assassin_user.id, \
                                        target_id=target_user.id, \
                                        game_id=game_id, \
                                        shot_picture=shot_picture_url)
            session.add(player_shooting_target)
            session.flush()
            session.commit()
            target_usergame = get_usergame(user_id=target_user.id, game_id=game_id)
            if player_shooting_target.is_valid():
                target_usergame.alive = None  # mark them as shot
                target_usergame.pending_shot = player_shooting_target.id
                session.add(target_usergame)
                session.flush()
                session.commit()
                response_dict = get_response_dict(True)
            else:
                if target_usergame.alive is None:
                    response_dict = get_response_dict(False, "Shot invalid.  Your target was previously shot, and the kill needs to be confirmed by him/her or the game master")
                else:
                    response_dict = get_response_dict(False, "Shot invalid.  If this was your target in this game, maybe they had a body double or you need to wait?")
        except Exception as e:
            session.rollback()
            response_dict = get_response_dict(False, e.message)
        finally:
            Session.remove()
            self.finish(simplejson.dumps(response_dict))
Пример #10
0
def meme(path):
    app.logger.info('New request for meme: "%s"', path)
    meme_name, top, bottom, ext = parse_meme_url(path)
    if is_custom_image(meme_name):
        meme_image = meme_name
    else:
        meme_image = guess_meme_image(meme_name)

    app.logger.info('Meme: "%s" / "%s" / "%s" . "%s"',
                    meme_image, top, bottom, ext)
    if ext == 'json':
        app.logger.info('Serving JSON')
        return json.dumps({'image': meme_image, 'top': top, 'bottom': bottom, 'custom': is_custom_image(meme_name)})
    elif ext in IMAGE_EXTENSIONS:
        image_path = meme_image_path(meme_image, top, bottom, ext)

        json_path = derive_meme_path(meme_name, top, bottom, 'json')
        with open(json_path, 'w') as f:  
            json.dump({
                "source": request.args.get('source'),
                "meme_image": meme_image,
                "meme_query": meme_name,
                "route": path,
                "top": top,
                "bottom": bottom,
                "ext": ext
            }, f, indent=2)

        host = request.args.get('host', None)
        if host == 'imgur':
            try:
                imgur_url = imgur.upload(image_path)
                app.logger.info('Uploaded: "%s" as "%s"',
                                image_path, imgur_url)
                app.logger.info('Redirecting to: "%s"', imgur_url)
                return redirect(imgur_url, code=301)
            except imgur.ImgurException as e:
                return error_image_response('Error uploading "%s" to Imgur:', image_path, e.message)

        app.logger.info('Serving: "%s"', image_path)
        return send_file(image_path)
Пример #11
0
def createHorizontalSingleBarGraph(name, x, y, x_axis, y_axis, title):
    # fig, ax = plt.subplots()

    plt.clf()
    y_pos = np.arange(len(x))
    ax = plt.subplot(111)
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    arr = plt.barh(y_pos, y, align='center', alpha=0.5)
    plt.yticks(y_pos, x, fontsize=14)
    plt.xticks(fontsize=14)
    plt.xlabel(x_axis, fontsize=16)
    plt.ylabel(y_axis, fontsize=16)
    plt.title(title, fontsize=22)
    for i, v in enumerate(y):
        ax.text(v, i, str("{:,}".format(v)), fontweight='bold')
    plt.text(0, -1.25, "Data source: www.twitter.com" "", fontsize=10)
    plt.tight_layout()

    # plt.savefig(path + screen_name + "_" + name + '.pdf')
    html = imgur.upload(plt.gcf(), title)
    return html
Пример #12
0
def meme(path):
    app.logger.info('New request for meme: "%s"', path)
    meme_name, top, bottom, ext = parse_meme_url(path)
    meme_image = guess_meme_image(meme_name)

    app.logger.info('Meme: "%s" / "%s" / "%s" . "%s"', meme_image, top, bottom, ext)
    if ext == 'json':
        app.logger.info('Serving JSON')
        return json.dumps({'image': meme_image, 'top': top, 'bottom': bottom})
    elif ext in IMAGE_EXTENSIONS:
        image_path = meme_image_path(meme_image, top, bottom, ext)

        host = request.args.get('host', None)
        if host == 'imgur':
            try:
                imgur_url = imgur.upload(image_path)
                app.logger.info('Uploaded: "%s" as "%s"', image_path, imgur_url)
                app.logger.info('Redirecting to: "%s"', imgur_url)
                return redirect(imgur_url, code=301)
            except imgur.ImgurException as e:
                return error_image_response('Error uploading "%s" to Imgur:', image_path, e.message)

        app.logger.info('Serving: "%s"', image_path)
        return send_file(image_path)
Пример #13
0
 def post(self):
     name = self.request.get("textline")
     img = self.request.get("datafile")
     self.response.out.write(imgur.upload(img, name))