def detectEmotion(request):
    try:
        data = str(request.POST.get('textInput'))
        port = str(request.POST.get('comPort'))
        username, password, version = get_API_credential()
        print(data, port)
        tone_analyzer = ToneAnalyzerV3(
            username=username,
            password=password,
            version=version
        )
        content_type = 'application/json'
        tone = tone_analyzer.tone({"text": data}, content_type)
        print(tone)
        emotion = tone['document_tone']['tones'][0]['tone_name']
        print(emotion)
        #score = tone['document_tone']['tones'][0]['score']
        em = ['Left', 'Right', 'Forward', 'Backward', 'Stop']
        dt = ['Joy', 'Anger', 'Fear', 'Sadness', 'Others']
        if str(emotion) in dt:
            command = dt.index(str(emotion))
        else:
            command = 4
        data = command
        command = em[command]
        if senddata(port, int(data) + 1) is True:
            print("Command sent - " + str(data))
        else:
            command = "NULL"
        return HttpResponse("Command Sent : <b>" + str(command) + "</b><br/>Emotion Detected : <b>" + str(emotion) + " </b>")
    except Exception as e:
        print(e)
        return HttpResponse("False")
def hello_world():
	cluster = Cluster(['172.17.0.2'])
	session = cluster.connect()
	session.execute("CREATE KEYSPACE IF NOT EXISTS results WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 3};")
	session.execute("USE results;")
	session.execute("create table IF NOT EXISTS result_table(translate_source text,translate_result text,analyze_result text,result_id text PRIMARY KEY);")
	
     	language_translation = LanguageTranslation(
		username='******',
		password='******')
 	f = open('translate_file.txt',"r")
	line = f.readline()
	translation = language_translation.translate(
    		text=line, 
    		source='fr', 
    		target='en')
	
	translated_text = json.dumps(translation, indent=2, ensure_ascii=False)
	tone_analyzer = ToneAnalyzerV3(
	username='******',
        password='******',
        version='2016-05-19 ')
	analyze = json.dumps(tone_analyzer.tone(text=translated_text), indent=2)
	session.execute("INSERT INTO result_table (translate_source,translate_result,analyze_result,result_id) VALUES(%s,%s,%s,%s)",(line,translated_text,analyze,1))
	session.execute("SELECT * FROM result_table;")
    	return(analyze)
def analysis(text,file):
    tone_analyzer = ToneAnalyzerV3(
        version='*********',
        username='******',
        password='******',
        url='https://gateway.watsonplatform.net/tone-analyzer/api'
    )

    tone_analysis = tone_analyzer.tone(
        {'text': text},
        'application/json'
    ).get_result()
    i=0
    a1=tone_analysis['document_tone']
    a2=a1['tones']
    while i<len(a2):
        a3=a2[i]
        #print(a3['tone_id'])
        if file=='0':
            dtoi[a3['tone_id']]=1
        if file=='1':
            dndtv[a3['tone_id']]=1
        i=i+1
    for x in d:
        d[x]=dtoi[x]+dndtv[x]
    database.ins(d)
    database.instoi(dtoi)
    database.insndtv(dndtv)
Example #4
0
def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    tone_analyzer = ToneAnalyzerV3(
        username='******',
        password='******',
        version='2016-05-19 ')

    language_translator = LanguageTranslator(
        username='******',
        password='******')

    # print(json.dumps(translation, indent=2, ensure_ascii=False))

    for post in posts:
        data = json.dumps(tone_analyzer.tone(text=post.text), indent=1)  # converting to string and storing in the data
        j = json.loads(data);
        post.info = j['document_tone']['tone_categories'][0]['tones']
        # post.info = json.dumps(post.info);
        post.angerScore = post.info[0]['score']
        post.disgustScore = post.info[1]['score']
        post.fearScore = post.info[2]['score']
        post.joyScore = post.info[3]['score']
        post.sadScore = post.info[4]['score']
        # print(post.info[0]['tone_name'])
        translation = language_translator.translate(
            text=post.text,
            source='en',
            target='es')
        post.translatedText = json.dumps(translation, indent=2, ensure_ascii=False)
    return render(request, 'blog/post_list.html', {'posts': posts})
def toneAnalyzer(lyrics):
    tone_analyzer = ToneAnalyzerV3(
        version='2016-05-19',
        iam_apikey='xRTFsyatVym6NfGc64o5oLwBfVABQicz396CjHuXy5y4',
        url='https://gateway-wdc.watsonplatform.net/tone-analyzer/api')

    tone_analysis = tone_analyzer.tone({
        'text': lyrics
    },
                                       'application/json',
                                       sentences='false',
                                       tones='emotion').get_result()
    tone = json.dumps(tone_analysis, indent=2)
    # converting the string obtained from json.dumps() to json format
    dcmnt_tone_json = json.loads(tone)
    dcmnt_tone = dcmnt_tone_json['document_tone']['tone_categories']

    # retrieving the dictionary in the list obtained in dcmnt_tone
    tone_category_dict = dcmnt_tone[0]

    dict_emotion = {}
    happy_sad_dict = {}
    for val in tone_category_dict['tones']:
        dict_score_emotion = {val['tone_name']: val['score']}
        dict_emotion.update(dict_score_emotion)
        if val['tone_name'] == 'Joy' or val['tone_name'] == 'Sadness':
            happy_sad = {val['tone_name']: val['score']}
            happy_sad_dict.update(happy_sad)
    final_tone = max(happy_sad_dict.items(), key=operator.itemgetter(1))[0]
    return final_tone
Example #6
0
def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    tone_analyzer = ToneAnalyzerV3(
        username='******',
        password='******',
        version='2016-05-19 ')

    language_translator = LanguageTranslator(
        username='******',
        password='******')

    # print(json.dumps(translation, indent=2, ensure_ascii=False))

    for post in posts:
        data = json.dumps(tone_analyzer.tone(text=post.text), indent=1)  # converting to string and storing in the data
        j = json.loads(data);
        post.info = j['document_tone']['tone_categories'][0]['tones']
        # post.info = json.dumps(post.info);
        post.angerScore = post.info[0]['score']
        post.disgustScore = post.info[1]['score']
        post.fearScore = post.info[2]['score']
        post.joyScore = post.info[3]['score']
        post.sadScore = post.info[4]['score']
        # print(post.info[0]['tone_name'])
        translation = language_translator.translate(
            text=post.text,
            source='en',
            target='es')
        post.translatedText = json.dumps(translation, indent=2, ensure_ascii=False)

    return render(request, 'blog/post_list.html', {'posts': posts})
Example #7
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 #8
0
def tone_score(article):
    from watson_developer_cloud import ToneAnalyzerV3
    tone_analyzer = ToneAnalyzerV3(
        username='******',
        password='******',
        version='2016-05-19 ')
    import nltk
    import re
    d_tone_score = {}
    d = {}
    rel_score = 0.5

    tone_dict = tone_analyzer.tone(article)

    for j in range(
            len(tone_dict["document_tone"]["tone_categories"][0]["tones"])):
        d_tone_score[tone_dict["document_tone"]["tone_categories"][0]["tones"]
                     [j]["tone_name"]] = tone_dict["document_tone"][
                         "tone_categories"][0]["tones"][j]["score"]

    d = {k: v * 100 for (k, v) in d_tone_score.items() if v > rel_score}
    tone_list = []
    for key, value in d.iteritems():
        tone_list.append(key)
        tone_list.append(value)
    return (tone_list)
Example #9
0
def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    tone_analyzer = ToneAnalyzerV3(
        username='******',
        password='******',
        version='2016-05-19 ')

    language_translator = LanguageTranslator(
        username='******',
        password='******')

    # print(json.dumps(translation, indent=2, ensure_ascii=False))

    for post in posts:
        data = json.dumps(tone_analyzer.tone(text=post.text), indent=1)  # converting to string and storing in the data
        j = json.loads(data);
        post.info = j['document_tone']['tone_categories'][0]['tones']
        # post.info = json.dumps(post.info);
        post.angerScore = post.info[0]['score']
        post.disgustScore = post.info[1]['score']
        post.fearScore = post.info[2]['score']
        post.joyScore = post.info[3]['score']
        post.sadScore = post.info[4]['score']
        # print(post.info[0]['tone_name'])
        translation = language_translator.translate(
            text=post.text,
            source='en',
            target='es')
        post.translatedText = json.dumps(translation, indent=2, ensure_ascii=False)
    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')
   tone_analyzer = ToneAnalyzerV3(
   username='******',
   password='******',
   version='2016-05-19 ')
  
   language_translator = LanguageTranslator(
   username='******',
   password='******')


   #print(json.dumps(translation, indent=2, ensure_ascii=False))
 
   for post in posts:
       data = json.dumps(tone_analyzer.tone(text=post.text), indent=1)#converting to string and storing in the data
       j = json.loads(data);
       post.info = j['document_tone']['tone_categories'][0]['tones']
       #post.info = json.dumps(post.info);
       post.angerScore = post.info[0]['score']
       post.disgustScore = post.info[1]['score']
       post.fearScore = post.info[2]['score']
       post.joyScore = post.info[3]['score']
       post.sadScore = post.info[4]['score']
       #print(post.info[0]['tone_name'])
       translation = language_translator.translate(
       text=post.text,
       source='en',
       target='es')
       post.translatedText = json.dumps(translation, indent=2, ensure_ascii=False)
   return render(request, 'blog/post_list.html', {'posts': posts})
Example #11
0
    def __init__(self):
        """
        Construct an instance. Fetches service parameters from VCAP_SERVICES
        runtime variable for Bluemix, or it defaults to local URLs.
        """
        vcapServices = os.getenv("VCAP_SERVICES")
        # Local variables
        # self.url = "<url>"
        # self.username = "******"
        # self.password = "******"
        #
        # if vcapServices is not None:
        #     print("Parsing VCAP_SERVICES")
        #     services = json.loads(vcapServices)
        #     svcName = "tone_analyzer"
        #     if svcName in services:
        #         print("Text to Speech service found!")
        #         svc = services[svcName][0]["credentials"]
        #         self.url = svc["url"]
        #         self.username = svc["username"]
        #         self.password = svc["password"]
        #         self.watson_module = ToneAnalyzerV3(
        #             username=self.username,
        #             password=self.password,
        #             url=self.url,
        #             version=ToneAnalyzerV3.latest_version)
        #     else:
        #         print("ERROR: The Text Analysis service you were looking for was not found")

        self.watson_module = ToneAnalyzerV3(
            username="******",
            password="******",
            version=ToneAnalyzerV3.latest_version)
Example #12
0
def lambda_handler(event, context):
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
    try:
        response = s3.get_object(Bucket=bucket, Key=key)
        print(response)
        print(response['Body'].read())
        return response['ContentType']
    except Exception as e:
        print(e)
        print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
        raise e
		
	#analysis
	tone_analyzer = ToneAnalyzerV3(
        username='******',
        password='******',
        version='2017-09-26'
    )
    tone = tone_analyzer.tone(message, tones='emotion', content_type='application/json')
    #analysis = requests.post('https://gateway.watsonplatform.net/tone-analyzer/api', auth =('25aff8c5-4afd-4b18-aed8-12bab8d78090','5dAUlipzhPdj'), data = message)
    print(tone)
    
    #send email
	SENDER = "*****@*****.**"
Example #13
0
def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    tone_analyzer = ToneAnalyzerV3(
        username='******',
        password='******',
        version='2016-05-19 ')

    language_translator = LanguageTranslator(
        username='******',
        password='******')

    # print(json.dumps(translation, indent=2, ensure_ascii=False))

    for post in posts:
        data = json.dumps(tone_analyzer.tone(text=post.text), indent=1)  # converting to string and storing in the data
        j = json.loads(data);
        post.info = j['document_tone']['tone_categories'][0]['tones']
        # post.info = json.dumps(post.info);
        post.angerScore = post.info[0]['score']
        post.disgustScore = post.info[1]['score']
        post.fearScore = post.info[2]['score']
        post.joyScore = post.info[3]['score']
        post.sadScore = post.info[4]['score']
        # print(post.info[0]['tone_name'])
        translation = language_translator.translate(
            text=post.text,
            source='en',
            target='es')
        post.translatedText = json.dumps(translation, indent=2, ensure_ascii=False)
    return render(request, 'blog/post_list.html', {'posts': posts})
def set_API_credential(request):
    try:
        if request.method == 'POST' and request.is_ajax:
            print(request.POST)
            username = request.POST.get('username')
            password = request.POST.get('password')
            version = request.POST.get('version')
            print(username, password, version, "this is it")
            tone_analyzer = ToneAnalyzerV3(
                username=username,
                password=password,
                version=version
            )
            tone = tone_analyzer.tone(tone_input="I am feeling hungry, I am angry, get out", content_type="text/plain")
            print(tone)
            fp = open('media/API.txt', 'w+')
            fp.writelines(username + "\n")
            fp.writelines(password + "\n")
            fp.writelines(version)
            fp.close()
        else:
            return HttpResponse("False")
    except Exception as e:
        print(e)
        return HttpResponse("False")
    return HttpResponse("True", {'Cusername': username, 'passw': password, 'vers': version})
Example #15
0
def watsonapi():

    tone_analyzer = ToneAnalyzerV3(
        version='2017-09-21',
        ##version='2016-05-19',
        username='******',
        password='******')

    tone_analyzer.set_url(
        'https://gateway.watsonplatform.net/tone-analyzer/api')

    tone_analyzer.set_detailed_response(False)

    content_type = 'application/json'

    try:
        trone = tone_analyzer.tone({"text": outlist[1]}, content_type, True)
    except WatsonApiException as ex:
        #except:
        print "Method failed with status code " + str(
            ex.code) + ": " + ex.message
        #print("Failure!")

    print(json.dumps(trone, indent=2))

    ##print(tone)

    return trone
def analyze_tone(read_data):
    # The ToneAnalyzer class from WDC
    from watson_developer_cloud import ToneAnalyzerV3

    # -------------------------------------------------------------------------
    # Instantiate TA Object with my Credentials
    # -------------------------------------------------------------------------
    tone_analyzer = ToneAnalyzerV3(
        iam_apikey="wN3kBNH9MJcyo7LDKBlrq2mmSbupCTnhC_hugTWgoa55",
        version='2018-02-16',
        url='https://gateway-lon.watsonplatform.net/tone-analyzer/api')

    # -------------------------------------------------------------------------

    # Pass a single review to TA (one by one):

    json_output = tone_analyzer.tone(read_data, content_type='text/plain')

    result = json_output.result
    for i in result['document_tone']['tones']:
        if i is None:
            break
        if i['tone_name'] not in ("Analytical", "Tentative", "Confident"):
            write_result(i['tone_name'] + ": " + str(i['score'] * 100) + "%")
            print(i['tone_name'] + ": " + str(i['score'] * 100) + "%")
Example #17
0
def post_list(request):
    posts = Post.objects.filter(
        published_date__lte=timezone.now()).order_by('published_date')
    tone_analyzer = ToneAnalyzerV3(
        username='******',
        password='******',
        version='2016-05-19 ')

    language_translator = LanguageTranslator(
        username='******',
        password='******')

    #print(json.dumps(translation, indent=2, ensure_ascii=False))

    for post in posts:
        data = json.dumps(
            tone_analyzer.tone(text=post.text),
            indent=1)  #converting to string and storing in the data
        j = json.loads(data)
        post.info = j['document_tone']['tone_categories'][0]['tones']
        #post.info = json.dumps(post.info);
        post.angerScore = post.info[0]['score']
        post.disgustScore = post.info[1]['score']
        post.fearScore = post.info[2]['score']
        post.joyScore = post.info[3]['score']
        post.sadScore = post.info[4]['score']
        #print(post.info[0]['tone_name'])
        translation = language_translator.translate(text=post.text,
                                                    source='en',
                                                    target='es')
        post.translatedText = json.dumps(translation,
                                         indent=2,
                                         ensure_ascii=False)
    return render(request, 'blog/post_list.html', {'posts': posts})
Example #18
0
def post_list(request):
    posts = Post.objects.filter(
        published_date__lte=timezone.now()).order_by('published_date')
    tone_analyzer = ToneAnalyzerV3(
        username='******',
        password='******',
        version='2016-05-19 ')

    language_translator = LanguageTranslator(
        username='******',
        password='******')

    for post in posts:
        data = json.dumps(tone_analyzer.tone(text=post.text), indent=1)
        j = json.loads(data)
        post.info = j['document_tone']['tone_categories'][0]['tones']
        post.angerScore = post.info[0]['score']
        post.disgustScore = post.info[1]['score']
        post.fearScore = post.info[2]['score']
        post.joyScore = post.info[3]['score']
        post.sadScore = post.info[4]['score']
    translation = language_translator.translate(text=post.text,
                                                source='en',
                                                target='es')
    post.translatedText = json.dumps(translation, indent=2, ensure_ascii=False)
    return render(request, 'blog1/post_list.html', {'posts': posts})
Example #19
0
def post_list(request):
    posts = Post.objects.filter(
        published_date__lte=timezone.now()).order_by('published_date')
    tone_analyzer = ToneAnalyzerV3(
        username='******',
        password='******',
        version='2016-05-19 ')

    language_translator = LanguageTranslator(
        username='******',
        password='******')

    # print(json.dumps(translation, indent=2, ensure_ascii=False))

    for post in posts:
        data = json.dumps(
            tone_analyzer.tone(text=post.text),
            indent=1)  # converting to string and storing in the data
        j = json.loads(data)
        post.info = j['document_tone']['tone_categories'][0]['tones']
        # post.info = json.dumps(post.info);
        post.angerScore = post.info[0]['score']
        post.disgustScore = post.info[1]['score']
        post.fearScore = post.info[2]['score']
        post.joyScore = post.info[3]['score']
        post.sadScore = post.info[4]['score']
        # print(post.info[0]['tone_name'])
        translation = language_translator.translate(text=post.text,
                                                    source='en',
                                                    target='es')
        post.translatedText = json.dumps(translation,
                                         indent=2,
                                         ensure_ascii=False)
    return render(request, 'blog/post_list.html', {'posts': posts})
Example #20
0
 def __init__(self):
     self.analyzer = ToneAnalyzerV3(
         version='2017-09-21',
         username='******',
         password='******',
     )
     self.tone = "none"
    def __init__(self, Reviews):

        self.reviews = Reviews
        self.positive = 0
        self.negative = 0

        tone_analyzer = ToneAnalyzerV3(
            username='******',
            password='******',
            version='2016-05-19 ')
        for review in self.reviews:
            to_analyze = review.text
            toneObj = json.dumps(tone_analyzer.tone(tone_input=to_analyze,
                                                    content_type="text/plain"),
                                 indent=2)
            review.toneObj2 = json.loads(toneObj)
            review.angerScore = review.toneObj2['document_tone'][
                'tone_categories'][0]['tones'][0]['score']
            review.disgustScore = review.toneObj2['document_tone'][
                'tone_categories'][0]['tones'][1]['score']
            review.fearScore = review.toneObj2['document_tone'][
                'tone_categories'][0]['tones'][2]['score']
            review.joyScore = review.toneObj2['document_tone'][
                'tone_categories'][0]['tones'][3]['score']
            review.sadScore = review.toneObj2['document_tone'][
                'tone_categories'][0]['tones'][4]['score']

            if (review.angerScore + review.disgustScore + review.fearScore +
                    review.sadScore > review.joyScore):
                self.negative = self.negative + 1
            else:
                self.positive = self.positive + 1
Example #22
0
def post_list(request):
    posts = Post.objects.filter(
        published_date__lte=timezone.now()).order_by('published_date')
    tone_analyzer = ToneAnalyzerV3(
        username='******',
        password='******',
        version='2016-05-19 ')

    language_translator = LanguageTranslator(
        username='******',
        password='******')

    #print(json.dumps(translation, indent=2, ensure_ascii=False))

    for post in posts:
        data = json.dumps(
            tone_analyzer.tone(text=post.text),
            indent=1)  #converting to string and storing in the data
        j = json.loads(data)
        post.info = j['document_tone']['tone_categories'][0]['tones']
        #post.info = json.dumps(post.info);
        post.angerScore = post.info[0]['score']
        post.disgustScore = post.info[1]['score']
        post.fearScore = post.info[2]['score']
        post.joyScore = post.info[3]['score']
        post.sadScore = post.info[4]['score']
        #print(post.info[0]['tone_name'])
        translation = language_translator.translate(text=post.text,
                                                    source='en',
                                                    target='es')
        post.translatedText = json.dumps(translation,
                                         indent=2,
                                         ensure_ascii=False)
    return render(request, 'blog/post_list.html', {'posts': posts})
Example #23
0
def post_list(request):
    posts = Post.objects.filter(
        published_date__lte=timezone.now()).order_by('published_date')
    tone_analyzer = ToneAnalyzerV3(
        username='******',
        password='******',
        version='2016-05-19 ')

    language_translator = LanguageTranslator(
        username='******',
        password='******')

    # print(json.dumps(translation, indent=2, ensure_ascii=False))

    for post in posts:
        data = json.dumps(
            tone_analyzer.tone(text=post.text),
            indent=1)  # converting to string and storing in the data
        j = json.loads(data)
        post.info = j['document_tone']['tone_categories'][0]['tones']
        # post.info = json.dumps(post.info);
        post.angerScore = post.info[0]['score']
        post.disgustScore = post.info[1]['score']
        post.fearScore = post.info[2]['score']
        post.joyScore = post.info[3]['score']
        post.sadScore = post.info[4]['score']
        # print(post.info[0]['tone_name'])
        translation = language_translator.translate(text=post.text,
                                                    source='en',
                                                    target='fr')
        post.translatedText = json.dumps(translation,
                                         indent=2,
                                         ensure_ascii=False)
    return render(request, 'blog/post_list.html', {'posts': posts})
Example #24
0
def get_playlist_tones(playlist):  #top_songs):
    play = []
    for i in range(len(playlist)):
        #for i in range(60): #taking the first 60 songs here for the playlist
        artist_name = playlist[i][1]  #top_songs.iloc[i, 2]
        title = playlist[i][0]  #top_songs.iloc[i, 3]
        try:
            lyr = lyricwikia(title, artist_name)
        except:
            print("\n SONG NOT FOUND: " + title + artist_name + "\n")
            continue
        tone_analyzer = ToneAnalyzerV3(
            version='2019-02-17',
            iam_apikey='6zSlji48p8DDphjnF_ZgfuU4pyP5PlXCk7LOEZq-YieR',
            url='https://gateway-lon.watsonplatform.net/tone-analyzer/api')
        text = lyr
        if (len(lyr) == 0):
            continue
        tone_analysis = tone_analyzer.tone({
            'text': text
        }, 'application/json').get_result()
        print(i)
        tone = tone_analysis['document_tone']['tones']
        play.append([artist_name, title, tone])
    return play
Example #25
0
def post_list(request):
    posts = Post.objects.filter(
        published_date__lte=timezone.now()).order_by('published_date')
    tone_analyzer = ToneAnalyzerV3(
        username='******',
        password='******',
        version='2016-05-19 ')

    language_translator = LanguageTranslator(
        username='******',
        password='******')

    # print(json.dumps(translation, indent=2, ensure_ascii=False))

    for post in posts:
        data = json.dumps(
            tone_analyzer.tone(text=post.text),
            indent=1)  # converting to string and storing in the data
        j = json.loads(data)
        post.info = j['document_tone']['tone_categories'][0]['tones']
        # post.info = json.dumps(post.info);
        post.angerScore = post.info[0]['score']
        post.disgustScore = post.info[1]['score']
        post.fearScore = post.info[2]['score']
        post.joyScore = post.info[3]['score']
        post.sadScore = post.info[4]['score']
        # print(post.info[0]['tone_name'])
        translation = language_translator.translate(text=post.text,
                                                    source='en',
                                                    target='es')
        post.translatedText = json.dumps(translation,
                                         indent=2,
                                         ensure_ascii=False)
    return render(request, 'blog/post_list.html', {'posts': posts})
Example #26
0
def post_list(request):
    posts = Post.objects.filter(
        published_date__lte=timezone.now()).order_by('published_date')
    tone_analyzer = ToneAnalyzerV3(
        username='******',
        password='******',
        version='2016-05-19 ')

    language_translator = LanguageTranslator(
        username='******',
        password='******')

    # print(json.dumps(translation, indent=2, ensure_ascii=False))

    for post in posts:
        data = json.dumps(
            tone_analyzer.tone(text=post.text),
            indent=1)  # converting to string and storing in the data
        j = json.loads(data)
        post.info = j['document_tone']['tone_categories'][0]['tones']
        # post.info = json.dumps(post.info);
        post.angerScore = post.info[0]['score']
        post.disgustScore = post.info[1]['score']
        post.fearScore = post.info[2]['score']
        post.joyScore = post.info[3]['score']
        post.sadScore = post.info[4]['score']
        # print(post.info[0]['tone_name'])
        translation = language_translator.translate(text=post.text,
                                                    source='en',
                                                    target='es')
        post.translatedText = json.dumps(translation,
                                         indent=2,
                                         ensure_ascii=False)
    return render(request, 'blog/post_list.html', {'posts': posts})
Example #27
0
 def __init__(self):
     self.url = "https://gateway.watsonplatform.net/tone-analyzer/api"
     self.username = "******"
     self.password = "******"
     self.tone_analyzer = ToneAnalyzerV3(username=self.username,
                                         password=self.password,
                                         version='2017-09-26')
Example #28
0
def post_list(request):
    posts = Post.objects.filter(
        published_date__lte=timezone.now()).order_by('published_date')
    tone_analyzer = ToneAnalyzerV3(
        username='******',
        password='******',
        version='2016-05-19 ')

    language_translator = LanguageTranslator(
        username='******',
        password='******')

    # print(json.dumps(translation, indent=2, ensure_ascii=False))

    for post in posts:
        data = json.dumps(
            tone_analyzer.tone(text=post.text),
            indent=1)  # converting to string and storing in the data
        j = json.loads(data)
        post.info = j['document_tone']['tone_categories'][0]['tones']
        # post.info = json.dumps(post.info);
        post.angerScore = post.info[0]['score']
        post.disgustScore = post.info[1]['score']
        post.fearScore = post.info[2]['score']
        post.joyScore = post.info[3]['score']
        post.sadScore = post.info[4]['score']
        # print(post.info[0]['tone_name'])
        translation = language_translator.translate(text=post.text,
                                                    source='en',
                                                    target='es')
        post.translatedText = json.dumps(translation,
                                         indent=2,
                                         ensure_ascii=False)
    return render(request, 'blog/post_list.html', {'posts': posts})
Example #29
0
def get_tone(text):
    tone_analyzer = ToneAnalyzerV3(
        version='2017-09-21',
        iam_apikey='Lp6lyTak20TWGCNTXyG2pAbzBPNLV5dERhclC439s3f9',
        url='https://gateway.watsonplatform.net/tone-analyzer/api')

    tone_analysis = tone_analyzer.tone({
        'text': text
    }, 'application/json', False).get_result()

    # Variables for extracting predicted tone
    mytones = tone_analysis['document_tone']['tones']
    highest = 0
    predict = 'neutral'
    valid = ['anger', 'fear', 'joy', 'sadness']

    #  Go through all identified tones
    for tone in mytones:

        cur = tone['tone_id']
        score = tone['score']

        # only report the highest tone
        if cur in valid and score > highest:
            highest = score
            predict = cur

    return predict, highest
Example #30
0
    def get(self, request, query):
        # http://127.0.0.1:8000/api/v1/watson/(thing to look for)/
        api = twitter.Api(
            base_url='https://api.twitter.com/1.1',
            consumer_key='QmMcxaV3mA4pkxiUFtCk5gu85',
            consumer_secret=
            'maFDNkP0W7NICOR77qzB4Fzwz2M4SJNa10KJgt7ovqPJBqSsg0',
            access_token_key=
            '2547825031-TWh0iKBPDA1LyRlc471ypxTBVyoEfKtCyAnUC79',
            access_token_secret='kF2yOMYDB5b1MXNFidOZy5QVkkIIsQ1OuqPZfcCiuCClN',
        )

        results = api.GetSearch(raw_query="q=" + query)

        data = []
        for stat in results:
            data.append(stat._json)

        tone_analyzer = ToneAnalyzerV3(
            version='2016-05-19',
            username='******',
            password='******')

        texto = ""

        for dat in data:
            texto = texto + dat['text']

        #tone = tone_analyzer.tone(texto, content_type='application/json')
        tone = tone_analyzer.tone(texto, content_type='text/plain')
        return Response(tone, status=status.HTTP_200_OK)