def get_tone(features_dict, text): if text: #just for reference tone_to_feature = { 'joy': 'energy', 'confident': 'danceability', 'anger': 'valence', 'fear': 'valence', 'sadness': 'valence', 'analytical': 'acousticness', 'tentative': 'instrumentalness' } #tones = ['anger', 'fear','joy', 'sadness', 'analytical', 'confident', 'tentative'] #spotifyfeatures = ['acousticness', 'danceability', 'energy', 'instrumentalness', 'valence', 'tempo'] tone_input = ToneInput(text) tone_dict = service.tone(tone_input=tone_input, content_type="application/json", sentences=False).get_result() for tone in tone_dict['document_tone']['tones']: tone_name = tone['tone_id'] feature = tone_to_feature[tone_name] if feature in features_dict: features_dict[feature].append(tone['score']) else: feature_vals = [] feature_vals.append(tone['score']) features_dict[feature] = feature_vals return features_dict
def get_tones(self, dream_text): # Authentication via IAM authenticator = IAMAuthenticator(os.getenv("TONE_ANALYZER_API_KEY")) service = ToneAnalyzerV3(version="2017-09-21", authenticator=authenticator) service.set_service_url( "https://api.us-south.tone-analyzer.watson.cloud.ibm.com/instances/35694f05-d1b2-4c03-9773-721372d1daf0" ) def french_or_english(dream_text): lang = langid.classify(dream_text) if lang[0] == "fr": return "fr" else: return "en" language = french_or_english(dream_text) tone_input = ToneInput(dream_text) tone_analysis = service.tone( tone_input=tone_input, content_type="application/json", content_language=language, accept_language=language, ).get_result() return tone_analysis
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) # post.tone3 = (tone2[1:500]) # print(post.tone3) 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 analyze_tone(self, msg): tone_input = ToneInput(msg) tone = self.tone_analyzer.tone(tone_input=tone_input, content_type="text/plain", sentences=True).get_result() estimated_polarity = self.polarity_finder(tone) return estimated_polarity
def gen_emotions(script: str) -> List[TonedSentence]: final_result = [] for batch in gen_batches(script): result = tone_analyzer.tone(ToneInput(''.join(batch)), sentences=True).get_result() for sentence in result['sentences_tone']: final_result.append(process_ibm_sentence(sentence)) return final_result
def text_emotion(text): tone_input = ToneInput(text) tone_analysis = service.tone(tone_input, content_type='application/json').get_result() best_score = 0 best_emotion = "neutral" tones = tone_analysis["document_tone"] for tone in tones["tones"]: if tone["score"] > best_score: best_score = tone["score"] best_emotion = tone["tone_id"] return best_emotion
def post_list(request, tag_slug=None): object_list = Post.published.all() tag = None kk = Post.objects.filter(publish__lte=timezone.now()).order_by('publish') for post in kk: posting = post.body translation = language_translator.translate( text=post.body, 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'] print("post.w_count",post.w_count) print("post.c_count", post.c_count) tone_input = ToneInput(post.body) 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("OOPS! Something went wrong while rendering the Document tone json") print("Score",post.Score1) print("tone",post.ToneName1) if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) paginator = Paginator(object_list, 3) # 3 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts = paginator.page(paginator.num_pages) return render(request, 'blog/post_list.html', {'page': page, 'posts': kk, 'tag': tag})
def tone_analyzer(self, text): service = ToneAnalyzerV3(version='2017-09-21', authenticator=self.TONE_AUTH) tone_input = ToneInput(text) tone = service.tone(tone_input=tone_input, content_type="application/json").get_result() tones = {} for tone in tone['document_tone']['tones']: if tone['tone_name'] not in tones: tones[tone['tone_name']] = {'score': []} tones[tone['tone_name']]['score'].append(tone['score']) return tones
# "user": "******" # }] # tone_chat = tone_analyzer.tone_chat(utterances).get_result() # print(json.dumps(tone_chat, indent=2)) # print("\ntone() example 2:\n") # with open(join(dirname(__file__), # 'resources/tone.json')) as tone_json: # tone = tone_analyzer.tone(json.load(tone_json)['text'], content_type="text/plain").get_result() # print(json.dumps(tone, indent=2)) # print("\ntone() example 6 with GDPR support:\n") # with open(join(dirname(__file__), # 'resources/tone.json')) as tone_html: # tone = tone_analyzer.tone( # json.load(tone_html)["text"], # content_type="text/html", # headers={ # 'Customer-Header': "custom_value" # }) # print(tone) # print(tone.get_headers()) # print(tone.get_result()) # print(tone.get_status_code()) 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").get_result() print(json.dumps(tone, indent=2))
def test_tone6(self): tone_input = ToneInput('I am very happy. It is a good day.') tone = self.tone_analyzer.tone( tone_input=tone_input, content_type="application/json").get_result() assert tone is not None
def tones_get(utterances): return tone_analyser.tone(ToneInput(utterances), content_type='text/plain').get_result()