def main(argv): parser = argparse.ArgumentParser(description='Template for storing/analyzing responses from Rosette APIs') parser.add_argument('-k', '--key', required=True, help="rosette api key") args = parser.parse_args() # initialize rosette = "" print "trytext.py: starting up..." ########## # extract text from the file sText = "\"Gigli\" -- which spawned the phenomenon the gossip pages and celebrity magazines so lovingly refer to as \"Bennifer\" -- is every bit as unwatchable as the deafening negative chatter would suggest. The dialogue from writer-/sdirector Martin Brest is clunky, the film has serious tonal inconsistencies and at more than two hours, it drags on way longer than it should. Even making a little game of it, and trying to pinpoint the exact moment when Ben Affleck and Jennifer Lopez fell in love, stops being fun after a while. Perhaps it\'s when he says, in an attempt to seduce her, \"I\'m the bull, you\'re the cow.\" Or when she beckons him into foreplay by lying back in bed and purring, \"Gobble, gobble\" -- which could forever change the way you view your Thanksgiving turkey. But as pop-star vehicles go, \"Gigli\" isn\'t as insufferable as, say, last year\'s Madonna-Guy Ritchie debacle, \"Swept Away.\" It\'s more on par with Mariah Carey\'s \"Glitter\" and Britney Spears\' \"Crossroads.\" If this were a movie starring two B-list actors, or two complete unknowns, it probably would have gone straight to video. After curious masochists and J.Lo fans check it out the first weekend, \"Gigli\" probably will have a drop-off in audience that rivals \"The Hulk\" -- 70 percent -- then go to video. And with the release next spring of Kevin Smith\'s \"Jersey Girl,\" in which they also co-star, we can have this little conversation all over again. For now, we have Affleck starring as incompetent mob thug Larry Gigli. (That\'s pronounced JEE-lee, which rhymes with really, a running joke that isn\'t particularly funny the first time.) Gigli is asked to kidnap Brian (Justin Bartha), the mentally disabled younger brother of a/sfederal prosecutor who\'s going after a New York mobster (Al Pacino). His boss, however, thinks he\'s incapable of handling the assignment alone and sends in Ricki (Lopez), another contractor, to help him. Gigli is an anti-social lout who lives in a seedy apartment. Ricki is beautiful, grounded, enlightened. She quotes Sun Tzu -- who could blame Gigli for falling for her? (And whether you like her or not, Lopez does have an undeniable presence.) But Ricki is also a lesbian -- so it makes absolutely no sense when she falls for him, too, although they have all the obligatory banter and alleged sexual tension required of a romantic comedy. (And it\'s only a romantic comedy sometimes. Other times, it aims to be an edgy action-crime movie; still other times, it aspires for gag-inducing poignancy.) Apparently, the only force that binds them is the fact that they both feel squeamish about cutting off Brian\'s thumb and mailing it to his prosecutor brother. Instead, they break into a morgue and saw the thumb off a corpse using a plastic knife, while Brian -- who has an unexplained penchant for old-school rap -- sings Sir Mix-a-Lot\'s \"Baby Got Back.\" It\'s also incredibly misinformed to suggest that Ricki can be \"converted\" to heterosexuality -- that a man\'s love is all she really needed to allay any confusion about all that silly lesbian stuff. So what you have here is \"Rain Man\" meets \"Chasing Amy\" -- which is apropos, since the latter is a 1997 Kevin Smith movie in which Affleck also starred as a guy who falls for a lesbian. Instead of counting matches and obsessing about \"The People\'s Court\" like Dustin Hoffman\'s \"Rain Man\" character, Brian counts sunflower seeds and obsesses over going to \"the Baywatch.\" Cameos from Pacino, Christopher Walken as a detective and Lainie Kazan as Gigli\'s mother don\'t help, either. Did they owe someone a favor? What are they doing here? Pacino won his one and only Oscar with Brest for 1992\'s \"Scent of a Woman,\" but couldn\'t he have just thanked the director instead? Instead, we get to see Pacino shoot someone in the head, then watch as fish in a nearby aquarium snack on splattered drops of the victim\'s blood." ########## # to do: strip ascii etc? # connect to rosette if not rosette: rosette = API(user_key=args.key) params = DocumentParameters() # send the text params['content'] = sText jResponse = rosette.entities(params) # entity linking is turned off print json.dumps(jResponse, sort_keys=True, indent=4, separators=(',', ': ')) jResponse = rosette.sentiment(params) # entity linking is turned off print json.dumps(jResponse, sort_keys=True, indent=4, separators=(',', ': ')) print "trytext.py: done"
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
def runRosette(text, key, alt_url='https://api.rosette.com/rest/v1/'): """ Run the example """ # Create default file to read from temp_file = tempfile.NamedTemporaryFile(suffix=".html") sentiment_file_data = "<html><head><title></title></head><body><p>" + text + "</p></body></html>" message = sentiment_file_data temp_file.write( message if isinstance(message, bytes) else message.encode()) temp_file.seek(0) # Create an API instance api = API(user_key=key, service_url=alt_url) params = DocumentParameters() params["language"] = "eng" params["content"] = text # Use an HTML file to load data instead of a string #params.load_document_file(temp_file.name) try: result = api.sentiment(params) #print (result) except RosetteException as exception: print(exception) finally: # Clean up the file temp_file.close() return result
def get_label(alt_url='https://api.rosette.com/rest/v1/', sentence="Default Sentence"): api = API(user_key=API_KEYS.ROSETTE_API_KEY, service_url=alt_url) params = DocumentParameters() label_set = set() final_response_list = [] params["content"] = sentence params["language"] = "eng" # params["modelType"] = "dnn" try: response_dict = json.loads(json.dumps( api.sentiment(params)))["document"] response_list = [] if str(response_dict["label"]) == "pos": response_list.append( ["POSITIVE", float(response_dict["confidence"])]) elif str(response_dict["label"]) == "neg": response_list.append( ["NEGATIVE", float(response_dict["confidence"])]) else: response_list.append( ["NEUTRAL", float(response_dict["confidence"])]) # ["sentiment"] # print response_dict return response_list[0] except RosetteException as exception: print(exception)
def run(key, alt_url='https://api.rosette.com/rest/v1/'): """ Run the example """ # Create default file to read from temp_file = tempfile.NamedTemporaryFile(suffix=".html") sentiment_file_data = "<html><head><title>New Ghostbusters Film</title></head><body><p>Original Ghostbuster Dan Aykroyd, who also co-wrote the 1984 Ghostbusters film, couldn’t be more pleased with the new all-female Ghostbusters cast, telling The Hollywood Reporter, “The Aykroyd family is delighted by this inheritance of the Ghostbusters torch by these most magnificent women in comedy.”</p></body></html>" message = sentiment_file_data temp_file.write( message if isinstance(message, bytes) else message.encode()) temp_file.seek(0) # Create an API instance api = API(user_key=key, service_url=alt_url) # Set selected API options. # For more information on the functionality of these # and other available options, see Rosette Features & Functions # https://developer.rosette.com/features-and-functions#sentiment-analysis # api.set_option('modelType','dnn') #Valid for English only params = DocumentParameters() params["language"] = "eng" # Use an HTML file to load data instead of a string params.load_document_file(temp_file.name) try: result = api.sentiment(params) except RosetteException as exception: print(exception) finally: # Clean up the file temp_file.close() return result
def run(key,url, alt_url='https://api.rosette.com/rest/v1/'): """ Run the example """ # Create an API instance api = API(user_key=key, service_url=alt_url) params = DocumentParameters() # Use a URL to input data instead of a string params["contentUri"] = url try: return(api.sentiment(params)) except RosetteException as exception: print(exception) return None
def run(key, altUrl='https://api.rosette.com/rest/v1/'): # Create default file to read from f = tempfile.NamedTemporaryFile(suffix=".html") message = "<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>" f.write(message) f.seek(0) # Create an API instance api = API(user_key=key, service_url=altUrl) params = DocumentParameters() # Use an HTML file to load data instead of a string params.load_document_file(f.name) result = api.sentiment(params) # Clean up the file f.close() return result
def run(key, url, alt_url='https://api.rosette.com/rest/v1/'): """ Run the example """ # Create default file to read from # Create an API instance api = API(user_key=key, service_url=alt_url) params = DocumentParameters() params["language"] = "eng" params["contentUri"] = url # Use an HTML file to load data instead of a string #params.load_document_file(temp_file.name) try: result = api.sentiment(params) except RosetteException as exception: print(exception) finally: # Clean up the file #temp_file.close() return result
def main(argv): parser = argparse.ArgumentParser( description='Template for storing/analyzing responses from Rosette APIs' ) parser.add_argument('-k', '--key', required=True, help="rosette api key") args = parser.parse_args() # initialize rosette = "" print "trytext.py: starting up..." ########## # extract text from the file sText = "\"Gigli\" -- which spawned the phenomenon the gossip pages and celebrity magazines so lovingly refer to as \"Bennifer\" -- is every bit as unwatchable as the deafening negative chatter would suggest. The dialogue from writer-/sdirector Martin Brest is clunky, the film has serious tonal inconsistencies and at more than two hours, it drags on way longer than it should. Even making a little game of it, and trying to pinpoint the exact moment when Ben Affleck and Jennifer Lopez fell in love, stops being fun after a while. Perhaps it\'s when he says, in an attempt to seduce her, \"I\'m the bull, you\'re the cow.\" Or when she beckons him into foreplay by lying back in bed and purring, \"Gobble, gobble\" -- which could forever change the way you view your Thanksgiving turkey. But as pop-star vehicles go, \"Gigli\" isn\'t as insufferable as, say, last year\'s Madonna-Guy Ritchie debacle, \"Swept Away.\" It\'s more on par with Mariah Carey\'s \"Glitter\" and Britney Spears\' \"Crossroads.\" If this were a movie starring two B-list actors, or two complete unknowns, it probably would have gone straight to video. After curious masochists and J.Lo fans check it out the first weekend, \"Gigli\" probably will have a drop-off in audience that rivals \"The Hulk\" -- 70 percent -- then go to video. And with the release next spring of Kevin Smith\'s \"Jersey Girl,\" in which they also co-star, we can have this little conversation all over again. For now, we have Affleck starring as incompetent mob thug Larry Gigli. (That\'s pronounced JEE-lee, which rhymes with really, a running joke that isn\'t particularly funny the first time.) Gigli is asked to kidnap Brian (Justin Bartha), the mentally disabled younger brother of a/sfederal prosecutor who\'s going after a New York mobster (Al Pacino). His boss, however, thinks he\'s incapable of handling the assignment alone and sends in Ricki (Lopez), another contractor, to help him. Gigli is an anti-social lout who lives in a seedy apartment. Ricki is beautiful, grounded, enlightened. She quotes Sun Tzu -- who could blame Gigli for falling for her? (And whether you like her or not, Lopez does have an undeniable presence.) But Ricki is also a lesbian -- so it makes absolutely no sense when she falls for him, too, although they have all the obligatory banter and alleged sexual tension required of a romantic comedy. (And it\'s only a romantic comedy sometimes. Other times, it aims to be an edgy action-crime movie; still other times, it aspires for gag-inducing poignancy.) Apparently, the only force that binds them is the fact that they both feel squeamish about cutting off Brian\'s thumb and mailing it to his prosecutor brother. Instead, they break into a morgue and saw the thumb off a corpse using a plastic knife, while Brian -- who has an unexplained penchant for old-school rap -- sings Sir Mix-a-Lot\'s \"Baby Got Back.\" It\'s also incredibly misinformed to suggest that Ricki can be \"converted\" to heterosexuality -- that a man\'s love is all she really needed to allay any confusion about all that silly lesbian stuff. So what you have here is \"Rain Man\" meets \"Chasing Amy\" -- which is apropos, since the latter is a 1997 Kevin Smith movie in which Affleck also starred as a guy who falls for a lesbian. Instead of counting matches and obsessing about \"The People\'s Court\" like Dustin Hoffman\'s \"Rain Man\" character, Brian counts sunflower seeds and obsesses over going to \"the Baywatch.\" Cameos from Pacino, Christopher Walken as a detective and Lainie Kazan as Gigli\'s mother don\'t help, either. Did they owe someone a favor? What are they doing here? Pacino won his one and only Oscar with Brest for 1992\'s \"Scent of a Woman,\" but couldn\'t he have just thanked the director instead? Instead, we get to see Pacino shoot someone in the head, then watch as fish in a nearby aquarium snack on splattered drops of the victim\'s blood." ########## # to do: strip ascii etc? # connect to rosette if not rosette: rosette = API(user_key=args.key) params = DocumentParameters() # send the text params['content'] = sText jResponse = rosette.entities(params) # entity linking is turned off print json.dumps(jResponse, sort_keys=True, indent=4, separators=(',', ': ')) jResponse = rosette.sentiment(params) # entity linking is turned off print json.dumps(jResponse, sort_keys=True, indent=4, separators=(',', ': ')) print "trytext.py: done"
<p>This is a simple sample HTML file to demonstrate the option of loading data from a file.</p> </body> </html>""" f.write(message) f.seek(0) # Collect arguments parser = argparse.ArgumentParser(description="Get the sentiment of the text in a local file") parser.add_argument("--key", required=True, help="Rosette API key") parser.add_argument("--service_url", nargs="?", help="Optional user service URL") parser.add_argument("--file", nargs="?", default=f.name, help="Optional input file for data") args = parser.parse_args() # Create an API instance if args.service_url: api = API(service_url=args.service_url, user_key=args.key) else: api = API(user_key=args.key) params = DocumentParameters() # Use an HTML file to load data instead of a string params.load_document_file(args.file) result = api.sentiment(params) # Clean up the file f.close() pprint.pprint(result)
class MonitorBasisAPI(): API_KEY = "cfdb0d7990f5c1d2546c61a94cf0a445" DO_NOT_CALL = False def __init__(self): self.rosette_handle = API(user_key=self.API_KEY) # altUrl='https://api.rosette.com/rest/v1/' # OPTION: service_url=altUrl result = self.rosette_handle.ping() print("/ping: ", result) def temp_demo(self): pass # NOT TESTED def get_basis_sentiment(self, txt_str): params = DocumentParameters() params["language"] = "eng" # Use an HTML file to load data instead of a string params.load_document_string(txt_str) try: result = self.rosette_handle.sentiment(params) except RosetteException as e: print(e) finally: print " DONE " # NOT TESTED def get_basis_categories(self, txt_str): # if self.DO_NOT_CALL == True: # return "POS" params = DocumentParameters() params["language"] = "eng" # Use an HTML file to load data instead of a string params.load_document_string(txt_str) typed_relations_resp = self.rosette_handle.categories(text=txt_str) print " >>> CALLED IBM - typed_relations_resp: " + str( typed_relations_resp) return json.dumps(typed_relations_resp) def get_basis_service_by_tag(self, txt_str, basis_str): ''' To Be Determined: - syntax_dependencies - morphology - name_translation - name_similarity ''' print "~~~~~~~~~~~~~~~~~~~~~~~~~~~ going to get_basis_service_by_tag: " + str( basis_str) # if ibm_str == "authors": # return self.get_basis_service(txt_str, self.rosette_handle.authors) # elif ibm_str == "concepts": # return self.get_basis_service(txt_str, self.rosette_handle.concepts) # elif ibm_str == "dates": # return self.get_basis_service(txt_str, self.rosette_handle.dates) # elif ibm_str == "emotion": # return self.get_basis_service(txt_str, self.rosette_handle.emotion) # elif ibm_str == "feeds": # return self.get_basis_service(txt_str, self.rosette_handle.feeds) # elif ibm_str == "keywords": # return self.get_basis_service(txt_str, self.rosette_handle.keywords) # elif ibm_str == "microformats": # return self.get_basis_service(txt_str, self.rosette_handle.microformats) # elif ibm_str == "publication_date": # return self.get_basis_service(txt_str, self.rosette_handle.publication_date) # # CURRENT LIST: "entities", "language", "relationships", "sentences", "sentiment", "syntax_dependencies", "tokens" if basis_str == "entities": return self.get_basis_service( txt_str, self.rosette_handle.entities ) # also could use params["genre"] = "social-media" elif basis_str == "language": return self.get_basis_service(txt_str, self.rosette_handle.language) #! elif basis_str == "relationships": return self.get_basis_service( txt_str, self.rosette_handle.relationships) #! elif basis_str == "sentences": return self.get_basis_service(txt_str, self.rosette_handle.sentences) #! elif basis_str == "sentiment": return self.get_basis_service(txt_str, self.rosette_handle.sentiment) elif basis_str == "syntax_dependencies": return self.get_basis_service( txt_str, self.rosette_handle.syntax_dependencies) elif basis_str == "tokens": return self.get_basis_service(txt_str, self.rosette_handle.tokens) #! # elif ibm_str == "title": # return self.get_basis_service(txt_str, self.rosette_handle.title) # elif ibm_str == "typed_relations": # return self.get_basis_service(txt_str, self.rosette_handle.typed_relations) def get_basis_service(self, txt_str, basis_func): if self.DO_NOT_CALL == True: return "POS" callStart = datetime.datetime.now() params = DocumentParameters() params["language"] = "eng" # Use an HTML file to load data instead of a string params.load_document_string(txt_str) # TODO: determine when to use # params["content"] vs load_document_string resp = {"return_data": basis_func(params)} # print " >>> CALLED IBM - resp: " + str(resp) resp_time = (datetime.datetime.now() - callStart).total_seconds() resp['resp_time'] = resp_time return resp # mba = MonitorBasisAPI()