Exemplo n.º 1
3
def upload(image_path):
    """ Takes a file path, and returns it's URL on Imgur """
    if CLIENT_ID == 'None':
        raise ImgurException('client_id not specified in env')
    if CLIENT_SECRET == 'None':
        raise ImgurException('client_secret not specified in env')
    try:
        client = ImgurClient(CLIENT_ID, CLIENT_SECRET)
        imgur_response = client.upload_from_path(image_path)
    except ImgurClientError as e:
        raise ImgurException(e.error_message)
    return imgur_response['link']
Exemplo n.º 2
0
def get_img(path):
    global pin
    client = ImgurClient(client_id, client_secret,'61c2a536adcd40eeedbd8e6fba18999f413bf5dc',
                         'aee3d76d7956080282f5d272f76ef12f19509a47')
##    if pin == None:
##        authorization_url = client.get_auth_url('pin')
##        print("Go to the following URL: {0}".format(authorization_url))
##        pin = input("Enter pin code: ")
##    else:
##        pass
##    credentials = client.authorize(pin, 'pin')
##    client.set_user_auth(credentials['access_token'], credentials['refresh_token'])
    # Example request
    album_id = '2hzdSFn'
    config = {
            'album': album_id,
            'name': 'test-name!',
            'title': 'test-title',
            'description': 'test-description'
            }
    print(client.get_album(album_id))
    client.upload_from_path(path,config=config,anon=False)
    images = client.get_album_images(album_id)
    url = images[len(images)-1].link
    return url
Exemplo n.º 3
0
class imgur:
    imgur_client_id = '48a4853a9c844df'
    imgur_client_secret = 'ebe25d36f196cff544aca408e8d7b02283290c50'
    refresh_token = "1750e9d83514f1b4f9c6260ba7974ade9c0ab58a"
    client = None

    def imgur_init(self):
        self.client = ImgurClient(self.imgur_client_id,
                                  self.imgur_client_secret)

        url = "https://api.imgur.com/oauth2/token"

        payload = {
            'refresh_token': self.refresh_token,
            'client_id': self.imgur_client_id,
            'client_secret': self.imgur_client_secret,
            'grant_type': 'refresh_token'
        }
        headers = {}
        files = []
        response = requests.request("POST",
                                    url,
                                    headers=headers,
                                    data=payload,
                                    files=files)
        a = json.loads(response.text)
        self.client.set_user_auth(a["access_token"], a["refresh_token"])

    def upload_fking_image(self):
        self.client.upload_from_path(r"pil_text_font2.png", anon=False)
Exemplo n.º 4
0
def get_img():
    client_id = 'b9ae77105014a61'
    client_secret = '720fc83b0d748eb6131f987949280e15bf3a6e66'
    client = ImgurClient(client_id, client_secret)
    authorization_url = client.get_auth_url('pin')
    print("Go to the following URL: {0}".format(authorization_url))
    if os.path.isfile('pin.txt'):
        with open('pin.txt', 'r') as f:
            pin = f.read()
    else:
        pin = input("Enter pin code: ")
        with open('pin.txt', 'w') as f:
            f.write(pin)
    credentials = client.authorize(pin, 'pin')
    client.set_user_auth(credentials['access_token'],
                         credentials['refresh_token'])
    # Example request
    album_id = 'ARm1Dtq'
    config = {
        'album': album_id,
        'name': 'test-name!',
        'title': 'test-title',
        'description': 'test-description'
    }
    print(client.get_album('ARm1Dtq'))
    client.upload_from_path('D:/python/linebot/linebot/in.jpg',
                            config=config,
                            anon=False)
    images = client.get_album_images(album_id)
    url = images[len(images) - 1].link
    return url
Exemplo n.º 5
0
def UploadPhoto(image, title, name, description):
    access_token, refresh_token, client_id, client_secret = Config.getImgurKeys(
    )
    client = ImgurClient(client_id, client_secret)
    client.set_user_auth(access_token, refresh_token)
    config = {'name': title, 'title': name, 'description': description}
    retVal = None
    tryCount = 0
    while tryCount < 4:
        try:
            retVal = client.upload_from_path(image, config=config, anon=False)
            break
        except:
            tryCount += 1
    if retVal == None:
        retVal = client.upload_from_path(image, config=config, anon=False)
    return retVal


#def main():
#    #x = CreateAlbum('Album 101','Album 101 desciption')
#    id = []
#    id.append( UploadPhoto('outputImages\\narendramodi_6.jpg')['id'])
#    id.append( UploadPhoto('outputImages\\narendramodi_5.jpg')['id'])
#    #id.append( UploadPhoto(['outputImages\\narendramodi_4.jpg'])['id'])
#    x = CreateAlbumAndUploadImages('album1-1-1','some description',id)
#    pass

#if __name__ == '__main__':
#    main()
Exemplo n.º 6
0
def handle_message(event):
    if isinstance(event.message, ImageMessage):
        uid = event.source.user_id  # user id
        profile = line_bot_api.get_profile(uid)
        ext = 'jpg'
        message_content = line_bot_api.get_message_content(event.message.id)
        with tempfile.NamedTemporaryFile(dir=static_tmp_path,
                                         prefix=ext + '-',
                                         delete=False) as tf:
            for chunk in message_content.iter_content():
                tf.write(chunk)
            tempfile_path = tf.name

        dist_path = tempfile_path + '.' + ext
        dist_name = os.path.basename(dist_path)
        os.rename(tempfile_path, dist_path)
        time_now = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        image_name = time_now + "_" + profile.display_name
        try:
            client = ImgurClient(client_id, client_secret, access_token,
                                 refresh_token)
            config = {
                'album': album_id,
                'name': image_name,
                'title': image_name,
                'description': '機器人備份圖片'
            }
            path = os.path.join('static', 'tmp', dist_name)
            client.upload_from_path(path, config=config, anon=False)
            os.remove(path)
            print(path)
        except:
            pass
        return 0
Exemplo n.º 7
0
def handle_image(event):
    print("hello")
    if isinstance(event.message, ImageMessage):
        ext = 'jpg'
        message_content = line_bot_api.get_message_content(event.message.id)
        with tempfile.NamedTemporaryFile(dir=static_tmp_path,
                                         prefix=ext + '-',
                                         delete=False) as tf:
            for chunk in message_content.iter_content():
                tf.write(chunk)
            tempfile_path = tf.name

        dist_path = tempfile_path + '.' + ext
        dist_name = os.path.basename(dist_path)
        os.rename(tempfile_path, dist_path)
        try:
            client = ImgurClient(client_id, client_secret, access_token,
                                 refresh_token)
            config = {
                'album': album_id,
                'name': 'Catastrophe!',
                'title': 'Catastrophe!',
                'description': 'Cute kitten being cute on '
            }
            path = os.path.join('static', 'tmp', dist_name)
            client.upload_from_path(path, config=config, anon=False)
            os.remove(path)
            print(path)
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text='上傳成功'))
        except:
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text='上傳失敗'))
        return 0

    elif isinstance(event.message, VideoMessage):
        ext = 'mp4'
    elif isinstance(event.message, AudioMessage):
        ext = 'm4a'
    elif isinstance(event.message, TextMessage):
        if event.message.text == "看看大家都傳了什麼圖片":
            client = ImgurClient(client_id, client_secret)
            images = client.get_album_images(album_id)
            index = random.randint(0, len(images) - 1)
            url = images[index].link
            image_message = ImageSendMessage(original_content_url=url,
                                             preview_image_url=url)
            line_bot_api.reply_message(event.reply_token, image_message)
            return 0
        else:
            line_bot_api.reply_message(
                event.reply_token,
                [TextSendMessage(text='輸入無效'), buttons_template])
            return 0

    ##elif :大盤指數
    ##elif :
    #純粹echo
    '''
Exemplo n.º 8
0
def imgurBot():
    client = ImgurClient(config.imgurId, config.imgurSecret)
    frequencyLink = (client.upload_from_path('wordFrequency.png',
                                             config=None,
                                             anon=True))['link']
    activityLink = (client.upload_from_path('mostActive.png',
                                            config=None,
                                            anon=True))['link']
    return frequencyLink, activityLink
Exemplo n.º 9
0
def handle_message(event):
    if isinstance(event.message, ImageMessage):
        ext = 'jpg'
        message_content = line_bot_api.get_message_content(event.message.id)
        with tempfile.NamedTemporaryFile(dir=static_tmp_path, prefix=ext + '-', delete=False) as tf:
            for chunk in message_content.iter_content():
                tf.write(chunk)
            tempfile_path = tf.name

        dist_path = tempfile_path + '.' + ext
        dist_name = os.path.basename(dist_path)

        os.rename(tempfile_path, dist_path)
        path = os.path.join('static', 'tmp', dist_name)
        print("接收到的圖片路徑:"+path)

        #將圖片上傳至google雲端硬碟
        

        #此處進入worker的工作排程,讓worker去雲端抓圖片

        q = Queue(connection=conn)
        from upload import post_image_to_url

        result = q.enqueue(post_image_to_url,path,timeout=3600)
        print("工人延遲運行的結果ID:"+result.id)

        
        try:
            client = ImgurClient(client_id, client_secret, access_token, refresh_token)
            config = {
                'album': 'UthLp77',
                'name': 'Catastrophe!',
                'title': 'Catastrophe!',
                'description': 'Cute kitten being cute on '
            }
            client.upload_from_path(path, config=config, anon=False)
            #os.remove(path)
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='上傳成功,請等待運算結果'))
            #job =  q.fetch_job(result.id)
            #print(job.result)
        except:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='上傳失敗'))
        return 0
Exemplo n.º 10
0
    def upload_file(self):
        timestamp = datetime.fromtimestamp(self.img.time).strftime(
            self.conf.imgur.timestamp_format or "%Y-%m-%dT%H:%M:%S"
        )
        config = dict(
            album=self.conf.imgur.album,
            name="{}_{}".format(timestamp, self.img.username).replace(":", "-"),
            title="{} (by {}; {})".format(self.img.caption or "No caption", self.img.username, timestamp),
        )

        try:
            client = ImgurClient(
                self.conf.imgur.client_id, self.conf.imgur.client_secret, refresh_token=self.conf.imgur.refresh_token
            )
            data = client.upload_from_path(self.img.local_path, config=config, anon=False)
        except ImgurClientError as e:
            msg = "Error uploading to imgur: {0.status_code} {0.error_message}".format(e)
            l.error(msg)
            self.reply(msg)
            raise

        l.info("uploaded image: {}", data)
        l.debug("X-RateLimit-ClientRemaining: {}", client.credits["ClientRemaining"])

        self.img = self.img._replace(url=data["link"])
        return True
Exemplo n.º 11
0
def PostView(request):
    user = CheckValidation(request)
    if user:
        if request.method == 'POST':
            form = PostForm(request.POST, request.FILES)
            if form.is_valid():
                image = form.cleaned_data.get('image')
                caption = form.cleaned_data.get('caption')

                # saving post in database

                post = PostModel(user=user, image=image, caption=caption)
                post.save()

                path = os.path.join(BASE_DIR, post.image.url)

                client = ImgurClient(
                    'c83158842a9256e',
                    'ba219c35073b2a80347afaf222e1ebc28dcc8e1a')
                post.image_url = client.upload_from_path(path,
                                                         anon=True)['link']

                #post.image_url = cloudinary.uploader.upload(path)
                post.save()
                return redirect('/')

        else:
            form = PostForm()
        return render(request, 'post.html', {'form': form})
    else:

        return redirect('/login/')
Exemplo n.º 12
0
def post_view(request):
    user = check_validation(request)

    if user:
        if request.method == 'POST':
            form = PostForm(request.POST, request.FILES)
            if form.is_valid():
                image = form.cleaned_data.get('image')
                caption = form.cleaned_data.get('caption')
                post = PostModel(user=user, image=image, caption=caption)
                post.save()

                path = str(BASE_DIR + post.image.url)

                client = ImgurClient(
                    '9c9bf0c17f4ac16',
                    'cd2f3f14d28677368f0c26ee558ff6841e6e098a')
                post.image_url = client.upload_from_path(path,
                                                         anon=True)['link']
                post.save()

                return redirect('/feed/')

        else:
            form = PostForm()
        return render(request, 'post.html', {'form': form})
    else:
        return redirect('/login/')
Exemplo n.º 13
0
def image_uploader(speech_text):

    if profile.data['imgur']['client_id'] == "xxxx" \
    or profile.data['imgur']['client_secret'] == "xxxx":
        msg = 'upload requires a client id and secret'
        print msg
        tts(msg)
        return;

    words_of_message = speech_text.split()
    words_of_message.remove('upload')
    cleaned_message = ' '.join(words_of_message)
    if len(cleaned_message) == 0:
        tts('upload requires a picture name')
        return;

    image_listing = img_list_gen()

    client = ImgurClient(profile.data['imgur']['client_id'],
                         profile.data['imgur']['client_secret'])

    for i in range(0, len(image_listing)):
        if cleaned_message in image_listing[i]:
            result = client.upload_from_path(image_listing[i], config=None, anon=True)

            conn = sqlite3.connect(profile.data['memory_db'])
            conn.execute("INSERT INTO image_uploads (filename, url, upload_date) VALUES (?, ?, ?)", (image_listing[i], result['link'], datetime.strftime(datetime.now(), '%d-%m-%Y')))
            conn.commit()
            conn.close()

            print result['link']
            tts('Your image has been uploaded')
Exemplo n.º 14
0
def img_upload(file_path, text, msg_id):
    """ uploads a file to imgur anonymously using the API keys
    stored as environment variables"""
    client = ImgurClient(client_id, client_secret)
    conf = {"description": text, "title": msg_id}
    res = client.upload_from_path(file_path, config=conf, anon=True)
    return res
def index():
    links = []

    if request.method == 'POST':
        imgur_client_id = os.environ['imgur_client_id']
        imgur_client_secret = os.environ['imgur_client_secret']
        imgur_client = ImgurClient(imgur_client_id, imgur_client_secret)

        file_list = request.files.getlist('file')

        if not file_list:
            return jsonify({'ok': False})

        file = file_list[0]
        filename = file.filename

        # If it's an accepted file
        if any(filename.lower().endswith(x) for x in ACCEPTED_EXTENSIONS):
            # Generate the path and save the file
            path = os.path.join(uploads_folder, secure_filename(filename))
            file.save(path)

            # Upload the file to imgur
            res = imgur_client.upload_from_path(path)

            # Delete the local file
            os.remove(path)

            # Return the IMGUR link
            return jsonify({'ok': True, 'link': res['link']})
        else:
            return jsonify({'ok': False})

    return render_template('index.html', links=links)
Exemplo n.º 16
0
def showImgur(fileName):
    # 連接imgur
    client = ImgurClient(client_id, client_secret, access_token, refresh_token)

    # 連接需要的參數
    config = {
        'album': album_id,  # 相簿名稱
        'name': fileName,  # 圖片名稱
        'title': fileName,  # 圖片標題
        'description': str(datetime.date.today())  # 備註,這邊打日期時間
    }

    # 開始上傳檔案
    try:
        print("[log:INFO]Uploading image... ")
        imgurl = client.upload_from_path(fileName + '.png',
                                         config=config,
                                         anon=False)['link']
        #string to dict
        print("[log:INFO]Done upload. ")
    except:
        # 如果失敗回傳"失敗"這張圖
        imgurl = 'https://i.imgur.com/RFmkvQX.jpg'
        print("[log:ERROR]Unable upload ! ")

    return imgurl
Exemplo n.º 17
0
def imgur_upload(photo_path):
    client = ImgurClient(imgur_client_id, imgur_client_secret)

    result = client.upload_from_path(photo_path, config=None, anon=True)
    logging.info('File uploaded to imgur '.format(result['link']))

    return result['link']
Exemplo n.º 18
0
def pitstop(tripid, userid):
    if request.method == 'GET':
        tripdetails=[]
        for x in TripDetails.query.filter_by(tripsmaster=request.args.get('tripid')):
            tripdetails.append(dict(location=x.location, text=x.text, image=x.image))
        return json.dumps(tripdetails)
    else:
        file = request.files['image']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        client = ImgurClient(client_id, client_secret)
        response = client.upload_from_path('/home/chakshu/WanderLust/Uploads/'+filename)
        tpid = TripsMaster.query.get(request.args.get('tripid'))
        tripdetails = TripDetails(tripsmaster = tpid,location=request.args.get('location'),
                                  timestamp=request.args.get('timestamp'),
                                  text=request.args.get('text'),
                                  image = str(response['link']))
        db.session.add(tripdetails)
       	# login_user(user)
       	# return redirect(url_for('index'))
        db.session.commit()
        tripdetails=[]
        for x in TripDetails.query.filter_by(tripsmaster=request.args.get('tripid')):
            tripdetails.append(dict(location=x.location, text=x.text, image=x.image))
        return json.dumps(tripdetails)
Exemplo n.º 19
0
def feed_back(request):
    dict = {}
    user = check_auth(request)
    if user == None:
        return redirect("/login/")
    else :
        if request.method == "GET":
            form = Postform()
            return render(request,"post.html",{'form':form})
        elif request.method == "POST":
            form = Postform(request.POST,request.FILES)
            if form :
                if form.is_valid():
                        image = form.cleaned_data.get('image')
                        caption = form.cleaned_data.get('caption')
                        post = Post_Model(user=user, image=image, caption=caption)
                        post.save()
                        image = post.image.url
                        path = str(BASE_DIR +"\\"+ image)
                        client = ImgurClient("9833d69a08cef7e", "f1603dd86bfe25b3f73427309b0561a92ff54262")
                        post.image_url = client.upload_from_path(path, anon=True)['link']
                        post.save()
                        print(post.image_url)
                        return redirect("/home/")
                else:
                        dict['no_post'] = "Please choose a file , Caption is Mandatory...."
                        return render(request,"post.html",dict)
Exemplo n.º 20
0
def post_view(request):
    user = check_validation(request)

    if user:
        if request.method == 'POST':
            form = PostForm(request.POST, request.FILES)
            if form.is_valid():
                image = form.cleaned_data.get('image')
                caption = form.cleaned_data.get('caption')
                post = PostModel(user=user, image=image, caption=caption)
                post.save()

                path = str(BASE_DIR + '/' +post.image.url)

                client = ImgurClient(YOUR_CLIENT_ID, YOUR_CLIENT_SECRET)
                post.image_url = client.upload_from_path(path, anon=True)['link']
                post.save()

                return redirect('/feed/')

        else:
            form = PostForm()
        return render(request, 'post.html', {'form': form})
    else:
        return redirect('/login/')
def upload_image():
    from imgurpython import ImgurClient

    client = ImgurClient(CLIENT_ID, CLIENT_SECRET)
    # response = client.upload_from_path(path)
    response = client.upload_from_path("nueva_image.jpg")
    return response["link"]
Exemplo n.º 22
0
def post_view(request):
    user = check_user(request)
    if user == None:
        return redirect('/login/')
    elif request.method == 'GET':
        post_form = PostForm()
        return render(request, 'post.html', {'post_form': post_form})
    elif request.method == "POST":
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            image = form.cleaned_data.get('image')
            caption = form.cleaned_data.get('caption')
            post = PostModel(user=user, image=image, caption=caption)
            post.save()
            client = ImgurClient('f9dc99672fce970','adac0c019ab6a9a2114e85c9c2e7829eb38a8b5d')
            path = str(BASE_DIR + "\\" +  post.image.url)
            post.image_url = client.upload_from_path(path,anon=True)['link']
            post.save()
            # app = ClarifaiApp()
            # app.tag_urls(urls=['https://samples.clarifai.com/wedding.jpg'], model='food-items-v1.0')

            return redirect("/feed/")
        else:
            return HttpResponse("Form data is not valid.")
    else:
        return HttpResponse("Invalid request.")
Exemplo n.º 23
0
    def on_enter_strategy_date(self, event):
        text = event.message.text
        split_date = text.split('~')
        start = check_date_format(split_date[0])[1]
        end = check_date_format(split_date[1])[1]
        s = start[4]
        start = datetime.strptime(start, f'%Y{s}%m{s}%d')
        end = datetime.strptime(end, f'%Y{s}%m{s}%d')
        num = user_strategy_num[event.source.user_id]
        df = pd.read_pickle(f'./strategy/strategy_{num}.pkl')
        df = df[(df.Date >= start) & (df.Date <= end)]
        df['ROI'] -= df['ROI'][0]
        if df.empty:
            content = '查無資料請重新輸入'
            send_message(event, TextSendMessage(text=content))
            self.go_back_future(event)
        else:
            # plot
            plot_roi(df, True, fig_path)
            # -- upload
            # imgur with account: [email protected]

            client = ImgurClient(CLIENT_ID, CLIENT_SECRET)
            print("Uploading image... ")
            image = client.upload_from_path(fig_path, anon=True)
            print("Done")

            url = image['link']
            image_message = ImageSendMessage(original_content_url=url,
                                             preview_image_url=url)
            send_message(event, image_message)
            print('查詢結束回到初始狀態')
            self.go_init(event)
Exemplo n.º 24
0
def uploadToImgur(userid,url):
	db = app.connect_db()
	c = db.cursor()
	c.execute('SELECT map_url,name,farmname,date,imgur_json FROM playerinfo WHERE url='+app.app.sqlesc,(url,))
	result = c.fetchone()
	if result[4] != None:
		previous_upload_properties = json.loads(result[4])
		if time.time() < previous_upload_properties['upload_time']+(2*3600):
			return {'error':'too_soon','link':previous_upload_properties['imgur_url']}
	map_url = result[0]
	titlestring = u"{} Farm, {} by {}".format(result[2],result[3],result[1])
	descriptionstring = u"Stardew Valley game progress, full summary at http://upload.farm/{}".format(url)
	# try:
	c.execute('SELECT imgur_json FROM users WHERE id='+app.app.sqlesc,(userid,))
	r = json.loads(c.fetchone()[0])
	access_token = r['access_token']
	refresh_token = r['refresh_token']
	client = ImgurClient(app.app.config['IMGUR_CLIENTID'],app.app.config['IMGUR_SECRET'])
	client.set_user_auth(access_token,refresh_token)
	# file = url_for('home',filename=map_url,_external=True)
	# print 'uploaded to',file
	# client.upload_from_url(file,config={'title':'uploaded from','description':'upload.farm'},anon=False)
	if app.app.config['IMGUR_DIRECT_UPLOAD'] == True:
		result = client.upload_from_path(map_url,config={'title':titlestring,'description':descriptionstring},anon=False)
	else:
		map_url = u"http://upload.farm/{}".format(map_url)
		result = client.upload_from_url(map_url,config={'title':titlestring,'description':descriptionstring},anon=False)
	print(result)
	imgur_json = json.dumps({'imgur_url':'http://imgur.com/'+result['id'],'upload_time':time.time()})
	c.execute('UPDATE playerinfo SET imgur_json='+app.app.sqlesc+' WHERE url='+app.app.sqlesc,(imgur_json,url))
	db.commit()
	try:
		return {'success':None,'link':result['link']}
	except:
		return {'error':'upload_issue','link':None}
Exemplo n.º 25
0
def post_view(request):
    user = check_validation(request)
    form = PostForm()
    if user:
        if request.method == 'GET':
            form = PostForm()
            return render(request, 'post.html', {'form': form})
        elif request.method == 'POST':
            form = PostForm(request.POST, request.FILES)
            if form.is_valid():
                image = form.cleaned_data.get('image')
                caption = form.cleaned_data.get('caption')
                userpost = PostModel(user=user, image=image, caption=caption)
                userpost.save()
                print userpost.image.url
                path = os.path.join(BASE_DIR, userpost.image.url)
                print BASE_DIR
                print path
                client = ImgurClient(
                    '4e7e0f86b1ec9cd',
                    '826ae58b2d75e41570e839f954b5ff3de73c4514')
                userpost.image_url = client.upload_from_path(path,
                                                             anon=True)['link']
                userpost.save()
                return redirect('/feed/')
            else:
                form = PostForm()
                return render(request, 'post.html', {'form': form})
    else:
        return redirect('/login/')
Exemplo n.º 26
0
def post_view(request):
    user = check_validation(request)

    if user:
        if request.method == 'POST':
            form = PostForm(request.POST, request.FILES)
            if form.is_valid():
                image = form.cleaned_data.get('image')
                #caption = form.cleaned_data.get('caption')
                post = PostModel(user=user, image=image)
                post.save()

                path = str(BASE_DIR + post.image.url)

                client = ImgurClient(YOUR_CLIENT_ID, YOUR_CLIENT_SECRET)
                post.image_url = client.upload_from_path(path,
                                                         anon=True)['link']
                post.save()
                ctypes.windll.user32.MessageBoxW(
                    0, u"post successsfully created", u"SUCCESS", 0)
                return redirect('/feed/')

        else:
            form = PostForm()
        return render(request, 'post.html', {'form': form})
    else:
        return redirect('/login/')
Exemplo n.º 27
0
 def post_view(request):
     user = check_validation(request)
     if user == None:
         return redirect('/login/')
     elif request.method == 'GET':
         post_form = PostForm()
         return render(request, 'post.html', {'post_form': post_form})
     elif request.method == "POST":
         form = PostForm(request.POST, request.FILES)
         if form.is_valid():
             image = form.cleaned_data.get('image')
             caption = form.cleaned_data.get('caption')
             post = PostModel(user=user, image=image, caption=caption)
             post.save()
             client = ImgurClient(
                 '13aab932636aa80',
                 '5d78c0178cb9258255982d328f803d536413f567')
             path = str(BASE_DIR + "\\" + post.image.url)
             post.image_url = client.upload_from_path(path,
                                                      anon=True)['link']
             post.save()
             return redirect("/feed/")
         else:
             return HttpResponse("Form data is not valid.")
     else:
         return HttpResponse("Invalid request.")
Exemplo n.º 28
0
class ScreenshotWeb():
    def __init__(self, pdfcrowdData, imgurData):
        self.API = pdfcrowd.HtmlToImageClient(pdfcrowdData[0], pdfcrowdData[1])
        self.API.setOutputFormat('png')
        self.API.setScreenshotWidth(1366)
        self.imgur = ImgurClient(imgurData[0], imgurData[1], imgurData[2],
                                 imgurData[3])
        self.workdir = os.getcwd()

    def uploader(self, path):
        try:
            data = self.imgur.upload_from_path(path, config=None, anon=False)
            os.remove(path)
            return data['link']
        except Exception as e:
            raise e

    def screenshotWeb(self, query):
        try:
            path = "".join(
                choice(string.ascii_letters + string.digits)
                for x in range(10)) + '.jpg'
            if 'http://' not in query and 'https://' not in query:
                query = 'http://' + query
            self.API.convertUrlToFile(query, path)
            return self.uploader(path)
        except Exception as e:
            raise e
Exemplo n.º 29
0
def post_view(request):
    user = check_validation(request)

    if user:
        if request.method == 'POST':
            form = PostForm(request.POST, request.FILES)
            if form.is_valid():
                image = form.cleaned_data.get('image')
                caption = form.cleaned_data.get('caption')
                post = PostModel(user=user, image=image, caption=caption)
                post.save()

                path = str(BASE_DIR + '//' + post.image.url)

                client = ImgurClient(
                    '4bede6ccfad6060',
                    'c598dc22ffa6f6521d905311f2fab28b89098885')

                post.image_url = client.upload_from_path(path,
                                                         anon=True)['link']
                post.save()
                app = ClarifaiApp(api_key="c106317b6810482599634b443a8e01d8")
                model = app.models.get('general-v1.3')
                response = model.predict_by_url(url=post.image_url)
                print response

                return redirect('/feed/')

        else:
            form = PostForm()
        return render(request, 'post.html', {'form': form})
    else:
        return redirect('/login/')
Exemplo n.º 30
0
    def __bug_report(self, imgpath):
        if self.reporting:
            self.log("Can not reporting for now.")
            return
        self.reporting = True

        try:
            self.log(">> Reporting started")
            client = ImgurClient(self.CLIENT_ID, None)
            config = {'album': "lP33mCsHgZrsO8K", 'title': self.__version__}
            image = client.upload_from_path(imgpath, config=config)
            deletehash = image['deletehash']
            url = 'https://api.imgur.com/3/image/' + deletehash
            headers = {'Authorization': 'Client-ID ' + self.CLIENT_ID}
            requests.post(url,
                          headers=headers,
                          data={'description': deletehash})
            self.log(image['link'])
            self.log("<< Reporting completed")
            self.suggestion_text = None
        except:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            lines = traceback.format_exception(exc_type, exc_value,
                                               exc_traceback)
            for l in lines:
                self.log(l)
            self.log("<< Reporting Failed")
        finally:
            self.reporting = False
Exemplo n.º 31
0
def post_view(request):
    user = check_validation(request)

    if user:
        if request.method == 'POST':
            form = PostForm(request.POST, request.FILES)
            if form.is_valid():
                image = form.cleaned_data.get('image')
                caption = form.cleaned_data.get('caption')
                new_post = PostModel(user=user, image=image, caption=caption)
                new_post.save()

                #path = str(BASE_DIR + new_post.image.url)
                path = os.path.join(BASE_DIR, new_post.image.url)
                client = ImgurClient(IMGUR_CLIENT_ID,IMGUR_CLIENT_SECRET)
                new_post.image_url = client.upload_from_path(path,anon=True)['link']
                
                new_post.save()

                return redirect('/feed')
                #return HttpResponse('Image Saved')
        else:
            form = PostForm()
        return render(request, 'post.html', {'form' : form})
    else:
        return redirect('/login/')
Exemplo n.º 32
0
def post_view(request):
    user = check_validation(request)
    if user:
        if request.method == 'GET':
            form = PostForm()
            return render(request, 'post.html', {'form': form})
        elif request.method == 'POST':
            form = PostForm(request.POST, request.FILES)
            if form.is_valid():
                image = form.cleaned_data.get('image')
                caption = form.cleaned_data.get('caption')
                post = PostModel(user=user, image=image, caption=caption)
                post.save()
                path = str(BASE_DIR + "\\" + post.image.url)
                client_id = 'f898fe4db2daebf'
                client_secret = '680cff299e71871090fa211b35dcb23ac0d2b008'
                client = ImgurClient(client_id, client_secret)
                post.image_url = client.upload_from_path(path,
                                                         anon=True)['link']
                post.save()
                return redirect('/feed/')
        else:
            form = PostForm()
            return render(request, 'post.html', {'form': form})
    else:
        return redirect('/login/')
Exemplo n.º 33
0
def upload_image(imgur_client_id,
                 imgur_client_secret,
                 app_name,
                 image_url=None,
                 image_file_path=None):
    """Uploads an image to Imgur by the image's url or file_path. Returns the
    Imgur api response."""
    if image_url is None and image_file_path is None:
        raise ValueError('Either image_url or image_file_path must be '
                         'supplied.')
    client = ImgurClient(imgur_client_id, imgur_client_secret)
    title = '{} Image Upload'.format(current_app.config['APP_NAME'])

    description = 'This is part of an idling vehicle report on {}.'.format(
        current_app.config['APP_NAME'])

    if image_url is not None:
        result = client.upload_from_url(url=image_url,
                                        config={
                                            'title': title,
                                            'description': description,
                                        })
    else:
        result = client.upload_from_path(path=image_file_path,
                                         config={
                                             'title': title,
                                             'description': description,
                                         })
        os.remove(image_file_path)

    return result['link'], result['deletehash']
Exemplo n.º 34
0
    def uploadGraffiti(self, filename):
        print 'hello upload'
        client = ImgurClient(self.clientId, self.clientSecret)

        uploadReturn = client.upload_from_path(self.fileUploadPath+filename, config=None, anon=True)
        print uploadReturn
        graffitiUploadLink = uploadReturn.get('link')
        return graffitiUploadLink
Exemplo n.º 35
0
class Imgur():

    def __init__(self, _id, _secret):
    	self._id = _id
    	self._secret = _secret
    	self.client = ImgurClient(self._id, self._secret)

    def Image_Upload(self, path):
    	return self.client.upload_from_path(path)
Exemplo n.º 36
0
def upload(path):
    CL_ID  = '4b627183be928c7'
    CL_SEC = '606e73952395dd3d06f309c4ace529e5b1386525'

    client = ImgurClient(CL_ID,CL_SEC)
    print "Uploading image"
    image = client.upload_from_path("foo.png")

    return image['link']
Exemplo n.º 37
0
class ImgurClient:
    def __init__(self, client_id, client_secret):
        self.client_id = client_id
        self.client_secret = client_secret
        self.client = IC(client_id, client_secret)

    # Returns a url to the file
    def upload_file(self, file_name):
        image = self.client.upload_from_path(file_name)
        return image['link']
Exemplo n.º 38
0
def upload_images(album_title, paths):
    client = ImgurClient(client_id, client_secret)
    client.set_user_auth(imgur_access_token, imgur_refresh_token)
    fields = {"title": album_title}
    album = client.create_album(fields)

    for i, img in enumerate(paths):
        config = {"album": album["id"], "name": str(i), "title": str(i)}
        image = client.upload_from_path(img, config=config, anon=False)
        remove(img)

    return album
Exemplo n.º 39
0
def link_for_original(original_photo):
    credentials = Credentials.for_imgur()
    data = credentials.data
    client = ImgurClient(
        data['client_id'], data['client_secret'],
        data['access_token'], data['refresh_token'],
    )
    with tempfile.NamedTemporaryFile() as f:
        original_photo.save(f, format='PNG')
        response = client.upload_from_path(f.name)

    return response['link']
Exemplo n.º 40
0
def imgur_upload(image, name):
    client = ImgurClient(imgur_client_id, imgur_client_secret)
    authorization_url = client.get_auth_url('pin')
    client.set_user_auth(imgur_access_token, imgur_refresh_token)
    config = {
            'album': 'IbzLr',
            'name':  name,
            'title': name,
            'description': name
            }
    image = client.upload_from_path(image, config=config, anon=False)
    return image['link']
Exemplo n.º 41
0
def upload_images(image1, image2):
    import subprocess

    diff_output = None
    with tempfile.NamedTemporaryFile(delete=False) as f:
        diff_output = f.name + '.pdf'

    # Create nice diff of image1 and image2
    subprocess.call(['compare', '-define', 'pdf:use-cropbox=true', image1, image2, diff_output])

    # Convert images to png
    image1 = to_png(image1)
    image2 = to_png(image2)
    diff_output = to_png(diff_output)

    # Upload to imgur
    from imgurpython import ImgurClient

    client_id = 'e32a7007635bb1f'
    client = ImgurClient(client_id, None)

    uploaded_image1 = client.upload_from_path(image1)
    uploaded_image2 = client.upload_from_path(image2)
    uploaded_diff = client.upload_from_path(diff_output)

    print "\nImages uploaded:"
    print " - Reference image: %s" % uploaded_image2['link']
    print " - Generated image: %s" % uploaded_image1['link']
    print " - Difference: %s" % uploaded_diff['link']

    print "\n-----"
    print "To delete image, execute these commands:"

    curl_command = 'curl -X DELETE -H "Authorization: Client-ID %s" https://api.imgur.com/3/image/%%s' % (client_id)

    print curl_command % uploaded_image1['deletehash']
    print curl_command % uploaded_image2['deletehash']
    print curl_command % uploaded_diff['deletehash']
    print "-----"
    print ""
Exemplo n.º 42
0
def imgur(image):

    client_id = 'c7702a9afb2bbf3'
    client_secret = '849693bb846b852c8808432540ef56a45883f776'
    imgur_uploader = ImgurClient(client_id, client_secret)
    # image_recovered = base64.b64decode(image)
    # f = open("temp.jpeg", "w")
    # f.write(image_recovered)
    # f.close()

    image_upload = imgur_uploader.upload_from_path(f, config=None, anon=True)

    return json.jsonify(link = image_upload)
Exemplo n.º 43
0
class Imgur():

    def __init__(self):
        self.imgur_client = ImgurClient(IMGUR_ID, IMGUR_SECRET)
        
    def save_from_url(self, image_url):
        logging.debug("trying to save %s" % image_url)
        response = self.imgur_client.upload_from_url(clean_path(image_url))
        return str(response['link'])

    def save_from_file(self, file_path):
        logging.debug("trying to save file %s" % file_path)
        response = self.imgur_client.upload_from_path(file_path)
        return (str(response['link']))
Exemplo n.º 44
0
class LlamaHandler():
    def __init__(self):
        self.llama = LlamaText()
        self.previousWords = dict()
        self.wordsFileName = "plugins/llamaFont/previousWords.list"
        self.imgurClientID = CLIENT_ID
        self.imgurClientSecret = CLIENT_SECRET

        if isfile(self.wordsFileName):
            previousWordsFile = open(self.wordsFileName, 'r')
            for line in previousWordsFile:
                line = line.split(";")
                word = line[0]
                url = line[1]
                deleteHash = line[2]
                self.previousWords[word] = {"url": url, "deleteHash": deleteHash}
                
            previousWordsFile.close()

        self.imgur = ImgurClient(self.imgurClientID, self.imgurClientSecret)


    def llamaItUp(self, word):
        word = re.sub(r"[^A-Za-z\!\?\. ]", '', word).lower()
        
        if word in self.previousWords:
            return self.previousWords[word]["url"]
        else:
            llamaImage = self.llama.new(word)
            _, tmpPath = mkstemp('.png')
            tmpImg = open(tmpPath, 'wb')
            llamaImage.save(tmpImg, "PNG")
            tmpImg.close()
            imageInfo = self.imgur.upload_from_path(tmpPath, {'title': word})
            self.storeWord(word, imageInfo)
            os.remove(tmpPath)
            return imageInfo['link']
        
    def storeWord(self, word, imageInfo):
        if not word in self.previousWords:
            self.previousWords[word] = {
                                        "url": imageInfo['link'],
                                        "deleteHash": imageInfo['deletehash']
                                        }
        
            previousWordsFile = open(self.wordsFileName, 'a')
            previousWordsFile.write("%s;%s;%s\n" % (word, imageInfo["link"],
                                    imageInfo["deletehash"]))
            previousWordsFile.close()
Exemplo n.º 45
0
def upload_image_to_imgur(file_path):
    client_id = "d423e3f49823d02"
    client_secret = "6d3052e94492d230cb7ef7117a781c52aafbaae4"
    imgur_client = ImgurClient(client_id, client_secret)
    config = {
        "album": None,
        "name": "SHIP IT",
        "title": "SHIP IT",
        "description": "Ship Bot strikes again! {0}".format(datetime.datetime.now())
    }
    print "Uploading image '{0}' to Imgur...".format(file_path)
    image = imgur_client.upload_from_path(file_path, config=config, anon=True)
    image_url = image["link"]
    print "Returned url: {0}".format(image_url)
    return image_url
Exemplo n.º 46
0
class SendImgur(Sender):
    def __init__(self, generate_img, name='img', position=1,
                 app_url='http://localhost:3000/values'):
        super(SendImgur, self).__init__(name, position, app_url)
        self.client_secret = os.environ['IMGUR_SECRET']
        self.client_id = os.environ['IMGUR_ID']
        self.client = ImgurClient(self.client_id, self.client_secret)
        self.generate_img = generate_img

    def on_epoch_end(self, epoch=None, logs={}):
        img = self.generate_img()
        res = self.client.upload_from_path(img)
        return requests.patch(self.app_url, json={
            'name': self.name, 'type': 'img', 'value': res['link'],
            'pos': self.position})
Exemplo n.º 47
0
    def upload_imgr(self, filename,albumhash):
        try:
	    config = {'album': albumhash,'name':'famibio','title': 'familabincubator','description': 'Cute organisms being cute on {0}'.format(datetime.now())}

            client = ImgurClient(IMGUR_ID,IMGUR_TOKEN)
            image_url=client.upload_from_path(filename,config=config,anon=False)
            return image_url
        except SNIMissingWarning:
            print "snimissingwarning"
            return image_url
        except InsecurePlatformWarning:
            print "oh noes insecure platform warning"
            return image_url
        except ImgurClientError, error:
                print error.error_message, error.status_code
Exemplo n.º 48
0
	def perform_actual_upload():
		# If you already have an access/refresh pair in hand
		client_id = snakebot_config.get("imgur", "client_id")
		client_secret = snakebot_config.get("imgur", "client_secret")
		access_token = snakebot_config.get("imgur", "access_token")
		refresh_token = snakebot_config.get("imgur", "refresh_token")

		# Note since access tokens expire after an hour, only the refresh token is required (library handles autorefresh)
		client = ImgurClient(client_id, client_secret, access_token, refresh_token)

		path = os.path.join(os.path.expanduser("~"), "Pictures/3dprinter", "photo.jpg")
		print "Uploading from ", path
		result = client.upload_from_path(path, anon=False)
		print result['link']

		return result['link']
Exemplo n.º 49
0
def upload_gif(gif):
    """Uploads an image file to Imgur"""

    client_id = os.environ.get('IMGUR_API_ID')
    client_secret = os.environ.get('IMGUR_API_SECRET')

    if client_id is None or client_secret is None:
        click.echo('Cannot upload - could not find IMGUR_API_ID or IMGUR_API_SECRET environment variables')
        return

    client = ImgurClient(client_id, client_secret)

    click.echo('Uploading file {}'.format(click.format_filename(gif)))

    response = client.upload_from_path(gif)

    click.echo('File uploaded - see your gif at {}'.format(response['link']))
Exemplo n.º 50
0
def inlinequery(bot, update):
    query_object = update.inline_query
    query = query_object.query
    results = []
    if not query_object.location:
        return []
    places = get_places(query, lat=query_object.location.latitude, lng=query_object.location.longitude)
    for place in places:
        keyboard = [[], []]
        if place.get('website'):
            website = InlineKeyboardButton(text='Сайт', url=place['website'])
            keyboard[0].append(website)
        if place.get('url'):
            google_map_url = InlineKeyboardButton(text='На карте', url=place['url'])
            keyboard[0].append(google_map_url)
        if place.get('formatted_phone_number'):
            phone_link = InlineKeyboardButton(text='На карте', url='tel:' + place['formatted_phone_number'])
        opening_hours = place.get('opening_hours')
        is_opened = True
        if opening_hours:
            is_opened = opening_hours.get('open_now')

        image_handler.handle_image(
            title=place.get('name'),
            location=place.get('formatted_address'),
            phone=place.get('formatted_phone_number'),
            is_active=is_opened,
            rating=place.get('rating')
        )
        client = ImgurClient(
            os.getenv('IMGUR_CLIENT_ID'),
            os.getenv('IMGUR_CLIENT_SECRET')
        )
        resp = client.upload_from_path('resources/output/temp.png')

        if keyboard[0]:
            results.append(InlineQueryResultArticle(id=uuid4(),
                                                    title=place.get('name'),
                                                    description=place.get('formatted_address'),
                                                    input_message_content=InputTextMessageContent(
                                                        format_response(place, resp),
                                                        parse_mode=ParseMode.MARKDOWN),
                                                    reply_markup=InlineKeyboardMarkup(inline_keyboard=keyboard),
                                                    thumb_url=place.get('icon')
                                                    ))
    bot.answerInlineQuery(update.inline_query.id, results=results)
Exemplo n.º 51
0
def upload(file: str) -> str:
    # Anonymous upload.
    # TODO: Upload to a specific user account. See #8.
    client_id = CONFIG.get(_name, "client_id")

    # access_token = kvstore["access_token"]
    # refresh_token = kvstore["refresh_token"]

    imgur_client = ImgurClient(client_id, None, None, None)

    file_metadata = None
    try:
        file_metadata = imgur_client.upload_from_path(file)
    except ImgurClientError as e:
        logging.error("Upload failed. Error message: {0}".format(e.error_message))

    url = file_metadata["link"] if file_metadata else None
    return url
Exemplo n.º 52
0
class ImageMakerGlue():
  def __init__(self, file):
    self.m = markov.Markov(2, file)
    print "Loaded corpus"
    self.client = ImgurClient(keys.imgur_client_id, keys.imgur_client_secret)
    print "Connected to Imgur"

  def gen(self, msg, max=None):
    comic, lengths = image_maker.pick()
    dialog = []
    for l in lengths:
      dialog.append(self.m.gen(msg, l))
      msg = ''
    print dialog
    file_name = image_maker.make(comic, dialog)
    link = str(self.client.upload_from_path(file_name)["link"])
    os.unlink(file_name)
    return link
Exemplo n.º 53
0
class imgur(handler):
    def __init__(self, file, server):
        handler.__init__(self, file, server)
        self.url = None
        self.apiKey = None
        self.clientId = None
        self.client = None

    def setConfig(self, val):
        self.config = val
        self.clientId = self.config[self.server]['ClientId']
        self.apiKey = self.config[self.server]['ApiKey']
        
        self.client = ImgurClient(self.clientId, self.apiKey)

    def upload(self):
        resp = self.client.upload_from_path(self.file)
        print('Uploaded to imgur. %s' % resp['link'])
        return 'Uploaded %s to : %s' % (path.split(self.file)[1], resp['link'])
Exemplo n.º 54
0
def videoCallback(frame, userdata=None):
  nparr = np.fromstring(frame, np.uint8)
  img = cv2.imdecode(nparr, cv2.CV_LOAD_IMAGE_COLOR)
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  # detect faces
  faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=5,
    minSize=(30,30),
    flags = cv2.cv.CV_HAAR_SCALE_IMAGE
  )
  i = 0
  # draw a rectangle around each face found
  for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
    print 'Found face'
    # save the image
    cv2.imwrite('picture.png', img)

    # upload detected image to imgur
    client_id = '<clientid>'
    client_secret = '<client_secret>'
    config = {
      'album': None,
      'name': 'intruder!',
      'title': 'intruder!',
      'description': 'intruder!'
    }
    client = ImgurClient(client_id, client_secret)

    image = client.upload_from_path('picture.png', config=config, anon=False)
    print image['link']

    # Your Account Sid and Auth Token from twilio.com/user/account
    account_sid = "<account_sid>"
    auth_token = "<auth_token>"
    client = TwilioRestClient(account_sid, auth_token)
    message = client.messages.create(body="Intruder Alert!!!",
      to="+15555555555", # Replace with your phone number
      from_="+18008888888",
      media_url=image['link']) # Replace with your Twilio number
    print message.sid
Exemplo n.º 55
0
def image_uploader(speech_text, client_id, client_secret, images_path):

    words_of_message = speech_text.split()
    words_of_message.remove('upload')
    cleaned_message = ' '.join(words_of_message)

    image_listing = img_list_gen(images_path)

    client = ImgurClient(client_id, client_secret)

    for i in range(0, len(image_listing)):
        if cleaned_message in image_listing[i]:
            result = client.upload_from_path(image_listing[i], config=None, anon=True)

            conn = sqlite3.connect('memory.db')
            conn.execute("INSERT INTO image_uploads (filename, url, upload_date) VALUES (?, ?, ?)", (image_listing[i], result['link'], datetime.strftime(datetime.now(), '%d-%m-%Y')))
            conn.commit()
            conn.close()

            print result['link']
            tts('Your image has been uploaded')
Exemplo n.º 56
0
class Image:

	imgur = None
	album_id = None

	def init(self):
		config = ConfigParser.ConfigParser()
                config.read('credentials.ini')
		
		client_id = config.get('credentials_imgur', 'client_id')
		client_secret = config.get('credentials_imgur', 'client_secret')
		
		self.album_id = config.get('credentials_imgur', 'album_id')		
		self.imgur  = ImgurClient(client_id, client_secret)

		# Authorization flow, pin example (see docs for other auth types)
		#authorization_url = self.imgur.get_auth_url('pin')

		#print("Go to the following URL: {0}".format(authorization_url))
		#pin = raw_input("Enter pin code: ")
		
		#credentials = self.imgur.authorize(pin, 'pin')
		#self.imgur.set_user_auth(credentials['access_token'], credentials['refresh_token'])	

	
	def upload_qr(self, data):
		if self.imgur is None:
			self.init()
		qrCode = pyqrcode.create('%s' % data['user']['id_str'])
		qrCode.png('qr.png', scale=20)

		#config = {
               	#	'album': self.album_id,
                #	'name':  data['user']['id_str'],
                #	'title': data['user']['id_str'],
		#}	
	
#		return self.imgur.upload_from_path('qr.png,config=config, anon=False)
		return self.imgur.upload_from_path('qr.png')