Example #1
0
 def test_remote_image(self):
     image_url = 'https://c2.staticflickr.com/6/5267/5669212075_039ed45bff_z.jpg'
     image_data, size = media.prepare_image(
         image_url, max_size=(400, 400), save_path='remote.jpg')
     self.assertLessEqual(size[0], 400, 'Invalid width.')
     self.assertLessEqual(size[1], 400, 'Invalid height.')
     self.assertGreater(len(image_data), 0)
def InstagramPoster(photo, description, credit):
    import requests
    import json
    import time
    from random import randint
    from instagram_private_api import Client, MediaRatios
    from instagram_private_api_extensions import media
    from PIL import Image

    global instagram_username, instagram_password, insta_hashtags

    InstagramAPI = Client(instagram_username, instagram_password)

    try:
        mycaption = '"' + description + '"' + " (Via: u/" + credit + ")\n\n.\n.\n.\n.\n.\n.\n" + insta_hashtags
        try:
            post_before = NumberOfPosts(instagram_username)
            photo_data, photo_size = media.prepare_image(
                'picture_to_post.jpg', aspect_ratios=MediaRatios.standard)
            InstagramAPI.post_photo(photo_data, photo_size, caption=mycaption)

            if NumberOfPosts(instagram_username) == post_before:
                print("ERROR: It did not post, please try again!")
            else:
                print("Photo posted!")

        except Exception as e:
            print("Error...")
            exit(0)

    except Exception as e:
        print(e)
Example #3
0
def send_picture(final_link, link):
    global tags
    global new_settings_file
    coup = BeautifulSoup(opener.open(link))
    for tag in coup.find_all("meta"):
        if tag.get("property", None) == "og:description":
            describtion = tag.get("content", None)
    for tag in coup.find_all("meta"):
        if tag.get("property", None) == "article:tag":
            if(tag.get("content", None).find("#") == -1):
                tags += "#"+(tag.get("content", None)).replace(" ", "_")+" "
            else: tags += (tag.get("content", None)).replace(" ", "_")+" "
    link_site = "aSPBe.ru"
    caption = BeautifulSoup(opener.open(link)).title.string+"\n"+describtion+"\n"+link_site+"\n"+tags
    print(final_link)
    if (final_link.find("jpeg") != -1):
        urllib.request.urlretrieve(final_link, "picture."+"jpg")
    else: urllib.request.urlretrieve(final_link, "picture."+final_link[-3:])
    if (final_link[-3:] == "png"):
        im = Image.open("picture.png")
        rgb_im = im.convert('RGB')
        rgb_im.save('picture.jpg')
    photo_data, photo_size = media.prepare_image("picture.jpg", aspect_ratios=MediaRatios.standard)
    if(photo_size[0]>photo_size[1] or photo_size[1]>photo_size[0]):
        work_image = Image.open("picture.jpg")
        make_square(work_image) 
    subprocess.call(["php", "inst_post.php", usr, pwd, "picture.jpg", caption])
    tags = ""
    s3.upload_fileobj(open('instagram.sqlite', "rb"), 'heroku', 'instagram.sqlite')
    s3.upload_fileobj(open('inst_link.txt', "rb"), 'heroku', 'inst_link.txt')
    print("Success")
 def test_prepare_image(self):
     _, size = media.prepare_image(self.TEST_IMAGE_PATH,
                                   max_size=(400, 400),
                                   aspect_ratios=0.8)
     self.assertLessEqual(size[0], 400, 'Invalid width.')
     self.assertLessEqual(size[1], 400, 'Invalid height.')
     self.assertEqual(round(1.0 * size[0] / size[1], 2), 0.8,
                      'Invalid aspect ratio.')
Example #5
0
 def test_prepare_image2(self):
     _, size = media.prepare_image(
         self.TEST_IMAGE_PATH, max_size=(400, 350), aspect_ratios=(0.8, 1.2))
     self.assertLessEqual(size[0], 400, 'Invalid width.')
     self.assertLessEqual(size[1], 350, 'Invalid height.')
     ar = 1.0 * size[0] / size[1]
     self.assertLessEqual(round(ar, 2), 1.2)
     self.assertGreaterEqual(round(ar, 2), 0.8)
Example #6
0
 def test_prepare_image3(self):
     _, size = media.prepare_image(
         self.TEST_IMAGE_PATH, max_size=(1080, 1350), aspect_ratios=(0.8, 1.2), min_size=(640, 640))
     self.assertLessEqual(size[0], 1080, 'Invalid width (max)')
     self.assertLessEqual(size[1], 1350, 'Invalid height (max).')
     self.assertGreaterEqual(size[0], 640, 'Invalid width (min)')
     self.assertGreaterEqual(size[1], 640, 'Invalid height (min)')
     ar = 1.0 * size[0] / size[1]
     self.assertLessEqual(round(ar, 2), 1.2)
     self.assertGreaterEqual(round(ar, 2), 0.8)
Example #7
0
 def prepare(self, story=False):
     ratio = MediaRatios.reel if story else MediaRatios.standard
     size = (1080, 1920) if story else (1080, 1350)
     # print('ratio is: ', ratio)
     if self.is_image():
         return IGMedia.prepare_image(self.media_path,
                                      max_size=size,
                                      aspect_ratios=ratio)
     elif self.is_video():
         max_time = 15.0 if story else 60.0
         return IGMedia.prepare_video(self.media_path,
                                      max_size=size,
                                      aspect_ratios=ratio,
                                      max_duration=max_time)
Example #8
0
def send_to_instagram(instance):
    photo_data, photo_size = media.prepare_image(
        instance.image.path, aspect_ratios=MediaRatios.standard)
    caption = instance.title.title() + "\n" + f"#{instance.category}"
    for tag in instance.tags.all():
        caption += f" #{tag}"

    for user, passwd in accounts.items():
        try:
            api = Client(user, passwd)
            api.post_photo(photo_data, photo_size, caption=caption)

        except Exception as error:
            with open("logs/insta_log.txt", 'a') as f:
                text = str(error) + "\n"
                f.write(text)
def post_photo(client, u_dir, c_dir, app_logger):
    '''
    Post photo WIP
    '''
    p_file = ''
    c_file = ''
    app_logger.debug('Uploading image from path {0!s}'.format(u_dir))
    files = os.listdir(u_dir)
    for each_file in files:
        if re.match(r'.*?\.jpg$', each_file.lower()):
            p_file = each_file
            break
    c_file = os.path.splitext(p_file)[0] + '.txt'
    if p_file:
        image_file = '{0!s}/{1!s}'.format(u_dir, p_file)
        caption_file = '{0!s}/{1!s}'.format(u_dir, c_file)
        caption_data = ''
        if os.path.isfile(caption_file):
            caption_data = read_file(caption_file, app_logger)
        else:
            app_logger.debug('Caption file does not exist')
        photo_data, photo_size = media.prepare_image(
            image_file, aspect_ratios=MediaRatios.standard)
        try:
            app_logger.debug(
                'Uploading image "{0!s}" with caption from "{1!s}"'.format(
                    image_file, caption_file))
            upload_response = client.post_photo(photo_data,
                                                photo_size,
                                                caption=caption_data)
            if upload_response['status'] == 'ok':
                app_logger.debug(
                    'Image "{0!s}" uploaded Successfully'.format(image_file))
                os.rename(image_file, '{0!s}/{1!s}'.format(c_dir, p_file))
                if os.path.isfile(caption_file):
                    os.rename(caption_file,
                              '{0!s}/{1!s}'.format(c_dir, c_file))
                return True
            return False
        except ClientError as u_err:
            app_logger.debug('Image "{0!s}" upload failed'.format(image_file))
            app_logger.critical(
                'ClientError {0!s} (Code: {1:d}, Response: {2!s})'.format(
                    u_err.msg, u_err.code, u_err.error_response))
            return False
    app_logger.debug('Image file does not exist')
    return False
 def test_prepare_image4(self):
     with self.assertRaises(ValueError):
         media.prepare_image(self.TEST_IMAGE_PATH,
                             max_size=(1080, 1350),
                             aspect_ratios=(4.0 / 5),
                             min_size=(1081, 640))
Example #11
0
def post_photo(api, filepath, caption):
    data, size = media.prepare_image(filepath, aspect_ratios=MediaRatios.standard)
    api.post_photo(data, size, caption)