def __call__(self, presentation_context) -> Optional[ImageData]:
        logger.debug('Calling generator_util.ExternalImageListGenerator')
        logger.debug('self._image_generator: {}'.format(self._image_generator))
        logger.debug('self._check_image_validness: {}'.format(
            self._check_image_validness))
        logger.debug('self._weighted: {}'.format(self._weighted))
        logger.debug('module where function def: {}'.format(
            self._image_generator.__module__))
        logger.debug(
            '****************************************************************')
        images = self._image_generator(presentation_context)
        logger.debug('images: {}'.format(images))
        logger.debug(
            '****************************************************************')

        while bool(images) and len(images) > 0:
            original_chosen_image = (random_util.weighted_random([
                image for image in images if image[0] > 0
            ]) if self._weighted else random.choice(images))
            if isinstance(original_chosen_image, str):
                chosen_image = ImageData(image_url=original_chosen_image)
            elif isinstance(original_chosen_image, ImageData):
                chosen_image = original_chosen_image
            else:
                logger.warning(
                    "INVALID IMAGE INPUT FOR EXTERNAL IMAGE GENERATOR / " +
                    str(original_chosen_image) + " / " +
                    str(type(original_chosen_image)))
                images.remove(original_chosen_image)
                continue

            return chosen_image
        return None
Exemplo n.º 2
0
def _map_to_image_data(photo):
    link_download = photo.link_download
    creator_user = photo.body["user"]
    creator_name = None
    if creator_user:
        creator_name = creator_user["name"] + " (Unsplash)"
    return ImageData(image_url=link_download, source=creator_name)
Exemplo n.º 3
0
def search_photos(query, orientation="all") -> List[ImageData]:
    api_key = get_pixabay_session()
    logger.debug("pixabay_api_key: {}".format(api_key))
    query = query.replace(' ', '+')
    logger.debug("pixabay.search_photos called with query: {}".format(query))
    url_query = f"https://pixabay.com/api/?key={api_key}&q={query}&image_type=photo&orientation={orientation}"
    logger.debug("pixabay url_query: {}".format(url_query))
    if api_key and url_query:
        results = requests.get(url=url_query)
        logger.debug("request response results: {}".format(results))
        response_data = results.json()
        if results.status_code == 200 and response_data["hits"]:
            images = []
            for photo in response_data["hits"]:
                link_download = photo["largeImageURL"]
                creator = photo[
                    "user"] + " (via Pixabay)" if "user" in photo else None
                images.append(
                    ImageData(image_url=link_download, source=creator))
            return images
        else:
            logger.warning(
                'Pixabay could not find results for "{}", which might be due to missing/erroneous access keys'
                .format(query))
    else:
        logger.warning(
            "No active Pixabay session due to missing/wrong credentials.")
Exemplo n.º 4
0
def search_photos(query) -> List[ImageData]:
    if pexels_session and query:
        results = _search_pexels(query)
        if results and results["photos"]:
            images = []
            for photo in results["photos"]:
                source = photo["src"]
                # link_download = (
                #     source["large"]
                #     if "large" in source
                #     else (source["original"] if "original" in source else photo["url"])
                # )
                link_download = source["original"]
                creator = ((photo["photographer"] + " (via Pexels)")
                           if "photographer" in photo else None)
                images.append(
                    ImageData(image_url=link_download, source=creator))
            return images
        else:
            logger.warning(
                'pexels could not find results for "{}", which might be due to missing/erroneous access keys'
                .format(query))
    else:
        logger.warning(
            "No active pexels session due to missing/wrong credentials.")
Exemplo n.º 5
0
def _add_image(slide,
               placeholder_id: int,
               image: ImageData,
               original_image_size: bool = True):
    if isinstance(image, ImageData):
        image_url = image.get_image_url()
    else:
        image_url = image

    if is_external_url(image_url):
        image_ref = ExternalImage(image_url)
    else:
        path = Path(image_url).absolute()
        image_ref = InternalImage(str(path))

    placeholder = slide.placeholders[placeholder_id]
    if original_image_size:
        # Calculate the image size of the image
        try:
            # Insert the picture
            try:
                width, height = image_ref.image().size
                # Make sure the placeholder doesn't zoom in
                placeholder.height = height
                placeholder.width = width
                placeholder = placeholder.insert_picture(
                    image_ref.get_file_like())
                # Calculate ratios and compare
                image_ratio = width / height
                placeholder_ratio = placeholder.width / placeholder.height
                ratio_difference = placeholder_ratio - image_ratio
                # Placeholder width too wide:
                if ratio_difference > 0:
                    difference_on_each_side = ratio_difference / 2
                    placeholder.crop_left = -difference_on_each_side
                    placeholder.crop_right = -difference_on_each_side
                # Placeholder height too high
                else:
                    difference_on_each_side = -ratio_difference / 2
                    placeholder.crop_bottom = -difference_on_each_side
                    placeholder.crop_top = -difference_on_each_side
                return placeholder
            except (ValueError, XMLSyntaxError, AttributeError) as e:
                logger.error("_add_image error: {}".format(e))
                return None

        except FileNotFoundError as fnfe:
            logger.error("_add_image file not found: {}".format(fnfe))
            return None
    else:
        try:
            return placeholder.insert_picture(image_ref.get_file_like())
        except (OSError, ValueError) as e:
            logger.error(e)
            logger.error("Unexpected error inserting image: {}:{}".format(
                image,
                sys.exc_info()[0]))
            return None
Exemplo n.º 6
0
def random(_=None):
    try:
        random_image = unsplash_session.photos(type_="random")
        image_url = random_image.body["links"]["download"]
        creator_name = random_image.body["user"]["name"]
        return ImageData(image_url=image_url, source=creator_name)
    except JSONDecodeError:
        logger.warning("Couldn't get random Unsplash image")
        return None
Exemplo n.º 7
0
 def __call__(self, seed: str):
     results = reddit.search_subreddit(
         self._subreddit,
         str(seed) + " nsfw:no (url:.jpg OR url:.png OR url:.gif)")
     if bool(results):
         return [
             ImageData(
                 image_url=post.url,
                 source="u/" + post.author.name + " (on " +
                 post.subreddit_name_prefixed + ")",
             ) for post in results
         ]
Exemplo n.º 8
0
def get_random_inspirobot_image(_=None):
    # Generate a random url to access inspirobot
    dd = str(random.randint(1, 73)).zfill(2)
    nnnn = random.randint(0, 9998)
    inspirobot_url = ("http://generated.inspirobot.me/"
                      "0{}/aXm{}xjU.jpg").format(dd, nnnn)

    # Download the image
    # image_url = os_util.to_actual_file(
    #     "downloads/inspirobot/{}-{}.jpg".format(dd, nnnn)
    # )
    # os_util.download_image(inspirobot_url, image_url)

    return ImageData(image_url=inspirobot_url, source="Inspirobot")
Exemplo n.º 9
0
def create_large_quote_slide(prs, title, text, background_image=None):
    if bool(text):
        slide = _create_slide(prs, LAYOUT_LARGE_QUOTE)
        if title:
            _add_title(slide, title)
        _add_text(slide, 1, text)
        if background_image:
            _add_image(slide, 11, background_image, False)

        # Add black transparent image for making other image behind it transparent (missing feature in python-pptx)
        data_folder = Path(
            __file__
        ).parent.parent / "data" / "images" / "black-transparent.png"
        _add_image(slide, 12, ImageData(str(data_folder.absolute())), False)

        return slide
Exemplo n.º 10
0
def search_photos(query, orientation="all") -> List[ImageData]:
    pixabay_session = get_pixabay_session()
    logger.debug('pixabay_session: {}'.format(pixabay_session))
    logger.debug('pixabay.search_photos called with query: {}'.format(query))
    if pixabay_session and query:
        results = pixabay_session.search(q=query, orientation=orientation)
        if results and results["hits"]:
            images = []
            for photo in results["hits"]:
                link_download = photo["largeImageURL"]
                creator = photo["user"] + " (via Pixabay)" if "user" in photo else None
                images.append(ImageData(image_url=link_download, source=creator))
            return images
        else:
            logger.warning(
                'Pixabay could not find results for "{}", which might be due to missing/erroneous access keys'.format(
                    query
                )
            )
    else:
        logger.warning("No active Pixabay session due to missing/wrong credentials.")
 def __call__(self, seed: str) -> ImageData:
     return ImageData(image_url=self._image_url_generator(seed))