Ontology Recommender Client Examples

From NCBO Wiki
Jump to navigation Jump to search

Perl Client Example

use strict;
use LWP::UserAgent;
use URI::Escape;
use XML::LibXML;

$| = 1;

my $RecommenderURL =
  'http://ncbolabs-dev2.stanford.edu:8080/OBS_v1/recommender1.1/';

# Sample text
my $text =
  uri_escape(
"Melanoma is a malignant tumor of melanocytes which are found predominantly in skin but also in the bowel and the eye"
  );

# create a user agent
my $ua = new LWP::UserAgent;

# create a parse to handle the output
my $parser = XML::LibXML->new();

# create a POST request
my $req = new HTTP::Request POST => "$RecommenderURL";
$req->content_type('application/x-www-form-urlencoded');

# Set parameters
$req->content(
	"method=1&"    #values: 1, 2, 3, 4
	  . "output=score&" #values: score, nb-annotating-concepts, normalized-score, overlap
	  . "respository=ncbo&"              #values: ncbo, umls, all
	  . "text=$text&" . "format=xml&"    #values: asText, asTextSimple, asXML
	  . "email=testClient\@NCBO.org"
);

# send request and get response
my $res = $ua->request($req);

# Check the outcome of the response
if ( $res->is_success ) {
	print STDERR "Successful Response...\n";

	my $time = localtime();
	print "Call successful at $time\n";

	print $res->decoded_content;
}
else {
	my $time = localtime();
	print $res->status_line, " at $time\n";
}

sub ParseOBAResponse {
	print STDERR "Parsing response\n";

	my ( $res, $parser ) = @_;
	my $dom  = $parser->parse_string( $res->decoded_content );
	my $root = $dom->getDocumentElement();
	my %MatchedConcepts;
	my %MatchedPhrase;

	my $results =
	  $root->findnodes(
		'/success/data/annotatorResultBean/annotations/annotationBean/concept');
	foreach my $c_node ( $results->get_nodelist ) {

		# Sample XPATH to extract concept info if needed
		print "ID = ",   $c_node->findvalue('localConceptId'), "\n";
		print "Name = ", $c_node->findvalue('preferredName'),  "\n";
		print "Type = ", $c_node->findvalue(
			'./semanticTypes/semanticTypeBean[1]/localSemanticTypeId'), "\n";
		print "Type name = ",
		  $c_node->findvalue('./semanticTypes/semanticTypeBean[1]/name'),
		  "\n\n";

		$MatchedConcepts{ $c_node->findvalue('localConceptId') } =
		  $c_node->findvalue('preferredName');
	}

	my $results =
	  $root->findnodes(
		'/success/data/annotatorResultBean/annotations/annotationBean/context');
	foreach my $c_node ( $results->get_nodelist ) {

		# Sample XPATH to extract concept info if needed
		print "ID = ",    $c_node->findvalue('./term/localConceptId'), "\n";
		print "Match = ", $c_node->findvalue('./term/name'),           "\n";
		print "From = ",  $c_node->findvalue('from'),                  "\n";
		print "To = ",    $c_node->findvalue('to'),                    "\n";

		$MatchedPhrase{ $c_node->findvalue('./term/localConceptId') } =
		  $c_node->findvalue('./term/name');
	}
	return ( \%MatchedConcepts, \%MatchedPhrase );
}