示例#1
0
def Service(apikey: str, url: str) -> watson.AssistantV1:
    authenticator = IAMAuthenticator(apikey)
    service = watson.AssistantV1(version=VERSION, authenticator=authenticator)
    service.set_service_url(url)
    return service
示例#2
0
import json
from ibm_watson import ToneAnalyzerV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

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

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


def get_tone(text):
    #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!'

    tone_analysis = tone_analyzer.tone(
        {
            'text': text
        }, content_type='application/json').get_result()
    #print(json.dumps(tone_analysis, indent=2))
    return tone_analysis
示例#3
0
# You need to install pyaudio to run this example
# pip install pyaudio

# In this example, the websocket connection is opened with a text
# passed in the request. When the service responds with the synthesized
# audio, the pyaudio would play it in a blocking mode

from ibm_watson import TextToSpeechV1
from ibm_watson.websocket import SynthesizeCallback
import pyaudio
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('your_api_key')
service = TextToSpeechV1(authenticator=authenticator)
service.set_service_url('https://stream.watsonplatform.net/speech-to-text/api')

class Play(object):
    """
    Wrapper to play the audio in a blocking mode
    """
    def __init__(self):
        self.format = pyaudio.paInt16
        self.channels = 1
        self.rate = 22050
        self.chunk = 1024
        self.pyaudio = None
        self.stream = None

    def start_streaming(self):
        self.pyaudio = pyaudio.PyAudio()
        self.stream = self._open_stream()
示例#4
0
from ibm_watson import VisualRecognitionV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from url_id import RetornaIdUrl

authenticator = IAMAuthenticator('{API key}')
visual_recognition = VisualRecognitionV3(version='2018-03-19',
                                         authenticator=authenticator)
visual_recognition.set_service_url('{Your Set Service URL}')


class CheckProfilePic:
    def verifica_imagem(self, url):
        self._classes = visual_recognition.classify(
            url=RetornaIdUrl.retorna_url_img_pelo_id(url),
            threshold='0.0',
            classifier_ids='{Your CustomModel ID}').get_result()
        self._dicionario_score = dict(self._classes, indent=2)
        return float(self._dicionario_score['images'][0]['classifiers'][0]
                     ['classes'][0]['score'])
示例#5
0
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions
from ibm_watson.websocket import RecognizeCallback, AudioSource
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from collections import defaultdict
from operator import itemgetter
import json

sentiment_analysis_authenticator = IAMAuthenticator(
    '9a-GE9xAuObCOU7mc31DPCs9Qbh8iuRnT7FC38Y7aVmK')


def sentiment_analysis(transcript):
    print("Initialize sentiment analysis...")
    service = NaturalLanguageUnderstandingV1(
        version='2018-03-16', authenticator=sentiment_analysis_authenticator)

    response = service.analyze(
        text=transcript,
        features=Features(entities=EntitiesOptions(emotion=True,
                                                   sentiment=True,
                                                   limit=2),
                          keywords=KeywordsOptions(emotion=True,
                                                   sentiment=True,
                                                   limit=2))).get_result()
    print("Analyzed sentiment...")
    return response


def handle_sentiment(sentiment):
    keywords = []
        restructured_json_entities_list = restructure_nlu_json_result(
            nlu_response)
        worst_entity_type, worst_entity_text, worst_score = get_worst_entity_data(
            nlu_response)

    if restructured_json_entities_list:
        recommendation = get_recommendation(carro, worst_entity_type,
                                            restructured_json_entities_list)
        json_final['recommendation'] = recommendation
        json_final['entities'] = restructured_json_entities_list

    #if worst_entity_type:
    #json_final['piorEntity'] = worst_entity_text
    #json_final['piorScore'] = worst_score
    #json_final['prioridadeDeMelhora'] = worst_entity_type

    return jsonify(json_final), 200


nlu_authenticator = IAMAuthenticator(apikey=nlu_apikey)
nlu_service = NaturalLanguageUnderstandingV1(version='2018-03-16',
                                             authenticator=nlu_authenticator)
nlu_service.set_service_url(nlu_service_url)

stt_authenticator = IAMAuthenticator(apikey=stt_apikey)
stt_service = SpeechToTextV1(authenticator=stt_authenticator)
stt_service.set_service_url(stt_service_url)

#if __name__ == '__main__':
#app.run(host='0.0.0.0', port=port)
示例#7
0
import os
import json
from os.path import join, dirname
from ibm_watson import SpeechToTextV1
from ibm_watson.websocket import RecognizeCallback, AudioSource
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator(
    'da9Fn8Ke9KDP_d5SKo99VaJ55e6hG-sqHDeJdXN8g1OP')
speech_to_text = SpeechToTextV1(authenticator=authenticator)
speech_to_text.set_service_url(
    'https://api.jp-tok.speech-to-text.watson.cloud.ibm.com/instances/51769b15-84b3-4ead-b824-5cf4cdd69495'
)


class MyRecognizeCallback(RecognizeCallback):
    def __init__(self):
        RecognizeCallback.__init__(self)

    def on_data(self, data):
        FileName = r'E:\originD\2019-2020\2019-2020-2\信存检\作业\小组作业\aResult\\' + ofiles[
            i][-12:-4] + "-.txt"
        raw = open(FileName, "w+")
        print(json.dumps(data, indent=2), file=raw)
        raw.close()

    def on_error(self, error):
        print('Error received: {}'.format(error))

    def on_inactivity_timeout(self, error):
        print('Inactivity timeout: {}'.format(error))
示例#8
0
TTS_URL_IBM = "https://gateway-wdc.watsonplatform.net/text-to-speech/api"
BEST_STORIES_API = "https://hacker-news.firebaseio.com/v0/beststories.json"
STORIES_FOR_DATE_PAGE = "https://news.ycombinator.com/front?day=%s"
STORY_API = "https://hacker-news.firebaseio.com/v0/item/%s.json"
VOICE_TYPE = 'en-US-WaveNet-D'
VOICE_GENDER = 'MALE'
VOICE_LANG = 'en-us'
TOTAL_SENTENCES = 2
NUMBER_ARTICLES = 30
TEMPLATE_FOLDER = "templates"
PODCASTS_FOLDER = "podcasts"
NEWS_DATA_FOLDER = "news_data"
TEMP_FOLDER = "temp"

t = jinja2.FileSystemLoader(TEMPLATE_FOLDER)
authenticator = IAMAuthenticator(IBM_API_KEY)
text_to_speech = TextToSpeechV1(authenticator=authenticator)
text_to_speech.set_service_url(TTS_URL_IBM)


def ssml_to_audio_google(ssml,
                         format='audio/ogg;codecs=opus',
                         voice_type=VOICE_TYPE,
                         voice_gender=VOICE_GENDER,
                         voice_lang=VOICE_LANG):
    accept_to_format = {
        'audio/ogg;codecs=opus': 'OGG_OPUS',
        'audio/wav': 'LINEAR16',
        'audio/mp3': 'MP3'
    }
示例#9
0
from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

#twitter junk
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
#twilio connection
client = Client("", "")

#ibm watson authentification
authenticator = IAMAuthenticator('')
service = NaturalLanguageUnderstandingV1(
    version='2018-03-16',
    authenticator=authenticator)
#connects to the language api
service.set_service_url('https://gateway.watsonplatform.net/natural-language-understanding/api')


def proces():
    #creates and opens gui to input phone numbers
    file = open("PhoneNumbers.txt", "a+")
    number1=Entry.get(E1)

    file.write(str(number1)+ '\n')
    file.close()
示例#10
0
import discord
import configparser
from ibm_watson import LanguageTranslatorV3 as LanguageTranslator
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

inifile = configparser.ConfigParser()
inifile.read('./config.ini', 'UTF-8')
version = inifile.get('languageTranslator', 'version')
apikey = inifile.get('languageTranslator', 'apikey')
token = inifile.get('discord', 'token')

client = discord.Client()
language_translator = LanguageTranslator(
    authenticator=IAMAuthenticator(apikey), version=version)


@client.event
async def on_ready():
    print('------')


@client.event
async def on_message(message):
    text = message.content
    jsonstr = language_translator.identify(text).get_result()
    source = jsonstr['languages'][0]['language']
    if client.user != message.author:
        if source in 'ja':
            target = 'en'
            data = language_translator.translate(text=text,
                                                 source=source,
示例#11
0
from ibm_watson import AssistantV2
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from session_manager import SessionManager
import logging
import actions
import os

logger = logging.getLogger('TelegramBot')

authenticator = IAMAuthenticator(os.environ.get('WATSON_ASSISTANT_IAM_TOKEN'))
assistant_id = os.environ.get('WATSON_ASSISTANT_ASSISTANT_ID')

assistant = AssistantV2(version='2020-02-05', authenticator=authenticator)

assistant.set_service_url(os.environ.get('WATSON_ASSISTANT_URL'))


def create_session():
    response = assistant.create_session(assistant_id)
    return response.get_result()['session_id']


def validate_session(chat_id):
    # check if session is valid for current chat_id
    logger.info('Validando sessão de ' + str(chat_id))
    if not SessionManager.getInstance().checkSession(chat_id):
        session_id = create_session()
        logger.info('Sessão criada para ' + str(chat_id))
    else:
        session_id = SessionManager.getInstance().getSession(chat_id)
        logger.info('Sessão atualizada para ' + str(chat_id))
def instantiate_stt(api_key, url_service):
    """Link a SDK instance with a IBM STT instance."""
    authenticator = IAMAuthenticator(api_key)
    speech_to_text = SpeechToTextV1(authenticator=authenticator)
    speech_to_text.set_service_url(url_service)
    return speech_to_text
示例#13
0
import json
import json as json_import
import platform
import os
import requests
import sys


from ibm_watson import AssistantV1

# from watson_developer_cloud import ConversationV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('aFkveMnv_OKL4nHMyj0HCb068Hb-LkEG4fyQUPzfwHs8')
assistant = AssistantV1(
            version='2020-07-03',
                authenticator=authenticator)
assistant.set_service_url('https://api.eu-gb.assistant.watson.cloud.ibm.com/instances/29093a9d-7ca1-425a-9103-b80c7a5bbb8e')

#workspace_id='',

#assistant.set_http_config({'timeout': 100})
#response = assistant.message(workspace_id=workspace_id, input={
     #   'text': 'What\'s up,Whats buddy?'}).get_result()
#print(json.dumps(response, indent=2))


#assistant = AssistantV1(


 #   ASSISTANT_IAM_API_KEY = 'aFkveMnv_OKL4nHMyj0HCb068Hb-LkEG4fyQUPzfwHs8',
示例#14
0
import random
import q

from ibm_watson import TextToSpeechV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.websocket import SynthesizeCallback

authenticator = IAMAuthenticator(
    'r0V3pXuPjLiNnDOVKJzn0UC2nVyPqV4m2OpnG3-wP23k')

voice = TextToSpeechV1(authenticator=authenticator)
voice.set_service_url('https://stream.watsonplatform.net/text-to-speech/api')

file_path = 'test.ogg'


class Say(SynthesizeCallback):
    def __init__(self):
        SynthesizeCallback.__init__(self)
        self.fd = open(file_path, 'ab')

    def on_connected(self):
        print('Connection was successful')

    def on_error(self, error):
        print('Error received: {}'.format(error))

    def on_content_type(self, content_type):
        print('Content type: {}'.format(content_type))

    def on_timing_information(self, timing_information):
示例#15
0
文件: app.py 项目: omar178/flask-api
def get_tone(client_id):
    """
    :return: hotel reviews scores
    """
    authenticator = IAMAuthenticator(
        'Bt_7ZXX7zc-nG_NWrRaNMwQTO3VD5je1F-4tJ7WIsad3')
    tone_analyzer = ToneAnalyzerV3(version='2017-09-21',
                                   authenticator=authenticator)
    tone_analyzer.set_service_url(
        'https://gateway-lon.watsonplatform.net/tone-analyzer/api')

    df = pd.read_csv('data.csv')
    df = df[['name', 'reviews.text']]
    tones = []
    scores = []
    for i in list(df['reviews.text']):
        tone_analysis = tone_analyzer.tone(
            {
                'text': i
            }, content_type='application/json').get_result()
        tone_analysis = tone_analysis['document_tone']['tones']
        tones.append([i['tone_name'] for i in tone_analysis])
        scores.append([i['score'] for i in tone_analysis])

    col_name = np.unique([j for i in tones for j in i])
    analytical = [
        scores[i][tones[i].index('Analytical')]
        if 'analytical' in tones[i] else 0 for i in range(len(tones))
    ]
    Confident = [
        scores[i][tones[i].index('Confident')]
        if 'Confident' in tones[i] else 0 for i in range(len(tones))
    ]
    Joy = [
        scores[i][tones[i].index('Joy')] if 'Joy' in tones[i] else 0
        for i in range(len(tones))
    ]
    Sadness = [
        scores[i][tones[i].index('Sadness')] if 'Sadness' in tones[i] else 0
        for i in range(len(tones))
    ]
    Tentative = [
        scores[i][tones[i].index('Tentative')]
        if 'Tentative' in tones[i] else 0 for i in range(len(tones))
    ]
    Anger = [
        scores[i][tones[i].index('Anger')] if 'Anger' in tones[i] else 0
        for i in range(len(tones))
    ]
    Fear = [
        scores[i][tones[i].index('Fear')] if 'Fear' in tones[i] else 0
        for i in range(len(tones))
    ]

    df_tone = pd.DataFrame({
        'Hotel_name': list(df['name']),
        'analytical': analytical,
        'Confident': Confident,
        'Joy': Joy,
        'Sadness': Sadness,
        'Tentative': Tentative,
        'Anger': Anger,
        'Fear': Fear
    })
    df_tone.to_csv('tones.csv')

    df_tone = df_tone.groupby('Hotel_name').agg('mean')
    result = {}
    for index, row in df_tone.iterrows():
        result[index] = dict(row)
    socketio.emit('my response', {'data': jsonify(result)}, room=client_id)
    print('generating tones for client {}'.format(client_id))
示例#16
0
# This Python file uses the following encoding: utf-8
import os, sys
import json
import re
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_watson.natural_language_understanding_v1 import *
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from csv import *
import math
from ibm_watson import ApiException
import pandas as pd
from collections import Counter

# Authentication via IAM
authenticator = IAMAuthenticator(
    'wdCPVYuTgefiUbrGjYYYYWZ4WaMnvxw-9CYRBj4kcZIc')
service = NaturalLanguageUnderstandingV1(version='2018-03-16',
                                         authenticator=authenticator)
service.set_service_url(
    'https://gateway-lon.watsonplatform.net/natural-language-understanding/api'
)

c = 0
data = list()
good_data = list()
bad_data = list()
mixed_data = list()

good_list = list()
bad_list = list()
示例#17
0
def home(request):
    try:
        authenticator = IAMAuthenticator(
            '-GEDGacgnI36ctk77Aa4X5k3PAXBA_AaRQIxp6G71sOP')
        natural_language_understanding = NaturalLanguageUnderstandingV1(
            version='2019-07-12', authenticator=authenticator)
        natural_language_understanding.set_service_url(
            'https://api.eu-gb.natural-language-understanding.watson.cloud.ibm.com/instances/b61e5fb9-726b-4cba-8b4b-12f1403ed4a1'
        )

        # ii = "Hello, I'm having a problem with your service. Nothing is working well. The service here is very bad. I am really very upset. I was expecting better than that. And my service has been stopped since yesterday. I have been suffering from this problem for a long time and cannot find a solution. The service here is bad most of times. Why you do not solve these problems. Some had left your service for this reason. The network is weak all the time, and it stops at the call. why this happen!? I wait. I'm fed up with complaining from the service."
        # ii = "Hello, I need some help. I've subscribed to some news services and want to cancel them.They were not helpful with me plus they used a lot of balance. I feel bad because I used this service. Please remove it and try to improve these services. It has more harm than good. I hope to improve some services and offer some offers soon. I have another problem. My service has been disabled since yesterday. I have been suffering from this problem for a different times and cannot find a solution. It affects my work and communication in some important times."
        ii = request.POST['text']
        response1 = natural_language_understanding.analyze(
            text=ii,
            features=Features(emotion=EmotionOptions(
                targets=[ii.split()[1]]))).get_result()

        response2 = natural_language_understanding.analyze(
            text=ii,
            features=Features(sentiment=SentimentOptions(
                targets=[ii.split()[1]]))).get_result()
        global sad, joy, fear, disgust, anger, sentiment_label, sentiment
        sad = response1['emotion']['document']['emotion']['sadness']
        joy = response1['emotion']['document']['emotion']['joy']
        fear = response1['emotion']['document']['emotion']['fear']
        disgust = response1['emotion']['document']['emotion']['disgust']
        anger = response1['emotion']['document']['emotion']['anger']
        sentiment_label = response2['sentiment']['document']['label']
        sentiment = response2['sentiment']['document']['score']

        ####################################################################

        data = pd.read_csv(
            "/Users/Ameen/Desktop/CV-projects/emotions/emotions/loyalty/dataset/final_dataset.csv"
        )
        X_train, X_test, y_train, y_test = train_test_split(
            data[["sadness", "joy", "fear", "disgust", 'anger', 'score']],
            data["label_state"],
            test_size=0.4)
        lsvm = LinearSVC()
        prid = lsvm.fit(X_train, y_train)
        accuracy = lsvm.score((X_test), y_test)
        # print(accuracy)
        out = lsvm.predict((X_test))
        from sklearn.metrics import classification_report
        # print(classification_report(out, y_test))
        lls = [sad, joy, fear, disgust, anger, sentiment]
        predict = lsvm.predict([lls])
        ss = predict
        if predict == [0]:
            predict = "leave"
        else:
            predict = "stay"

        form = file_form()
        context = {
            'sad': sad,
            'joy': joy,
            'fear': fear,
            'disgust': disgust,
            'anger': anger,
            'sentiment_label': sentiment_label,
            'sentiment': sentiment,
            'predict': predict,
            'form': form
        }
        return render(request, 'temp.html', context)
    except Exception as e:
        form = file_form()
        messages.error(request, e, extra_tags='error')
        return render(request, 'temp.html', {'form': form})
示例#18
0
from ibm_watson import DiscoveryV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from settings import START_DATE, END_DATE

authenticator = IAMAuthenticator(
    'o-V5I0eeHruCOX5uyc8dICpCNT4Uzbd-6Q8JEpuCM7_D')
discovery = DiscoveryV1(version='2019-11-30', authenticator=authenticator)

discovery.set_service_url(
    'https://gateway-lon.watsonplatform.net/discovery/api')


def extract_resources(news_result):
    if not news_result.get("enriched_text"):
        return []
    enriched_text = news_result["enriched_text"]
    res_dict = {}

    if enriched_text.get("entities"):
        for e in enriched_text["entities"]:
            if not e.get("disambiguation") or not e.get("disambiguation")\
                    .get("dbpedia_resource") or e["relevance"] < 0.5:
                continue

            val = e["disambiguation"]["dbpedia_resource"]
            if not res_dict.get(val) or res_dict[val] < e["relevance"]:
                res_dict[val] = e["relevance"]

    if enriched_text.get("concepts"):
        for c in enriched_text["concepts"]:
            if c["relevance"] < 0.5:
示例#19
0
# Studio's Speech To Text Below Code
# Accepts only .mp3 Format of Audio file

import json
import csv
from os.path import join, dirname
from ibm_watson import SpeechToTextV1
from ibm_watson.websocket import RecognizeCallback, AudioSource
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
import pandas as pd
import config
#STT code
# Insert API Key in place of
# 'YOUR UNIQUE API KEY'

authenticator = IAMAuthenticator(config.STT_API_KEY)
service = SpeechToTextV1(authenticator=authenticator)

#Insert URL in place of 'API_URL'
service.set_service_url(config.STT_URL)

# Insert local mp3 file path in place of 'LOCAL FILE PATH'
#with open(join(dirname('__file__'), r'./audio2.mp3'), #need to make this dynamic for different file names
with open('masa-audio.mp3', 'rb') as audio_file:

    dic = json.loads(
        json.dumps(
            service.recognize(
                audio=audio_file,
                content_type=
                'audio/mp3',  #make sure to change content type according to files 
from flask import Flask, jsonify, request
import json
from ibm_watson import ToneAnalyzerV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
import pandas as pd
from ibm_watson import ApiException
from elasticsearch import Elasticsearch

df = pd.read_csv('wuzzf.csv')
df = df[df.categories == 'Hotels']
apikey = 'zTX1zlvOnIQfwCQ_HQHA9zF8iQxCg25DDqudKdG3HlGd'
url = 'https://api.eu-gb.tone-analyzer.watson.cloud.ibm.com/instances/e6a5b86b-3f53-4e37-b6e3-1943c084a331'
authenticator = IAMAuthenticator(apikey)
tone_analyzer = ToneAnalyzerV3(version='2017-09-21',
                               authenticator=authenticator)

d
tones = {}
errors = []
for hotel in df['name'].unique():
    try:
        tones[hotel] = get_hotel_tones(hotel)
    except ApiException as ex:
        errors.append(hotel)
        print("Method failed with status code " + str(ex.code) + ": " +
              ex.message)
with open('tones.json', 'w') as fp:
    json.dump(tones, fp)
from ibm_cloud_security_advisor import FindingsApiV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator(apikey='abc')
findings_service = FindingsApiV1(authenticator=authenticator)
findings_service.set_service_url(
    "https://us-south.secadvisor.cloud.ibm.com/findings")

response = findings_service.create_occurrence(
    account_id="abc123",
    provider_id="sdktest",
    note_name="abc123/providers/sdktest/notes/sdk_note_id1",
    kind="FINDING",
    id="sdk_occ_id1",
    context={
        "region": "us-south",
        "resource_type": "Cluster",
        "service_name": "Kubernetes Cluster",
        "account_id": "abc123"
    },
    finding={
        "severity": "LOW",
        "next_steps": [{
            "title": "string",
            "url": "string"
        }]
    })

print(response)
示例#22
0
import json
import os
from ibm_watson import VisualRecognitionV4
from ibm_watson.visual_recognition_v4 import FileWithMetadata, TrainingDataObject, Location, AnalyzeEnums
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator(
    'YOUR APIKEY')
service = VisualRecognitionV4(
    '2018-03-19',
    authenticator=authenticator)
service.set_service_url('https://gateway.watsonplatform.net/visual-recognition/api')

# create a classifier
my_collection = service.create_collection(
    name='',
    description='testing for python'
).get_result()
collection_id = my_collection.get('collection_id')

# add images
with open(os.path.join(os.path.dirname(__file__), '../resources/South_Africa_Luca_Galuzzi_2004.jpeg'), 'rb') as giraffe_info:
    add_images_result = service.add_images(
        collection_id,
        images_file=[FileWithMetadata(giraffe_info)],
    ).get_result()
print(json.dumps(add_images_result, indent=2))
image_id = add_images_result.get('images')[0].get('image_id')

# add image training data
training_data = service.add_image_training_data(
from gtts import gTTS
import base64
from ibm_watson import SpeechToTextV1, LanguageTranslatorV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

ltapikey = 'OZmPVJ_4X70AzVgC5OtKU-36Rk5ErjZw-cCJaifRlhKF'
lturl = 'https://api.eu-gb.language-translator.watson.cloud.ibm.com/instances/1cd1e936-c1f3-4451-80dc-5de9c7be086a'

ltauthenticator = IAMAuthenticator(ltapikey)
lt = LanguageTranslatorV3(version='2018-05-01', authenticator=ltauthenticator)
lt.set_service_url(lturl)


def text2Speech(data):
    my_text = data
    greek = 'en-el'
    chinese = 'en-zh'
    hindi = 'en-hi'
    translation = lt.translate(text=my_text, model_id=hindi).get_result()
    translatedtext = translation['translations'][0]['translation']

    tts = gTTS(text=translatedtext, lang='en', slow=False)
    tts.save('converted-file.mp3')  # save file as ... (here saving as mp3)
    with open("converted-file.mp3", "rb") as file:
        my_string = base64.b64encode(file.read())
    return my_string
import json
from os.path import join, dirname
from ibm_watson import SpeechToTextV1
from ibm_watson.websocket import RecognizeCallback, AudioSource
import threading
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator


#textinput = input("Enter your IBM API: ")
authenticator = IAMAuthenticator('XwvYD2lx1j4b-Ip7BS-JWvcQG_u1-ShyZ43yKRoWf7Ck')
service = SpeechToTextV1(authenticator=authenticator)
#textinput = input("Enter your IBM Cloud Service URL: ")
service.set_service_url('https://api.us-south.speech-to-text.watson.cloud.ibm.com/instances/a848b861-711c-48a8-b2e7-680d73a7ea1f')

models = service.list_models().get_result()
# print(json.dumps(models, indent=2))

#model = service.get_model('en-US_BroadbandModel').get_result()
model = service.get_model('en-US_BroadbandModel').get_result()
# print(json.dumps(model, indent=2))

#harvard.wav isn't working right now
with open(join(dirname(__file__), '../resources/speech.wav'),
          'rb') as audio_file:
    output = json.dumps(
        service.recognize(
            audio=audio_file,
            continuous=True,
            content_type='audio/wav').get_result(),
        indent=2)
示例#25
0
from .models import User

import soundfile
import librosa
import pyttsx3
import json
import numpy as np
from scipy.io.wavfile import read as read_wav
import librosa
import speech_recognition as sr

engine = pyttsx3.init()
clf = load('leo/model19.joblib')
clf2 = load('leo/agg.joblib')
vec = load('leo/vec.joblib')
authenticator = IAMAuthenticator(
    '6RDOALhXeOxtJNBvB9DgE7WcpMe_Wda0XeHCg424WD0d')
service = ToneAnalyzerV3(version='2017-09-21', authenticator=authenticator)
service.set_service_url(
    'https://gateway-lon.watsonplatform.net/tone-analyzer/api')
context = ContextRecognition()
context.load_corpus("corpus/")
context.load_model()
r = sr.Recognizer()

before1 = []
after1 = []
name1 = ''
text1 = ''
emotions1 = ''

示例#26
0
文件: test.py 项目: Josh236/Everyware
import json
from ibm_watson import ToneAnalyzerV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

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

tone_analyzer.set_service_url('https://api.eu-gb.tone-analyzer.watson.cloud.ibm.com')

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!'

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

#for item in tone_analysis:
 #   if "tones" in item:
  #      print item.get("tones").get("tone_name")

extract_element_from_json(tone_analysis, ["document_tone"]["tones"][0]["tone_name"])
print(json.dumps(tone_analysis, array, indent=2))
示例#27
0
# Imports
import importlib
import json
import ibm_watson
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

# Global Variables & settings
AssistantV2 = ibm_watson.AssistantV2

assistantParams = None
with open('./assistantParams.json') as f:
    assistantParams = json.load(f)

authenticator = IAMAuthenticator(assistantParams['apikey'])
assistant = AssistantV2(version=assistantParams['version'],
                        authenticator=authenticator)
assistant.set_service_url(assistantParams['url'])
assistant.set_default_headers({'x-watson-learning-opt-out': "true"})

GLOBAL_sessionID = None


# Methods
# create a new session ID for watson assistant
def createSessionID(assistantID):
    sessionData = assistant.create_session(
        assistant_id=assistantID).get_result()
    return sessionData['session_id']


# Send a user message to ibm assistant to be processed and classified
from ibm_watson import TextToSpeechV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from playsound import playsound

authenticator = IAMAuthenticator('CFyTHJwrk3xhhKO-zD9MerHvcOImWZPusaOWUMCXINjw')
text_to_speech = TextToSpeechV1(
    authenticator=authenticator
)

text_to_speech.set_service_url('https://api.eu-gb.text-to-speech.watson.cloud.ibm.com/instances/d02db692-89fa-4015-a3b6-ccf6e15abfa9')

with open('new.mp3', 'wb') as audio_file:
    audio_file.write(
        text_to_speech.synthesize(
            'Hello all.How are you.',
            voice='en-US_AllisonV3Voice',
            accept='audio/mp3'        
        ).get_result().content
    
playsound('new.mp3')
示例#29
0
import json
from ibm_watson import DiscoveryV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('o2AHBjAYfudK0mXXt7dFmQFx8oaldIae5oG3du2iIf9K')
discovery = DiscoveryV1(
    version='2019-04-30',
    authenticator=authenticator
)

discovery.set_service_url('https://api.us-south.discovery.watson.cloud.ibm.com/instances/beff1375-93ea-4b19-b90a-10fbf38f45fd')

envID = '35ef0ced-f8c5-4f16-a57c-098c66505472'
colID = 'c7bf0198-9e14-40db-9e96-2b4d348585c1'

def getNLQ(tweet: str):
    areaFilter = '(latitude>' + str(eval("40 - .5")) + ',latitude<' + str(eval("40 - (.5) * -1")) + ',longitude>' + str(eval("(83 * 1) - .5")) + ',longitude<' + str(eval("(83 * 1) - (.5 * -1)")) + ')'
    DetailedResponse = discovery.query(environment_id = envID, collection_id = colID, filter = areaFilter, natural_language_query = tweet, count = 10)
    response = json.dumps(DetailedResponse.get_result(), indent = 2)
    response = json.loads(response)
    return response
示例#30
0
import json
from ibm_watson import VisualRecognitionV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator(
    'QeULZ3tNyXhuGlh4eQWn0DTJgcQET86_fym6s3Yn_A8z')
visual_recognition = VisualRecognitionV3(version='2018-03-19',
                                         authenticator=authenticator)

visual_recognition.set_service_url(
    'https://api.us-south.visual-recognition.watson.cloud.ibm.com/instances/e83c2dab-5735-4074-8358-f792e6c3dc47'
)

url = 'https://www.biggerbolderbaking.com/wp-content/uploads/2019/07/15-Minute-Pizza-WS-Thumbnail.png'
classifier_ids = ["food"]

classes_result = visual_recognition.classify(
    url=url, classifier_ids=classifier_ids).get_result()
print(json.dumps(classes_result, indent=2))