Exemplo n.º 1
0
def get_vector(folder, file):
    f = open(folder + file, "r")
    embeddings_data = f.read()

    api = API(user_key="", service_url="http://localhost:8181/rest/v1/")
    params = DocumentParameters()
    params["content"] = embeddings_data

    try:
        vector = api.text_embedding(params)
        save_vector(file, vector, "doc", "")
    except RosetteException as exception:
        print(exception)
    except:
        print('unkown error in get vector')

    try:
        sentences = api.sentences(params)
        sentences = sentences.get('sentences')
        for x in sentences:
            params["content"] = x
            sentence_vector = api.text_embedding(params)
            save_vector(file, sentence_vector, "sen", x)
    except RosetteException as exception:
        print(exception)
    except:
        print('unkown sentence error')
Exemplo n.º 2
0
def run(key, alt_url='https://api.rosette.com/rest/v1/'):
    """ Run the example """
    # Create default file to read from
    temp_file = tempfile.NamedTemporaryFile(suffix=".html")
    sentiment_file_data = "<html><head><title>New Ghostbusters Film</title></head><body><p>Original Ghostbuster Dan Aykroyd, who also co-wrote the 1984 Ghostbusters film, couldn’t be more pleased with the new all-female Ghostbusters cast, telling The Hollywood Reporter, “The Aykroyd family is delighted by this inheritance of the Ghostbusters torch by these most magnificent women in comedy.”</p></body></html>"
    message = sentiment_file_data
    temp_file.write(
        message if isinstance(message, bytes) else message.encode())
    temp_file.seek(0)

    # Create an API instance
    api = API(user_key=key, service_url=alt_url)
    # Set selected API options.
    # For more information on the functionality of these
    # and other available options, see Rosette Features & Functions
    # https://developer.rosette.com/features-and-functions#sentiment-analysis

    # api.set_option('modelType','dnn') #Valid for English only

    params = DocumentParameters()
    params["language"] = "eng"

    # Use an HTML file to load data instead of a string
    params.load_document_file(temp_file.name)
    try:
        result = api.sentiment(params)
    except RosetteException as exception:
        print(exception)
    finally:
        # Clean up the file
        temp_file.close()

    return result
Exemplo n.º 3
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)
    embeddings_data = "Cambridge, Massachusetts"
    params = DocumentParameters()
    params["content"] = embeddings_data
    return api.text_embedding(params)
Exemplo n.º 4
0
def main(argv):
       
    parser = argparse.ArgumentParser(description='Template for storing/analyzing responses from Rosette APIs')
    parser.add_argument('-k', '--key', required=True, help="rosette api key")
    args = parser.parse_args()

    # initialize
    rosette = ""
    
    print "trytext.py: starting up..."
    
    ##########
    # extract text from the file
    sText = "\"Gigli\" -- which spawned the phenomenon the gossip pages and celebrity magazines so lovingly refer to as \"Bennifer\" -- is every bit as unwatchable as the deafening negative chatter would suggest. The dialogue from writer-/sdirector Martin Brest is clunky, the film has serious tonal inconsistencies and at more than two hours, it drags on way longer than it should. Even making a little game of it, and trying to pinpoint the exact moment when Ben Affleck and Jennifer Lopez fell in love, stops being fun after a while. Perhaps it\'s when he says, in an attempt to seduce her, \"I\'m the bull, you\'re the cow.\" Or when she beckons him into foreplay by lying back in bed and purring, \"Gobble, gobble\" -- which could forever change the way you view your Thanksgiving turkey. But as pop-star vehicles go, \"Gigli\" isn\'t as insufferable as, say, last year\'s Madonna-Guy Ritchie debacle, \"Swept Away.\" It\'s more on par with Mariah Carey\'s \"Glitter\" and Britney Spears\' \"Crossroads.\" If this were a movie starring two B-list actors, or two complete unknowns, it probably would have gone straight to video. After curious masochists and J.Lo fans check it out the first weekend, \"Gigli\" probably will have a drop-off in audience that rivals \"The Hulk\" -- 70 percent -- then go to video. And with the release next spring of Kevin Smith\'s \"Jersey Girl,\" in which they also co-star, we can have this little conversation all over again. For now, we have Affleck starring as incompetent mob thug Larry Gigli. (That\'s pronounced JEE-lee, which rhymes with really, a running joke that isn\'t particularly funny the first time.) Gigli is asked to kidnap Brian (Justin Bartha), the mentally disabled younger brother of a/sfederal prosecutor who\'s going after a New York mobster (Al Pacino). His boss, however, thinks he\'s incapable of handling the assignment alone and sends in Ricki (Lopez), another contractor, to help him. Gigli is an anti-social lout who lives in a seedy apartment. Ricki is beautiful, grounded, enlightened. She quotes Sun Tzu -- who could blame Gigli for falling for her? (And whether you like her or not, Lopez does have an undeniable presence.) But Ricki is also a lesbian -- so it makes absolutely no sense when she falls for him, too, although they have all the obligatory banter and alleged sexual tension required of a romantic comedy. (And it\'s only a romantic comedy sometimes. Other times, it aims to be an edgy action-crime movie; still other times, it aspires for gag-inducing poignancy.) Apparently, the only force that binds them is the fact that they both feel squeamish about cutting off Brian\'s thumb and mailing it to his prosecutor brother. Instead, they break into a morgue and saw the thumb off a corpse using a plastic knife, while Brian -- who has an unexplained penchant for old-school rap -- sings Sir Mix-a-Lot\'s \"Baby Got Back.\" It\'s also incredibly misinformed to suggest that Ricki can be \"converted\" to heterosexuality -- that a man\'s love is all she really needed to allay any confusion about all that silly lesbian stuff. So what you have here is \"Rain Man\" meets \"Chasing Amy\" -- which is apropos, since the latter is a 1997 Kevin Smith movie in which Affleck also starred as a guy who falls for a lesbian. Instead of counting matches and obsessing about \"The People\'s Court\" like Dustin Hoffman\'s \"Rain Man\" character, Brian counts sunflower seeds and obsesses over going to \"the Baywatch.\" Cameos from Pacino, Christopher Walken as a detective and Lainie Kazan as Gigli\'s mother don\'t help, either. Did they owe someone a favor? What are they doing here? Pacino won his one and only Oscar with Brest for 1992\'s \"Scent of a Woman,\" but couldn\'t he have just thanked the director instead? Instead, we get to see Pacino shoot someone in the head, then watch as fish in a nearby aquarium snack on splattered drops of the victim\'s blood."
    ##########
    # to do: strip ascii etc?
    # connect to rosette 
    if not rosette:
        rosette = API(user_key=args.key)
        params = DocumentParameters()
    # send the text
    params['content'] = sText
    jResponse = rosette.entities(params)  # entity linking is turned off
    print json.dumps(jResponse, sort_keys=True, indent=4, separators=(',', ': '))
    jResponse = rosette.sentiment(params)  # entity linking is turned off
    print json.dumps(jResponse, sort_keys=True, indent=4, separators=(',', ': '))
     
    print "trytext.py: done"
Exemplo n.º 5
0
Arquivo: tt.py Projeto: OmkarB/pecan
def run(input, key=user_key, alt_url=ros_url):
    api = API(user_key=key, service_url=alt_url)
    content = ''.join(ch.lower() for ch in input if ch not in set(string.punctuation))
    params = DocumentParameters()
    params["content"] = content
    params["language"] = "eng"
    return api.morphology(params, MorphologyOutput.LEMMAS)
Exemplo n.º 6
0
Arquivo: tt.py Projeto: OmkarB/pecan
def proper_noun(key_word, key=user_key, alt_url=ros_url):
    api = API(user_key=key, service_url=alt_url)
    params = DocumentParameters()
    params["content"] = key_word
    params["language"] = "eng"
    api = api.morphology(params, MorphologyOutput.PARTS_OF_SPEECH)
    return "PROP" in str(json.loads(json.dumps(api, indent=2, ensure_ascii=False)))
Exemplo n.º 7
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    params = DocumentParameters()
    params["content"] = u"Last month director Paul Feig announced the movie will have an all-star female cast including Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon."
    return api.entities(params, True)  # entity linking is turned on
Exemplo n.º 8
0
def test_debug():
    # Doesn't really matter what it returns for this test, so just making sure it catches all of them
    endpoints = ["categories", "entities", "entities/linked", "language", "matched-name", "morphology-complete",
                 "sentiment", "translated-name", "relationships"]
    expected_status_filename = response_file_dir + "eng-sentence-entities.status"
    expected_output_filename = response_file_dir + "eng-sentence-entities.json"
    for rest_endpoint in endpoints:
        httpretty.register_uri(httpretty.POST, "https://api.rosette.com/rest/v1/" + rest_endpoint,
                               status=get_file_content(expected_status_filename),
                               body=get_file_content(expected_output_filename),
                               content_type="application/json")

    with open(expected_output_filename, "r") as expected_file:
        expected_result = json.loads(expected_file.read())

    # need to mock /info call too because the api will call it implicitly
    with open(response_file_dir + "info.json", "r") as info_file:
        body = info_file.read()
        httpretty.register_uri(httpretty.GET, "https://api.rosette.com/rest/v1/info",
                               body=body, status=200, content_type="application/json")
        httpretty.register_uri(httpretty.POST, "https://api.rosette.com/rest/v1/info",
                               body=body, status=200, content_type="application/json")

    api = API("0123456789", debug=True)

    content = "He also acknowledged the ongoing U.S. conflicts in Iraq and Afghanistan, noting that he is the \"commander in chief of a country that is responsible for ending a war and working in another theater to confront a ruthless adversary that directly threatens the American people\" and U.S. allies."

    params = DocumentParameters()
    params.__setitem__("content", content)
    api.entities(params)

    # Check that the most recent querystring had debug=true
    assert httpretty.last_request().querystring == {'debug': ['true']}
Exemplo n.º 9
0
    def __init__(self):
        self.rosette_handle = API(user_key=self.API_KEY)
        # altUrl='https://api.rosette.com/rest/v1/'
        # OPTION: service_url=altUrl

        result = self.rosette_handle.ping()
        print("/ping: ", result)
Exemplo n.º 10
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    params = DocumentParameters()
    params["content"] = u"The quick brown fox jumped over the lazy dog. Yes he did."
    return api.morphology(params)
Exemplo n.º 11
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)
    entities_text_data = "Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a cameo in Boston this… http://dlvr.it/BnsFfS"
    params = DocumentParameters()
    params["content"] = entities_text_data
    return api.entities(params)  # entity linking is turned off
Exemplo n.º 12
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    params = DocumentParameters()
    params["content"] = u"北京大学生物系主任办公室内部会议"
    return api.morphology(params, MorphologyOutput.HAN_READINGS)
def runRosette(text, key, alt_url='https://api.rosette.com/rest/v1/'):
    """ Run the example """
    # Create default file to read from
    temp_file = tempfile.NamedTemporaryFile(suffix=".html")
    sentiment_file_data = "<html><head><title></title></head><body><p>" + text + "</p></body></html>"
    message = sentiment_file_data
    temp_file.write(
        message if isinstance(message, bytes) else message.encode())
    temp_file.seek(0)

    # Create an API instance
    api = API(user_key=key, service_url=alt_url)

    params = DocumentParameters()
    params["language"] = "eng"
    params["content"] = text

    # Use an HTML file to load data instead of a string
    #params.load_document_file(temp_file.name)
    try:
        result = api.sentiment(params)
        #print (result)
    except RosetteException as exception:
        print(exception)
    finally:
        # Clean up the file
        temp_file.close()

    return result
Exemplo n.º 14
0
def get_label(alt_url='https://api.rosette.com/rest/v1/',
              sentence="Default Sentence"):

    api = API(user_key=API_KEYS.ROSETTE_API_KEY, service_url=alt_url)
    params = DocumentParameters()
    label_set = set()
    final_response_list = []
    params["content"] = sentence
    params["language"] = "eng"
    # params["modelType"] = "dnn"
    try:
        response_dict = json.loads(json.dumps(
            api.sentiment(params)))["document"]
        response_list = []
        if str(response_dict["label"]) == "pos":
            response_list.append(
                ["POSITIVE", float(response_dict["confidence"])])
        elif str(response_dict["label"]) == "neg":
            response_list.append(
                ["NEGATIVE", float(response_dict["confidence"])])
        else:
            response_list.append(
                ["NEUTRAL", float(response_dict["confidence"])])
        # ["sentiment"]
        # print response_dict
        return response_list[0]
    except RosetteException as exception:
        print(exception)
Exemplo n.º 15
0
def get_label(alt_url='https://api.rosette.com/rest/v1/', sentence = "Default Sentence"):

    api = API(user_key=API_KEYS.ROSETTE_API_KEY, service_url=alt_url)
    params = DocumentParameters()
    label_set = set()
    final_response_list = []
    params["content"] = sentence
    params["language"] = "eng"
    try:
        response_dict = json.loads(json.dumps(api.categories(params)))["categories"]
        response_list = []
        for item in response_dict:
            response_list.append([str(item["label"]).replace("_", " "), float(item["confidence"])])

        response_list_sorted = sorted(response_list, key=getKey, reverse=True)

        for item in response_list_sorted:
            label = item[0]
            if not label in label_set:
                final_response_list.append(item)
                label_set.add(label)

        return final_response_list[:5]
    except RosetteException as exception:
        print(exception)
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    params = DocumentParameters()
    params["content"] = u"Rechtsschutzversicherungsgesellschaften"
    return api.morphology(params, MorphologyOutput.COMPOUND_COMPONENTS)
Exemplo n.º 17
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    params = DocumentParameters()
    params["content"] = u"The fact is that the geese just went back to get a rest and I'm not banking on their return soon"
    return api.morphology(params, MorphologyOutput.PARTS_OF_SPEECH)
Exemplo n.º 18
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create default file to read from
    f = tempfile.NamedTemporaryFile(suffix=".html")
    sentiment_file_data = "<html><head><title>New Ghostbusters Film</title></head><body><p>Original Ghostbuster Dan Aykroyd, who also co-wrote the 1984 Ghostbusters film, couldn’t be more pleased with the new all-female Ghostbusters cast, telling The Hollywood Reporter, “The Aykroyd family is delighted by this inheritance of the Ghostbusters torch by these most magnificent women in comedy.”</p></body></html>"
    message = sentiment_file_data
    f.write(message)
    f.seek(0)

    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    params = DocumentParameters()
    params["language"] = "eng"

    # Use an HTML file to load data instead of a string
    params.load_document_file(f.name)
    try:
        result = api.sentiment(params)
    except RosetteException as e:
        print(e)
    finally:
        # Clean up the file
        f.close()

    return result
Exemplo n.º 19
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)
    params = RelationshipsParameters()
    params["content"] = u"Bill Murray is in the new Ghostbusters film!"
    params["options"] = {"accuracyMode": "PRECISION"}
    return api.relationships(params)
Exemplo n.º 20
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    params = DocumentParameters()
    params["content"] = u"北京大学生物系主任办公室内部会议"
    return api.tokens(params)
Exemplo n.º 21
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)
    relationships_text_data = "Bill Gates, Microsoft's former CEO, is a philanthropist."
    params = DocumentParameters()
    params["content"] = relationships_text_data
    api.setOption('accuracyMode', 'PRECISION')
    return api.relationships(params)
Exemplo n.º 22
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    tokens_data = "北京大学生物系主任办公室内部会议"
    params = DocumentParameters()
    params["content"] = tokens_data
    return api.tokens(params)
Exemplo n.º 23
0
def vectorize_text(text, key, url='https://api.rosette.com/rest/v1/'):
    """
    Return the vector representation of the input text (as a list of floats).
    """
    api = API(user_key=key, service_url=url)
    params = DocumentParameters()
    params["content"] = text
    return api.text_embedding(params)["embedding"]
Exemplo n.º 24
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    params = DocumentParameters()

    params["content"] = u"Por favor Señorita, says the man."
    return api.language(params)
Exemplo n.º 25
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    morphology_compound_components_data = "Rechtsschutzversicherungsgesellschaften"
    params = DocumentParameters()
    params["content"] = morphology_compound_components_data
    return api.morphology(params, MorphologyOutput.COMPOUND_COMPONENTS)
Exemplo n.º 26
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)
    relationships_text_data = "The Ghostbusters movie was filmed in Boston."
    params = DocumentParameters()
    params["content"] = relationships_text_data
    api.setOption('accuracyMode', 'PRECISION')
    return api.relationships(params)
Exemplo n.º 27
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    params = NameMatchingParameters()
    params["name1"] = {"text": "Michael Jackson", "language": "eng", "entityType": "PERSON"}
    params["name2"] = {"text": "迈克尔·杰克逊", "entityType": "PERSON"}
    return api.matched_name(params)
Exemplo n.º 28
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    morphology_complete_data = "The quick brown fox jumped over the lazy dog. Yes he did."
    params = DocumentParameters()
    params["content"] = morphology_complete_data
    return api.morphology(params)
Exemplo n.º 29
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    syntax_dependencies_data = "Yoshinori Ohsumi, a Japanese cell biologist, was awarded the Nobel Prize in Physiology or Medicine on Monday."
    params = DocumentParameters()
    params["content"] = syntax_dependencies_data
    params["genre"] = "social-media"
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)
    return api.syntax_dependencies(params)
Exemplo n.º 30
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    try:
        return api.info()
    except RosetteException as e:
        print(e)
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    morphology_han_readings_data = "北京大学生物系主任办公室内部会议"
    params = DocumentParameters()
    params["content"] = morphology_han_readings_data
    return api.morphology(params, MorphologyOutput.HAN_READINGS)
Exemplo n.º 32
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    morphology_lemmas_data = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon"
    params = DocumentParameters()
    params["content"] = morphology_lemmas_data
    return api.morphology(params, MorphologyOutput.LEMMAS)
Exemplo n.º 33
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)
    entities_text_data = "Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a cameo in Boston this… http://dlvr.it/BnsFfS"
    params = DocumentParameters()
    params["content"] = entities_text_data
    params["genre"] = "social-media"
    return api.entities(params)
Exemplo n.º 34
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    params = DocumentParameters()
    params["content"] = u"This land is your land. This land is my land\nFrom California to the New York island;\nFrom the red wood forest to the Gulf Stream waters\n\nThis land was made for you and Me.\n\nAs I was walking that ribbon of highway,\nI saw above me that endless skyway:\nI saw below me that golden valley:\nThis land was made for you and me."

    return api.sentences(params)
Exemplo n.º 35
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    url = "Sony Pictures is planning to shoot a good portion of the new "Ghostbusters" in Boston as well."
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)
    params = DocumentParameters()

    # Use a URL to input data instead of a string
    params["contentUri"] = url
    return api.categories(params)
Exemplo n.º 36
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    sentences_data = "This land is your land. This land is my land\nFrom California to the New York island;\nFrom the red wood forest to the Gulf Stream waters\n\nThis land was made for you and Me.\n\nAs I was walking that ribbon of highway,\nI saw above me that endless skyway:\nI saw below me that golden valley:\nThis land was made for you and me."
    params = DocumentParameters()
    params["content"] = sentences_data

    return api.sentences(params)
Exemplo n.º 37
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    language_data = "Por favor Señorita, says the man."
    params = DocumentParameters()
    params["content"] = language_data
    api.setCustomHeaders("X-RosetteAPI-App", "python-app")
    return api.language(params)
Exemplo n.º 38
0
def run(key, alt_url='https://api.rosette.com/rest/v1/'):
    """ Run the example """
    # Create an API instance
    api = API(user_key=key, service_url=alt_url)

    try:
        return api.ping()
    except RosetteException as exception:
        print(exception)
Exemplo n.º 39
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    params = NameTranslationParameters()
    params["name"] = u"معمر محمد أبو منيار القذاف"
    params["entityType"] = "PERSON"
    params["targetLanguage"] = "eng"
    return api.translated_name(params)
Exemplo n.º 40
0
Arquivo: tt.py Projeto: OmkarB/pecan
def find_similar(key_word, key=user_key, alt_url=ros_url):
    api = API(user_key=key, service_url=alt_url)
    if len(key_word.split()) > 1:
        key_word = "_".join(key_word.split())
    params = DocumentParameters()
    params["content"] = key_word
    params["language"] = "eng"
    json_obj = json.loads(json.dumps(api.morphology(params, MorphologyOutput.LEMMAS),
                                     indent=2, ensure_ascii=False))
    return search_for(json_obj['lemmas'][0]['lemma'])
Exemplo n.º 41
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    entities_linked_text_data = "Last month director Paul Feig announced the movie will have an all-star female cast including Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon."
    params = DocumentParameters()
    params["content"] = entities_linked_text_data
    params["genre"] = "social-media"
    # This syntax is deprecated, call api.entities(params)
    return api.entities(params, True)
Exemplo n.º 42
0
def run(alt_url='https://api.rosette.com/rest/v1/', sentence = "Default Sentence"):

    api = API(user_key=API_KEYS.ROSETTE_API_KEY, service_url=alt_url)
    params = DocumentParameters()

    params["content"] = sentence
    try:
        return api.categories(params)
    except RosetteException as exception:
        print(exception)
Exemplo n.º 43
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    categories_url_data = "http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/"
    url = categories_url_data
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)
    params = DocumentParameters()

    # Use a URL to input data instead of a string
    params["contentUri"] = url
    return api.categories(params)
Exemplo n.º 44
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    matched_name_data1 = "Michael Jackson"
    matched_name_data2 = "迈克尔·杰克逊"
    params = NameSimilarityParameters()
    params["name1"] = {"text": matched_name_data1, "language": "eng", "entityType": "PERSON"}
    params["name2"] = {"text": matched_name_data2, "entityType": "PERSON"}
    return api.name_similarity(params)
Exemplo n.º 45
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    morphology_parts_of_speech_data = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon"
    params = DocumentParameters()
    params["content"] = morphology_parts_of_speech_data
    try:
        return api.morphology(params, MorphologyOutput.PARTS_OF_SPEECH)
    except RosetteException as e:
        print(e)
Exemplo n.º 46
0
def run(key, alt_url='https://api.rosette.com/rest/v1/'):
    """ Run the example """
    # Create an API instance
    api = API(user_key=key, service_url=alt_url)
    relationships_text_data = "FLIR Systems is headquartered in Oregon and produces thermal imaging, night vision, and infrared cameras and sensor systems.  According to the SEC’s order instituting a settled administrative proceeding, FLIR entered into a multi-million dollar contract to provide thermal binoculars to the Saudi government in November 2008.  Timms and Ramahi were the primary sales employees responsible for the contract, and also were involved in negotiations to sell FLIR’s security cameras to the same government officials.  At the time, Timms was the head of FLIR’s Middle East office in Dubai."
    params = DocumentParameters()
    params["content"] = relationships_text_data
    try:
        return api.relationships(params)
    except RosetteException as exception:
        print(exception)
Exemplo n.º 47
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    translated_name_data = "معمر محمد أبو منيار القذاف"
    params = NameTranslationParameters()
    params["name"] = translated_name_data
    params["entityType"] = "PERSON"
    params["targetLanguage"] = "eng"
    params["targetScript"] = "Latn"
    return api.name_translation(params)
Exemplo n.º 48
0
def run(key, alt_url='https://api.rosette.com/rest/v1/'):
    """ Run the example """
    syntax_dependencies_data = "Yoshinori Ohsumi, a Japanese cell biologist, was awarded the Nobel Prize in Physiology or Medicine on Monday."
    params = DocumentParameters()
    params["content"] = syntax_dependencies_data
    # Create an API instance
    api = API(user_key=key, service_url=alt_url)
    try:
        return api.syntax_dependencies(params)
    except RosetteException as exception:
        print(exception)
Exemplo n.º 49
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)
    relationships_text_data = "Bill Gates, Microsoft's former CEO, is a philanthropist."
    params = DocumentParameters()
    params["content"] = relationships_text_data
    api.setOption('accuracyMode', 'PRECISION')
    try:
        return api.relationships(params)
    except RosetteException as e:
        print(e)
Exemplo n.º 50
0
def run(key, alt_url='https://api.rosette.com/rest/v1/'):
    """ Run the example """
    # Create an API instance
    api = API(user_key=key, service_url=alt_url)
    embeddings_data = "Cambridge, Massachusetts"
    params = DocumentParameters()
    params["content"] = embeddings_data
    try:
        return api.text_embedding(params)
    except RosetteException as exception:
        print(exception)
Exemplo n.º 51
0
def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    morphology_han_readings_data = "北京大学生物系主任办公室内部会议"
    params = DocumentParameters()
    params["content"] = morphology_han_readings_data
    try:
        return api.morphology(params, api.morphology_output['HAN_READINGS'])
    except RosetteException as e:
        print(e)
Exemplo n.º 52
0
def test_retryNum():
    with open(response_file_dir + "info.json", "r") as info_file:
        body = info_file.read()
        httpretty.register_uri(httpretty.GET, "https://api.rosette.com/rest/v1/info",
                               body=body, status=500, content_type="application/json")
    test = API(user_key=None, retries=5)
    try:
        result = test.info()
        assert False
    except RosetteException as e:
        assert e.message == "A retryable network operation has not succeeded after 5 attempts"
        assert e.status == "unknownError"
Exemplo n.º 53
0
def test_the_max_pool_size(json_response, doc_params):
    httpretty.enable()
    httpretty.register_uri(httpretty.POST, "https://api.rosette.com/rest/v1/language",
                           body=json_response, status=200, content_type="application/json",
                           adding_headers={
                               'x-rosetteapi-concurrency': 5
                           })
    api = API('bogus_key')
    assert api.getPoolSize() == 1
    result = api.language(doc_params)
    assert result["name"] == "Rosette API"
    assert api.getPoolSize() == 5
    httpretty.disable()
    httpretty.reset()
Exemplo n.º 54
0
Arquivo: main.py Projeto: OmkarB/pecan
def get_wol(wol, key=user_key, alt_url=ros_url):
    lst = wol.split("|")
    lst.sort(key=lambda a: len(a))
    api = API(user_key=user_key, service_url=alt_url)
    params = DocumentParameters()
    params["language"] = "eng"
    rtotal = []
    for line in lst:
        params["content"] = line
        json_obj = json.loads(json.dumps(api.entities(params, True), indent=2, ensure_ascii=False))
        if json_obj["entities"] and len(rtotal) < 4:
            rtotal.append(line)
    result = "<ul> "
    for x in lst:
        result += "<li>" + x + "</li>"
    result += "</ul>"
    return result
Exemplo n.º 55
0
def wikipedia_summary(query, key=user_key, alt_url=ros_url):
    # Create an API instance
    api = API(user_key=key, service_url=alt_url)

    params = NameMatchingParameters()
    params['name1'] = query
    max = ['error', 0]
    for x in wikipedia.search(query):
        params["name2"] = x
        val = json.loads(json.dumps(api.matched_name(params), indent=2,
                                    ensure_ascii=False))['result']['score'] > max[1]
        if val > max[1]:
            max = [x, val]
    if max[0] != 'error':
        return wikipedia.summary(max[0])
    else:
        raise Exception("No wiki articles found")
Exemplo n.º 56
0
Arquivo: tt.py Projeto: OmkarB/pecan
def proper_key_words(key_word, key=user_key, alt_url=ros_url):
    # Create an API instance
    api = API(user_key=key, service_url=alt_url)

    params = NameMatchingParameters()
    params['name1'] = key_word
    max = ['error', 0]
    for x in wikipedia.search(key_word):
        params["name2"] = x
        val = json.loads(json.dumps(api.matched_name(params), indent=2,
                                    ensure_ascii=False))['result']['score'] > max[1]
        if val > max[1]:
            max = [x, val]
    params = DocumentParameters()
    params['content'] = wikipedia.summary(max[0])
    json_obj = json.loads(json.dumps(api.entities(params), indent=2, ensure_ascii=False,
                                     sort_keys=True))
    return parse_with_queue(json_obj, key_word)