Last active
October 4, 2019 09:17
-
-
Save anuragmishra1/a41d7e84207acd52b59e538be1ef5262 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import os | |
import sys | |
import json | |
import time | |
from datetime import timedelta | |
import argparse | |
#We need to get our API credentials in the code for authentication that we have stored as Environment Variables locally | |
Ocp_Apim_Subscription_Key = os.environ.get("KEY_NLP") | |
#Following line is used to save all the console output into a text file | |
sys.stdout = open('nlp_api_output.txt', 'a') | |
start_time = time.monotonic() | |
def input_file(text_file_path): | |
global text | |
if os.path.isfile(text_file_path): | |
with open(text_file_path, 'r') as text_file: | |
text = text_file.read() | |
else: | |
print("File doesn't exist in the directory!") | |
def analyze_text(): | |
headers = { | |
# NOTE: Replace the "Ocp-Apim-Subscription-Key" value with a valid subscription key. | |
'Ocp-Apim-Subscription-Key': Ocp_Apim_Subscription_Key, | |
} | |
urls = ['https://eastus2.api.cognitive.microsoft.com/text/analytics/v2.0/languages', 'https://eastus2.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment', 'https://eastus2.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases'] | |
documents = { 'documents': [ | |
{ 'id': '1', 'language': 'en', 'text': text }]} | |
try: | |
# NOTE: You must use the same location in your REST call as you used to obtain your subscription keys. | |
# For example, if you obtained your subscription keys from westus, replace "eastus2" in the | |
# URLs above with "westus". | |
for url in urls: | |
response = requests.post(url = url, | |
headers = headers, | |
data = (json.dumps(documents)).encode('utf-8')) | |
data = response.json() | |
print(data) | |
print('\n') | |
except Exception as e: | |
print('Error: ', e) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser( | |
description = __doc__, | |
formatter_class = argparse.RawDescriptionHelpFormatter) | |
parser.add_argument( | |
'text_file_path', | |
help = 'The complete file path of the text file you want to analyze.') | |
args = parser.parse_args() | |
input_file(args.text_file_path) | |
analyze_text() | |
end_time = time.monotonic() | |
print("Execution_Time:", timedelta(seconds = end_time - start_time)) | |
print('\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment