import requests
import json
import random
import time

def call_askbert(sentence, threshold=0.2, attribute=False):
    url = "http://localhost:5000/"
    #url = "http://localhost:8080"
    #port = random.randint(0, 4)
    #url += ":" + str(5000 + port)
    #try:
    response = requests.request("POST", url, data={"state": sentence, "threshold": threshold, "attribute": attribute})
    response = json.JSONDecoder().decode(response.text)
    # print("from askbert: {}".format(response))
    #except:
    #    return None
    #    print("AskBERT error")
    #   response = {"openie": []}
    return response

def set_batch_mode(batch_size):
    url = "http://localhost:8081/models"

    querystring = {"url": "albert.mar", "batch_size": batch_size, "max_batch_delay": "100", "initial_workers": "1"}

    response = requests.request("POST", url, params=querystring)

    print(response.text)


if __name__ == "__main__":
    import timeit


    def clean(s):
        garbage_chars = ['\n', '*', '-', '(', ')', '<', '>']
        for c in garbage_chars:
            s = s.replace(c, ' ')
        return s.strip().lower()
    #sent = "West of House You are standing in an open field west of a white house, with a boarded front door. There is a small mailbox here.   You are empty handed.  West of House You are standing in an open field west of a white house, with a boarded front door. There is a small mailbox here."
    #sent = "kitchen you are in the kitchen of the white house. a table seems to have been used recently for the preparation of food. a passage leads to the west and a dark staircase can be seen leading upward. a dark chimney leads down and to the east is a small window which is open. a bottle is sitting on the table. the glass bottle contains:   a quantity of water there is a brown sack here. the brown sack contains:   a lunch   [sep] you are carrying:   a nasty knife   a rope   a brass lantern  providing light    a clove of garlic   a jewel encrusted egg   [sep] kitchen a bottle is sitting on the table. the glass bottle contains:   a quantity of water there is a brown sack here. the brown sack contains:   a lunch"
    sent = "[loc]  lobby this is the entrance to the library. the circulation desk dominates the room, seemingly cobbled together over the course of several generations from an assortment of desks and tables. a pair of security gates stands before the front doors to prevent people from stealing books. a card catalog lurks in a dark and dusty corner of the room, seemingly cringing away from the harsh flourescent light. glass doors to the west lead to the book stacks; an archway to the northwest is labelled \"duplicating services\"; a door to the north bears a sign marked \"private\" in large friendly letters; and the exit is to the east  you can see a circulation desk attendant here. [inv] you are carrying:   an id card [obs]                                                             all quiet on the library front                                                  [please press space to begin.]                                                                                           every library should try to be complete                                             on something, if it were only the history                                             of pinheads.                                                                                               oliver wendell holmes,                                                  the poet at the breakfast table                                              you are a student at anycollege, in anytown, and it's the end of the semester!  you've been slacking off all semester long, and it's catching up to you. that final paper is due for your computer science class  \"the history of if games\" , and you desperately need to check out a comprehensive book on graham nelson, one of the foremost authors of the obscure genre of interactive fiction. you know there is exactly one such book, but you have no idea where it might be!   the first time player should probably type \"help\".  all quiet on the library front an interactive vignette release 2 / serial number 951204 / inform v1502 library 5/12 standard interpreter 1.0  lobby this is the entrance to the library. the circulation desk dominates the room, seemingly cobbled together over the course of several generations from an assortment of desks and tables. a pair of security gates stands before the front doors to prevent people from stealing books. a card catalog lurks in a dark and dusty corner of the room, seemingly cringing away from the harsh flourescent light. glass doors to the west lead to the book stacks; an archway to the northwest is labelled \"duplicating services\"; a door to the north bears a sign marked \"private\" in large friendly letters; and the exit is to the east  you can see a circulation desk attendant here. [atr] talkable, seen, lieable, enterable, nodwarf, indoors, visited, handed, lockable, surface, thing, water_room, unlock, lost, afflicted, is_treasure, converse, mentioned, male, npcworn, no_article, relevant, scored, queryable, town, pluggable, happy, is_followable, legible, multitude, burning, room, clothing, underneath, ward_area, little, intact, animate, bled_in, supporter, readable, openable, near, nonlocal, door, plugged, sittable, toolbit, vehicle, light, lens_searchable, open, familiar, is_scroll, aimable, takeable, static, unique, concealed, vowelstart, alcoholic, bodypart, general, is_spell, full, dry_land, pushable, known, proper, inside, clean, ambiguously_plural, container, edible, treasure, can_plug, weapon, is_arrow, insubstantial, pluralname, transparent, is_coin, air_room, scenery, on, is_spell_book, burnt, burnable, auto_searched, locked, switchable, absent, rockable, beenunlocked, progressing, severed, worn, windy, stone, random, neuter, legible, female, asleep, wiped"
    #resp = call_askbert(clean(sent))
    #exit()
    set_batch_mode(16)
    #exit()
    #time.sleep(10)
    sents = [sent] * 16

    from glob import glob
    import multiprocessing
    from functools import partial

    #multiprocessing.set_start_method('spawn')
    manager = multiprocessing.Manager()  # create SyncManager
    matches = manager.list()  # create a shared list here
    link_matches = partial(call_askbert, matches)  # create one arg callable to
    # pass to pool.map()
    pool = multiprocessing.Pool(processes=16)

    # exit()
    d = timeit.default_timer()
    pool.map(call_askbert, sents)  # apply partial to files list
    pool.close()
    pool.join()
    print("total", timeit.default_timer() - d)
