def request_image(window, keyword, num_of_try=0, translate=True):
    """
    Queries Bing for images and retries up to 5 times if the randomly selected image could not be accessed
    :param keyword:
        string which specifies the image content
    :param num_of_try:
        internal parameter that increases if the selected image could not be retrieved (e.g. Forbidden Error)
    :param translate:
        Should the keyword be translated to english before the search? (may increase result size)
    :return:
        The image data in bytes
    """

    if keyword is None:
        return None
    if translate:
        ms_key = open('../ms.key').read()
        trans = Translator('__RealTimeStoryIllustrator__', ms_key)
        translatedkw = trans.translate(keyword, lang_from='de', lang_to='en')
        print("IMAGE SERVICE: Getting image for " + str(keyword) + ". Searched for the english translation '" +
              str(translatedkw) + "'.")
    else:
        translatedkw = keyword
        print("IMAGE SERVICE: Getting image for " + str(keyword) + ".")

    if num_of_try > 5:  # no images were found
        logger.error("IMAGE SERVICE: Could not find an image after 5 tries for " + str(translatedkw) + ".")
        return None

    # OLD CODE FOR SEARCHING BEGIN

    # term = urllib.parse.quote_plus(translatedkw)

    # sites = [line.rstrip() for line in
    #         open(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'data', 'sites.txt'),
    #              encoding="utf-8")]
    # excludedsites = ""
    # for site in sites:
    #    excludedsites = excludedsites + "-site:" + urllib.parse.quote_plus(site) + '%20'

    # img_type = '%7Eillustration+AND+clipart'
    # opener = urllib.request.build_opener()
    # opener.addheaders = [('User-agent', 'Mozilla/5.0')]

    # url = ('http://ajax.googleapis.com/ajax/services/search/images?' +
    #      'v=1.0&q=' + term + '%20' + img_type + '%20' + excludedsites + '%20&userip=91.141.0.105' +
    #       '&rsz=8&imgsz=medium&safe=active' + '&tbs=ic:color')

    # OLD CODE FOR SEARCHING END

    try:
        params = {'$format': 'json', '$top': 10, 'ImageFilters': '\'Size:Small\''}
        bing_key = open('../bing.key').read()
        api = BingSearchAPI(bing_key)
        result = api.search_image(str(translatedkw+'+AND+(illustration+OR+clipart)'), params)
        amount = len(result.json()['d']['results'])
        # print(json.dumps(result.json(), sort_keys=True, indent=2))

        # print(result.json())
        # print(result.json()['d']['results'][0]['MediaUrl'])
        img_num = random.randint(0, amount-1)
        data = urllib.request.urlopen(result.json()['d']['results'][img_num]['MediaUrl'], timeout=2).read()
        return data
    except Exception as e:  # have to catch everything since socket exceptions seem to be broken
        print("ERROR in IMAGE SERVICE: Trying again, request was denied "+str(e))
        return request_image(window, keyword, num_of_try + 1, translate=translate)
def request_image(window, keyword, num_of_try=0, translate=True):
    """
    Queries Bing for images and retries up to 5 times if the randomly selected image could not be accessed
    :param keyword:
        string which specifies the image content
    :param num_of_try:
        internal parameter that increases if the selected image could not be retrieved (e.g. Forbidden Error)
    :param translate:
        Should the keyword be translated to english before the search? (may increase result size)
    :return:
        The image data in bytes
    """

    if keyword is None:
        return None
    if translate:
        ms_key = open('../ms.key').read()
        trans = Translator('__RealTimeStoryIllustrator__', ms_key)
        translatedkw = trans.translate(keyword, lang_from='de', lang_to='en')
        print("IMAGE SERVICE: Getting image for " + str(keyword) +
              ". Searched for the english translation '" + str(translatedkw) +
              "'.")
    else:
        translatedkw = keyword
        print("IMAGE SERVICE: Getting image for " + str(keyword) + ".")

    if num_of_try > 5:  # no images were found
        logger.error(
            "IMAGE SERVICE: Could not find an image after 5 tries for " +
            str(translatedkw) + ".")
        return None

    # OLD CODE FOR SEARCHING BEGIN

    # term = urllib.parse.quote_plus(translatedkw)

    # sites = [line.rstrip() for line in
    #         open(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'data', 'sites.txt'),
    #              encoding="utf-8")]
    # excludedsites = ""
    # for site in sites:
    #    excludedsites = excludedsites + "-site:" + urllib.parse.quote_plus(site) + '%20'

    # img_type = '%7Eillustration+AND+clipart'
    # opener = urllib.request.build_opener()
    # opener.addheaders = [('User-agent', 'Mozilla/5.0')]

    # url = ('http://ajax.googleapis.com/ajax/services/search/images?' +
    #      'v=1.0&q=' + term + '%20' + img_type + '%20' + excludedsites + '%20&userip=91.141.0.105' +
    #       '&rsz=8&imgsz=medium&safe=active' + '&tbs=ic:color')

    # OLD CODE FOR SEARCHING END

    try:
        params = {
            '$format': 'json',
            '$top': 10,
            'ImageFilters': '\'Size:Small\''
        }
        bing_key = open('../bing.key').read()
        api = BingSearchAPI(bing_key)
        result = api.search_image(
            str(translatedkw + '+AND+(illustration+OR+clipart)'), params)
        amount = len(result.json()['d']['results'])
        # print(json.dumps(result.json(), sort_keys=True, indent=2))

        # print(result.json())
        # print(result.json()['d']['results'][0]['MediaUrl'])
        img_num = random.randint(0, amount - 1)
        data = urllib.request.urlopen(
            result.json()['d']['results'][img_num]['MediaUrl'],
            timeout=2).read()
        return data
    except Exception as e:  # have to catch everything since socket exceptions seem to be broken
        print("ERROR in IMAGE SERVICE: Trying again, request was denied " +
              str(e))
        return request_image(window,
                             keyword,
                             num_of_try + 1,
                             translate=translate)