Beispiel #1
0
def searchAgain(chat_id, context):
    """
    User has selected a picture she likes and would like to run a visual search agaist
    this picture. This fn collects the url of the liked picture and sends it to doSearchEncounter
    """
    from_user = context['from_user']
    prev_context = retrieveContext(chat_id, from_user)
    print prev_context.keys()
    if 'image_query_result' not in prev_context and 'text_query_result' not in prev_context:
        say(chat_id, context, canned_responses.error_message())
        return Response(status=200)
    elif 'selected_outfit' not in prev_context:
        say(chat_id, context, canned_responses.error_message())
        return Response(status=200)
    else:
        i = int(prev_context['selected_outfit']) - 1
        if prev_context['search_type'] == 'image':
            i = i + int(
                prev_context['image_query_result_index']) - SHOW_THIS_MANY
            user_img_url = prev_context['image_query_result']['images'][i][
                'imageUrl']
        elif prev_context['search_type'] == 'text':
            i = i + int(
                prev_context['text_query_result_index']) - SHOW_THIS_MANY
            user_img_url = prev_context['text_query_result']['products'][i][
                'image']['sizes']['Best']['url']
        prev_context['user_img_url'] = user_img_url
        prev_context['search_type'] = 'image'
        storeContext(chat_id, from_user, prev_context, action='searchAgain')
        doSearchEncounter(chat_id, prev_context)
    return Response(status=200)
Beispiel #2
0
def searchAgain(chat_id,context):
    """
    User has selected a picture she likes and would like to run a visual search agaist
    this picture. This fn collects the url of the liked picture and sends it to doSearchEncounter
    """
    from_user = context['from_user']
    prev_context = retrieveContext(chat_id,from_user)
    print prev_context.keys()
    if 'image_query_result' not in prev_context and 'text_query_result' not in prev_context:
        say(chat_id,context,canned_responses.error_message())
        return Response(status=200)
    elif  'selected_outfit' not in prev_context:
        say(chat_id,context,canned_responses.error_message())
        return Response(status=200)
    else:
        i = int(prev_context['selected_outfit'])-1
        if prev_context['search_type'] == 'image':
            i = i+ int(prev_context['image_query_result_index'])- SHOW_THIS_MANY 
            user_img_url = prev_context['image_query_result']['images'][i]['imageUrl']
        elif prev_context['search_type'] == 'text':
            i = i+ int(prev_context['text_query_result_index'])- SHOW_THIS_MANY 
            user_img_url = prev_context['text_query_result']['products'][i]['image']['sizes']['Best']['url']
        prev_context['user_img_url'] = user_img_url
        prev_context['search_type'] = 'image'
        storeContext(chat_id,from_user,prev_context,action='searchAgain')
        doSearchEncounter(chat_id, prev_context)
    return Response(status=200)
Beispiel #3
0
def showShopStyleResults(chat_id,from_user,context):
    api_json = context['text_query_result']
    result_image_urls = [value['image']['sizes']['IPhone']['url'] for value in api_json['products']]
    
    text_query_result_index = int(context['text_query_result_index'])
    i = 0
    if text_query_result_index+SHOW_THIS_MANY >= len(result_image_urls):
        message = "Well, maybe not. Gosh, you're hard to please :/ Try sending me back a pic of something I've showed you already to keep looking."
        sendSuggestedResponseHowTo(chat_id,from_user,message,context)
        return api_json
    urls=[]
    titles=[]
    for an_image in result_image_urls[text_query_result_index:]:
        if i >= SHOW_THIS_MANY:
            break
        title = api_json['products'][i]['brandedName']
        urls.append(an_image)
        titles.append(title)
        if context['platform'] == 'KIK':
            picture_message = PictureMessage(to=from_user, chat_id=chat_id, pic_url=an_image)
            picture_message.attribution = CustomAttribution(name=title)
            kik.send_messages([picture_message])

        i +=1
    if context['platform'] == 'FB':
        dispatchMessage(context,'image',chat_id,from_user,urls,suggested_responses=titles)
    context['text_query_result_index'] = i + text_query_result_index # remember which results we've showed
    context['text_query_result'] = api_json
    storeContext(chat_id,from_user,context,action='showShopStyleResults')
    if context['platform'] == 'KIK':
        selectAnImageMsg(chat_id,context)
        return api_json
Beispiel #4
0
def doTextSearchEncounter(chat_id, context):
    """
    User has sent a message like 'find me a red sundress'
    this fn is called by Wit when it thinks a phrase has a text_search intention
    """
    from_user = context['from_user']
    context = retrieveContext(chat_id, from_user)
    context['search_type'] = 'text'
    storeContext(chat_id, from_user, context, action='doTextSearchEncounter')
    doSearchEncounter(chat_id, context)
Beispiel #5
0
def doTextSearchEncounter(chat_id,context):
    """
    User has sent a message like 'find me a red sundress'
    this fn is called by Wit when it thinks a phrase has a text_search intention
    """
    from_user = context['from_user']
    context = retrieveContext(chat_id,from_user)
    context['search_type'] = 'text'
    storeContext(chat_id,from_user,context,action='doTextSearchEncounter')
    doSearchEncounter(chat_id,context)
Beispiel #6
0
def showFitRoomResults(chat_id, from_user, context):
    """ Sends picture messages through kik using results from Fitroom
    args: chat_id
          from_user
          responseFromAPI:  json from fitroom
    returns:
          responseFromAPI: removed dead image links
    """

    responseFromAPI = context['image_query_result']
    # clean up resuts, lots of duplicates in results....
    result_image_urls = [
        value['imageUrl'] for value in responseFromAPI['images']
    ]

    image_query_result_index = int(context['image_query_result_index'])
    i = 0
    if image_query_result_index + SHOW_THIS_MANY >= len(result_image_urls):
        say(
            chat_id, context,
            "Well, maybe not. Gosh, you're hard to please :/ Try sending me back a pic of something I've showed you already to keep looking."
        )
        return responseFromAPI
    urls = []
    titles = []
    for an_image in result_image_urls[image_query_result_index:]:
        if i >= SHOW_THIS_MANY:
            break
        # some images are blank, they have exactly 5086 or 3084 bytes. This hack
        # skips any images that size. Hacky fix until they fix it on the backend.
        is_blank = requests.head(an_image,
                                 headers={'Accept-Encoding': 'identity'})
        if is_blank.status_code != 200 or is_blank.headers[
                'content-length'] in ('5086', '3084'):
            responseFromAPI['images'].pop(i)
            continue

        urls.append(an_image)
        titles.append(responseFromAPI['images'][i]['title'])
        print an_image, responseFromAPI['images'][i]['pageUrl']
        i += 1
    dispatchMessage(context,
                    'image',
                    chat_id,
                    from_user,
                    urls,
                    suggested_responses=titles)

    context[
        'image_query_result_index'] = i + image_query_result_index  # remember which results we've showed
    context['image_query_result'] = responseFromAPI
    storeContext(chat_id, from_user, context, action='showFitroomResults')
    if context['platform'] == 'KIK':
        selectAnImageMsg(chat_id, context)
        return responseFromAPI
Beispiel #7
0
def index_kik():
    """
    Main entry point for Kik POSTing to us.
    Get messages in batches an iter through each message, deciding what to do
    """
    # Make sure it's Kik sending us messages
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
                                request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        context0 = {'from_user': message.from_user, 'chat_id': message.chat_id}
        # Respond to mentions: we must send only one batch of messages
        if message.mention is not None:
            say(
                message.chat_id, context0,
                "Whoah Whoah Whoah! One at a time please. Are you trying to overload my circuts?!"
            )
            continue
        # check to see if we've seen this user before, collect their previous context
        if retrieveContext(message.chat_id, message.from_user):
            context0 = retrieveContext(message.chat_id, message.from_user)
        context0['platform'] = 'KIK'
        if isinstance(message, TextMessage):
            storeContext(message.chat_id,
                         message.from_user,
                         context0,
                         msg=message.body)
            selectActionFromText(message.chat_id, message.from_user,
                                 message.body, context0)
        elif isinstance(message, PictureMessage):
            # Always do a fitroom search when we get a picture message
            context0['user_img_url'] = message.pic_url
            context0['search_type'] = 'image'
            storeContext(message.chat_id, message.from_user, context0)
            doSearchEncounter(message.chat_id, context0)

        elif isinstance(message, StartChattingMessage):
            # User has started a chart for the first time; this is sent only once every for each user
            sendWelcomeMessage(message.chat_id, context0)
        else:
            # don't know how to respond to other messages e.g. videos
            say(
                message.chat_id, context0,
                "I'm new here. I'll be learning as I'm going. Try sending me a pic of a dress you'd like to search for"
            )

    return Response(
        status=200
    )  # If we return anything besides 200, Kik will try 3 more time to send the message
Beispiel #8
0
def showShopStyleResults(chat_id, from_user, context):
    api_json = context['text_query_result']
    result_image_urls = [
        value['image']['sizes']['IPhone']['url']
        for value in api_json['products']
    ]

    text_query_result_index = int(context['text_query_result_index'])
    i = 0
    if text_query_result_index + SHOW_THIS_MANY >= len(result_image_urls):
        message = "Well, maybe not. Gosh, you're hard to please :/ Try sending me back a pic of something I've showed you already to keep looking."
        sendSuggestedResponseHowTo(chat_id, from_user, message, context)
        return api_json
    urls = []
    titles = []
    for an_image in result_image_urls[text_query_result_index:]:
        if i >= SHOW_THIS_MANY:
            break
        title = api_json['products'][i]['brandedName']
        urls.append(an_image)
        titles.append(title)
        if context['platform'] == 'KIK':
            picture_message = PictureMessage(to=from_user,
                                             chat_id=chat_id,
                                             pic_url=an_image)
            picture_message.attribution = CustomAttribution(name=title)
            kik.send_messages([picture_message])

        i += 1
    if context['platform'] == 'FB':
        dispatchMessage(context,
                        'image',
                        chat_id,
                        from_user,
                        urls,
                        suggested_responses=titles)
    context[
        'text_query_result_index'] = i + text_query_result_index  # remember which results we've showed
    context['text_query_result'] = api_json
    storeContext(chat_id, from_user, context, action='showShopStyleResults')
    if context['platform'] == 'KIK':
        selectAnImageMsg(chat_id, context)
        return api_json
Beispiel #9
0
def showFitRoomResults(chat_id,from_user,context):
    """ Sends picture messages through kik using results from Fitroom
    args: chat_id
          from_user
          responseFromAPI:  json from fitroom
    returns:
          responseFromAPI: removed dead image links
    """

    responseFromAPI = context['image_query_result'] 
        # clean up resuts, lots of duplicates in results....
    result_image_urls = [value['imageUrl'] for value in responseFromAPI['images']]

    
    image_query_result_index = int(context['image_query_result_index'])
    i=0
    if image_query_result_index+SHOW_THIS_MANY >= len(result_image_urls):
        say(chat_id,context,"Well, maybe not. Gosh, you're hard to please :/ Try sending me back a pic of something I've showed you already to keep looking.")
        return responseFromAPI
    urls=[]
    titles=[]
    for an_image in result_image_urls[image_query_result_index:]:
        if i >= SHOW_THIS_MANY:
            break
        # some images are blank, they have exactly 5086 or 3084 bytes. This hack
        # skips any images that size. Hacky fix until they fix it on the backend.
        is_blank =requests.head(an_image, headers={'Accept-Encoding': 'identity'})
        if is_blank.status_code != 200 or is_blank.headers['content-length'] in ('5086', '3084'):
            responseFromAPI['images'].pop(i)
            continue
        
        urls.append(an_image)
        titles.append(responseFromAPI['images'][i]['title'])
        print an_image, responseFromAPI['images'][i]['pageUrl']
        i +=1
    dispatchMessage(context,'image',chat_id,from_user,urls,suggested_responses=titles)
    
    context['image_query_result_index'] = i + image_query_result_index # remember which results we've showed
    context['image_query_result'] = responseFromAPI
    storeContext(chat_id,from_user,context,action='showFitroomResults')
    if context['platform'] == 'KIK':
        selectAnImageMsg(chat_id,context)
        return responseFromAPI
Beispiel #10
0
def index_kik():
    """
    Main entry point for Kik POSTing to us.
    Get messages in batches an iter through each message, deciding what to do
    """
    # Make sure it's Kik sending us messages
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
        return Response(status=403)
    
    messages = messages_from_json(request.json['messages'])

    for message in messages:
        context0 = {'from_user':message.from_user,'chat_id':message.chat_id}
        # Respond to mentions: we must send only one batch of messages
        if message.mention is not None: 
            say(message.chat_id,context0,"Whoah Whoah Whoah! One at a time please. Are you trying to overload my circuts?!")
            continue
        # check to see if we've seen this user before, collect their previous context
        if retrieveContext(message.chat_id,message.from_user):
            context0 = retrieveContext(message.chat_id,message.from_user)
        context0['platform'] = 'KIK'
        if isinstance(message, TextMessage):
            storeContext(message.chat_id,message.from_user,context0,msg=message.body)
            selectActionFromText(message.chat_id,message.from_user,message.body,context0)
        elif isinstance(message, PictureMessage):
            # Always do a fitroom search when we get a picture message
            context0['user_img_url'] = message.pic_url
            context0['search_type'] = 'image'
            storeContext(message.chat_id,message.from_user,context0)
            doSearchEncounter(message.chat_id, context0)
        
        elif isinstance(message, StartChattingMessage):
            # User has started a chart for the first time; this is sent only once every for each user
            sendWelcomeMessage(message.chat_id,context0)
        else:
            # don't know how to respond to other messages e.g. videos
            say(message.chat_id,context0,"I'm new here. I'll be learning as I'm going. Try sending me a pic of a dress you'd like to search for")
             
    return Response(status=200) # If we return anything besides 200, Kik will try 3 more time to send the message
Beispiel #11
0
def index_fb():
    #    return Response(status=200)
    chat_id = None
    if request.method == 'GET':
        if request.args.get('hub.mode') == 'subscribe' and request.args.get(
                'hub.verify_token') == 'AnnaFashionBot':
            return Response(request.args.get('hub.challenge'), status=200)
    elif request.method == 'POST':
        output = request.json
        print output
        entires = output['entry']
        for entry in entires:
            for msg_obj in entry['messaging']:
                from_user = msg_obj['sender']['id']
                chat_id = from_user
                context0 = {'from_user': from_user, 'chat_id': chat_id}
                if retrieveContext(chat_id, from_user):
                    context0 = retrieveContext(chat_id, from_user)
                context0['platform'] = 'FB'
                if msg_obj.get('message') and msg_obj['message'].get(
                        'attachments'):
                    img_url = msg_obj['message'].get(
                        'attachments')[0]['payload']['url']
                    context0['user_img_url'] = img_url
                    context0['search_type'] = 'image'
                    storeContext(chat_id, from_user, context0)
                    doSearchEncounter(chat_id, context0)
                elif msg_obj.get('message') and msg_obj['message'].get('text'):
                    msg = msg_obj['message']['text']
                    storeContext(chat_id, from_user, context0, msg=msg)
                    selectActionFromText(chat_id, from_user, msg, context0)
                elif msg_obj.get('postback') and msg_obj['postback'].get(
                        'payload'):
                    msg = msg_obj['postback'].get('payload')
                    storeContext(chat_id, from_user, context0, msg=msg)
                    print msg
                    selectActionFromText(chat_id, from_user, msg, context0)
                else:
                    continue

        return Response(status=200)
    return Response(status=200)
Beispiel #12
0
def index_fb():
#    return Response(status=200)
    chat_id = None
    if request.method == 'GET':
        if request.args.get('hub.mode') == 'subscribe' and request.args.get('hub.verify_token') == 'AnnaFashionBot':
            return Response(request.args.get('hub.challenge'),status=200)
    elif request.method == 'POST':
        output = request.json
        print output
        entires = output['entry']
        for entry in entires:
            for msg_obj in entry['messaging']:
                from_user = msg_obj['sender']['id']
                chat_id = from_user
                context0 = {'from_user':from_user,'chat_id':chat_id}
                if retrieveContext(chat_id,from_user):
                    context0 = retrieveContext(chat_id,from_user)
                context0['platform'] = 'FB'
                if msg_obj.get('message') and msg_obj['message'].get('attachments'):
                    img_url = msg_obj['message'].get('attachments')[0]['payload']['url']
                    context0['user_img_url'] = img_url
                    context0['search_type'] = 'image'
                    storeContext(chat_id,from_user,context0)
                    doSearchEncounter(chat_id, context0)
                elif msg_obj.get('message') and msg_obj['message'].get('text'):
                    msg = msg_obj['message']['text']
                    storeContext(chat_id,from_user,context0,msg=msg)
                    selectActionFromText(chat_id,from_user, msg,context0)
                elif  msg_obj.get('postback')and msg_obj['postback'].get('payload'):
                    msg = msg_obj['postback'].get('payload')
                    storeContext(chat_id,from_user,context0,msg=msg)
                    print msg
                    selectActionFromText(chat_id,from_user, msg,context0)
                else:
                    continue

        return Response(status=200)
    return Response(status=200)