Example #1
0
def post_list(request):
    posts = Post.objects.filter(
        published_date__lte=timezone.now()).order_by('published_date')

    for post in posts:
        posting = post.text

        translation = language_translator.translate(
            text=post.text, model_id='en-es').get_result()
        obj = (json.dumps(translation, indent=2, ensure_ascii=False))
        print(obj)
        obj2 = json.loads(obj)
        post.obj2 = obj2['translations'][0]['translation']
        post.w_count = obj2['word_count']
        post.c_count = obj2['character_count']
        tone_input = ToneInput(post.text)
        tone = service.tone(tone_input=tone_input,
                            content_type="application/json")
        tone2 = str(tone)
        print(tone2)
        post.tone3 = ""
        #print(post.tone3)
        temp = json.loads(tone2)
        if (len(temp['result']['document_tone']['tones']) > 0):
            temp2 = temp['result']['document_tone']['tones']
            for x in temp2:
                post.tone3 += 'Tone name: ' + x[
                    'tone_name'] + '\t' + '|\tScore: ' + str(x['score']) + '\r'
        else:
            post.tone3 = 'Tone name: n/a\t|\tScore: n/a'

    return render(request, 'blog/post_list.html', {'posts': posts})
Example #2
0
def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')

    for post in posts:
        posting = post.text

        translation = language_translator.translate(
            text= post.text, model_id='en-es').get_result()
        obj = (json.dumps(translation, indent=2, ensure_ascii=False))
        # print(obj)
        obj2 = json.loads(obj)
        post.obj2 = obj2['translations'][0]['translation']
        post.w_count = obj2['word_count']
        post.c_count = obj2['character_count']

        tone_input = ToneInput(post.text)
        try:
            tone = tone_analyzer.tone(tone_input=tone_input, content_type="application/json").get_result()
            jsonText = (json.dumps(tone, indent=2, ensure_ascii=False))
            jsonParse = json.loads(jsonText)
            post.Score1 = jsonParse['document_tone']['tones'][0]['score']
            post.ToneName1 = jsonParse['document_tone']['tones'][0]['tone_name']
        except:
            pass
            post.Score1 = "Missing data in response"
            post.ToneName1 ="no response from API"
            print("Encountered an issue please hold tight! We are working on it ")
    return render(request, 'blog/post_list.html', {'posts': posts})
Example #3
0
def post_list(request):
    posts = Post.objects.filter(
        published_date__lte=timezone.now()).order_by('published_date')

    for post in posts:
        posting = post.text

        translation = language_translator.translate(
            text=post.text, model_id='en-es').get_result()
        obj = (json.dumps(translation, indent=2, ensure_ascii=False))
        print(obj)
        obj2 = json.loads(obj)
        post.obj2 = obj2['translations'][0]['translation']
        post.w_count = obj2['word_count']
        post.c_count = obj2['character_count']

        tone_input = ToneInput(post.text)
        tone = tone_analyzer.tone(tone_input=tone_input,
                                  content_type="application/json")
        tone2 = str(tone)
        json_data = json.loads(tone2)
        post.json_score1 = json_data['result']['document_tone']['tones'][0][
            'score']
        post.json_score2 = json_data['result']['document_tone']['tones'][1][
            'score']
        post.json_name1 = json_data['result']['document_tone']['tones'][0][
            'tone_name']
        post.json_name2 = json_data['result']['document_tone']['tones'][1][
            'tone_name']

        post.tone3 = (tone2[1:500])

        print(post.tone3)

    return render(request, 'blog/post_list.html', {'posts': posts})
Example #4
0
def get_essay_emotion(path):
    """
	Identifies the user's mood based on a piece of writing authored by them

	Args:

	path: path to the file with text written by the user

	Returns:

	The user's emotion as identified
	"""
    file = open(path, "r")
    text = file.read()
    print()
    print('Identifying mood...')
    service = ToneAnalyzerV3(username=const.watson_username,
                             password=const.watson_password,
                             version='2017-09-21')
    service.set_detailed_response(True)
    tone_input = ToneInput(text)

    tone = service.tone(tone_input=tone_input, content_type="application/json")

    emo_score = []
    for emotion in tone.result["document_tone"]["tones"]:
        print(emotion["score"])
        print(emotion["tone_id"])
        emo_score.append(emotion["score"])
    print(tone.result["document_tone"]["tones"][emo_score.index(
        max(emo_score))]["tone_id"])
    return (tone.result["document_tone"]["tones"][emo_score.index(
        max(emo_score))]["tone_id"])
Example #5
0
def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')

    for post in posts:
        posting = post.text

        translation = language_translator.translate(
            text= post.text, model_id='en-es').get_result()
        obj = (json.dumps(translation, indent=2, ensure_ascii=False))
        print(obj)
        obj2 = json.loads(obj)
        post.obj2 = obj2['translations'][0]['translation']
        post.w_count = obj2['word_count']
        post.c_count = obj2['character_count']

        tone_input = ToneInput(post.text)
        tone = service.tone(tone_input=tone_input, content_type="application/json")
        tone2 = str(tone)
        post.tone3 = (tone2[1:500])
        print(post.tone3)

        toneObject = json.dumps(service.tone(tone_input=posting, content_type="text/plain").get_result(), indent=2)
        post.obj3 = json.loads(toneObject)
        print(toneObject)

        try:
            post.firstTone = post.obj3['document_tone']['tones'][0]['tone_name']
            post.firstScore = post.obj3['document_tone']['tones'][0]['score']
            post.secondTone = post.obj3['document_tone']['tones'][1]['tone_name']
            post.secondScore = post.obj3['document_tone']['tones'][1]['score']

        except:
            pass

    return render(request, 'blog/post_list.html', {'posts': posts})
Example #6
0
def ProcessImage(image_path):
    """
    Identifies the emotion of an image, using the Watson Visual Recognition API

    Args:

    image_path: the path to the image file

    Returns:

    The emotion of the image
    """
    service = VisualRecognitionV3(
        '2018-03-19',
        url='https://gateway.watsonplatform.net/visual-recognition/api',
        iam_apikey='dnckUYEa5ip8jnJvWFdeFA7aMsRCXx9agFgEiGO3NBpu')
    path = abspath(image_path)
    text = " "
    try:
        with open(path, 'rb') as images_file:
            results = service.classify(images_file=images_file,
                                       threshold='0.1',
                                       classifier_ids=['default'
                                                       ]).get_result()
            #print()
            for value in results["images"][0]["classifiers"][0]["classes"]:
                text = text + " " + value["class"]
            print(text)
            text += "."
            puncs1 = [
                '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+',
                '=', '{', '}', '[', ']', '|', '\\', '"', "'", ';', ':', '<',
                '>', '/'
            ]
            for punc in puncs1:
                text = text.replace(punc, '')
    except WatsonApiException as ex:
        print(ex)

    service = ToneAnalyzerV3(username='******',
                             password='******',
                             version='2017-09-21')
    service.set_detailed_response(True)
    tone_input = ToneInput(text)
    tone = service.tone(tone_input=tone_input, content_type="application/json")

    emo_score = []
    for emotion in tone.result["document_tone"]["tones"]:
        print(emotion["score"])
        print(emotion["tone_name"])
        emo_score.append(emotion["score"])
    if not emo_score:
        return 'Neutral'
    else:
        return (tone.result["document_tone"]["tones"][emo_score.index(
            max(emo_score))]["tone_name"])
Example #7
0
def analyze_tone(tone_analyzer: T, text: str) -> dict:
    """Analyzes text input with tone analyzer object"""
    try:
        tone_input = ToneInput(text)
        return tone_analyzer.tone(
            tone_input,
            'application/json'
        ).get_result()

    except WatsonApiException:
        traceback.print_exc(limit=1)
Example #8
0
    def analyze(message):

        service = ToneAnalyzerV3(
            ## url is optional, and defaults to the URL below. Use the correct URL for your region.
            # url='https://gateway.watsonplatform.net/tone-analyzer/api',
            username='******',
            password='******',
            version='2017-09-21')
        tone_input = ToneInput(message)
        result = service.tone(tone_input=tone_input,
                              content_type="application/json").get_result()
        return result
Example #9
0
def post_list(request):
    posts = Post.objects.filter(
        published_date__lte=timezone.now()).order_by('published_date')

    for post in posts:
        posting = post.text

        translation = language_translator.translate(
            text=post.text, model_id='en-es').get_result()
        obj = (json.dumps(translation, indent=2, ensure_ascii=False))
        # print(obj)
        obj2 = json.loads(obj)
        post.obj2 = obj2['translations'][0]['translation']
        post.w_count = obj2['word_count']
        post.c_count = obj2['character_count']

        tone_input = ToneInput(post.text)
        # tone = tone_analyzer.tone(tone_input=tone_input, content_type="application/json")
        # print(tone)
        # print('//////////////////////////////////////////////////////')
        # tone2 = str(tone)
        # post.tone3 = (tone2[1:500])
        # print('*********************************************************************')
        # print(post.tone3)
        # print('*********************************************************************')
        # JsonText = json.dumps(post.tone3)
        # d2=json.loads(JsonText)
        # print(d2['result'][0])

        # jsonText = json.dumps(tone, indent=2, ensure_ascii=False)
        # tone_score = json.loads(jsonText)['results']
        # print(tone_score)
        try:
            tone = tone_analyzer.tone(
                tone_input=tone_input,
                content_type="application/json").get_result()
            jsonText = (json.dumps(tone, indent=2, ensure_ascii=False))
            jsonParse = json.loads(jsonText)
            post.Score1 = jsonParse['document_tone']['tones'][0]['score']
            post.ToneName1 = jsonParse['document_tone']['tones'][0][
                'tone_name']
        except:
            pass
            post.Score1 = "no-data value for key Score from API response"
            post.ToneName1 = "no-data value for key ToneName from API response"
            print(
                "****************************Something went wrong while rendering the Document tone json"
            )
    return render(request, 'blog/post_list.html', {'posts': posts})
Example #10
0
def post_list(request):
    posts = Post.objects.filter(
        published_date__lte=timezone.now()).order_by('published_date')

    for post in posts:
        posting = post.text

        translation_ch = language_translator.translate(
            text=post.text, model_id='en-zh-TW').get_result()
        translation_fr = language_translator.translate(
            text=post.text, model_id='en-fr').get_result()
        obj_ch = (json.dumps(translation_ch, indent=2, ensure_ascii=False))
        print(obj_ch)
        obj2_ch = json.loads(obj_ch)
        post.obj2_ch = obj2_ch['translations'][0]['translation']
        post.w_count_ch = obj2_ch['word_count']
        post.c_count_ch = obj2_ch['character_count']

        obj_fr = (json.dumps(translation_fr, indent=2, ensure_ascii=False))
        print(obj_fr)
        obj2_fr = json.loads(obj_fr)
        post.obj2_fr = obj2_fr['translations'][0]['translation']
        post.w_count_fr = obj2_fr['word_count']
        post.c_count_fr = obj2_fr['character_count']

        # tone_input = ToneInput(post.text)
        # post.tone = service.tone(tone_input=tone_input, content_type="application/json")
        # tone2 = str(tone)
        # post.tone3 = (tone2[1:500])
        # print(post.tone3)

        tone_input = ToneInput(post.text)
        tone = service.tone(tone_input=tone_input,
                            content_type="application/json")
        tone_type = []
        tone_score = []
        document_tones = tone.result["document_tone"]["tones"]
        i = 0

        for i in range(len(document_tones)):
            tone_type.append(document_tones[i]["tone_name"])
            tone_score.append(document_tones[i]["score"])

        return render(request, 'blog/post_list.html', {
            'posts': posts,
            'tone_type': tone_type,
            'tone_score': tone_score
        })
Example #11
0
def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')

    language_translator = LanguageTranslatorV3(
        version='2018-05-31',
        iam_apikey='HlK2hXGChPDwRQ9J32GYzPduHQqhNTDBsvsYg4Yvtop0')

    service = ToneAnalyzerV3(
        version='2017-09-26',
        iam_apikey='DRPM3RA0gH0UcfLkZUBwpAo91JwbgEYDgiXtjV3mZeFS')

    for post in posts:
        posting = post.text

        translation = language_translator.translate(
            text= post.text, model_id='en-es').get_result()
        obj = (json.dumps(translation, indent=2, ensure_ascii=False))
        # print(obj)
        obj2 = json.loads(obj)
        post.obj2 = obj2['translations'][0]['translation']
        post.w_count = obj2['word_count']
        post.c_count = obj2['character_count']

        tone_input = ToneInput(post.text)
        tone = service.tone(tone_input=tone_input, content_type="application/json")
        tone2 = str(tone)
        json_data = json.loads(tone2)
        # print(json_data)
        try:
            post.json_score1 = json_data['result']['document_tone']['tones'][0]['score']
            post.json_name1 = json_data['result']['document_tone']['tones'][0]['tone_name']
            post.json_score2 = json_data['result']['document_tone']['tones'][1]['score']
            post.json_name2 = json_data['result']['document_tone']['tones'][1]['tone_name']

        except:
            pass

        post.tone3 = (tone2[1:500])
        # print(post.tone3)

    return render(request, 'blog/post_list.html', {'posts': posts})
def getEmotion(text):

    print(text)
    service = ToneAnalyzerV3(username='******',
                             password='******',
                             version='2017-09-21')
    service.set_detailed_response(True)
    tone_input = ToneInput(text)
    tone = service.tone(tone_input=tone_input, content_type="application/json")

    emo_score = []
    for emotion in tone.result["document_tone"]["tones"]:
        print(emotion["score"])
        print(emotion["tone_name"])
        emo_score.append(emotion["score"])
    if not emo_score:
        print('Neutral')
        return 'Neutral'
    else:
        print(tone.result["document_tone"]["tones"][emo_score.index(
            max(emo_score))]["tone_name"])
        return (tone.result["document_tone"]["tones"][emo_score.index(
            max(emo_score))]["tone_name"])
Example #13
0
 def analyze_sentiment(self, text):
     if text == '':
         return {}
     tone_input = ToneInput(text)
     return self.tone_analyzer.tone(tone_input, 'application/json')
Example #14
0
import pandas as pd
import csv

# If service instance provides API key authentication
service = ToneAnalyzerV3(
    #     ## url is optional, and defaults to the URL below. Use the correct URL for your region.
    url='https://gateway.watsonplatform.net/tone-analyzer/api',
    version='2017-09-21',
    iam_apikey='H7sXUX39LzgVDqO4IcZaoX3dbsiZYn8GVo2wnZvXd6oP')

filename = raw_input()
f = []
filetext = filename + ".txt"
t = open(filetext, 'r')
text = t.read()
tone_input = ToneInput(text)
tone = service.tone(tone_input=tone_input, content_type="application/json")
#print(json.dumps(tone.get_result(), indent=2))
data = tone.get_result()
score1 = 0
score2 = 0

word_valence = []
for i in range(len(data["sentences_tone"])):
    txt = data["sentences_tone"][i]["text"]
    txt = txt.replace("'", "")
    txt = txt.replace(",", "")

    corresponding_valence = 0
    max_probable_tone_id = ''
    max_probablity = -1
Example #15
0
def home():
	user_id = session.get('id')

	if 'logged_in' not in session:
		session['logged_in']=False
		return render_template('index1a.html',uname="")
	elif session['logged_in'] is False:
		
		return render_template('index1a.html',uname="")
	else:
		
		nme = session['this']
		print(nme)
		
		
		auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
  
        # Access to user's access key and access secret 
		auth.set_access_token(access_key, access_secret) 
  
        # Calling api 
		api = tweepy.API(auth) 
  
        # 200 tweets to be extracted 
		number_of_tweets=3
		tweets = api.user_timeline(screen_name=nme) 
		results = api.get_user(nme)
		url = "https://avatars.io/twitter/"+nme
  
        # Empty Array 
		tmp=[]  
  
        # create array of tweet information: username,  
        # tweet id, date/time, text 
		tweets_for_csv = [tweet.text for tweet in tweets] # CSV file created  
		for j in tweets_for_csv: 
  
            # Appending tweets to the empty array tmp 
			tmp.append(j)  

		tlen=len(tmp)
		results = api.get_user(nme)
		fname=results.name
		prlink = "https://twitter.com/intent/user?user_id=" + str(results.id)

		moodans=[]
		for item in tmp:
			tone_input = ToneInput(item)
			tone = service.tone(tone_input=tone_input, content_type="application/json", sentences=False).get_result()
			#print(json.dumps(tone, indent=2))
			parsed = json.loads(json.dumps(tone, indent=2))
		
			i=0;
			ak="Neutral"
			for tones in parsed['document_tone']['tones']:
				ak=tones['tone_name']
				i=i+1
				if(i==1):
					break


			moodans.append(ak)
		return render_template('index1a.html',uname=nme,tmp=tmp,dictcolor=dictcolor,moodans=moodans,dict=dict,url=url,tlen=tlen,prlink=prlink,fname=fname)
Example #16
0
               '../resources/tone-example.json')) as tone_json:
    tone = tone_analyzer.tone(tone_input=json.load(tone_json),
                              content_type='application/json')
print(json.dumps(tone, indent=2))

print("\ntone() example 5:\n")
with open(join(dirname(__file__),
               '../resources/tone-example-html.json')) as tone_html:
    tone = tone_analyzer.tone(json.load(tone_html)['text'],
                              content_type='text/html')
print(json.dumps(tone, indent=2))

print("\ntone() example 6 with GDPR support:\n")
tone_analyzer.set_detailed_response(True)
with open(join(dirname(__file__),
               '../resources/tone-example-html.json')) as tone_html:
    tone = tone_analyzer.tone(json.load(tone_html)['text'],
                              content_type='text/html',
                              headers={'Custom-Header': 'custom_value'})

print(tone)
print(tone.get_headers())
print(tone.get_result())
tone_analyzer.set_detailed_response(False)

print("\ntone() example 7:\n")
tone_input = ToneInput('I am very happy. It is a good day.')
tone = tone_analyzer.tone(tone_input=tone_input,
                          content_type="application/json")
print(json.dumps(tone, indent=2))
Example #17
0
# with open(join(dirname(__file__),
#                '../resources/tone-example-html.json')) as tone_html:
#     tone = service.tone(
#         json.load(tone_html)['text'], content_type='text/html').get_result()
# print(json.dumps(tone, indent=2))

# print("\ntone() example 6 with GDPR support:\n")
# service.set_detailed_response(True)
# with open(join(dirname(__file__),
#                '../resources/tone-example-html.json')) as tone_html:
#     tone = service.tone(
#         json.load(tone_html)['text'],
#         content_type='text/html',
#         headers={
#             'Custom-Header': 'custom_value'
#         })

# print(tone)
# print(tone.get_headers())
# print(tone.get_result())
# print(tone.get_status_code())
# service.set_detailed_response(False)

# print("\ntone() example 7:\n")

test_tone = "Hi Team, The times are difficult! Our sales have been disappointing for the past three quarters for our data analytics product suite. We have a competitive data analytics product suite in the industry. However, we are not doing a good job at selling it, and this is really frustrating.We are missing critical sales opportunities. We cannot blame the economy for our lack of execution. Our clients need analytical tools to change their current business outcomes. In fact, it is in times such as this, our clients want to get the insights they need to turn their businesses around. It is disheartening to see that we are failing at closing deals, in such a hungry market. Let's buckle up and execute.Jennifer BakerSales Leader, North-East region"
tone_input = ToneInput(test_tone)
result = service.tone(tone_input=tone_input,
                      content_type="application/json").get_result()
# print(type(json.dumps(tone, indent=2)))
pprint(result)