Ejemplo n.º 1
0
 def __init__(self):
     self.tone_analyzer = ToneAnalyzerV3(
         version='2017-09-21',
         iam_apikey=WATSON_IAM_APIKEY,
         url='https://gateway.watsonplatform.net/tone-analyzer/api'
     )
     self.songs_cache = FromCsvFilePath(SONGS_CACHE_FILE_PATH, idColumn='spotify_song_id')
Ejemplo n.º 2
0
def ibm_tone(text):
    #apikey = 'EKJ2es4GQg5UrMiW6cY16R06b1yzPH_0aB7yInFi5cgY'
    apikey = 'mA_4uqt2kbCe0ulfIL_-w-s6d9QF1-tsC0ZB0_tWmDZu'
    authenticator = IAMAuthenticator(apikey)
    tone_analyzer = ToneAnalyzerV3(version='2017-09-21',
                                   authenticator=authenticator)

    tone_analyzer.set_service_url(
        'https://api.au-syd.tone-analyzer.watson.cloud.ibm.com/instances/a4959905-de76-443d-9f76-3da83ecaa3cf'
    )
    text = text
    tone_analysis = tone_analyzer.tone(
        {
            'text': text
        }, content_type='application/json').get_result()
    query = f'.document_tone .tones[] | {{score: .score, tone_name: .tone_name}}'
    output = pyjq.all(query, tone_analysis)
    scores = []
    tones = []
    for i in range(len(output)):
        my_dict = output[i]
        score = my_dict["score"]
        tone = my_dict["tone_name"]
        scores.append(score)
        tones.append(tone)
    return scores, tones
Ejemplo n.º 3
0
def tone_analysis():
    global result, splitTime, transcriptList
    authenticator = IAMAuthenticator(IBM_TONE_ANALYZER_API_KEY)
    tone_analyzer = ToneAnalyzerV3(
        version='2017-09-21',
        authenticator=authenticator
    )

    tone_analyzer.set_service_url(IBM_TONE_ANALYZER_SERVICE_URL)
    tone_list = []
    for x in transcriptList:
        tone_list.append(tone_analyzer.tone({'text': x}, content_type='application/json'
                                            ).get_result())
    time_list = []
    tone_name_list = []
    i = 1
    fin_tones = ''
    for tone in tone_list:
        if len(tone['document_tone']['tones']) > 0:
            for toneType in tone['document_tone']['tones']:
                time_list.append([splitTime * (i - 1), splitTime * i])
                tone_name_list.append(toneType['tone_name'])
                fin_tones += 'Tone: {} was detected from: {} sec to {} sec\n'.format(toneType['tone_name'],
                                                                                     splitTime * (i - 1),
                                                                                     splitTime * i)
        i += 1

    result['tones'] = {'time': time_list, 'tone': tone_name_list}
    result['finTones'] = fin_tones
    with open(os.path.join(STATICFILES_DIRS[0], 'JSON', 'result.json'), 'w') as json_file:
        json.dump(result, json_file)
    print('toneAnalysis finished')
Ejemplo n.º 4
0
def testtone(tweettext):
    tone_analyzer = ToneAnalyzerV3(
        version='2017-09-21',
        iam_apikey='N07MuzLARtF0AVKnRv19KfBABJusMoRRoo1ePVnKeQkY',
        url='https://gateway.watsonplatform.net/tone-analyzer/api')

    # text = 'Team, I know that times are tough! Product '\
    #     'sales have been disappointing for the past three '\
    #     'quarters. We have a competitive product, but we '\
    #     'need to do a better job of selling it!'
    text = tweettext
    try:
        tone_analysis = tone_analyzer.tone(
            {
                'text': text
            }, content_type='application/json').get_result()
        print('*************tone analysis successful*******************')
        print(json.dumps(tone_analysis, indent=2))
        print(tone_analysis['document_tone']['tones'])
        if len(tone_analysis['document_tone']['tones']) == 0:
            print('result is empty!')
            return False
        else:
            print(json.dumps(tone_analysis, indent=2))
            return tone_analysis['document_tone']['tones']
    except ApiException as ex:
        print('Method failed with status code ' + str(ex.code) + ': ' +
              ex.message)
        return False
def get_hotel_tone(hotel_name):
    '''
    return normalized score using hotel name
    '''
    text = hotels_df.loc[[hotel_name]]['reviews.text'].values.tolist()

    tone_analyzer = ToneAnalyzerV3(
        version='2017-09-21',
        iam_apikey="2wWjeivhvC9z64A2sSTcJxmq2C6c-6MspUeRGzq9J_Qm",
        url="https://gateway-lon.watsonplatform.net/tone-analyzer/api")

    scores = {}
    for x in text:
        tone_analysis = tone_analyzer.tone(
            {
                'text': x
            }, content_type='application/json').get_result()
        for tone_item in tone_analysis['document_tone']['tones']:
            try:
                scores[tone_item['tone_name']]['score'] += tone_item['score']
                scores[tone_item['tone_name']]['count'] += 1
            except:
                scores[tone_item['tone_name']] = {
                    'score': tone_item['score'],
                    'count': 1
                }
    print('finished calculating scores')
    normalized_scores = dict([(k, scores[k]['score'] / scores[k]['count'])
                              for k in scores])
    return jsonify(normalized_scores)
Ejemplo n.º 6
0
def toneAnalyzer(text):
    # print(text)
    authenticator = IAMAuthenticator(
        'Wxw1mVFTAI3bWwDrZ1XtoM03pWvbdZo5pNiTt1YsO17y')
    tone_analyzer = ToneAnalyzerV3(version='2017-09-21',
                                   authenticator=authenticator)
    # print("This")

    # tone_analyzer.set_service_url('https://api.us-south.tone-analyzer.watson.cloud.ibm.com/instances/28e8a715-3ae4-45b5-a691-0d388f58e276')
    tone_analyzer.set_service_url(
        'https://api.us-south.tone-analyzer.watson.cloud.ibm.com/instances/28e8a715-3ae4-45b5-a691-0d388f58e276'
    )

    # text = output()
    # print("This")

    tone_analysis = tone_analyzer.tone(
        {
            'text': text
        }, content_type='application/json').get_result()
    #dictTones = json.loads(json.dumps(tone_analysis, indent=2))
    #dictTones = json.loads(tone_analysis)
    # print("This")
    # print(tone_analysis)
    # print(tone_analysis['document_tone'])
    return tone_analysis['document_tone']
Ejemplo n.º 7
0
def tone_analyzer():
    text = request.json['text']
    from ibm_watson import ToneAnalyzerV3
    from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

    authenticator = IAMAuthenticator('')
    tone_analyzer = ToneAnalyzerV3(
        version='2017-09-21',
        authenticator=authenticator
    )

    tone_analyzer.set_service_url('https://api.us-south.tone-analyzer.watson.cloud.ibm.com/instances/1ff8997b-7f27-4424-99a2-514475e44d41/v3/tone?version=2017-09-21')

    if text is None:
        text = 'Team, I know that times are tough! Product ' \
               'sales have been disappointing for the past three ' \
               'quarters. We have a competitive product, but we ' \
               'need to do a better job of selling it!'\
               'I am sure we can do it! We did it before and we can do it now! '

    tone_analysis = tone_analyzer.tone(
        {'text': text},
        content_type='application/json',
        sentences= True
    ).get_result()
    return json.dumps(tone_analysis, indent=2)
Ejemplo n.º 8
0
def emotions():
    global text
    emotion = []
    tone_analyzer = ToneAnalyzerV3(
        version='2017-09-21',
        iam_apikey='Iw1X1i5s-OK_c5RRmmWBVGRQyDwoqmtQ-NXvbQVBAcs7',
        url='https://gateway.watsonplatform.net/tone-analyzer/api'
    )
    tone_analysis = tone_analyzer.tone(
        {'text': text},
        content_type='application/json'
    ).get_result()

    print(tone_analysis)
    document = "Overall speech tone: " + str(int(tone_analysis["document_tone"]["tones"][0]["score"]*100)) + "% "
    document += tone_analysis["document_tone"]["tones"][0]["tone_name"]
    emotion.append(document)

    if "sentences_tone" in tone_analysis:
        for sentence in tone_analysis["sentences_tone"]:
            detect = sentence["text"] + ": "
            if len(sentence["tones"]) > 0:
                detect += str(int(sentence["tones"][0]["score"]*100)) + "% "
                detect += sentence["tones"][0]["tone_name"]
            else:
                detect += "No emotion detected"
            emotion.append(detect)
    return json.dumps(emotion)
Ejemplo n.º 9
0
def main():
    with open('texts.json') as f:
        data = json.load(f)

    authenticator = IAMAuthenticator(APIKEY)
    tone_analyzer = ToneAnalyzerV3(version=VERSION,
                                   authenticator=authenticator)

    tone_analyzer.set_service_url(URL)
    for item in data:
        params = (
            ('version', '2017-09-21'),
            ('text', item['text']),
        )

        response = requests.get(URL + '/v3/tone',
                                params=params,
                                auth=('apikey', APIKEY))
        response = json.loads(response.text)
        print(response)

        if 'document_tone' not in response:
            break

        item['document_tone'] = response['document_tone']

    with open('back-end/cache-new.json', 'w') as json_file:
        json.dump(data, json_file)
Ejemplo n.º 10
0
def get(raw_text):
    """
    Fetches tone information from IBM tone API for given text

    Args:
        raw_text (str): Text to analyze

    Returns:
        Raw API response object on success. Error on failure.
    """
    authenticator = IAMAuthenticator(IBM_API_KEY)
    tone_analyzer = ToneAnalyzerV3(version='2020-02-25',
                                   authenticator=authenticator)
    tone_analyzer.set_service_url(
        'https://api.us-south.tone-analyzer.watson.cloud.ibm.com/instances/39cb10a6-c500-45b2-8481-053a17155502'
    )
    try:
        resp = tone_analyzer.tone({'text': raw_text},
                                  content_type='application/json',
                                  sentences=False)
        if resp.status_code == 200:
            return resp.result
        else:
            return {'error': resp.status_code}
    except Exception as e:
        return {'error': e}
    def __init__(self):
        # Speech To Text Service Initialization
        self.speech_to_text_authenticator = IAMAuthenticator(
            youtubePredictorConstants.SPEECH_TO_TEXT_API_KEY)
        self.speech_to_text = SpeechToTextV1(
            authenticator=self.speech_to_text_authenticator)
        self.speech_to_text.set_service_url(
            youtubePredictorConstants.SPEECH_TO_TEXT_API_URL)

        # Tone Analyzer Service Initialization
        self.tone_analyzer_authenticator = IAMAuthenticator(
            apikey=youtubePredictorConstants.TONE_ANALYZER_API_KEY)
        self.tone_analyzer = ToneAnalyzerV3(
            version=youtubePredictorConstants.TONE_ANALYZER_VERSION,
            authenticator=self.tone_analyzer_authenticator)
        self.tone_analyzer.set_service_url(
            youtubePredictorConstants.TONE_ANALYZER_API_URL)

        # Variables
        self.record_id = 0
        self.average_tones_data = []
        self.urls = []
        self.ytdl_stt_info = []
        self.video_info = []
        self.youtube_downloads_folder = Path("audio_files/").rglob('*.mp3')
        self.audio_files = [x for x in self.youtube_downloads_folder]
        self.ydl_opts = youtubePredictorConstants.YOUTUBE_DOWNLOAD_OPTIONS
        self.ydl_alt_opts = youtubePredictorConstants.YOUTUBE_DOWNLOAD_ALTERNATIVE_OPTIONS
        self.model = {}
        self.record_table = PrettyTable()
        self.record_table.field_names = youtubePredictorConstants.CSV_FROM_DATABASE_FILE_COLUMN_NAMES
Ejemplo n.º 12
0
def detect_tone(ukr_text):
    """
    Detects text's tone by using IBM tine analyzer.
    """
    api_key = 'Yy-P5OCreKDNC9ib2RARfMcU3CPEbybYrm5tKQGyp7w_'
    service_url = 'https://api.eu-gb.tone-analyzer.watson.cloud.ibm.com/' \
                  'instances/094eb0dc-d562-4a31-b130-1076bb4493bd'

    en_text = translate_to_en(ukr_text)
    authenticator = IAMAuthenticator(api_key)

    tone_analyzer = ToneAnalyzerV3(version='2017-09-21',
                                   authenticator=authenticator)

    tone_analyzer.set_service_url(service_url)

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

    tone = None

    try:
        tone = json_to_tone(tone_analysis)

    except IndexError as ex:
        logging.error(f"Emotion wasn't found for text: "
                      f"{en_text} "
                      f"Original error: {str(ex)}")
    return tone
Ejemplo n.º 13
0
    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
Ejemplo n.º 14
0
def AnalyzeToneforAHotel(HotelReview=[]):
    
    tone_analyzer = ToneAnalyzerV3(
    version='2017-09-21',
    iam_apikey='CX5ULZg1Bn5b8IF6U6-3hgPdUnw0XNivs_mQEezPen03',
    url='https://gateway-syd.watsonplatform.net/tone-analyzer/api')
    
    
    TonesScores ={}
    TonesCount= {}
    for review in HotelReview:
            tone_analysis = tone_analyzer.tone({'text': review},content_type='application/json').get_result()
            for i in range (len(tone_analysis['document_tone']['tones'])):
                
                toneName= tone_analysis['document_tone']['tones'][i]['tone_name']
                Score= tone_analysis['document_tone']['tones'][i]['score']
                if(TonesScores.has_key(toneName)):
                    TonesScores[toneName]= TonesScores[toneName] + Score
                    TonesCount[toneName]= TonesCount[toneName]+1
                else:
                    TonesScores[toneName]= Score
                    TonesCount[toneName]= 1
    
    for key in TonesCount.keys():
        TonesScores[key]= TonesScores[key]/TonesCount[key]
    
    return TonesScores 
Ejemplo n.º 15
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("\nSONG NOT FOUND\n")
            continue
        # authenticator = IAMAuthenticator('07LcRRjqMx-6e7iTD64yqkhCom4mAJIA8tJ9N_s8bUmr')
        authenticator = IAMAuthenticator(
            '6zSlji48p8DDphjnF_ZgfuU4pyP5PlXCk7LOEZq-YieR')
        tone_analyzer = ToneAnalyzerV3(version='2017-09-21',
                                       authenticator=authenticator)
        # tone_analyzer.set_service_url('https://api.us-east.tone-analyzer.watson.cloud.ibm.com')
        tone_analyzer.set_service_url(
            'https://gateway-lon.watsonplatform.net/tone-analyzer/api')
        text = lyr
        if (len(lyr) == 0):
            continue

        tone_analysis = tone_analyzer.tone(
            {
                'text': text
            }, content_type='application/json').get_result()
        print(i)
        tone = tone_analysis['document_tone']['tones']
        play.append([artist_name, title, tone])
    return play
def get_tone_analysis():
    """
    gets tones/emotions used in transcript using IBM Watson Tone Analyser
    https://www.ibm.com/watson/services/tone-analyzer/
    """
    global split_time, transcript_list, tones
    authenticator = IAMAuthenticator(IBM_TONE_ANALYZER_API_KEY)
    tone_analyzer = ToneAnalyzerV3(
        version='2017-09-21',
        authenticator=authenticator
    )
    tone_analyzer.set_service_url(IBM_TONE_ANALYZER_SERVICE_URL)

    tone_list = []
    for x in transcript_list:
        tone_list.append(tone_analyzer.tone({'text': x}, content_type='application/json').get_result())
    time_list = []
    tone_name_list = []
    i = 1
    tones = []
    for tone in tone_list:
        if len(tone['document_tone']['tones']) > 0:
            for toneType in tone['document_tone']['tones']:
                time_list.append([split_time * (i - 1), split_time * i])
                tone_name_list.append(toneType['tone_name'])
                temp_str = 'Tone: {} was detected from: {} sec to {} sec'. \
                    format(toneType['tone_name'], split_time * (i - 1), split_time * i)
                tones.append(temp_str)
        i += 1
    print('get_tone_analysis finished')
Ejemplo n.º 17
0
    def post(self,hotel_name):
        print("---Hotel analyser---")
        
        # 1.extract hotel data
        print("name:" + hotel_name)
        hotel_data = hotel_list[hotel_list["name"]== hotel_name]
        hotel_review = hotel_data["reviews.text"]
        print(hotel_review.head())
        # 2.create json/ string 
        watson_input = hotel_review.to_json()
        
        # 3.send it to watson
        tone_analyzer = ToneAnalyzerV3(
            version='2017-09-21',
            iam_apikey=watson_key,
            url=watson_url)
        try : 
            #watson 
            print("requesting tone analysis")
            watson_responce = tone_analyzer.tone(
                    {'text':watson_input} , 
                    content_language='en', sentences=False, 
                    content_type="application/json").get_result()
            print("watson responded" )

            return (watson_responce) ,200
        except: 
            return {"message":"failed to connect"} ,500   
def get_watson_api() -> ToneAnalyzerV3:
    """Retrieves a ToneAnalyzerV3 API object, this object is utilized for analyzing the sentiment of Tweets."""
    authenticator = IAMAuthenticator(os.environ['WATSON_API_KEY'])
    tone_analyzer = ToneAnalyzerV3(version=os.environ['WATSON_VERSION'],
                                   authenticator=authenticator)
    tone_analyzer.set_service_url(os.environ['WATSON_URL'])
    return tone_analyzer
Ejemplo n.º 19
0
    def __init__(self):

        self.nlu_authenticator = IAMAuthenticator(
            'MfGCw7jH73n6Eaee1xPJA_ZC6VkJldmbNL9fsrHQe1qm')
        self.natural_language_understanding = NaturalLanguageUnderstandingV1(
            version='2019-07-12', authenticator=self.nlu_authenticator)

        self.tone_authenticator = IAMAuthenticator(
            'gAdmEsh1sEKmYlw2FjabXQtE_znP26DF7ZUwa4Pltx4K')
        self.tone_analyzer = ToneAnalyzerV3(
            version='2019-07-12', authenticator=self.tone_authenticator)

        self.visual_authenticator = IAMAuthenticator(
            '5w-5fC5sEzkc9W2SCBUAUrq6CuI_ZQO5KeRQC3VLuFSt')
        self.visual_recognition = VisualRecognitionV3(
            version='2019-07-12', authenticator=self.visual_authenticator)

        self.visual_recognition.set_service_url(
            'https://gateway.watsonplatform.net/visual-recognition/api')

        self.tone_analyzer.set_service_url(
            'https://api.eu-gb.tone-analyzer.watson.cloud.ibm.com/instances/175258bd-a3f9-4f9e-a7c6-1a012b72d887'
        )

        self.natural_language_understanding.set_service_url(
            'https://gateway-lon.watsonplatform.net/natural-language-understanding/api'
        )
Ejemplo n.º 20
0
def emotion_analysis(username):
    timeline = username + '_timeline.csv'
    user_timeline = pd.read_csv(folder_path + timeline, encoding='utf-8')
    tweet_count = user_timeline[user_timeline['isRT'] == False].shape[0]
    rt_count = user_timeline[user_timeline['isRT'] == True].shape[0]
    time_ordered = user_timeline
    time_ordered['time'] = pd.to_datetime(time_ordered.time)
    time_ordered = time_ordered.sort_values(by=['time'])
    last_tweet = time_ordered.tail(1).iloc[0]['time']
    print(last_tweet)

    filtered_timeline = user_timeline[(user_timeline['isRT'] == False)
                                      & (user_timeline['lang'] == 'en')]
    filtered_timeline.loc[:, 'text'] = filtered_timeline['text'].apply(
        lambda x: re.sub(r'(^|[^@\w])@(\w{1,15})\b', ' ', x))  #user tags
    filtered_timeline.loc[:, 'text'] = filtered_timeline['text'].apply(
        lambda x: re.sub(r'http\S+', ' ', x))  #urls
    filtered_timeline.loc[:, 'text'] = filtered_timeline['text'].apply(
        lambda x: x.replace('\n', ' '))
    filtered_timeline.loc[:, 'text'] = filtered_timeline['text'].apply(
        lambda x: x.replace('"', ' '))
    filtered_timeline.loc[:, 'text'] = filtered_timeline['text'].apply(
        deEmojify)  #emojis
    filtered_timeline = filtered_timeline.drop(filtered_timeline[
        filtered_timeline.text == ''].index)  #delete empty strings
    single_tweet = '. '.join(filtered_timeline.text.values)
    authenticator = IAMAuthenticator(
        'nI-bfS7Ga_2rnVsqfzLcxcIMFn7LJXaIs__9CQdsyYde')
    tone_analyzer = ToneAnalyzerV3(version='2017-09-21',
                                   authenticator=authenticator)
    tone_analyzer.set_service_url(
        'https://gateway-lon.watsonplatform.net/tone-analyzer/api')
    tone_analysis = tone_analyzer.tone(
        {
            'text': single_tweet
        }, content_type='application/json').get_result()
    sentence_count = len(tone_analysis['sentences_tone'])
    tone_dict = {
        'anger': 0,
        'fear': 0,
        'joy': 0,
        'sadness': 0,
        'analytical': 0,
        'confident': 0,
        'tentative': 0
    }
    for sentence in tone_analysis['sentences_tone']:
        for tone in sentence['tones']:
            tone_dict[tone['tone_id']] += tone['score']
    for tone in tone_dict.keys():
        tone_dict[tone] = tone_dict[tone] / sentence_count
    # sorted(tone_dict.items(), key=lambda x:x[-1], reverse=True)
    user_emotion_row = [
        timeline.split('_timeline')[0], tone_dict['anger'], tone_dict['fear'],
        tone_dict['joy'], tone_dict['sadness'], tone_dict['analytical'],
        tone_dict['confident'], tone_dict['tentative'], tweet_count, rt_count,
        last_tweet
    ]
    return user_emotion_row
Ejemplo n.º 21
0
 def __init__(self):
     conf_path = os.path.join(os.path.dirname(__file__), 'conf.json')
     with open(conf_path) as f_h:
         conf_file = json.load(f_h)
         api_conf = conf_file['IBM']
     self.tone_analyzer = ToneAnalyzerV3(version='2017-09-21',
                                         iam_apikey=api_conf['apikey'],
                                         url=api_conf['endpoint'])
def init_analyzer(api_string, service_url_string):
    authenticator = IAMAuthenticator(api_string)
    analyzer = ToneAnalyzerV3(
        version='2016-05-19',
        authenticator=authenticator)
    analyzer.set_service_url(service_url_string)
    
    return analyzer
Ejemplo n.º 23
0
    def __init__(self):

        # TODO - API KEY!

        self.tone_analyzer = ToneAnalyzerV3(
            iam_apikey="",
            url="https://gateway.watsonplatform.net/tone-analyzer/api",
            version="2017-09-21")
Ejemplo n.º 24
0
 def __init__(self):
     # credentials to access Tone Analyzer API
     cred = parse_yaml('conf.yaml')
     API_KEY = cred['ibm_api_key']
     URL = cred['ibm_url']
     self.api = ToneAnalyzerV3(version=get_todays_date(),
                               iam_apikey=API_KEY,
                               url=URL)
Ejemplo n.º 25
0
def get_text_sentiment(text):
    authenticator = IAMAuthenticator(api_key)

    tone_analyzer = ToneAnalyzerV3(version="2019-11-24", authenticator=authenticator)

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

    return tone_analyzer.tone(text).result['document_tone']['tones']
Ejemplo n.º 26
0
def get_tone(reviews, json_output):
    toness = []
    score = 0
    count = 0
    sum = []

    tone_analyzer = ToneAnalyzerV3(
        version='2017-09-21',
        iam_apikey='YWrrmTxtFzUDJAYUk2J93PEUiDC1O8368ec-OQEwuKDO',
        url='https://gateway-lon.watsonplatform.net/tone-analyzer/api')

    #we can enable it, for the sake of speed disabled here
    #tone_analyzer.disable_SSL_verification()

    #***************************************************************************************************
    #all tones listed here : https://github.com/IBM/tone-analyzer-ios/blob/master/README.md
    #(anger, disgust, fear, joy and sadness),
    #social propensities (openness, conscientiousness, extroversion, agreeableness, and emotional range),
    #and language styles (analytical, confident and tentative)
    tone_id = [
        'anger', 'disgust', 'fear', 'joy', 'sadness', 'openness',
        'conscientiousness', 'extroversion', 'agreeableness',
        'emotional range', 'analytical', 'confident', 'tentative'
    ]

    #we initilaize a new summary object per hotel_reviews
    summary = pd.DataFrame(list(zip(tone_id, [0] * 13, [0] * 13)),
                           columns=['tone_id', 'score', 'count'])

    try:
        for r in reviews:
            json_output = tone_analyzer.tone(
                {
                    'text': r
                }, content_type='application/json').get_result()
            i = json_output['document_tone']['tones']
            #each review can have multiple tones
            for j in i:
                t = str(j['tone_id'])
                s = j['score']
                summary.loc[summary['tone_id'] == t, 'score'] += s
                summary.loc[summary['tone_id'] == t, 'count'] += 1
                toness.append(json.dumps(i))

        summary['mean'] = summary['score'] / summary['count']
        # not all tones are detected in the reviews of a hotel,
        # get rid of zero tones.
        summary = summary[summary['score'] != 0]

        summary_json = summary.to_json(orient='records')

    except ApiException as ex:
        print "Method failed with status code " + str(
            ex.code) + ": " + ex.message
    if json_output:
        return summary_json
    else:
        return summary
Ejemplo n.º 27
0
def tone_analyzer(text):
    # Tone Authenticator to analyze emotion on the basis of NLP by Proccessed Text.
    authenticator = IAMAuthenticator(oapikey)
    ta = ToneAnalyzerV3(version='2020-05-20', authenticator=authenticator)

    ta.set_service_url(ourl)
    tone_ana = ta.tone(text).get_result()
    #print(tone_ana)
    return tone_ana['document_tone']['tones']
Ejemplo n.º 28
0
 def __init__(self):
     self.tone_analyzer = ''
     authenticator = IAMAuthenticator(
         'DUma1tFHRoi2LePb3uHHbWgPOtHF1YrSPJrtLv0-1NHu')
     self.tone_analyzer = ToneAnalyzerV3(version='2017-09-21',
                                         authenticator=authenticator)
     self.tone_analyzer.set_service_url(
         'https://api.au-syd.tone-analyzer.watson.cloud.ibm.com/instances/943a9480-4385-4d56-bfde-9e236aa2efd2'
     )
Ejemplo n.º 29
0
def res(): 
    print ('inicia') 
    
    audio = pyaudio.PyAudio()
    stream = audio.open(format = pyaudio.paInt16, channels = 2, rate = 44100, frames_per_buffer = 1024, input = True)
    print('Inicia grabación')
        
    frames = []
    tiempo = 5 #segundos
    for i in range(0, int(44100/1024*tiempo)):
        tmp = stream.read(1024)
        frames.append(tmp)
            
    print('Acaba la captura')
    stream.stop_stream()
    stream.close()
        
    waveFile = wave.open('graba.wav','wb')
    waveFile.setnchannels(2)
    waveFile.setframerate(44100)
    waveFile.setsampwidth(audio.get_sample_size(pyaudio.paInt16))
    waveFile.writeframes(b''.join(frames))
    waveFile.close()

    servicio = SpeechToTextV1(iam_apikey ='id de watson') 
    with open('graba.wav','rb') as fichero:


        res = json.dumps(servicio.recognize(audio = fichero,timestamps = True,model = 'es-ES_NarrowbandModel', word_confidence = True).get_result(),sort_keys=True ,indent = 2)
        resultado=json.loads(res)
        res=resultado["results"]
        res=res[0]
        res=res["alternatives"]
        res=res[0]
        res=res["transcript"]
             
        print(res)
    audio= res
    #----------------------------------------traduccion----------------------------------------------
    language_translator = LanguageTranslatorV3(
    version='2018-05-01',
    iam_apikey='id de watson',
    url='https://gateway.watsonplatform.net/language-translator/api')
    
    translation = language_translator.translate(
    text=res, model_id='es-en').get_result()
    traduccion=json.dumps(translation, indent=2, ensure_ascii=False)
       
    #print(traduccion)
    traduccion=json.loads(traduccion)
    traduccion= traduccion["translations"]
    traduccion= traduccion[0]
    traduccion= traduccion["translation"]
    print(traduccion)
    traduccion1=traduccion
    ##-----------------------------------------------analizador
    tone_analyzer = ToneAnalyzerV3(version = '2017-09-21',iam_apikey = 'id de watson, url = 'https://gateway.watsonplatform.net/tone-analyzer/api'  )
Ejemplo n.º 30
0
def authentication_function():

    global TTS_AUTH
    global TTS_SERVICE
    global WATSON_KEY
    global WATSON_AUTH
    global WATSON_ASSISTANT
    global HEADERS
    global USERPASS
    global URL
    global TONE_AUTHENTICATOR
    global TONE_SERVICE

    # TTS
    TTS_AUTH = IAMAuthenticator('4CUYHU_68pReHO4xyfisGiuH7fQmXanfbgf4OR94gp2l')
    TTS_SERVICE = TextToSpeechV1(authenticator=TTS_AUTH)
    TTS_SERVICE.set_service_url(
        'https://api.us-south.text-to-speech.watson.cloud.ibm.com/instances/806b8f05-e01e-4b2b-8d83-194205e7733b'
    )
    # END TTS

    # STT
    HEADERS = {}
    USERPASS = "******".join(get_auth())
    HEADERS["Authorization"] = "Basic " + base64.b64encode(
        USERPASS.encode()).decode()
    URL = get_url()
    # END STT

    # WATSON
    # put the general watson api key here
    WATSON_AUTH = IAMAuthenticator(
        'AGesgrUJa4L4OVBHpbJgTKfOeCU6kVeVxo2qhIVFqIYS')
    WATSON_ASSISTANT = AssistantV2(version='2018-09-20',
                                   authenticator=WATSON_AUTH)
    WATSON_ASSISTANT.set_service_url(
        'https://api.us-south.assistant.watson.cloud.ibm.com/instances/28f6a127-f399-482b-9b66-5502ad5af6f5'
    )
    # WATSON_ASSISTANT.set_service_url(
    #    'https://api.us-south.assistant.watson.cloud.ibm.com/instances/28f6a127-f399-482b-9b66-5502ad5af6f5')
    # session = WATSON_ASSISTANT.create_session(
    #    "82b5e8f6-5a1d-44a5-930e-a388332db998").get_result()  # put the specific assistant api key
    session = WATSON_ASSISTANT.create_session(
        "9bf7bf36-235e-4089-bf1d-113791da5b43").get_result(
        )  # put the specific assistant api key
    WATSON_KEY = session.get("session_id", "")
    # END WATSON

    # TONE ANALYZER
    TONE_AUTHENTICATOR = IAMAuthenticator(
        'b0DmzKxaFck7YymuFStEYpJPMmt_bbYLPu8fPO9aEend')
    TONE_SERVICE = ToneAnalyzerV3(version='2017-09-21',
                                  authenticator=TONE_AUTHENTICATOR)
    TONE_SERVICE.set_service_url(
        'https://api.us-south.tone-analyzer.watson.cloud.ibm.com/instances/4a4d15eb-5212-447b-8da9-dcad6434130a'
    )