NAV
shell Python PHP R Java Ruby C# JavaScript

Introduction

# This tab illustrates how to call that endpoint using cURL
# This tab illustrates how to call that endpoint using the Python binding

# The Python binding supports applications with Python 2.6 or greater
// This tab illustrates how to call that endpoint using the PHP binding
// This tab illustrates how to call that endpoint using the Java binding
# This tab illustrates how to call that endpoint using the R binding
# This tab illustrates how to call that endpoint using the Ruby binding
// This tab illustrates how to call that endpoint using the C# binding
// This tab illustrates how to call that endpoint using the Node.js binding

Welcome to the Rosette API suite of linguistic tools and services! With the Rosette API endpoints you can extract entities and relationships, translate and compare names, and analyze sentiment of documents and entities from large amounts of unstructured text.

The gray area on the right has code examples for each of the endpoints. You can switch the programming language of the examples by clicking the tab at the top.

GitHub Logo You can also get bindings from Github in Python, PHP, Java, Node.js, .NET/C#, Ruby, and R. If you’d rather not code, don’t miss our RapidMiner extension or community github.

Limits

All API plans allow customers to process one call (active HTTP connection) at a time. You can send a second call once you have received a response from the first. Contact us for greater concurrency.

The maximum payload size is 600KB, with a maximum character count of 50,000.

Inter-Version Compatibility and LABS Endpoints

In an effort to improve the accuracy and performance of our software we often make changes to our machine learned models. Occasionally, these adjustments may cause unexpected changes in the results our system outputs (e.g. the sentiment, entities and confidence reported by the system on a given document may change). Further, the statistical nature of our software means that the results produced by different versions of Rosette API will sometimes be incompatible or non-comparable. This is especially true for our “LABS” endpoints, which are experimental, new technology. They are subject to change at any time and should not be deployed in production without consulting Basis Technology support staff in advance.

Please let us know if you are caching, storing, indexing, or otherwise comparing results across versions so that we can provide timely warnings of non-comparable changes to Rosette API results and/or work with you to ensure a smooth migration between versions. We are also happy to discuss on-premise deployment options which can be shielded from upgrades and other changes. Get in touch with us at support@rosette.com.

Authentication


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Send ping to check for reachability of Rosette API"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();

var api = new Api(args.key, args.url);
var endpoint = "ping";

api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err)
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class ping
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //ping yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            }
            try
            {
                CAPI NewCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                //The results of the API call will come back in the form of a Dictionary
                PingResponse response = NewCAPI.Ping();
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

if (is.na(opt$url)){
   result <- api(opt$key, "ping")
} else {
   result <- api(opt$key, "ping", FALSE, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end
begin
  response = rosette_api.ping
  puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
  printf('Rosette API Error (%s): %s', rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.PingResponse;

import java.io.IOException;

public final class PingExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new PingExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder().key(getApiKeyFromSystemProperty()).url(getAltUrlFromSystemProperty()).build();
        PingResponse response = rosetteApi.ping();
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}

$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);

try {
    $result = $api->ping();
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, RosetteException


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.ping()
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))

curl "https://api.rosette.com/rest/v1/ping" -H 'X-RosetteAPI-Key: [your_api-key]'

Ping returns a language specific data structure that represents the following JSON from Rosette API


{
  "message": "Rosette API at your service",
  "time": 1498152252884,
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:12 GMT, Thu, 22 Jun 2017 17:24:12 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "f0077632-56d2-4531-a08f-0461abcd51af",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

Rosette uses API keys to allow access to the API. You can authenticate and send a ping with the same code.

You can find your Rosette API key on the Developer Portal, or Sign Up for a new API key.

Include your API key in all API requests to the server in a header:

X-RosetteAPI-Key="[your_api-key]"

Transliteration [Labs New]

Introduction


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
    addHelp: true,
    description: "Get the transliteration from a piece of text"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();

var api = new Api(args.key, args.url);
var endpoint = "transliteration";

var transliteration_data = "ana r2ye7 el gam3a el sa3a 3 el 3asr";

api.parameters.content = transliteration_data;

api.rosette(endpoint, function(err, res) {
    if (err) {
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class transliteration
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //matched_name yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            }
            try
            {
                CAPI rosetteApi = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string transliteration_data = "ana r2ye7 el gam3a el sa3a 3 el 3asr";
                string transliteration_language_data = "Por favor Señorita, says the man.";

                //The results of the API call will come back in the form of a Dictionary
                TransliterationResponse response = rosetteApi.Transliteration(transliteration_data, transliteration_language_data);

                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

transliteration_data <- "ana r2ye7 el gam3a el sa3a 3 el 3asr"

parameters <- list()
parameters[[ "content" ]] <- transliteration_data

if (is.na(opt$url)){
   result <- api(opt$key, "transliteration", parameters)
} else {
   result <- api(opt$key, "transliteration", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

transliteration_content_data = 'Kareem Abdul Jabbar holds the records for most points in the NBA'

begin
  params = DocumentParameters.new
  params.content = transliteration_content_data
  response = rosette_api.get_transliteration(params)
  puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
  printf('Rosette API Error (%s): %s', rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.TransliterationOptions;
import com.basistech.rosette.apimodel.TransliterationResponse;
import com.basistech.util.LanguageCode;

import java.io.IOException;

public class TransliterationExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new TransliterationExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String transliterationData = "ana r2ye7 el gam3a el sa3a 3 el 3asr";

        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                .key(getApiKeyFromSystemProperty())
                .url(getAltUrlFromSystemProperty())
                .build();
        // The API object creates an HTTP client, but to provide your own:
        // HttpRosetteAPI.Builder#httpClient(CloseableHttpClient)
        DocumentRequest<TransliterationOptions> request = new DocumentRequest.Builder<TransliterationOptions>()
                .content(transliterationData)
                .language(LanguageCode.ARABIC)
                .build();
        TransliterationResponse response = rosetteApi.perform(HttpRosetteAPI.TRANSLITERATION_SERVICE_PATH, request, TransliterationResponse.class);
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$transliteration_data = "ana r2ye7 el gam3a el sa3a 3 el 3asr";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$params->set('content', $transliteration_data);

try {
    $result = $api->transliteration($params);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, DocumentParameters, RosetteException


def run(key, altUrl='https://api.rosette.com/rest/v1/'):
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)

    transliteration_data = "ana r2ye7 el gam3a el sa3a 3 el 3asr"
    params = DocumentParameters()
    params["content"] = transliteration_data

    try:
        return api.transliteration(params)
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"content": "ana r2ye7 el gam3a el sa3a 3 el 3asr" }' \
    "https://api.rosette.com/rest/v1/transliteration"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "transliteration": "كريم عبدالجبار هلدس ذي ريكوردس فر مست بوينتس إن ذي نبا",
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:14 GMT, Thu, 22 Jun 2017 17:24:14 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "821c5431-b534-4abd-a48d-22fb1fef8936",
    "x-rosetteapi-processedlanguage": "eng",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-processedby": "whole-document-language@10.1.1.171,arabic-chat-transliterator@10.1.1.171",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Transliteration REST endpoint is https://api.rosette.com/rest/v1/transliteration

Rosette can transliterate Arabic written in Arabizi or Romanized Arabic chat alphabet to native Arabic script and vice versa. Arabizi is a casual version of Arabic written using just the ASCII characters on Western keyboards on mobile phones and computers.

To transliterate from native Arabic script to Arabizi, add "options":{"reversed":"true"} to your parameters.

Know what your language is?

Transliteration is only supported for Arabic, so Rosette ignores the language field and assumes the language is Arabic.

Language Support

Rosette ignores the language field and assumes the input language is Arabic.

Language (code)

Sentiment Analysis

Introduction


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;
var tmp = require("temporary");

var parser = new ArgumentParser({
  addHelp: true,
  description: "Get the sentiment of the text in a local file"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();

var file = new tmp.File();
var 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>";
var fileContents = sentiment_file_data;

file.writeFileSync(fileContents);

var api = new Api(args.key, args.url);
var endpoint = "sentiment";

api.parameters.documentFile = file.path;
api.parameters.language = "eng";

api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class sentiment
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //sentiment yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            }

            try
            {
                CAPI SentimentCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                var newFile = Path.GetTempFileName();
                StreamWriter sw = new StreamWriter(newFile);
                string 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>";
                sw.WriteLine(sentiment_file_data);
                sw.Flush();
                sw.Close();
                //Rosette API provides File upload options (shown here)
                //Simply create a new RosetteFile using the path to a file
                //The results of the API call will come back in the form of a Dictionary
                SentimentResponse response = SentimentCAPI.Sentiment(new RosetteFile(newFile, @"application/octet-stream", "{\"language\":\"eng\"}"));
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());

                if (File.Exists(newFile)) {
                    File.Delete(newFile);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

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>"

parameters <- list()
parameters[[ "content" ]] <- sentiment_file_data
parameters[[ "documentFile" ]] <- "true"

if (is.na(opt$url)){
   result <- api(opt$key, "sentiment", parameters)
} else {
   result <- api(opt$key, "sentiment", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'tempfile'
require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

file = Tempfile.new(%w[foo .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>"
file.write(sentiment_file_data)
file.close
begin
  params = DocumentParameters.new(file_path: file.path, language: 'eng')
  response = rosette_api.get_sentiment(params)
  puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
  printf('Rosette API Error (%s): %s', rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.SentimentOptions;
import com.basistech.rosette.apimodel.SentimentResponse;

import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public final class SentimentExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new SentimentExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        // the temp file substitutes for an actual disk file.
        String sentimentFileData = "<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>";
        try (InputStream inputStream = Files.newInputStream(createTempDataFile(sentimentFileData))) {
            HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                    .key(getApiKeyFromSystemProperty())
                    .url(getAltUrlFromSystemProperty())
                    .build();
            //The api object creates an http client, but to provide your own:
            //api.httpClient(CloseableHttpClient)
            // When no options, use <?>.
            DocumentRequest<SentimentOptions> request = new DocumentRequest.Builder<SentimentOptions>().contentBytes(inputStream, "text/html").build();
            SentimentResponse response = rosetteApi.perform(HttpRosetteAPI.SENTIMENT_SERVICE_PATH, request, SentimentResponse.class);
            System.out.println(responseToJson(response));
        }

    }

    private static Path createTempDataFile(String data) throws IOException {
        Path file = Files.createTempFile("example.", ".html");
        try (Writer writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
            writer.write(data);
        }
        file.toFile().deleteOnExit();
        return file;
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$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>";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$params->set('language', 'eng');
$content = $sentiment_file_data;
$temp = tmpfile();  // write above html content to a temp file
fwrite($temp, $content);
$params->loadDocumentFile(stream_get_meta_data($temp)['uri']);

try {
    $result = $api->sentiment($params);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
} finally {
    fclose($temp);  // clean up the temp file
}


import argparse
import json
import os
import tempfile

from rosette.api import API, DocumentParameters, RosetteException


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


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"content": "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.”" }' \
    "https://api.rosette.com/rest/v1/sentiment"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "document": {
    "label": "pos",
    "confidence": 0.7962072011038756
  },
  "entities": [
    {
      "type": "PRODUCT",
      "mention": "Ghostbusters",
      "normalized": "Ghostbusters",
      "count": 3,
      "entityId": "Q108745",
      "sentiment": {
        "label": "pos",
        "confidence": 0.8111117726721541
      }
    },
    {
      "type": "PERSON",
      "mention": "Aykroyd",
      "normalized": "Original Ghostbuster Dan Aykroyd",
      "count": 2,
      "entityId": "Q105221",
      "confidence": 0.9990000128746033,
      "sentiment": {
        "label": "pos",
        "confidence": 0.6504190808944779
      }
    },
    {
      "type": "ORGANIZATION",
      "mention": "The Hollywood Reporter",
      "normalized": "The Hollywood Reporter",
      "count": 1,
      "entityId": "Q61503",
      "sentiment": {
        "label": "pos",
        "confidence": 0.5338094035254866
      }
    }
  ],
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:13 GMT, Thu, 22 Jun 2017 17:24:13 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "ff6c1b59-9f51-4d54-a593-6b011188ab4e",
    "x-rosetteapi-processedlanguage": "eng",
    "x-rosetteapi-stats-admentitymentioncount": "6",
    "x-rosetteapi-stats-admentitycount": "3",
    "x-rosetteapi-stats-admscriptregioncount": "1",
    "x-rosetteapi-stats-admsentencecount": "1",
    "x-rosetteapi-stats-requestlanguage": "eng",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-docsizesourcerawbytes": "392",
    "x-rosetteapi-stats-docsizechars": "303",
    "x-rosetteapi-stats-admresolvedentitycount": "3",
    "x-rosetteapi-stats-admtokencount": "55",
    "x-rosetteapi-stats-processedby": "text-extractor@10.1.1.171,entity-extraction@10.1.1.171,sentiment@10.1.1.171",
    "x-rosetteapi-stats-requesttextextraction": "true",
    "x-rosetteapi-stats-content-type": "text/html; charset=UTF-8",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Sentiment REST endpoint is: https://api.rosette.com/rest/v1/sentiment

Rosette analyzes the sentiment (subjective attitude) of the input as positive (pos), negative (neg), or neutral (neu). Given the input we return a sentiment label with a confidence score between 0 and 1.

When Rosette detects entities within your input, it also returns the sentiment for each unique entity in the document. It groups all of the relevant sentiment about that entity into one mention, identified by its entity ID.

Before analyzing, Rosette filters out some stop words and punctuation, such as “the” “?” “a” “it”, to increase the accuracy of the assessment.

Know what your language is?

If you know the language of your input, include the three-letter language code in your call to speed up the response time.

Otherwise, Rosette identifies the language of your input.

Language Support

Language (code)

You can specify the language of your input with the three-letter language code. If you do not specify the language then Rosette automatically detects it.

Categorization

Introduction


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Get the category of a piece of a document at a URL"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();
var api = new Api(args.key, args.url);
var endpoint = "categories";

var categories_url_data = "http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/";
api.parameters.contentUri = categories_url_data;

api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class categories
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //categories yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            }
            try
            {
                CAPI CategoriesCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string categories_text_data = @"Sony Pictures is planning to shoot a good portion of the new ""Ghostbusters"" in Boston as well.";
                //The results of the API call will come back in the form of a Dictionary
                CategoriesResponse response = CategoriesCAPI.Categories(categories_text_data,  null, null, null);
                Console.WriteLine(response.ContentAsJson);

                //Rosette API also supports Dictionary inputs
                //Simply instantiate a new dictionary object with the fields options as keys and inputs as values
                string categories_url_data = @"http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/";
                response = CategoriesCAPI.Categories(new Dictionary<object, object>()
                {
                    {"contentUri", categories_url_data}

                });
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

categories_url_data <- "http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/"

parameters <- list()
parameters[[ "contentUri" ]] <- categories_url_data

if (is.na(opt$url)){
   result <- api(opt$key, "categories", parameters)
} else {
   result <- api(opt$key, "categories", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

categories_url_data = "http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/"
begin
  params = DocumentParameters.new(content_uri: categories_url_data)
  response = rosette_api.get_categories(params)
  puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
  printf('Rosette API Error (%s): %s', rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.CategoriesOptions;
import com.basistech.rosette.apimodel.CategoriesResponse;
import com.basistech.rosette.apimodel.DocumentRequest;

import java.io.IOException;

public final class CategoriesExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new CategoriesExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String categoriesUrlData = "http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/";
        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                                .key(getApiKeyFromSystemProperty())
                                .url(getAltUrlFromSystemProperty())
                                .build();
        //The api object creates an http client, but to provide your own:
        //api.httpClient(CloseableHttpClient)
        DocumentRequest<CategoriesOptions> request = new DocumentRequest.Builder<CategoriesOptions>().contentUri(categoriesUrlData).build();
        CategoriesResponse response = rosetteApi.perform(HttpRosetteAPI.CATEGORIES_SERVICE_PATH, request, CategoriesResponse.class);
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$categories_url_data = "http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$params->set('contentUri', $categories_url_data);

try {
    $result = $api->categories($params);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, DocumentParameters, RosetteException


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
    try:
        return api.categories(params)
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"contentUri": "http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/" }' \
    "https://api.rosette.com/rest/v1/categories"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "categories": [
    {
      "label": "ARTS_AND_ENTERTAINMENT",
      "confidence": 0.23572849069656435
    }
  ],
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:10 GMT, Thu, 22 Jun 2017 17:24:10 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "88fbadaa-597b-4920-bdcf-a1b34a9b4343",
    "x-rosetteapi-processedlanguage": "eng",
    "x-rosetteapi-stats-admsentencecount": "8",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-docsizesourcerawbytes": "69510",
    "x-rosetteapi-stats-docsizechars": "616",
    "x-rosetteapi-stats-admtokencount": "120",
    "x-rosetteapi-stats-processedby": "url-content-downloader@10.1.1.171,text-extractor@10.1.1.171,whole-document-language@10.1.1.171,base-linguistics@10.1.1.171,categorization@10.1.1.171",
    "x-rosetteapi-stats-requestcontenturi": "true",
    "x-rosetteapi-stats-requesttextextraction": "true",
    "x-rosetteapi-stats-content-type": "text/html; charset=UTF-8",
    "x-rosetteapi-stats-admscriptregioncount": "1",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Categorization REST endpoint is: https://api.rosette.com/rest/v1/categories

Based on its analysis of the content of a string in English, the Rosette categorizer recognizes the following contextual categories:

Categories
Arts & Entertainment Travel
Business Automotive
Education Careers
Food & Drink Family & Parenting
Hobbies & Interests Health & Fitness
Law, Gov’t & Politics Home & Garden
Personal Finance Pets
Real Estate Religion & Spirituality
Science Sports
Society Technology & Computing
Style & Fashion

These are based on the Tier 1 contextual categories defined by the IAB Quality Assurance Guidelines (QAG) Taxonomy.

Before analyzing, Rosette filters out some stop words and punctuation, such as “the” “?” “a” “it”, to increase the accuracy of the analysis.

Confidence

Rosette returns a confidence score with the category result, ranging from 0 to 1. It is a measurement that you can use as a threshold for filtering out undesired results.

Language Support

The Rosette categorization endpoint currently only supports English language input.

Relationship Extraction [labs]

Introduction


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
    addHelp: true,
    description: "Get the relationships from a piece of text"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();

var api = new Api(args.key, args.url);
var endpoint = "relationships";

var 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.";
var content = relationships_text_data;

api.parameters.content = content;
api.parameters.options = { "accuracyMode": "PRECISION" };

api.rosette(endpoint, function(err, res) {
    if (err) {
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class relationships
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //relationships yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            }
            try
            {
                CAPI RelationshipsCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string 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.";
                //The results of the API call will come back in the form of a Dictionary
                RelationshipsResponse response = RelationshipsCAPI.Relationships(relationships_text_data);
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

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."

parameters <- list()
parameters[[ "content" ]] <- relationships_text_data

if (is.na(opt$url)){
   result <- api(opt$key, "relationships", parameters)
} else {
   result <- api(opt$key, "relationships", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

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."
begin
  params = DocumentParameters.new(content: relationships_text_data)
  params.rosette_options = { accuracyMode: 'PRECISION' }
  response = rosette_api.get_relationships(params)
  puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
  printf('Rosette API Error (%s): %s', rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.LanguageOptions;
import com.basistech.rosette.apimodel.RelationshipsResponse;

import java.io.IOException;

public final class RelationshipsExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new RelationshipsExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String relationshipsTextData = "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.";

        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                .key(getApiKeyFromSystemProperty())
                .url(getAltUrlFromSystemProperty())
                .build();
        //The api object creates an http client, but to provide your own:
        //api.httpClient(CloseableHttpClient)
        DocumentRequest<LanguageOptions> request = new DocumentRequest.Builder<LanguageOptions>().content(relationshipsTextData).build();
        RelationshipsResponse response = rosetteApi.perform(HttpRosetteAPI.RELATIONSHIPS_SERVICE_PATH, request, RelationshipsResponse.class);
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$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.";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$params->set('content', $relationships_text_data);
$api->setOption('accuracyMode', 'RECALL');

try {
    $result = $api->relationships($params);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, DocumentParameters, RosetteException


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 = "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
    api.set_option('accuracyMode', 'PRECISION')
    try:
        return api.relationships(params)
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"content": "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."}' \
    "https://api.rosette.com/rest/v1/relationships/"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "relationships": [
    {
      "predicate": "Organization Headquarters",
      "predicateId": "ORG-HEADQUARTERS",
      "arg1": "FLIR Systems",
      "arg1Id": "Q5426537",
      "arg2": "Oregon",
      "arg2Id": "Q824"
    },
    {
      "predicate": "Person Employee or Member of",
      "predicateId": "PER-EMPLOYEE-MEMBER-OF",
      "arg1": "Timms",
      "arg2": "FLIR"
    },
    {
      "predicate": "Organization top employees",
      "predicateId": "ORG-TOP-EMPLOYEES",
      "arg1": "FLIR",
      "arg2": "Timms"
    }
  ],
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:13 GMT, Thu, 22 Jun 2017 17:24:13 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "c675b4e4-8943-4017-a970-3d07912f4856",
    "x-rosetteapi-processedlanguage": "eng",
    "x-rosetteapi-stats-admsentencecount": "4",
    "x-rosetteapi-stats-admentitymentioncount": "12",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-admentitycount": "10",
    "x-rosetteapi-stats-admresolvedentitycount": "5",
    "x-rosetteapi-stats-admtokencount": "102",
    "x-rosetteapi-stats-processedby": "whole-document-language@10.1.1.171,relationship-extraction@10.1.1.171",
    "x-rosetteapi-stats-admrelationshipcount": "3",
    "x-rosetteapi-stats-requestrelaxaccuracymode": "precision",
    "x-rosetteapi-stats-admscriptregioncount": "1",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Relationship Extraction REST endpoint is: https://api.rosette.com/rest/v1/relationships

Building on the results of entity extraction and linking, Rosette relationship extraction identifies how entities are related to each other.

Rosette performs targeted relationship extraction by finding anything within the text that looks like one of the supported relationship types. This allows you to filter and process the results according to your needs.

Using linguistic tools and Wikidata to bootstrap its knowledge, Rosette identifies the exact action connecting the entities and other related information. It uses machine learning methods over parse trees and entity mentions to analyze the connection, and then return the components within the relationships.

If you’d like to see open relationship results, along with the specific supported relationship types, add this to the body of your call: "options": {“discoveryMode”: “true”}.

Relationship Types

Relation Description
ORG-FOUNDED Holds between an organization and a person or another organization that founded it
ORG-HEADQUARTERS Holds between an organization and the location where its headquarters are located
ORG-SUBSIDIARY-OF Holds between two organizations where the first is a subsidiary of the second
ORG-COLLABORATORS Holds between two organizations the are working together toward a project or a goal
ORG-ACQUIRED-BY Holds between two organizations where the first organization was acquired by the second one
ORG-PROVIDER-TO Holds between two organization where the first organization is providing services or products to the second organization
ORG-TOP-EMPLOYEES Holds between an organization and a person who is one of the organization’s top employees
PER-BIRTH-PLACE Holds between a person and the location in which he was born
PER-EMPLOYEE-MEMBER-OF Holds between a person and an organization with which the person is affiliated
PER-RESIDENCE Holds between a person and its current or past location of residence
PER-PARENTS Holds between two person entities where the second is the parent of the first
PER-SIBLINGS Holds between two person entities which are siblings of one another
PER-SPOUSE Holds between two person entities which are the life partners of one another
PER-OTHER-FAMILY Holds between two person entities that belong to the same family but are not siblings, parents, children, or spouse of one another
CIT-OF Holds between a person and his country of citizenship
EDU-AT Holds between a person and an academic institution he is affiliated with

Relationship Components

The endpoint identifies the following elements:

Language Support

The Rosette relationship extraction endpoint currently only supports English language input.

Text Embedding [labs]

Introduction


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Get the text embedding from a piece of text"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();

var api = new Api(args.key, args.url);
var endpoint = "textEmbedding";
var embeddings_data = "Cambridge, Massachusetts"

api.parameters.content = embeddings_data;
api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class text_embedding
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //text-embedding yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            }
            try
            {
                CAPI EmbeddingCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string embedding_data = @"Cambridge, Massachusetts";
                //The results of the API call will come back in the form of a Dictionary
                TextEmbeddingResponse response = EmbeddingCAPI.TextEmbedding(embedding_data);
                foreach (KeyValuePair<string, string> h in response.Headers)
                {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }

                Console.WriteLine(response.ContentAsJson);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

embeddings_data <- "Cambridge, Massachusetts"

parameters <- list()
parameters[[ "content" ]] <- embeddings_data

if (is.na(opt$url)){
   result <- api(opt$key, "text-embedding", parameters)
} else {
   result <- api(opt$key, "text-embedding", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

embeddings_data = "Cambridge, Massachusetts"
begin
  params = DocumentParameters.new(content: embeddings_data)
  response = rosette_api.get_text_embedding(params)
  puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
  printf('Rosette API Error (%s): %s', rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.TextEmbeddingResponse;

import java.io.IOException;

public final class TextEmbeddingExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new TextEmbeddingExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String embeddingsData = "Cambridge, Massachusetts";

        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                .key(getApiKeyFromSystemProperty())
                .url(getAltUrlFromSystemProperty())
                .build();
        //The api object creates an http client, but to provide your own:
        //api.httpClient(CloseableHttpClient)
        // When no options, use <?>.
        DocumentRequest<?> request = new DocumentRequest.Builder<>().content(embeddingsData).build();
        TextEmbeddingResponse response = rosetteApi.perform(HttpRosetteAPI.TEXT_EMBEDDING_SERVICE_PATH, request, TextEmbeddingResponse.class);
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$embeddings_data = "Cambridge, Massachusetts";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$content = $embeddings_data;
$params->set('content', $content);

try {
    $result = $api->textEmbedding($params, false);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, DocumentParameters, RosetteException


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
    try:
        return api.text_embedding(params)
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"content": "Cambridge, Massachusetts" }' \
    "https://api.rosette.com/rest/v1/text-embedding"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "embedding": [
    0.022025604,
    0.036339976,
    0.052465487,
    -0.03751056,
    0.034733504,
    0.024797512,
    -0.038605057,
    0.0060357396,
    -0.042440686,
    0.005218131,
    0.017406568,
    -0.08501768,
    -0.019187056,
    -0.05974227,
    0.007629127,
    -0.00020685681,
    -0.046394948,
    0.00458408,
    0.012205962,
    0.06160719,
    -0.039888024,
    -0.030956516,
    -0.011825466,
    0.048615705,
    0.029674347,
    -0.045608677,
    -0.16111824,
    -0.06562275,
    0.0020886592,
    0.016227394,
    -0.09196278,
    0.13520485,
    0.036651377,
    -0.017487364,
    0.059087627,
    0.07113674,
    0.04435388,
    -0.04436791,
    -0.0018729026,
    -0.036128953,
    0.0032484145,
    0.021822201,
    0.0041496186,
    0.027506191,
    -0.0046664677,
    -0.035163473,
    0.0006168559,
    0.030713867,
    0.060716,
    -0.053943817,
    -0.03460756,
    -0.091690496,
    -0.04351116,
    0.030959161,
    0.072648324,
    0.004402438,
    -0.064870045,
    -0.012432695,
    -0.025948446,
    0.064032525,
    0.05990276,
    0.08421157,
    0.0011394282,
    -0.051880825,
    0.013367516,
    0.057371285,
    0.0868928,
    -0.027974723,
    0.029518684,
    -0.06528687,
    -0.02593506,
    -0.1377904,
    0.050219353,
    -0.00331138,
    0.0034542882,
    -0.080660395,
    -0.029972563,
    0.04178474,
    -0.16860084,
    -0.0020299442,
    0.04082655,
    0.040526383,
    -0.02616019,
    -0.070799045,
    0.041142035,
    -0.05405192,
    -0.020795293,
    0.033622585,
    0.12866253,
    0.046861827,
    0.032054592,
    0.018449787,
    0.105773665,
    -0.043312363,
    0.035504982,
    0.034989387,
    -0.052367248,
    0.056506965,
    -0.032297965,
    -0.059114814,
    0.080418065,
    -0.010934181,
    -0.04541076,
    0.004990573,
    0.033790544,
    0.019859122,
    0.054343533,
    -0.06876269,
    -0.021424888,
    -0.043686822,
    -0.023400914,
    0.042717077,
    -0.03868493,
    0.03260612,
    -0.0031060237,
    -0.08135383,
    0.03890613,
    0.052065287,
    0.019026382,
    -0.03261049,
    -0.012250968,
    -0.04929554,
    0.06811376,
    -0.10045446,
    -0.037727106,
    0.06436889,
    0.033533704,
    0.031109469,
    -0.010103673,
    -0.03986244,
    0.013409139,
    -0.06304926,
    0.053656735,
    -0.07044137,
    0.06421522,
    0.0632241,
    -0.04348637,
    0.13118945,
    -0.020826306,
    0.07590587,
    -0.048133265,
    -0.025774928,
    0.056429293,
    0.00033934723,
    -0.010245161,
    0.063916475,
    0.032646753,
    -0.02187326,
    0.04832495,
    0.022412589,
    0.056819815,
    -0.041249637,
    0.08708096,
    0.060668726,
    -0.03356391,
    -0.033277135,
    -0.034491815,
    -0.020472195,
    0.065979816,
    0.08629483,
    0.03777988,
    0.011912889,
    0.10955901,
    -0.05159367,
    1.4314965e-05,
    -0.0043508057,
    -0.071393326,
    -0.10915583,
    -0.065822646,
    -0.027544636,
    0.04510804,
    0.09508634,
    -0.02923319,
    0.036278628,
    0.026470473,
    0.06838391,
    0.07216309,
    -0.008090509,
    0.072488345,
    0.012326396,
    -0.09173338,
    -0.02095788,
    0.02871792,
    -0.03392723,
    0.05959549,
    -0.10397915,
    -0.038203258,
    -0.052221153,
    -0.022968179,
    -0.06410559,
    0.02745123,
    0.023348646,
    -0.024462057,
    -0.12417631,
    -0.01871051,
    0.024395408,
    -0.024814317,
    -0.038801547,
    0.04188481,
    0.023009732,
    0.106005274,
    0.02696968,
    0.027882474,
    0.05024018,
    0.059075646,
    0.028567951,
    -0.0074076615,
    0.022897637,
    -0.064362705,
    -0.007494853,
    -0.031114511,
    0.065808445,
    0.02102997,
    -0.10717536,
    0.16490568,
    0.030473657,
    -0.024549985,
    0.07184675,
    -0.025044587,
    -0.11541119,
    0.039153546,
    -0.031878352,
    -0.054945864,
    -0.15862629,
    -0.027798157,
    0.007245611,
    0.009018073,
    -0.015190015,
    0.04528573,
    -0.05221211,
    0.012603455,
    -0.016520651,
    0.013243823,
    -0.016889771,
    0.010708759,
    -0.03916383,
    -0.03296183,
    -0.06774635,
    -0.053886928,
    -0.013208868,
    0.07467077,
    0.06863626,
    -0.064392775,
    0.061134093,
    -0.0012258054,
    -0.041174095,
    0.11657882,
    -0.019798826,
    -0.01714609,
    -0.006212828,
    0.059066307,
    0.004046627,
    0.02791196,
    -0.11955266,
    -0.062343203,
    -0.12302965,
    0.047498047,
    -0.05722075,
    0.083425544,
    -0.061689798,
    0.017107904,
    0.103013396,
    0.0057518734,
    -0.012239589,
    -0.011060308,
    0.027331827,
    -0.054657456,
    -0.006390925,
    0.10582153,
    0.051196028,
    -0.16957831,
    0.060564604,
    0.05737981,
    0.12555394,
    -0.009639132,
    -0.15966235,
    0.06239227,
    -0.015199974,
    -0.0065381415,
    -0.017599579,
    -0.002819649,
    -0.07387377,
    0.015420447,
    -0.015746351,
    0.099608615,
    0.06726488,
    0.013819766,
    0.031044612,
    0.051405653,
    -0.08996302,
    0.06713541,
    -0.10765704,
    -0.009756809,
    0.1513082,
    0.012883504,
    -0.0025149365,
    -0.027431866,
    0.009554175,
    -0.10639542,
    0.04656886
  ],
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:13 GMT, Thu, 22 Jun 2017 17:24:14 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "ea4c1322-333e-426f-8279-0273ddfa1baa",
    "x-rosetteapi-processedlanguage": "eng",
    "x-rosetteapi-stats-admsentencecount": "1",
    "x-rosetteapi-stats-admtokencount": "3",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-processedby": "whole-document-language@10.1.1.171,base-linguistics@10.1.1.171,doc-vectors@10.1.1.171",
    "x-rosetteapi-stats-admscriptregioncount": "1",
    "x-rosetteapi-stats-isadmresponse": "false",
    "vary": "Accept-Encoding",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Text Embedding REST endpoint is: https://api.rosette.com/rest/v1/text-embedding

The Text Embedding endpoint returns a single vector of floating point numbers for your input, known as a text embedding. Among other uses, a text embedding enables you to calculate the similarity between two documents or two words.

The text embedding represents the relationships between words in your document in the semantic space. The semantic space is a multilingual network that maps the input based on the words and their context. Words with similar meanings have similar contexts, and Rosette maps them close to each other.

In the semantic space, the same words in different languages have similar meanings and therefore close mappings. For example, “Washington was the first president of the United States” is similar to “Washington fue el primer presidente de los Estados Unidos”. These sentences have very similar meanings in both Spanish and English, and their text embeddings are very close to each other.

Contact us to discuss ways to build text embeddings into your applications, or check out our blog post and sample code for an example use case.

Know what your language is?

If you know the language of your input, include the three-letter language code in your call to speed up the response time.

Otherwise, Rosette identifies the language of your input.

Language Support

Language (code)

You can specify the language of your input with the three-letter language code. If you do not specify the language then Rosette automatically detects it.

Syntactic Dependencies [labs]

Introduction


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Get the syntactic dependencies from a piece of text"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();

var api = new Api(args.key, args.url);
var endpoint = "syntax_dependencies";
var syntax_dependencies_data = "Yoshinori Ohsumi, a Japanese cell biologist, was awarded the Nobel Prize in Physiology or Medicine on Monday.";

api.parameters.content = syntax_dependencies_data;
api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class entities
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //entities yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            }
            try
            {
                CAPI api = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string syntax_dependencies_data = "Yoshinori Ohsumi, a Japanese cell biologist, was awarded the Nobel Prize in Physiology or Medicine on Monday.";
                //The results of the API call will come back in the form of a Dictionary
                SyntaxDependenciesResponse response = api.SyntaxDependencies(syntax_dependencies_data);
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

syntax_dependencies_data <- "Yoshinori Ohsumi, a Japanese cell biologist, was awarded the Nobel Prize in Physiology or Medicine on Monday."

parameters <- list()
parameters[[ "content" ]] <- syntax_dependencies_data

if (is.na(opt$url)){
   result <- api(opt$key, "syntax/dependencies", parameters)
} else {
   result <- api(opt$key, "syntax/dependencies", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

syntax_dependencies_data = "Yoshinori Ohsumi, a Japanese cell biologist, was awarded the Nobel Prize in Physiology or Medicine on Monday."
begin
  params = DocumentParameters.new(content: syntax_dependencies_data)
  response = rosette_api.get_syntax_dependencies(params)
  puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
  printf('Rosette API Error (%s): %s', rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.SyntaxDependenciesResponse;
import com.basistech.rosette.apimodel.DocumentRequest;

import java.io.IOException;

public final class SyntaxDependenciesExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new SyntaxDependenciesExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String syntaxDependenciesData = "Yoshinori Ohsumi, a Japanese cell biologist, was awarded the Nobel Prize in Physiology or Medicine on Monday.";
        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                                .key(getApiKeyFromSystemProperty())
                                .url(getAltUrlFromSystemProperty())
                                .build();
        //The api object creates an http client, but to provide your own:
        //api.httpClient(CloseableHttpClient)
        DocumentRequest<?> request = new DocumentRequest.Builder<>().content(syntaxDependenciesData).build();
        SyntaxDependenciesResponse response = rosetteApi.perform(HttpRosetteAPI.SYNTAX_DEPENDENCIES_SERVICE_PATH, request, SyntaxDependenciesResponse.class);
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$syntax_dependencies_data = "Yoshinori Ohsumi, a Japanese cell biologist, was awarded the Nobel Prize in Physiology or Medicine on Monday.";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$content = $syntax_dependencies_data;
$params->set('content', $content);

try {
    $result = $api->syntaxDependencies($params, false);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, DocumentParameters, RosetteException


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
    # Create an API instance
    api = API(user_key=key, service_url=altUrl)
    try:
        return api.syntax_dependencies(params)
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"content": "Yoshinori Ohsumi, a Japanese cell biologist, was awarded the Nobel Prize in Physiology or Medicine on Monday." }' \
    "https://api.rosette.com/rest/v1/syntax/dependencies"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "sentences": [
    {
      "startTokenIndex": 0,
      "endTokenIndex": 19,
      "dependencies": [
        {
          "dependencyType": "name",
          "governorTokenIndex": 1,
          "dependentTokenIndex": 0
        },
        {
          "dependencyType": "nsubjpass",
          "governorTokenIndex": 9,
          "dependentTokenIndex": 1
        },
        {
          "dependencyType": "punct",
          "governorTokenIndex": 1,
          "dependentTokenIndex": 2
        },
        {
          "dependencyType": "det",
          "governorTokenIndex": 6,
          "dependentTokenIndex": 3
        },
        {
          "dependencyType": "amod",
          "governorTokenIndex": 6,
          "dependentTokenIndex": 4
        },
        {
          "dependencyType": "compound",
          "governorTokenIndex": 6,
          "dependentTokenIndex": 5
        },
        {
          "dependencyType": "appos",
          "governorTokenIndex": 1,
          "dependentTokenIndex": 6
        },
        {
          "dependencyType": "punct",
          "governorTokenIndex": 1,
          "dependentTokenIndex": 7
        },
        {
          "dependencyType": "auxpass",
          "governorTokenIndex": 9,
          "dependentTokenIndex": 8
        },
        {
          "dependencyType": "root",
          "governorTokenIndex": -1,
          "dependentTokenIndex": 9
        },
        {
          "dependencyType": "det",
          "governorTokenIndex": 12,
          "dependentTokenIndex": 10
        },
        {
          "dependencyType": "compound",
          "governorTokenIndex": 12,
          "dependentTokenIndex": 11
        },
        {
          "dependencyType": "dobj",
          "governorTokenIndex": 9,
          "dependentTokenIndex": 12
        },
        {
          "dependencyType": "case",
          "governorTokenIndex": 14,
          "dependentTokenIndex": 13
        },
        {
          "dependencyType": "nmod",
          "governorTokenIndex": 12,
          "dependentTokenIndex": 14
        },
        {
          "dependencyType": "cc",
          "governorTokenIndex": 14,
          "dependentTokenIndex": 15
        },
        {
          "dependencyType": "conj",
          "governorTokenIndex": 14,
          "dependentTokenIndex": 16
        },
        {
          "dependencyType": "case",
          "governorTokenIndex": 18,
          "dependentTokenIndex": 17
        },
        {
          "dependencyType": "nmod",
          "governorTokenIndex": 9,
          "dependentTokenIndex": 18
        },
        {
          "dependencyType": "punct",
          "governorTokenIndex": 9,
          "dependentTokenIndex": 19
        }
      ]
    }
  ],
  "tokens": [
    "Yoshinori",
    "Ohsumi",
    ",",
    "a",
    "Japanese",
    "cell",
    "biologist",
    ",",
    "was",
    "awarded",
    "the",
    "Nobel",
    "Prize",
    "in",
    "Physiology",
    "or",
    "Medicine",
    "on",
    "Monday",
    "."
  ],
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:13 GMT, Thu, 22 Jun 2017 17:24:13 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "75663382-c232-4701-8afb-4fb7c7a6ce1a",
    "x-rosetteapi-processedlanguage": "eng",
    "x-rosetteapi-stats-admsentencecount": "1",
    "x-rosetteapi-stats-admtokencount": "20",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-processedby": "whole-document-language@10.1.1.171,dependency-parsing@10.1.1.171",
    "x-rosetteapi-stats-isadmresponse": "false",
    "vary": "Accept-Encoding",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Syntactic Dependencies REST endpoint is https://api.rosette.com/rest/v1/syntax/dependencies

The rules governing the hierarchical structure of a sentence are called “syntax” in linguistics. Knowing the structure of a sentence helps to understand how the words in a sentence are related to each other. In a sentence like “I don’t like beer”, syntax is what tells us that the verb “like” is what’s negated by “not”. In fact, Rosette’s relationships functionality uses syntax to help understand the relationships between entities in sentences.

Dependency grammars are a specific approach to modelling syntax which identify labeled dependencies, or direct connections, between words rather than intervening structures like a verb phrase or noun phrase. A dependency grammar places the verb as the structural root of the sentence, to which all other dependencies link directly or indirectly.

The Rosette API’s /syntax/dependencies endpoint will return the list of tokens, or words, in the input sentence, as well as the labeled directed links each token has to another token in the sentence. The indices correspond to the list of tokens within the results; the list of tokens returned from Rosette’s /tokens endpoint may vary.

Know what your language is?

If you know the language of your input, include the three-letter language code in your call to speed up the response time.

Otherwise, Rosette identifies the language of your input.

Language Support

You can specify the language of your input with the three-letter language code. If you do not specify the language then Rosette automatically detects it.

Language (code)

Entity Extraction

Introduction


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Get the entities from a piece of text"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();

var api = new Api(args.key, args.url);
var endpoint = "entities";
var 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";

api.parameters.content = entities_text_data;
api.parameters.genre = "social-media";
api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class entities
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //entities yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            }
            try
            {
                CAPI EntitiesCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string 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";
                //The results of the API call will come back in the form of a Dictionary
                EntitiesResponse response = EntitiesCAPI.Entity(entities_text_data, null, null, null, "social-media");
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

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"

parameters <- list()
parameters[[ "content" ]] <- entities_text_data
parameters[[ "genre" ]] <- "social-media"
# advanced output
url_parameters <- list(output = "rosette")

if (is.na(opt$url)){
   result <- api(opt$key, "entities", parameters, url_parameters = url_parameters)
} else {
   result <- api(opt$key, "entities", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


# encoding: UTF-8
require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

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"
begin
    params = DocumentParameters.new(content: entities_text_data, genre: 'social-media')
    response = rosette_api.get_entities(params)
    puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
    printf("Rosette API Error (%s): %s", rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.EntitiesOptions;
import com.basistech.rosette.apimodel.EntitiesResponse;

import java.io.IOException;

public final class EntitiesExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new EntitiesExample().run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void run() throws IOException {
        String entitiesTextData = "Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a cameo in Boston this… http://dlvr.it/BnsFfS";
        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                                .key(getApiKeyFromSystemProperty())
                                .url(getAltUrlFromSystemProperty())
                                .build();
        DocumentRequest<EntitiesOptions> request = new DocumentRequest.Builder<EntitiesOptions>().content(entitiesTextData).build();
        EntitiesResponse response = rosetteApi.perform(HttpRosetteAPI.ENTITIES_SERVICE_PATH, request, EntitiesResponse.class);
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$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";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$content = $entities_text_data;
$params->set('content', $content);
$params->set('genre', 'social-media');

try {
    $result = $api->entities($params);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, DocumentParameters, RosetteException


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"
    try:
        return api.entities(params)
    except RosetteException as e:
        print(e)

parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"content": "Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a cameo in Boston this… http://dlvr.it/BnsFfS", "genre": "social-media" }' \
    "https://api.rosette.com/rest/v1/entities"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "entities": [
    {
      "type": "PERSON",
      "mention": "Bill Murray",
      "normalized": "Bill Murray",
      "count": 1,
      "entityId": "Q29250",
      "confidence": 0.9990000128746033
    },
    {
      "type": "PRODUCT",
      "mention": "Ghostbusters",
      "normalized": "Ghostbusters",
      "count": 1,
      "entityId": "Q108745"
    },
    {
      "type": "TITLE",
      "mention": "Dr.",
      "normalized": "Dr.",
      "count": 1,
      "entityId": "T2",
      "confidence": 0.9990000128746033
    },
    {
      "type": "PERSON",
      "mention": "Peter Venkman",
      "normalized": "Peter Venkman",
      "count": 1,
      "entityId": "Q2483011",
      "confidence": 0.9990000128746033
    },
    {
      "type": "LOCATION",
      "mention": "Boston",
      "normalized": "Boston",
      "count": 1,
      "entityId": "Q100"
    },
    {
      "type": "IDENTIFIER:URL",
      "mention": "http://dlvr.it/BnsFfS",
      "normalized": "http://dlvr.it/BnsFfS",
      "count": 1,
      "entityId": "T5"
    }
  ],
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:10 GMT, Thu, 22 Jun 2017 17:24:11 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "64637439-5a05-447d-aa13-74ffc1a63243",
    "x-rosetteapi-processedlanguage": "eng",
    "x-rosetteapi-stats-admsentencecount": "1",
    "x-rosetteapi-stats-admentitymentioncount": "6",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-admentitycount": "6",
    "x-rosetteapi-stats-admresolvedentitycount": "4",
    "x-rosetteapi-stats-admtokencount": "28",
    "x-rosetteapi-stats-processedby": "whole-document-language@10.1.1.171,entity-extraction@10.1.1.171",
    "x-rosetteapi-stats-admscriptregioncount": "1",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Entity Extraction REST endpoint is: https://api.rosette.com/rest/v1/entities

The Rosette entity extraction endpoint uses case-sensitive statistical models, patterns, and exact matching to indentify entities in documents. An entity refers to an object of interest such as a person, organization, location, date, or email address. Identifying entities can help you classify the document and the kinds of data it contains.

The statistical models are based on computational linguistics and human-annotated training documents. The patterns are regular expressions that identify entities such as dates, times, and geographical coordinates. The exact matcher uses lists of entities to match words exactly in one or more languages.

Statistical model based extractions can return confidence scores for each entity. Confidence score calculation correlates well with precision and may be used for thresholding and removal of false positives. To include the scores in the result, simply add an option to the request:

{"content": "your_text_here", "options": {"calculateConfidence": true}}

Know what your language is?

If you know the language of your input, include the three-letter language code in your call to speed up the response time.

Otherwise, Rosette identifies the language of your input.

Entity Types

The Rosette entity extraction endpoint can extract the following entity types:

The following entities are available in select languages. Contact us for more information.

Entity Linking

Text that refers to an entity is called an entity mention, such as “Bill Clinton” and “William Jefferson Clinton”. Rosette connects these two entity mentions with entity linking, since they refer to the same real-world PERSON entity. Linking helps establish the identity of the entity by disambiguating common names and matching a variety of names, such as nicknames and formal titles, with an entity ID.

Rosette uses the Wikidata knowledgebase as a base to link Person, Location, and Organization entities in Chinese, English, Japanese, and Spanish. If the entity exists in Wikidata, then Rosette returns the Wikidata QID, such as Q1 for the Universe.

If Rosette cannot link the entity, then it creates a placeholder temporary (“T”) entity ID to link mentions of the same entity in the document. However, the TID may be different across documents for the same entity.

Entity linking is on by default. To disable entity linking add {"options": {"linkEntities": "false"}} to improve the call speed. Rosette returns the entities with a TID.

Language Support

Language (code)

You can specify the language of your input with the three-letter language code. If you do not specify the language then Rosette automatically detects it.

Language Identification


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Determine the language of a piece of text"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();
var api = new Api(args.key, args.url);
var endpoint = "language";
var appHeader = [];
appHeader[0] = "X-RosetteAPI-App"
appHeader[1] = "app";
api.parameters.customHeaders = [appHeader];

var language_data = "Por favor Señorita, says the man.";

api.parameters.content = language_data;
var appHeader = [];
appHeader[0] = "X-RosetteAPI-App"
appHeader[1] = "app";
api.parameters.customHeaders = [appHeader];

api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class language
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //language yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            } 
            try
            {
                CAPI LanguageCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string language_data = @"Por favor Señorita, says the man.";
                //The results of the API call will come back in the form of a Dictionary
                LanguageCAPI.SetCustomHeaders("X-RosetteAPI-App", "csharp-app");
                LanguageIdentificationResponse response = LanguageCAPI.Language(language_data);
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

language_data <- "Por favor Señorita, says the man."

parameters <- list()
parameters[[ "content" ]] <- language_data
custom_headers <- c("X-RosetteAPI-App" = "r-application-test")

if (is.na(opt$url)){
  result <- api(opt$key, "language", parameters = parameters, custom_headers = custom_headers)
} else {
  result <- api(opt$key, "language", parameters = parameters, custom_headers = custom_headers, NULL, url = opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

language_data = "Por favor Señorita, says the man."
begin
    params = DocumentParameters.new(content: language_data)
    params.custom_headers = { 'X-RosetteAPI-App'=> 'ruby-app'}
    response = rosette_api.get_language(params)
    puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
    printf("Rosette API Error (%s): %s", rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.LanguageOptions;
import com.basistech.rosette.apimodel.LanguageResponse;

import java.io.IOException;

public final class LanguageExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new LanguageExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String languageData = "Por favor Señorita, says the man.";

        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                                    .key(getApiKeyFromSystemProperty())
                                    .url(getAltUrlFromSystemProperty())
                                    .build();
        //The api object creates an http client, but to provide your own:
        //api.httpClient(CloseableHttpClient)
        DocumentRequest<LanguageOptions> request = new DocumentRequest.Builder<LanguageOptions>().content(languageData).build();
        LanguageResponse response = rosetteApi.perform(HttpRosetteAPI.LANGUAGE_SERVICE_PATH, request, LanguageResponse.class);
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$language_data = "Por favor Señorita, says the man.";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$content = $language_data;
$params->set('content', $content);
$api->setCustomHeader('X-RosetteAPI-App', 'php-app');

try {
    $result = $api->language($params);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, DocumentParameters, RosetteException


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.set_custom_headers("X-RosetteAPI-App", "python-app")
    try:
        return api.language(params)
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"content": "Por favor Señorita, says the man." }' \
    "https://api.rosette.com/rest/v1/language"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "languageDetections": [
    {
      "language": "spa",
      "confidence": 0.3845151225848894
    },
    {
      "language": "eng",
      "confidence": 0.3316587067222248
    },
    {
      "language": "por",
      "confidence": 0.055137014673966325
    },
    {
      "language": "deu",
      "confidence": 0.02994955618443865
    },
    {
      "language": "swe",
      "confidence": 0.02760169719402306
    }
  ],
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:11 GMT, Thu, 22 Jun 2017 17:24:11 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "3cbbbcfe-3d08-4fa7-8460-aee09905af8c",
    "x-rosetteapi-processedlanguage": "spa",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-processedby": "whole-document-language@10.1.1.171",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Language Identification REST endpoint is: https://api.rosette.com/rest/v1/language

The Rosette language identifier endpoint identifies in which language(s) the input is written. The endpoint returns a list of language identification results in descending order of confidence, so the first result is the best.

The input data may be in any of 364 language- encoding-script combinations, involving 56 languages, 48 encodings, and 18 writing scripts. The language identifier uses an n-gram algorithm to detect language. Each of the 155 built-in profiles contains the quad-grams (i.e., four consecutive bytes) that are most frequently encountered in documents in a given language, encoding, and script. The default number of n-grams is 10,000 for double-byte encodings and 5,000 for single-byte encodings.

When input text is submitted for detection, a similar n-gram profile is built based on that data. The input profile is then compared with all the built-in profiles (a vector distance measure between the input profile and the built-in profile is calculated). The pre-built profiles are then returned in ascending order by the (shortest) distance of the input from the pre-built profiles.

For a number of languages, the endpoint provides a different proprietary algorithm for detecting the language of short strings (140 characters or less).

Confidence

Rosette returns a confidence score with each language result, ranging from 0 to 1. It is a measurement that you can use as a threshold for filtering out undesired results.

Language Support

Language (code) Short Strings Support
Albanian (sqi)
Arabic (ara)
Bengali (ben)
Bulgarian (bul)
Catalan (cat)
Chinese: Simplified & Traditional (zho)
Croatian (hrv)
Czech (ces)
Danish (dan)
Dutch (nld)
English (eng)
Estonian (est)
Finnish (fin)
French (fra)
German (deu)
Greek (ell)
Gujarati (guj)
Hebrew (heb)
Hindi (hin)
Hungarian (hun)
Icelandic (isl)
Indonesian (ind)
Italian (ita)
Japanese (jpn)
Kannada (kan)
Korean (kor)
Kurdish (kur)
Latvian (lav)
Lithuanian (lit)
Macedonian (mkd)
Malay (msa)
Malayalam (mal)
Norwegian: Bokmål & Nynorsk (nor)
Pashto (pus)
Persian: Dari & Farsi (fas)
Polish (pol)
Portuguese (por)
Romanian (ron)
Russian (rus)
Serbian (srp)
Slovak (slk)
Slovenian (slv)
Somali (som)
Spanish (spa)
Swedish (swe)
Tagalog (tgl)
Tamil (tam)
Telugu (tel)
Thai (tha)
Turkish (tur)
Ukrainian (ukr)
Urdu (urd)
Uzbek (uzb)
Vietnamese (vie)

Morphological Analysis

Introduction

The Morphological Analysis REST endpoint is: https://api.rosette.com/rest/v1/morphology/{morphoFeature}

The Rosette morphology endpoint provides language-specific tools for returning parts-of-speech, lemmas (dictionary form), compound components, and Han-readings for each token in the input.

For languages with compound words, Rosette divides the words into components which improves recall for search engines.

For Chinese tokens in Han script, Rosette returns pinyin transcriptions as the Han-reading. For Japanese tokens in Han script, Rosette returns Furigana transcriptions rendered in Hiragana as the Han-reading.

Know what your language is?

If you know the language of your input, include the three-letter language code in your call to speed up the response time.

Otherwise, Rosette identifies the language of your input.

You can append a morphoFeature or a comma-delimited list of features to the /morphology/ endpoint to specify which feature or features you want Rosette to return. /morphology/complete returns all results for all features available for the language of the input text.

morphoFeature options
Lemmas
Compound Components
Parts-of-Speech
Han-Readings
Complete (all of the above)

Lemmas


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Get the complete morphological analysis of a piece of text"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();
var api = new Api(args.key, args.url);
var endpoint = "morphology";

var 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";
var content = morphology_lemmas_data;

api.parameters.content = content;
api.parameters.morphology = "lemmas";

api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class morphology_lemmas
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //morphology_lemmas yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            } 
            try
            {
                CAPI MorphologyCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string 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";
                //The results of the API call will come back in the form of a Dictionary
                RosetteResponse response = MorphologyCAPI.Morphology(morphology_lemmas_data, null, null, null, MorphologyFeature.lemmas);
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ContentAsJson);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

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"

parameters <- list()
parameters[[ "content" ]] <- morphology_lemmas_data
parameters[[ "morphology" ]] <- "lemmas"

if (is.na(opt$url)){
   result <- api(opt$key, "morphology", parameters)
} else {
   result <- api(opt$key, "morphology", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

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"
begin
    params = DocumentParameters.new(content: morphology_lemmas_data)
    response = rosette_api.get_lemmas(params)
    puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
    printf("Rosette API Error (%s): %s", rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.api.MorphologicalFeature;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.MorphologyOptions;
import com.basistech.rosette.apimodel.MorphologyResponse;

import java.io.IOException;

public final class MorphologyLemmasExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new MorphologyLemmasExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String morphologyLemmasData = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon";
        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                .key(getApiKeyFromSystemProperty())
                .url(getAltUrlFromSystemProperty())
                .build();
        DocumentRequest<MorphologyOptions> request = new DocumentRequest.Builder<MorphologyOptions>().content(morphologyLemmasData)
                .build();
        MorphologyResponse response = rosetteApi.perform(HttpRosetteAPI.MORPHOLOGY_SERVICE_PATH + "/" + MorphologicalFeature.LEMMAS,
                request, MorphologyResponse.class);
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteConstants;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$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";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$params->set('content', $morphology_lemmas_data);

try {
    $result = $api->morphology($params, RosetteConstants::$MorphologyOutput['LEMMAS']);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, DocumentParameters, RosetteException


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
    try:
        return api.morphology(params, api.morphology_output['LEMMAS'])
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"content": "The fact is that the geese just went back to get a rest and I\u0027m not banking on their return soon"}' \
    "https://api.rosette.com/rest/v1/morphology/lemmas"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "tokens": [
    "The",
    "fact",
    "is",
    "that",
    "the",
    "geese",
    "just",
    "went",
    "back",
    "to",
    "get",
    "a",
    "rest",
    "and",
    "I",
    "'m",
    "not",
    "banking",
    "on",
    "their",
    "return",
    "soon"
  ],
  "lemmas": [
    "the",
    "fact",
    "be",
    "that",
    "the",
    "goose",
    "just",
    "go",
    "back",
    "to",
    "get",
    "a",
    "rest",
    "and",
    "I",
    "be",
    "not",
    "bank",
    "on",
    "they",
    "return",
    "soon"
  ],
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:11 GMT, Thu, 22 Jun 2017 17:24:12 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "b6de4306-c0e0-47a1-8c83-626d04ad6357",
    "x-rosetteapi-processedlanguage": "eng",
    "x-rosetteapi-stats-admsentencecount": "1",
    "x-rosetteapi-stats-admtokencount": "22",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-processedby": "whole-document-language@10.1.1.171,base-linguistics@10.1.1.171",
    "x-rosetteapi-stats-admscriptregioncount": "1",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Lemmas REST endpoint is https://api.rosette.com/rest/v1/morphology/lemmas

A lemma is the dictionary form of a word. Rosette determines the lemma each word in the input based on its usage and context.

For example, saw can be used as a noun or a past tense verb.
In the sentence “The carpenter picked up the saw from the workbench,” Rosette returns the lemma “saw”, a noun.
However, in the sentence “The bird saw the worm in the shade of the tree,” Rosette returns the lemma “see”, the dictionary-form of the verb.

You can specify the language of your input by including the three-letter language code within your request. If you do not include this field then Rosette automatically detects the language of the input.

Compound Components


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Get the complete morphological analysis of a piece of text"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();
var api = new Api(args.key, args.url);
var endpoint = "morphology";

var morphology_compound_components_data = "Rechtsschutzversicherungsgesellschaften";
var content = morphology_compound_components_data;

api.parameters.content = content;
api.parameters.morphology = "compound-components";

api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    }
        console.log(JSON.stringify(res, null, 2));

});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class morphology_compound_components
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //morphology_compound_components yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            } 
            try
            {
                CAPI MorphologyCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string morphology_compound_components_data = @"Rechtsschutzversicherungsgesellschaften";
                //The results of the API call will come back in the form of a Dictionary
                MorphologyResponse response = MorphologyCAPI.Morphology(morphology_compound_components_data, null, null, null, MorphologyFeature.compoundComponents);
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

morphology_compound_components_data <- "Rechtsschutzversicherungsgesellschaften"

parameters <- list()
parameters[[ "content" ]] <- morphology_compound_components_data
parameters[[ "morphology" ]] <- "compound-components"

if (is.na(opt$url)){
   result <- api(opt$key, "morphology", parameters)
} else {
   result <- api(opt$key, "morphology", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

morphology_compound_components_data = "Rechtsschutzversicherungsgesellschaften"
begin
    params = DocumentParameters.new(content: morphology_compound_components_data)
    response = rosette_api.get_compound_components(params)
    puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
    printf("Rosette API Error (%s): %s", rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.api.MorphologicalFeature;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.MorphologyOptions;
import com.basistech.rosette.apimodel.MorphologyResponse;
import com.basistech.util.LanguageCode;

import java.io.IOException;

public final class MorphologyCompoundComponentsExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new MorphologyCompoundComponentsExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String morphologyCompoundComponentsData = "Rechtsschutzversicherungsgesellschaften";
        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                                    .key(getApiKeyFromSystemProperty())
                                    .url(getAltUrlFromSystemProperty())
                                    .build();
        //The api object creates an http client, but to provide your own:
        //api.httpClient(CloseableHttpClient)
        DocumentRequest<MorphologyOptions> request = new DocumentRequest.Builder<MorphologyOptions>().content(morphologyCompoundComponentsData)
                .language(LanguageCode.GERMAN) // example of specifying the language.
                .build();
        MorphologyResponse response = rosetteApi.perform(HttpRosetteAPI.MORPHOLOGY_SERVICE_PATH + "/" + MorphologicalFeature.COMPOUND_COMPONENTS,
                request, MorphologyResponse.class);

        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteConstants;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$morphology_compound_components_data = "Rechtsschutzversicherungsgesellschaften";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$params->set('content', $morphology_compound_components_data);

try {
    $result = $api->morphology($params, RosetteConstants::$MorphologyOutput['COMPOUND_COMPONENTS']);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, DocumentParameters, RosetteException


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
    try:
        return api.morphology(params, api.morphology_output['COMPOUND_COMPONENTS'])
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"content": "Rechtsschutzversicherungsgesellschaften"}' \
    "https://api.rosette.com/rest/v1/morphology/compound-components"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "tokens": [
    "Rechtsschutzversicherungsgesellschaften"
  ],
  "compoundComponents": [
    [
      "Recht",
      "Schutz",
      "Versicherung",
      "Gesellschaft"
    ]
  ],
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:11 GMT, Thu, 22 Jun 2017 17:24:11 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "a158a897-c9f2-4508-b0b4-330ea5b6bb81",
    "x-rosetteapi-processedlanguage": "deu",
    "x-rosetteapi-stats-admsentencecount": "1",
    "x-rosetteapi-stats-admtokencount": "1",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-processedby": "whole-document-language@10.1.1.171,base-linguistics@10.1.1.171",
    "x-rosetteapi-stats-admscriptregioncount": "1",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Compound Components REST endpoint is https://api.rosette.com/rest/v1/morphology/compound-components

With the compound components feature, Rosette breaks down compound words into sub-components and returns the individual elements. This is useful for increasing search relevancy in languages such as German and Korean.

For example, the German compound word “Rechtsschutzversicherungsgesellschaften” means “legal expenses insurance companies”.
Rosette returns these compound components: “Recht”, “Schutz”, “Versicherung”, and “Gesellschaft”.

You can specify the language of your input by including the three-letter language code within your request. If you do not include this field then Rosette automatically detects the language of the input.

Parts-of-Speech


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Get the complete morphological analysis of a piece of text"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();
var api = new Api(args.key, args.url);
var endpoint = "morphology";

var 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";
var content = morphology_parts_of_speech_data;

api.parameters.content = content;
api.parameters.morphology = "parts-of-speech";

api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class morphology_parts_of_speech
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //morphology_parts_of_speech yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            }
            try
            {
                CAPI MorphologyCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string 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";
                //The results of the API call will come back in the form of a Dictionary
                MorphologyResponse response = MorphologyCAPI.Morphology(morphology_parts_of_speech_data, null, null, null, MorphologyFeature.partsOfSpeech);
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

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"

parameters <- list()
parameters[[ "content" ]] <- morphology_parts_of_speech_data
parameters[[ "morphology" ]] <- "parts-of-speech"

if (is.na(opt$url)){
   result <- api(opt$key, "morphology", parameters)
} else {
   result <- api(opt$key, "morphology", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

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"
begin
    params = DocumentParameters.new(content: morphology_parts_of_speech_data)
    response = rosette_api.get_parts_of_speech(params)
    puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
    printf("Rosette API Error (%s): %s", rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.api.MorphologicalFeature;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.MorphologyOptions;
import com.basistech.rosette.apimodel.MorphologyResponse;

import java.io.IOException;

public final class MorphologyPartsOfSpeechExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new MorphologyPartsOfSpeechExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String morphologyPartsOfSpeechData = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon";

        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                .key(getApiKeyFromSystemProperty())
                .url(getAltUrlFromSystemProperty())
                .build();
        DocumentRequest<MorphologyOptions> request = new DocumentRequest.Builder<MorphologyOptions>().content(morphologyPartsOfSpeechData)
                .build();
        MorphologyResponse response = rosetteApi.perform(HttpRosetteAPI.MORPHOLOGY_SERVICE_PATH + "/" + MorphologicalFeature.PARTS_OF_SPEECH,
                request, MorphologyResponse.class);
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteConstants;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$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";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$params->set('content', $morphology_parts_of_speech_data);

try {
    $result = $api->morphology($params, RosetteConstants::$MorphologyOutput['PARTS_OF_SPEECH']);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, DocumentParameters, RosetteException


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, api.morphology_output['PARTS_OF_SPEECH'])
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"content": "The fact is that the geese just went back to get a rest and I\u0027m not banking on their return soon"}' \
    "https://api.rosette.com/rest/v1/morphology/parts-of-speech"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "tokens": [
    "The",
    "fact",
    "is",
    "that",
    "the",
    "geese",
    "just",
    "went",
    "back",
    "to",
    "get",
    "a",
    "rest",
    "and",
    "I",
    "'m",
    "not",
    "banking",
    "on",
    "their",
    "return",
    "soon"
  ],
  "posTags": [
    "DET",
    "NOUN",
    "VERB",
    "SCONJ",
    "DET",
    "NOUN",
    "ADV",
    "VERB",
    "ADV",
    "PART",
    "VERB",
    "DET",
    "NOUN",
    "CONJ",
    "PRON",
    "VERB",
    "PART",
    "VERB",
    "ADP",
    "DET",
    "NOUN",
    "ADV"
  ],
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:12 GMT, Thu, 22 Jun 2017 17:24:12 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "2cf077d1-d7a1-4847-9075-9ecce95834da",
    "x-rosetteapi-processedlanguage": "eng",
    "x-rosetteapi-stats-admsentencecount": "1",
    "x-rosetteapi-stats-admtokencount": "22",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-processedby": "whole-document-language@10.1.1.171,base-linguistics@10.1.1.171",
    "x-rosetteapi-stats-admscriptregioncount": "1",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Parts-of-Speech REST endpoint is https://api.rosette.com/rest/v1/morphology/parts-of-speech

The morphology endpoint grammatically analyzes text to determine the role of each word within the input. The Parts-of-Speech feature returns a part-of-speech (POS) tag for each of the words, depending on the context of how it is used.

For example, spoke can be classified as a noun or a verb. “The wheel spoke creaked,” (noun) compared to, “She spoke the truth” (verb).

Universal POS Tags

All of the supported languages return the following Universal Parts-of-Speech Tags:

Han-Readings


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Get the complete morphological analysis of a piece of text"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();
var api = new Api(args.key, args.url);
var endpoint = "morphology";

var morphology_han_readings_data = "北京大学生物系主任办公室内部会议";
var content = morphology_han_readings_data;

api.parameters.content = content;
api.parameters.morphology = "han-readings";

api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class morphology_han_readings
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //morphology_han_readings yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            } 
            try
            {
                CAPI MorphologyCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string morphology_han_readings_data = @"北京大学生物系主任办公室内部会议";
                //The results of the API call will come back in the form of a Dictionary
                MorphologyResponse response = MorphologyCAPI.Morphology(morphology_han_readings_data, null, null, null, MorphologyFeature.hanReadings);
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

morphology_han_readings_data <- "北京大学生物系主任办公室内部会议"

parameters <- list()
parameters[[ "content" ]] <- morphology_han_readings_data
parameters[[ "morphology" ]] <- "han-readings"

if (is.na(opt$url)){
   result <- api(opt$key, "morphology", parameters)
} else {
   result <- api(opt$key, "morphology", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
    rosette_api = RosetteAPI.new(api_key)
else
    rosette_api = RosetteAPI.new(api_key, url)
end

morphology_han_readings_data = "北京大学生物系主任办公室内部会议"
begin
    params = DocumentParameters.new(content: morphology_han_readings_data)
    response = rosette_api.get_han_readings(params)
    puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
    printf("Rosette API Error (%s): %s", rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.api.MorphologicalFeature;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.MorphologyOptions;
import com.basistech.rosette.apimodel.MorphologyResponse;

import java.io.IOException;

public final class MorphologyHanReadingsExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new MorphologyHanReadingsExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String morphologyHanReadingsData = "北京大学生物系主任办公室内部会议";
        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                .key(getApiKeyFromSystemProperty())
                .url(getAltUrlFromSystemProperty())
                .build();
        DocumentRequest<MorphologyOptions> request = new DocumentRequest.Builder<MorphologyOptions>().content(morphologyHanReadingsData)
                .build();
        MorphologyResponse response = rosetteApi.perform(HttpRosetteAPI.MORPHOLOGY_SERVICE_PATH + "/" + MorphologicalFeature.HAN_READINGS,
                request, MorphologyResponse.class);
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteConstants;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$morphology_han_readings_data = "北京大学生物系主任办公室内部会议";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$params->set('content', $morphology_han_readings_data);

try {
    $result = $api->morphology($params, RosetteConstants::$MorphologyOutput['HAN_READINGS']);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, DocumentParameters, RosetteException


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)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"content": "北京大学生物系主任办公室内部会议"}' \
    "https://api.rosette.com/rest/v1/morphology/han-readings"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "tokens": [
    "北京大学",
    "生物系",
    "主任",
    "办公室",
    "内部",
    "会议"
  ],
  "hanReadings": [
    [
      "Bei3-jing1-Da4-xue2"
    ],
    null,
    [
      "zhu3-ren4"
    ],
    [
      "ban4-gong1-shi4"
    ],
    [
      "nei4-bu4"
    ],
    [
      "hui4-yi4"
    ]
  ],
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:11 GMT, Thu, 22 Jun 2017 17:24:11 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "8a6d9a34-0820-408d-8a64-0aea439ddd56",
    "x-rosetteapi-processedlanguage": "zho",
    "x-rosetteapi-stats-admsentencecount": "1",
    "x-rosetteapi-stats-admtokencount": "6",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-processedby": "whole-document-language@10.1.1.171,base-linguistics@10.1.1.171",
    "x-rosetteapi-stats-admscriptregioncount": "1",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Han-Readings REST endpoint is https://api.rosette.com/rest/v1/morphology/han-readings

The Han-readings feature provides pronounciation information for Han script, in both Chinese and Japanese input text.

For Chinese tokens in Han script, Rosette returns pinyin transcriptions.
If you call Rosette with “美国大选中的”, it returns these Han-readings: “Mei3-guo2”, “da4-xuan3”, “zhong1”, “de0”.

For Japanese tokens in Han script, Rosette returns Furigana transcriptions rendered in Hiragana.
If you call Rosette with “医療番組”, it returns these Han-readings: “イリョウ”, “バングミ”.

You can specify the language of your input by including the three-letter language code within your request. If you do not include this field then Rosette automatically detects the language of the input.

Complete


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Get the complete morphological analysis of a piece of text"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();
var api = new Api(args.key, args.url);
var endpoint = "morphology";

var morphology_complete_data = "The quick brown fox jumped over the lazy dog. 👍🏾 Yes he did. B)";
var content = morphology_complete_data;

api.parameters.content = content;
api.parameters.morphology = "complete";

api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class morphology_complete
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //morphology_complete yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            } 
            try
            {
                CAPI MorphologyCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string morphology_complete_data = @"The quick brown fox jumped over the lazy dog. 👍🏾 Yes he did. B)";
                //The results of the API call will come back in the form of a Dictionary
                MorphologyResponse response = MorphologyCAPI.Morphology(morphology_complete_data);
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

morphology_complete_data <- "The quick brown fox jumped over the lazy dog. 👍🏾 Yes he did. B)"

parameters <- list()
parameters[[ "content" ]] <- morphology_complete_data
parameters[[ "morphology" ]] <- "complete"

if (is.na(opt$url)){
   result <- api(opt$key, "morphology", parameters)
} else {
   result <- api(opt$key, "morphology", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

morphology_complete_data = "The quick brown fox jumped over the lazy dog. 👍🏾 Yes he did. B)"
begin
    params = DocumentParameters.new(content: morphology_complete_data)
    response = rosette_api.get_morphology_complete(params)
    puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
    printf("Rosette API Error (%s): %s", rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.api.MorphologicalFeature;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.MorphologyOptions;
import com.basistech.rosette.apimodel.MorphologyResponse;

import java.io.IOException;

public final class MorphologyCompleteExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new MorphologyCompleteExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String morphologyCompleteData = "The quick brown fox jumped over the lazy dog. 👍🏾 Yes he did. B)";

        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                                    .key(getApiKeyFromSystemProperty())
                                    .url(getAltUrlFromSystemProperty())
                                    .build();
        DocumentRequest<MorphologyOptions> request = new DocumentRequest.Builder<MorphologyOptions>().content(morphologyCompleteData).build();
        //The api object creates an http client, but to provide your own:
        //api.httpClient(CloseableHttpClient)
        MorphologyResponse response = rosetteApi.perform(HttpRosetteAPI.MORPHOLOGY_SERVICE_PATH + "/" + MorphologicalFeature.COMPLETE, request, MorphologyResponse.class);
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteConstants;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$morphology_complete_data = "The quick brown fox jumped over the lazy dog. 👍🏾 Yes he did. B)";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$params->set('content', $morphology_complete_data);

try {
    $result = $api->morphology($params, RosetteConstants::$MorphologyOutput['COMPLETE']);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, DocumentParameters, RosetteException


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. B)"
    params = DocumentParameters()
    params["content"] = morphology_complete_data
    try:
        return api.morphology(params)
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"content": "The quick brown fox jumped over the lazy dog. 👍🏾 Yes he did. B)"}' \
    "https://api.rosette.com/rest/v1/morphology/complete"

The example above returns JSON with the following fragments:


{
  "tokens": [
    "The",
    "quick",
    "brown",
    "fox",
    "jumped",
    "over",
    "the",
    "lazy",
    "dog",
    ".",
    "👍🏾",
    "Yes",
    "he",
    "did",
    ".",
    "B)"
  ],
  "posTags": [
    "DET",
    "ADJ",
    "ADJ",
    "NOUN",
    "VERB",
    "ADP",
    "DET",
    "ADJ",
    "NOUN",
    "PUNCT",
    "SYM",
    "ADV",
    "PRON",
    "VERB",
    "PUNCT",
    "SYM"
  ],
  "lemmas": [
    "the",
    "quick",
    "brown",
    "fox",
    "jump",
    "over",
    "the",
    "lazy",
    "dog",
    ".",
    "👍",
    "yes",
    "he",
    "do",
    ".",
    "B)"
  ],
  "compoundComponents": [
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null
  ],
  "hanReadings": [
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null
  ],
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:11 GMT, Thu, 22 Jun 2017 17:24:11 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "9d267911-e24e-4d4c-a781-ed61292e1ab3",
    "x-rosetteapi-processedlanguage": "eng",
    "x-rosetteapi-stats-admsentencecount": "3",
    "x-rosetteapi-stats-admtokencount": "16",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-processedby": "whole-document-language@10.1.1.171,base-linguistics@10.1.1.171",
    "x-rosetteapi-stats-admscriptregioncount": "1",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Complete Morphology REST endpoint is https://api.rosette.com/rest/v1/morphology/complete

You can call the complete set of Morphology features and Rosette returns the lemmas, compound components, Han-readings, and parts-of-speach tags for the input text.

Check Language Support for the input languages supported by each of the features.

Language Support

You can specify the language of your input with the three-letter language code. If you do not specify the language then Rosette automatically detects it.

Language (code) Parts-of-Speech Lemmas Compound Components Han-Readings
Arabic (ara)
Chinese: Simplified & Traditional (zho)
Czech (ces)
Danish (dan)
Dari (prs)
Dutch (nld)
English (eng)
French (fra)
German (deu)
Greek (ell)
Hungarian (hun)
Italian (ita)
Japanese (jpn)
Korean (kor)
Norwegian: Bokmål & Nynorsk (nor)
Persian (fas)
Polish (pol)
Portuguese (por)
Romanian (ron)
Russian (rus)
Spanish (spa)
Swedish (swe)
Urdu (urd)
Western Farsi (pes)

Tokenization

Introduction


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Get the words in a piece of text"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();
var api = new Api(args.key, args.url);
var endpoint = "tokens";

var tokens_data = "北京大学生物系主任办公室内部会议";
var content = tokens_data;
api.parameters.content = content;

api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class tokens
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //tokens yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            }
            try
            {
                CAPI TokensCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string tokens_data = @"北京大学生物系主任办公室内部会议";
                //The results of the API call will come back in the form of a Dictionary
                TokenizationResponse response = TokensCAPI.Tokens(tokens_data, null, "sentence", null);
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

tokens_data <- "北京大学生物系主任办公室内部会议"

parameters <- list()
parameters[[ "content" ]] <- tokens_data

if (is.na(opt$url)){
   result <- api(opt$key, "tokens", parameters)
} else {
   result <- api(opt$key, "tokens", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

tokens_data = "北京大学生物系主任办公室内部会议"
begin
  params = DocumentParameters.new(content: tokens_data)
  response = rosette_api.get_tokens(params)
  puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
  printf('Rosette API Error (%s): %s', rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.TokensResponse;

import java.io.IOException;

public final class TokensExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new TokensExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String tokensData = "北京大学生物系主任办公室内部会议";

        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                .key(getApiKeyFromSystemProperty())
                .url(getAltUrlFromSystemProperty())
                .build();
        //The api object creates an http client, but to provide your own:
        //api.httpClient(CloseableHttpClient)
        // When no options, use <?>.
        DocumentRequest<?> request = new DocumentRequest.Builder<>().content(tokensData).build();
        TokensResponse response = rosetteApi.perform(HttpRosetteAPI.TOKENS_SERVICE_PATH, request, TokensResponse.class);
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteConstants;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$tokens_data = "北京大学生物系主任办公室内部会议";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$params->set('content', $tokens_data);

try {
    $result = $api->tokens($params);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, DocumentParameters, RosetteException


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
    try:
        return api.tokens(params)
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"content": "北京大学生物系主任办公室内部会议"}' \
    "https://api.rosette.com/rest/v1/tokens"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "tokens": [
    "北京大学",
    "生物系",
    "主任",
    "办公室",
    "内部",
    "会议"
  ],
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:14 GMT, Thu, 22 Jun 2017 17:24:14 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "d203c7f5-d3f4-4c34-85c4-4d7985177069",
    "x-rosetteapi-processedlanguage": "zho",
    "x-rosetteapi-stats-admsentencecount": "1",
    "x-rosetteapi-stats-admtokencount": "6",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-processedby": "whole-document-language@10.1.1.171,base-linguistics@10.1.1.171",
    "x-rosetteapi-stats-admscriptregioncount": "1",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Tokenization REST endpoint is: https://api.rosette.com/rest/v1/tokens

Rosette identifies and separates each word into one or more tokens through advanced statistical modeling. A token is an atomic element such as a word, number, possessive affix, or punctuation.

The resulting token output minimizes index size, enhances search accuracy, and increases relevancy.

Know what your language is?

If you know the language of your input, include the three-letter language code in your call to speed up the response time.

Otherwise, Rosette identifies the language of your input.

Language Support

You can specify the language of your input with the three-letter language code. If you do not specify the language then Rosette automatically detects it.

Language (code)

Sentence Tagging

Introduction


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Get sentences from a piece of text"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();

var api = new Api(args.key, args.url);
var endpoint = "sentences";

var sentences_data = "This land is your land. This land is my land, from California to the New York island; from the red wood forest to the Gulf Stream waters. This land was made for you and Me. As I was walking that ribbon of highway, I saw above me that endless skyway: I saw below me that golden valley: This land was made for you and me.";
var content = sentences_data;

api.parameters.content = content;

api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class sentences
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //sentences yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            }
            try
            {
                CAPI SentencesCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string sentences_data = @"This land is your land. This land is my land, from California to the New York island; from the red wood forest to the Gulf Stream waters. This land was made for you and Me. As I was walking that ribbon of highway, I saw above me that endless skyway: I saw below me that golden valley: This land was made for you and me.";
                //The results of the API call will come back in the form of a Dictionary
                SentenceTaggingResponse response = SentencesCAPI.Sentences(sentences_data);
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

sentences_data <- "This land is your land. This land is my land, from California to the New York island; from the red wood forest to the Gulf Stream waters. This land was made for you and Me. As I was walking that ribbon of highway, I saw above me that endless skyway: I saw below me that golden valley: This land was made for you and me."

parameters <- list()
parameters[[ "content" ]] <- sentences_data

if (is.na(opt$url)){
   result <- api(opt$key, "sentences", parameters)
} else {
   result <- api(opt$key, "sentences", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

sentences_data = "This land is your land. This land is my land, from California to the New York island; from the red wood forest to the Gulf Stream waters. This land was made for you and Me. As I was walking that ribbon of highway, I saw above me that endless skyway: I saw below me that golden valley: This land was made for you and me."

begin
  params = DocumentParameters.new
  params.content = sentences_data
  response = rosette_api.get_sentences(params)
  puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
  printf('Rosette API Error (%s): %s', rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.SentencesResponse;

import java.io.IOException;

public final class SentencesExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new SentencesExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String sentencesData = "This land is your land. This land is my land, from California to the New York island; from the red wood forest to the Gulf Stream waters. This land was made for you and Me. As I was walking that ribbon of highway, I saw above me that endless skyway: I saw below me that golden valley: This land was made for you and me.";

        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                .key(getApiKeyFromSystemProperty())
                .url(getAltUrlFromSystemProperty())
                .build();
        //The api object creates an http client, but to provide your own:
        //api.httpClient(CloseableHttpClient)
        // When no options, use <?>.
        DocumentRequest<?> request = new DocumentRequest.Builder<>().content(sentencesData).build();
        SentencesResponse response = rosetteApi.perform(HttpRosetteAPI.SENTENCES_SERVICE_PATH, request, SentencesResponse.class);
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$sentences_data = "This land is your land. This land is my land, from California to the New York island; from the red wood forest to the Gulf Stream waters. This land was made for you and Me. As I was walking that ribbon of highway, I saw above me that endless skyway: I saw below me that golden valley: This land was made for you and me.";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$content = $sentences_data;
$params->set('content', $content);

try {
    $result = $api->sentences($params);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, DocumentParameters, RosetteException


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, from California to the New York island; from the red wood forest to the Gulf Stream waters. This land was made for you and Me. As I was walking that ribbon of highway, I saw above me that endless skyway: I saw below me that golden valley: This land was made for you and me."
    params = DocumentParameters()
    params["content"] = sentences_data

    try:
        return api.sentences(params)
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"content": "This land is your land. This land is my land, from California to the New York island; from the red wood forest to the Gulf Stream waters. This land was made for you and Me. As I was walking that ribbon of highway, I saw above me that endless skyway: I saw below me that golden valley: This land was made for you and me." }' \
    "https://api.rosette.com/rest/v1/sentences"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "sentences": [
    "This land is your land. ",
    "This land is my land, from California to the New York island; from the red wood forest to the Gulf Stream waters. ",
    "This land was made for you and Me. ",
    "As I was walking that ribbon of highway, I saw above me that endless skyway: I saw below me that golden valley: This land was made for you and me."
  ],
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:13 GMT, Thu, 22 Jun 2017 17:24:13 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "43e164fd-d7b6-4eb3-b54a-c8a167095327",
    "x-rosetteapi-processedlanguage": "eng",
    "x-rosetteapi-stats-admsentencecount": "4",
    "x-rosetteapi-stats-admtokencount": "74",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-processedby": "whole-document-language@10.1.1.171,base-linguistics@10.1.1.171",
    "x-rosetteapi-stats-admscriptregioncount": "1",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Sentence Tagging REST endpoint is https://api.rosette.com/rest/v1/sentences

Rosette can parse your input and return a list of sentences.

It can identify the start and end of each sentence, even though punctuation may be ambiguous.

Know what your language is?

If you know the language of your input, include the three-letter language code in your call to speed up the response time.

Otherwise, Rosette identifies the language of your input.

Language Support

You can specify the language of your input with the three-letter language code. If you do not specify the language then Rosette automatically detects it.

Language (code)

Name Translation

Introduction


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Translate a name from one language to another"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();
var api = new Api(args.key, args.url);
var endpoint = "nameTranslation";

var translated_name_data = "معمر محمد أبو منيار القذاف";
api.parameters.name = translated_name_data;
api.parameters.entityType = "PERSON";
api.parameters.targetLanguage = "eng";
api.parameters.targetScript = "Latn";

api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class translated_name
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //translated_name yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            }
            try
            {
                CAPI TranslatedNameCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string translated_name_data = @"معمر محمد أبو منيار القذاف";
                //The results of the API call will come back in the form of a Dictionary
                TranslateNamesResponse response = TranslatedNameCAPI.NameTranslation(translated_name_data, null, null, "eng", "Latn", null, null, "PERSON");
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

translated_name_data <- "معمر محمد أبو منيار القذاف"

parameters <- list()
parameters[[ "name" ]] <- translated_name_data
parameters[[ "targetLanguage" ]] <- "eng"
parameters[[ "targetScript" ]] <- "Latn"

if (is.na(opt$url)){
   result <- api(opt$key, "name-translation", parameters)
} else {
   result <- api(opt$key, "name-translation", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

translated_name_data = "معمر محمد أبو منيار القذاف"
begin
  params = NameTranslationParameters.new(translated_name_data, 'eng', target_script: 'Latn')
  response = rosette_api.get_name_translation(params)
  puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
  printf('Rosette API Error (%s): %s', rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.NameTranslationRequest;
import com.basistech.rosette.apimodel.NameTranslationResponse;
import com.basistech.util.LanguageCode;

import java.io.IOException;

public final class NameTranslationExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new NameTranslationExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String translatedNameData = "معمر محمد أبو منيار القذاف";
        NameTranslationRequest request = new NameTranslationRequest.Builder(translatedNameData, LanguageCode.ENGLISH)
                .build();

        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                                    .key(getApiKeyFromSystemProperty())
                                    .url(getAltUrlFromSystemProperty())
                                    .build();
        //The api object creates an http client, but to provide your own:
        //api.httpClient(CloseableHttpClient)
        NameTranslationResponse response = rosetteApi.perform(HttpRosetteAPI.NAME_TRANSLATION_SERVICE_PATH, request, NameTranslationResponse.class);
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\NameTranslationParameters;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$name_translation_data = "معمر محمد أبو منيار القذاف";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new NameTranslationParameters();
$params->set('name', $name_translation_data);
$params->set('targetLanguage', 'eng');
$params->set('targetScript', 'Latn');
$params->set('targetScheme', 'IC');
$params->set('sourceLanguageOfOrigin', 'ara');
$params->set('sourceLanguageOfUse', 'ara');


try {
    $result = $api->nameTranslation($params);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, NameTranslationParameters, RosetteException


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"
    try:
        return api.name_translation(params)
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"name": "معمر محمد أبو منيار القذاف", "targetLanguage": "eng", "targetScript": "Latn"}"' \
    "https://api.rosette.com/rest/v1/name-translation"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "translation": "Mu'ammar Muhammad Abu-Minyar al-Qadhaf",
  "targetLanguage": "eng",
  "targetScript": "Latn",
  "targetScheme": "IC",
  "confidence": 0.06856099342585828,
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:12 GMT, Thu, 22 Jun 2017 17:24:12 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "b047149c-5d9b-430c-9d59-6d40f5bd213f",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Name Translation REST endpoint is: https://api.rosette.com/rest/v1/name-translation

The name translation endpoint can translate the name of an entity (Person, Location, or Organization) from English to another language, or to English from another language.

When you are converting from English to another language, the endpoint is optimized to convert the English version of a person’s name back to the native language of that name. For example, you can translate Vladimir Nabokov into Russian (rus) and the endpoint returns "translation": "Владимир Набоков".

Confidence

Rosette returns a confidence score with each entity result, ranging from 0 to 1. It is a measurement that you can use as a threshold for filtering out undesired results.

Request Fields

You must specify the name and the targetLanguage for the translation when you submit a request to the /name-translation endpoint.

For example, to translate “بدر شاكر السياب” from Arabic to English, “Badr Shakir al-Sayyab”, you would use the values in the Example column.

Field Description Value Example
name Name to translate String “بدر شاكر السياب”
targetLanguage Translate name into this language 3-letter language code eng

Optionally, you can include any of the following fields:

Field Description Value Example
entityType The type of name PERSON (default), LOCATION, or ORGANIZATION PERSON
sourceScript Script of the name as in the input 4-letter script abbr. Arab
sourceLanguageOfOrigin Native language the name originates in 3-letter language code ara
sourceLanguageOfUse ¹ Language of the name as in the input 3-letter language code ara
targetScript Translate name into this script 4-letter script abbr. Latn
targetScheme (ADVANCED-USE ONLY) Scheme for transliteration Translit. scheme abbr. IC

Language Support

The name translation endpoint supports translations from the following languages and scripts to English. It also supports translation from English to all of these languages, except Japanese and Urdu.

When translating from English, we recommend you use the endpoint to translate names of people to the name’s native language.

Language (code) Script(s) (Abbr.) Transliteration scheme(s) (ABBR.) ¹
Arabic (ara) Arabic (Arab) Default (IC); Standard Arabic Technical Transliteration System (SATTS), US Board on Geographic Names (BGN)
Chinese: Simplified & Traditional (zho Han (Hani) Default (IC); Hanyu Pinyin (HYPY), Hanyu Pinyin Toned (HYPY_TONED)
English (eng) Latin (Latn) Default (NATIVE)**
Hindi (hin) Devanagari (Deva) Default (NATIVE)**
Japanese (jpn Kanji (Hani), Hiragana (Hira), Katakana (Kana) Default, Hebon Romaji (HEBON); Kunrei Romaji (KUNREI)
Korean (kor Hangul (Hang), Hanja (Hani) Default, Revised Romanization of Korean (MOCT); McCune-Reischauer (MCR)
Pashto (pus) Arabic (Arab) Default (IC); US Board on Geographic Names (BGN)
Persian:
Dari (prs), Western Farsi (pes) & Persian (‘fas’)
Arabic (Arab) Default (IC); US Board on Geographic Names (BGN)
Russian (rus) Cyrillic (Cyrl) Default (IC); US Board on Geographic Names (BGN)
Urdu (urd) Arabic (Arab) Default (IC); US Board on Geographic Names (BGN)

Name Similarity

Introduction


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Get the similarity score of two names"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();
var api = new Api(args.key, args.url);
var endpoint = "nameSimilarity";

var matched_name_data1 = "Michael Jackson";
var matched_name_data2 = "迈克尔·杰克逊";

api.parameters.name1 = {"text": matched_name_data1, "language": "eng", "entityType": "PERSON"};
api.parameters.name2 = {"text": matched_name_data2, "entityType": "PERSON"};

api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class matched_name
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //matched_name yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            } 
            try
            {
                CAPI MatchedNameCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string matched_name_data1 = @"Michael Jackson";
                string matched_name_data2 = @"迈克尔·杰克逊";
                //The results of the API call will come back in the form of a Dictionary
                NameSimilarityResponse response = MatchedNameCAPI.NameSimilarity(new Name(matched_name_data1, "eng", null, "PERSON"), new Name(matched_name_data2, null, null, "PERSON"));
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

matched_name_data1 <- "Michael Jackson"
matched_name_data2 <- "迈克尔·杰克逊"

parameters <- list()
parameters[[ "name1" ]] <- matched_name_data1
parameters[[ "name2" ]] <- matched_name_data2

if (is.na(opt$url)){
   result <- api(opt$key, "name-similarity", parameters)
} else {
   result <- api(opt$key, "name-similarity", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

matched_name_data1 = "Michael Jackson"
matched_name_data2 = "迈克尔·杰克逊"
begin
  name1 = NameParameter.new(matched_name_data1, entity_type: 'PERSON', language: 'eng')
  params = NameSimilarityParameters.new(name1, matched_name_data2)
  response = rosette_api.get_name_similarity(params)
  puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
  printf('Rosette API Error (%s): %s', rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.Name;
import com.basistech.rosette.apimodel.NameSimilarityRequest;
import com.basistech.rosette.apimodel.NameSimilarityResponse;
import com.basistech.util.ISO15924;
import com.basistech.util.LanguageCode;

import java.io.IOException;

public final class NameSimilarityExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new NameSimilarityExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String matchedNameData1 = "Michael Jackson";
        String matchedNameData2 = "迈克尔·杰克逊";
        Name name1 = new Name(matchedNameData1, "PERSON", ISO15924.Zyyy, LanguageCode.ENGLISH);
        Name name2 = new Name(matchedNameData2);
        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                                    .key(getApiKeyFromSystemProperty())
                                    .url(getAltUrlFromSystemProperty())
                                    .build();
        //The api object creates an http client, but to provide your own:
        //api.httpClient(CloseableHttpClient)
        NameSimilarityRequest request = new NameSimilarityRequest(name1, name2);
        NameSimilarityResponse response = rosetteApi.perform(HttpRosetteAPI.NAME_SIMILARITY_SERVICE_PATH, request, NameSimilarityResponse.class);
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\Name;
use rosettepi\NameSimilarityParameters;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$name_similarity_data1 = "Michael Jackson";
$name_similarity_data2 = "迈克尔·杰克逊";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new NameSimilarityParameters(new Name($name_similarity_data1), new Name($name_similarity_data2));

try {
    $result = $api->nameSimilarity($params);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, NameSimilarityParameters, RosetteException


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"}
    try:
        return api.name_similarity(params)
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"name1": {"text": "Michael Jackson"}, "name2": {"text": "迈克尔·杰克逊"} }' \
    "https://api.rosette.com/rest/v1/name-similarity"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "score": 0.7340747743038697,
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:12 GMT, Thu, 22 Jun 2017 17:24:12 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "6a303e6d-2be3-471c-913b-02f40b7e6f1f",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Name Similarity REST endpoint is https://api.rosette.com/rest/v1/name-similarity

Rosette can compare two entity names (Person, Location, or Organization) and return a match score from 0 to 1.

Rosette handles name variations (such as misspellings and nicknames) with multilingual support by using a linguistic, statistically-based system.

Request Fields

Example:

{
  "name1": {
    "text": "Влади́мир Влади́мирович Пу́тин",
    "language": "rus",
    "entityType": "PERSON"
  },
  "name2": {
    "text": "Vladimir Putin",
    "language": "eng",
    "entityType": "PERSON"
  }
}

{
  "result": {
    "score": 0.9486632809417912
  }
}

When you submit a name-similarity request, you must specify name1 and name2 with the text for each. Although not required, we strongly recommend specifying the source language (if known) for better accuracy. If you do not specify the source language then the Rosette name similarity algorithm will guess the language.

NOTE: Do not use the Rosette language detection endpoint to determine source language of names as the language guesser within the name similarity endpoint uses an algorithm tuned specifically for names rather than general text.

For each name, you can also include any of the additional fields that appear in the following table.

Field Description Required
text Name to match yes
language Three-letter language code for the name no
entityType PERSON (default), LOCATION, or ORGANIZATION no
script Four-letter language code for script in which the name is written no

Based on the text of the two names, the Rosette Name Similarity endpoint infers values for any of the fields you do not specify, and uses these values when it calculates the match score. If you know the value, especially entityType and language (in cases where the language may be difficult to infer accurately, such as a Japanese or Korean name in Han script), you may improve the accuracy of the match score by specifying the field. See Language Support for languages that are supported.

The Rosette Name Similarity endpoint determines a score by matching tokens generated from both input names. If the names do not have a specified entityType and contain a small number of tokens, Rosette Name Similarity will attempt to match the few tokens as best it can. Without more information, names with a small number of generated tokens will produce the same similarity score. For example, without an entityType of Location, the similarity scores for Canada to Mexico and Beijing to Mexico are the same.

Language Support

The Rosette Name Similarity endpoint supports matches between names in the following languages. It also supports matching names between all these languages and English.

Language (code) Script(s) (Abbr.)
Arabic (ara) Arabic (Arab)
Chinese: Simplified & Traditional (zho Han (Hani)
English (eng) Latin (Latn)
French (fra) Latin (Latn)
German (deu) Latin (Latn)
Italian (ita) Latin (Latn)
Japanese (jpn Han (Hani), Hiragana (Hira), Katakana (Kana), (Hrkt) Hira + Kana, Japanese (Jpan) Han + Hira + Kana
Korean (kor Hangul (Hang), Han (Hani), Korean (Kor) Hang + Hani
Pashto (pus) Arabic (Arab)
Persian: Dari & Farsi (fas) Arabic (Arab)
Portuguese (por) Latin (Latn)
Russian (rus) Cyrillic (Cyrl)
Spanish (spa) Latin (Latn)
Urdu (urd) Arabic (Arab)

API Information


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Get information about Rosette API"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();
var api = new Api(args.key, args.url);
var endpoint = "info";

api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class info
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //info yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            } 
            try
            {
                CAPI InfoCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                //The results of the API call will come back in the form of a Dictionary
                InfoResponse response = InfoCAPI.Info();
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

if (is.na(opt$url)){
   result <- api(opt$key, "info")
} else {
   result <- api(opt$key, "info", FALSE, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end
response = rosette_api.info
begin
    puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
    printf("Rosette API Error (%s): %s", rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.InfoResponse;

import java.io.IOException;

public final class InfoExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new InfoExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                                .key(getApiKeyFromSystemProperty())
                                .url(getAltUrlFromSystemProperty())
                                .build();
        //The api object creates an http client, but to provide your own:
        //api.httpClient(CloseableHttpClient)
        InfoResponse response = rosetteApi.info();
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}

$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);

try {
    $result = $api->info();
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, RosetteException


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.ping()
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


# result is a python dictionary with the message that
# appears in the JSON below.

curl -X GET \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    "https://api.rosette.com/rest/v1/info/"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "name": "Rosette API",
  "version": "1.7.100.201706132118",
  "buildNumber": "",
  "buildTime": "01706132",
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:11 GMT, Thu, 22 Jun 2017 17:24:11 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "9589bbe1-98cb-4436-829d-0c51daec85d1",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Info REST endpoint is: https://api.rosette.com/rest/v1/info

Retrieves API information such as version and build.

Processing Local Files


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;
var tmp = require("temporary");

var parser = new ArgumentParser({
  addHelp: true,
  description: "Get the sentiment of the text in a local file"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();

var file = new tmp.File();
var 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>";
var fileContents = sentiment_file_data;

file.writeFileSync(fileContents);

var api = new Api(args.key, args.url);
var endpoint = "sentiment";

api.parameters.documentFile = file.path;
api.parameters.language = "eng";

api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class sentiment
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //sentiment yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            }

            try
            {
                CAPI SentimentCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                var newFile = Path.GetTempFileName();
                StreamWriter sw = new StreamWriter(newFile);
                string 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>";
                sw.WriteLine(sentiment_file_data);
                sw.Flush();
                sw.Close();
                //Rosette API provides File upload options (shown here)
                //Simply create a new RosetteFile using the path to a file
                //The results of the API call will come back in the form of a Dictionary
                SentimentResponse response = SentimentCAPI.Sentiment(new RosetteFile(newFile, @"application/octet-stream", "{\"language\":\"eng\"}"));
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());

                if (File.Exists(newFile)) {
                    File.Delete(newFile);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

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>"

parameters <- list()
parameters[[ "content" ]] <- sentiment_file_data
parameters[[ "documentFile" ]] <- "true"

if (is.na(opt$url)){
   result <- api(opt$key, "sentiment", parameters)
} else {
   result <- api(opt$key, "sentiment", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'tempfile'
require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

file = Tempfile.new(%w[foo .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>"
file.write(sentiment_file_data)
file.close
begin
  params = DocumentParameters.new(file_path: file.path, language: 'eng')
  response = rosette_api.get_sentiment(params)
  puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
  printf('Rosette API Error (%s): %s', rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.SentimentOptions;
import com.basistech.rosette.apimodel.SentimentResponse;

import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public final class SentimentExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new SentimentExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        // the temp file substitutes for an actual disk file.
        String sentimentFileData = "<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>";
        try (InputStream inputStream = Files.newInputStream(createTempDataFile(sentimentFileData))) {
            HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                    .key(getApiKeyFromSystemProperty())
                    .url(getAltUrlFromSystemProperty())
                    .build();
            //The api object creates an http client, but to provide your own:
            //api.httpClient(CloseableHttpClient)
            // When no options, use <?>.
            DocumentRequest<SentimentOptions> request = new DocumentRequest.Builder<SentimentOptions>().contentBytes(inputStream, "text/html").build();
            SentimentResponse response = rosetteApi.perform(HttpRosetteAPI.SENTIMENT_SERVICE_PATH, request, SentimentResponse.class);
            System.out.println(responseToJson(response));
        }

    }

    private static Path createTempDataFile(String data) throws IOException {
        Path file = Files.createTempFile("example.", ".html");
        try (Writer writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
            writer.write(data);
        }
        file.toFile().deleteOnExit();
        return file;
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$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>";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$params->set('language', 'eng');
$content = $sentiment_file_data;
$temp = tmpfile();  // write above html content to a temp file
fwrite($temp, $content);
$params->loadDocumentFile(stream_get_meta_data($temp)['uri']);

try {
    $result = $api->sentiment($params);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
} finally {
    fclose($temp);  // clean up the temp file
}


import argparse
import json
import os
import tempfile

from rosette.api import API, DocumentParameters, RosetteException


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


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"content": "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.”" }' \
    "https://api.rosette.com/rest/v1/sentiment"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "document": {
    "label": "pos",
    "confidence": 0.7962072011038756
  },
  "entities": [
    {
      "type": "PRODUCT",
      "mention": "Ghostbusters",
      "normalized": "Ghostbusters",
      "count": 3,
      "entityId": "Q108745",
      "sentiment": {
        "label": "pos",
        "confidence": 0.8111117726721541
      }
    },
    {
      "type": "PERSON",
      "mention": "Aykroyd",
      "normalized": "Original Ghostbuster Dan Aykroyd",
      "count": 2,
      "entityId": "Q105221",
      "confidence": 0.9990000128746033,
      "sentiment": {
        "label": "pos",
        "confidence": 0.6504190808944779
      }
    },
    {
      "type": "ORGANIZATION",
      "mention": "The Hollywood Reporter",
      "normalized": "The Hollywood Reporter",
      "count": 1,
      "entityId": "Q61503",
      "sentiment": {
        "label": "pos",
        "confidence": 0.5338094035254866
      }
    }
  ],
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:13 GMT, Thu, 22 Jun 2017 17:24:13 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "ff6c1b59-9f51-4d54-a593-6b011188ab4e",
    "x-rosetteapi-processedlanguage": "eng",
    "x-rosetteapi-stats-admentitymentioncount": "6",
    "x-rosetteapi-stats-admentitycount": "3",
    "x-rosetteapi-stats-admscriptregioncount": "1",
    "x-rosetteapi-stats-admsentencecount": "1",
    "x-rosetteapi-stats-requestlanguage": "eng",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-docsizesourcerawbytes": "392",
    "x-rosetteapi-stats-docsizechars": "303",
    "x-rosetteapi-stats-admresolvedentitycount": "3",
    "x-rosetteapi-stats-admtokencount": "55",
    "x-rosetteapi-stats-processedby": "text-extractor@10.1.1.171,entity-extraction@10.1.1.171,sentiment@10.1.1.171",
    "x-rosetteapi-stats-requesttextextraction": "true",
    "x-rosetteapi-stats-content-type": "text/html; charset=UTF-8",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

The Rosette bindings handle files or input streams differently depending on the programming language’s design. There are examples in the right-hand column for each of the supported languages to show how they process the multipart/form-data type of input.

Processing URIs


"use strict";

var Api = require("../lib/Api");
var ArgumentParser = require("argparse").ArgumentParser;

var parser = new ArgumentParser({
  addHelp: true,
  description: "Get the category of a piece of a document at a URL"
});
parser.addArgument(["--key"], {help: "Rosette API key", required: true});
parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false});
var args = parser.parseArgs();
var api = new Api(args.key, args.url);
var endpoint = "categories";

var categories_url_data = "http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/";
api.parameters.contentUri = categories_url_data;

api.rosette(endpoint, function(err, res){
    if(err){
        console.log(err);
    } else {
        console.log(JSON.stringify(res, null, 2));
    }
});


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using rosette_api;

namespace rosette_apiExamples
{
    class categories
    {
        static void Main(string[] args)
        {
            //To use the C# API, you must provide an API key
            string apikey = "Your API key";
            string alturl = string.Empty;

            //You may set the API key via command line argument:
            //categories yourapikeyhere
            if (args.Length != 0)
            {
                apikey = args[0];
                alturl = args.Length > 1 ? args[1] : string.Empty;
            }
            try
            {
                CAPI CategoriesCAPI = string.IsNullOrEmpty(alturl) ? new CAPI(apikey) : new CAPI(apikey, alturl);
                string categories_text_data = @"Sony Pictures is planning to shoot a good portion of the new ""Ghostbusters"" in Boston as well.";
                //The results of the API call will come back in the form of a Dictionary
                CategoriesResponse response = CategoriesCAPI.Categories(categories_text_data,  null, null, null);
                Console.WriteLine(response.ContentAsJson);

                //Rosette API also supports Dictionary inputs
                //Simply instantiate a new dictionary object with the fields options as keys and inputs as values
                string categories_url_data = @"http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/";
                response = CategoriesCAPI.Categories(new Dictionary<object, object>()
                {
                    {"contentUri", categories_url_data}

                });
                foreach (KeyValuePair<string, string> h in response.Headers) {
                    Console.WriteLine(string.Format("{0}:{1}", h.Key, h.Value));
                }
                Console.WriteLine(response.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}


source("../R/Api.R")
library(jsonlite)
library("optparse")

option_list = list( make_option(c("-k", "--key"), action="store", default=NA, type='character',
              help="Rosette API key"), make_option(c("-u", "--url"), action="store", default=NA, type='character',
              help="Rosette API url"))
opt_parser = OptionParser(option_list=option_list)
opt = parse_args(opt_parser)

categories_url_data <- "http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/"

parameters <- list()
parameters[[ "contentUri" ]] <- categories_url_data

if (is.na(opt$url)){
   result <- api(opt$key, "categories", parameters)
} else {
   result <- api(opt$key, "categories", parameters, NULL, NULL, opt$url)
}
print(jsonlite::toJSON(result$header, pretty = TRUE))
print(jsonlite::toJSON(result$content, pretty = TRUE))


require 'rosette_api'

api_key, url = ARGV

if !url
  rosette_api = RosetteAPI.new(api_key)
else
  rosette_api = RosetteAPI.new(api_key, url)
end

categories_url_data = "http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/"
begin
  params = DocumentParameters.new(content_uri: categories_url_data)
  response = rosette_api.get_categories(params)
  puts JSON.pretty_generate(response)
rescue RosetteAPIError => rosette_api_error
  printf('Rosette API Error (%s): %s', rosette_api_error.status_code, rosette_api_error.message)
end


package com.basistech.rosette.examples;

import com.basistech.rosette.api.HttpRosetteAPI;
import com.basistech.rosette.apimodel.CategoriesOptions;
import com.basistech.rosette.apimodel.CategoriesResponse;
import com.basistech.rosette.apimodel.DocumentRequest;

import java.io.IOException;

public final class CategoriesExample extends ExampleBase {
    public static void main(String[] args) {
        try {
            new CategoriesExample().run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void run() throws IOException {
        String categoriesUrlData = "http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/";
        HttpRosetteAPI rosetteApi = new HttpRosetteAPI.Builder()
                                .key(getApiKeyFromSystemProperty())
                                .url(getAltUrlFromSystemProperty())
                                .build();
        //The api object creates an http client, but to provide your own:
        //api.httpClient(CloseableHttpClient)
        DocumentRequest<CategoriesOptions> request = new DocumentRequest.Builder<CategoriesOptions>().contentUri(categoriesUrlData).build();
        CategoriesResponse response = rosetteApi.perform(HttpRosetteAPI.CATEGORIES_SERVICE_PATH, request, CategoriesResponse.class);
        System.out.println(responseToJson(response));
    }
}


<?php

require_once dirname(__FILE__) . '/../vendor/autoload.php';
use rosettepi\Api;
use rosettepi\DocumentParameters;
use rosettepi\RosetteException;

$options = getopt(null, array('key:', 'url::'));
if (!isset($options['key'])) {
    echo 'Usage: php ' . __FILE__ . " --key <api_key> --url=<alternate_url>
";
    exit();
}
$categories_url_data = "http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/";
$api = isset($options['url']) ? new Api($options['key'], $options['url']) : new Api($options['key']);
$params = new DocumentParameters();
$params->set('contentUri', $categories_url_data);

try {
    $result = $api->categories($params);
    var_dump($result);
} catch (RosetteException $e) {
    error_log($e);
}


import argparse
import json
import os

from rosette.api import API, DocumentParameters, RosetteException


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
    try:
        return api.categories(params)
    except RosetteException as e:
        print(e)


parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)
parser.add_argument('-u', '--url', help="Alternative API URL", default='https://api.rosette.com/rest/v1/')

if __name__ == '__main__':
    args = parser.parse_args()
    result = run(args.key, args.url)
    print(json.dumps(result, indent=2, ensure_ascii=False, sort_keys=True).encode("utf8"))


curl -X POST \
    -H "X-RosetteAPI-Key: your_api_key" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"contentUri": "http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/" }' \
    "https://api.rosette.com/rest/v1/categories"

The example above returns a language specific data structure that represents the following JSON from Rosette API


{
  "categories": [
    {
      "label": "ARTS_AND_ENTERTAINMENT",
      "confidence": 0.23572849069656435
    }
  ],
  "responseHeaders": {
    "date": "Thu, 22 Jun 2017 17:24:10 GMT, Thu, 22 Jun 2017 17:24:10 GMT",
    "content-type": "application/json",
    "x-rosetteapi-request-id": "88fbadaa-597b-4920-bdcf-a1b34a9b4343",
    "x-rosetteapi-processedlanguage": "eng",
    "x-rosetteapi-stats-admsentencecount": "8",
    "x-rosetteapi-stats-requestgenre": "social-media",
    "x-rosetteapi-stats-docsizesourcerawbytes": "69510",
    "x-rosetteapi-stats-docsizechars": "616",
    "x-rosetteapi-stats-admtokencount": "120",
    "x-rosetteapi-stats-processedby": "url-content-downloader@10.1.1.171,text-extractor@10.1.1.171,whole-document-language@10.1.1.171,base-linguistics@10.1.1.171,categorization@10.1.1.171",
    "x-rosetteapi-stats-requestcontenturi": "true",
    "x-rosetteapi-stats-requesttextextraction": "true",
    "x-rosetteapi-stats-content-type": "text/html; charset=UTF-8",
    "x-rosetteapi-stats-admscriptregioncount": "1",
    "x-rosetteapi-stats-isadmresponse": "false",
    "connection": "close",
    "server": "Jetty(9.2.11.v20150529)"
  }
}

Processing URI content is supported by submitting {{contentUri}} in your requests.

This procedure is available for all the Rosette API POST endpoints except /name-translation and /name-similarity.

Limitations of the downloading component:

Errors

The Rosette API uses the following error codes:

Error Code Meaning
400 Bad Request – There was something wrong with your request, or the language was not supported by the endpoint.
401 Unauthorized – Your API key was wrong.
403 Forbidden – Access denied. This could be based on plan, limits, or profiles.
404 Not Found – The specified URI could not be found.
405 Method Not Allowed – You tried to access the Rosette API with an invalid method.
406 Not Acceptable – You requested a format that wasn’t JSON.
409 Incompatible Client Version – Your binding was out of date. Please update to the latest version.
413 Too Much Data – Your payload was bigger than the size limit of 600KB, or 50K characters.
429 Too Many Requests – Slow down! Rosette can only process one call at a time.
500 Internal Server Error – We had a problem with our server. Please try again later.
503 Service Unavailable – We’re temporarily offline for maintenance. Please try again later.
Back to Top