<commit_before>from __future__ import unicode_literals

import imghdr
import os
import shutil
import struct
import time

from requests_toolbelt import MultipartEncoder

from . import config


def download_photo(self, media_id, filename, media=False, folder="photos"):
    if not media:
        self.media_info(media_id)
        if not self.last_json.get("items"):
            return True
        media = self.last_json["items"][0]
    if media["media_type"] == 2:
        return True
    elif media["media_type"] == 1:
        filename = (
            "{}_{}.jpg".format(media["user"]["username"], media_id)
            if not filename
            else "{}.jpg".format(filename)
        )
        images = media["image_versions2"]["candidates"]
        fname = os.path.join(folder, filename)
        if os.path.exists(fname):
            self.logger.info("File already esists, skipping...")
            return os.path.abspath(fname)
        response = self.session.get(images[0]["url"], stream=True)
        if response.status_code == 200:
            with open(fname, "wb") as f:
                response.raw.decode_content = True
                shutil.copyfileobj(response.raw, f)
            return os.path.abspath(fname)
    else:
        success = False
        video_included = False
        for index in range(len(media["carousel_media"])):
            if media["carousel_media"][index]["media_type"] != 1:
                video_included = True
                continue
            filename_i = (
                "{}_{}_{}.jpg".format(
                    media["user"]["username"],
                    media_id,
                    index
                )
                if not filename
                else "{}_{}.jpg".format(filename, index)
            )
            images = \
                media["carousel_media"][index]["image_versions2"]["candidates"]
            fname = os.path.join(folder, filename_i)
            if os.path.exists(fname):
                return os.path.abspath(fname)
            response = self.session.get(images[0]["url"], stream=True)
            if response.status_code == 200:
                success = True
                with open(fname, "wb") as f:
                    response.raw.decode_content = True
                    shutil.copyfileobj(response.raw, f)
        if success:
            return os.path.abspath(fname)
        elif video_included:
            return True


def compatible_aspect_ratio(size):
    min_ratio, max_ratio = 4.0 / 5.0, 90.0 / 47.0
    width, height = size
    ratio = width * 1.0 / height * 1.0
    print("FOUND: w:{} h:{} r:{}".format(width, height, ratio))
    return min_ratio <= ratio <= max_ratio


def configure_photo(self, upload_id, photo, caption=""):
    (w, h) = get_image_size(photo)
    data = self.json_data(
        {
            "media_folder": "Instagram",
            "source_type": 4,
            "caption": caption,
            "upload_id": upload_id,
            "device": self.device_settings,
            "edits": {
                "crop_original_size": [w * 1.0, h * 1.0],
                "crop_center": [0.0, 0.0],
                "crop_zoom": 1.0,
            },
            "extra": {"source_width": w, "source_height": h},
        }
    )
    return self.send_request("media/configure/?", data)


def upload_photo(
    self,
    photo,
    caption=None,
    upload_id=None,
    from_video=False,
    force_resize=False,
    options={},
):
    """Upload photo to Instagram

    @param photo         Path to photo file (String)
    @param caption       Media description (String)
    @param upload_id     Unique upload_id (String). When None, then generate
                         automatically
    @param from_video    A flag that signals whether the photo is loaded from
                         the video or by itself
                         (Boolean, DEPRECATED: not used)
    @param force_resize  Force photo resize (Boolean)
    @param options       Object with difference options, e.g.
                         configure_timeout, rename (Dict)
                         Designed to reduce the number of function arguments!
                         This is the simplest request object.

    @return Boolean
    """
    options = dict(
        {"configure_timeout": 15, "rename": True},
        **(options or {})
    )
    if upload_id is None:
        upload_id = str(int(time.time() * 1000))
    if not photo:
        return False
    if not compatible_aspect_ratio(get_image_size(photo)):
        self.logger.error(
            "Photo does not have a compatible photo aspect ratio."
        )
        if force_resize:
            photo = resize_image(photo)
        else:
            return False

    with open(photo, "rb") as f:
        photo_bytes = f.read()

    data = {
        "upload_id": upload_id,
        "_uuid": self.uuid,
        "_csrftoken": self.token,
        "image_compression": '{"lib_name":"jt","lib_version":"1.3.0",' +
        '"quality":"87"}',
        "photo": (
            "pending_media_%s.jpg" % upload_id,
            photo_bytes,
            "application/octet-stream",
            {"Content-Transfer-Encoding": "binary"},
        ),
    }
#     self.session.headers.update(
#         {
#             "X-IG-Capabilities": "3Q4=",
#             "X-IG-Connection-Type": "WIFI",
#             "Cookie2": "$Version=1",
#             "Accept-Language": "en-US",
#             "Accept-Encoding": "gzip, deflate",
#             "Content-type": m.content_type,
#             "Connection": "close",
#             "User-Agent": self.user_agent,
#         }
#     )
#     response = self.session.post(
#         config.API_URL + "upload/photo/",
#         data=m.to_string()
#     )

    dataEncoded = MultipartEncoder(data, boundary=self.uuid).to_string()
    response = self.send_request(config.API_URL + 'upload/photo/', dataEncoded, False, False)<commit_msg>Fix Formatting<commit_after>from __future__ import unicode_literals

import imghdr
import os
import shutil
import struct
import time

from requests_toolbelt import MultipartEncoder

from . import config


def download_photo(self, media_id, filename, media=False, folder="photos"):
    if not media:
        self.media_info(media_id)
        if not self.last_json.get("items"):
            return True
        media = self.last_json["items"][0]
    if media["media_type"] == 2:
        return True
    elif media["media_type"] == 1:
        filename = (
            "{}_{}.jpg".format(media["user"]["username"], media_id)
            if not filename
            else "{}.jpg".format(filename)
        )
        images = media["image_versions2"]["candidates"]
        fname = os.path.join(folder, filename)
        if os.path.exists(fname):
            self.logger.info("File already esists, skipping...")
            return os.path.abspath(fname)
        response = self.session.get(images[0]["url"], stream=True)
        if response.status_code == 200:
            with open(fname, "wb") as f:
                response.raw.decode_content = True
                shutil.copyfileobj(response.raw, f)
            return os.path.abspath(fname)
    else:
        success = False
        video_included = False
        for index in range(len(media["carousel_media"])):
            if media["carousel_media"][index]["media_type"] != 1:
                video_included = True
                continue
            filename_i = (
                "{}_{}_{}.jpg".format(
                    media["user"]["username"],
                    media_id,
                    index
                )
                if not filename
                else "{}_{}.jpg".format(filename, index)
            )
            images = \
                media["carousel_media"][index]["image_versions2"]["candidates"]
            fname = os.path.join(folder, filename_i)
            if os.path.exists(fname):
                return os.path.abspath(fname)
            response = self.session.get(images[0]["url"], stream=True)
            if response.status_code == 200:
                success = True
                with open(fname, "wb") as f:
                    response.raw.decode_content = True
                    shutil.copyfileobj(response.raw, f)
        if success:
            return os.path.abspath(fname)
        elif video_included:
            return True


def compatible_aspect_ratio(size):
    min_ratio, max_ratio = 4.0 / 5.0, 90.0 / 47.0
    width, height = size
    ratio = width * 1.0 / height * 1.0
    print("FOUND: w:{} h:{} r:{}".format(width, height, ratio))
    return min_ratio <= ratio <= max_ratio


def configure_photo(self, upload_id, photo, caption=""):
    (w, h) = get_image_size(photo)
    data = self.json_data(
        {
            "media_folder": "Instagram",
            "source_type": 4,
            "caption": caption,
            "upload_id": upload_id,
            "device": self.device_settings,
            "edits": {
                "crop_original_size": [w * 1.0, h * 1.0],
                "crop_center": [0.0, 0.0],
                "crop_zoom": 1.0,
            },
            "extra": {"source_width": w, "source_height": h},
        }
    )
    return self.send_request("media/configure/?", data)


def upload_photo(
    self,
    photo,
    caption=None,
    upload_id=None,
    from_video=False,
    force_resize=False,
    options={},
):
    """Upload photo to Instagram

    @param photo         Path to photo file (String)
    @param caption       Media description (String)
    @param upload_id     Unique upload_id (String). When None, then generate
                         automatically
    @param from_video    A flag that signals whether the photo is loaded from
                         the video or by itself
                         (Boolean, DEPRECATED: not used)
    @param force_resize  Force photo resize (Boolean)
    @param options       Object with difference options, e.g.
                         configure_timeout, rename (Dict)
                         Designed to reduce the number of function arguments!
                         This is the simplest request object.

    @return Boolean
    """
    options = dict(
        {"configure_timeout": 15, "rename": True},
        **(options or {})
    )
    if upload_id is None:
        upload_id = str(int(time.time() * 1000))
    if not photo:
        return False
    if not compatible_aspect_ratio(get_image_size(photo)):
        self.logger.error(
            "Photo does not have a compatible photo aspect ratio."
        )
        if force_resize:
            photo = resize_image(photo)
        else:
            return False

    with open(photo, "rb") as f:
        photo_bytes = f.read()

    data = {
        "upload_id": upload_id,
        "_uuid": self.uuid,
        "_csrftoken": self.token,
        "image_compression": '{"lib_name":"jt","lib_version":"1.3.0",' +
        '"quality":"87"}',
        "photo": (
            "pending_media_%s.jpg" % upload_id,
            photo_bytes,
            "application/octet-stream",
            {"Content-Transfer-Encoding": "binary"},
        ),
    }
#     self.session.headers.update(
#         {
#             "X-IG-Capabilities": "3Q4=",
#             "X-IG-Connection-Type": "WIFI",
#             "Cookie2": "$Version=1",
#             "Accept-Language": "en-US",
#             "Accept-Encoding": "gzip, deflate",
#             "Content-type": m.content_type,
#             "Connection": "close",
#             "User-Agent": self.user_agent,
#         }
#     )
#     response = self.session.post(
#         config.API_URL + "upload/photo/",
#         data=m.to_string()
#     )

    dataEncoded = MultipartEncoder(data, boundary=self.uuid).to_string()
    response = self.send_request('upload/photo/', dataEncoded, with_signature=False)
{'fraction_non_alphanumeric': 0.12247667514843087, 'fraction_numerical': 0.00916030534351145, 'mean_word_length': 1.8140811455847254, 'pattern_counts': {'":': 62, '<': 7, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4088685', 'n_tokens_mistral': 3512, 'n_tokens_neox': 3372, 'n_words': 784}