コード例 #1
0
        def runtime(authoring_key):
            print("coucou2")  #ne s'affiche pas
            client = LUISRuntimeClient(
                'https://westus.api.cognitive.microsoft.com',
                CognitiveServicesCredentials(authoring_key),
            )

            print(
                "coucou3")  #ne s'affiche pas car je ne rentre pas dans le def

            luis_result = client.prediction.resolve("echo-bot")

            try:

                query = 'https://westus.api.cognitive.microsoft.com/luis/prediction/v3.0/apps/7d7790aa-e24d-425f-a286-9ca3fac558a2/slots/production/predict?subscription-key=1e58a4a4242342afb484f85352ef5c72&verbose=true&show-all-intents=true&log=true&query=YOUR_QUERY_HERE'  #MODIFICATION
                print("Executing query: {}".format(query))
                result = client.prediction.resolve(
                    "7d7790aa-e24d-425f-a286-9ca3fac558a2",
                    query)  #Problème ici, le client n'est pas reconnu

                print("\nDetected intent: {} (score: {:d}%)".format(
                    result.top_scoring_intent.intent,
                    int(result.top_scoring_intent.score * 100)))
                print("Detected entities:")
                for entity in result.entities:
                    print("\t-> Entity '{}' (type: {}, score:{:d}%)".format(
                        entity.entity, entity.type,
                        int(entity.additional_properties['score'] * 100)))
                print("\nComplete result object as dictionnary")
                pprint(result.as_dict())

            except Exception as err:
                print("Encountered exception. {}".format(err))
コード例 #2
0
def runtime(subscription_key):
    """Resolve.

    This will execute LUIS prediction
    """
    client = LUISRuntimeClient(
        'https://westus.api.cognitive.microsoft.com',
        CognitiveServicesCredentials(subscription_key),
    )

    try:
        query = "Look for hotels near LAX airport"
        print("Executing query: {}".format(query))
        result = client.prediction.resolve(
            "bce13896-4de3-4783-9696-737d8fde8cd1",  # LUIS Application ID
            query)

        print("\nDetected intent: {} (score: {:d}%)".format(
            result.top_scoring_intent.intent,
            int(result.top_scoring_intent.score * 100)))
        print("Detected entities:")
        for entity in result.entities:
            print("\t-> Entity '{}' (type: {}, score:{:d}%)".format(
                entity.entity, entity.type,
                int(entity.additional_properties['score'] * 100)))
        print("\nComplete result object as dictionnary")
        pprint(result.as_dict())

    except Exception as err:
        print("Encountered exception. {}".format(err))
コード例 #3
0
ファイル: app2.py プロジェクト: jacmckenna/NLPDemo
def predict():
    authoringKey = '20dc03f3f35e418b9c38bb1553ad8b24'
    authoringEndpoint = 'https://jemdemo5.cognitiveservices.azure.com/'
    predictionKey = '20dc03f3f35e418b9c38bb1553ad8b24'
    predictionEndpoint = 'https://jemdemo5.cognitiveservices.azure.com/'
    
    appName = "Luis Demo v20"
    versionId = "0.1"
    client = LUISAuthoringClient(authoringEndpoint, CognitiveServicesCredentials(authoringKey))
    app_id = '5eab7501-e61b-4b51-8831-d9f7657ee00f'
    
    responseEndpointInfo = client.apps.publish(app_id, versionId, is_staging=False)
    
    runtimeCredentials = CognitiveServicesCredentials(predictionKey)
    clientRuntime = LUISRuntimeClient(endpoint=predictionEndpoint, credentials=runtimeCredentials)

	#Alternative Usage of Saved Model
	# joblib.dump(clf, 'NB_spam_model.pkl')
	# NB_spam_model = open('NB_spam_model.pkl','rb')
	# clf = joblib.load(NB_spam_model)

    if request.method == 'POST':
        message = request.form['message']
        my_prediction = clientRuntime.prediction.get_slot_prediction(app_id, "Production", {"query":message}).prediction.top_intent
        my_prediction = my_prediction.replace("_"," ")
        my_prediction = my_prediction.capitalize()
    return render_template('result.html',prediction = my_prediction)
コード例 #4
0
    async def construct(  # type: ignore
            self,
            _global_config: GlobalConfig,
            endpoint: str,
            authoring_key: str,
            *args,
            runtime_key: Optional[str] = None,
            **kwargs) -> None:
        """
        Args:
            _global_config: Global configuration for the whole test framework.
            endpoint: The endpoint to use to access LUIS, e.g.
                `https://westeurope.api.cognitive.microsoft.com/`.
            authoring_key: The access key for the LUIS authoring API.
            runtime_key: The access key for the LUIS runtime API. Defaults to the authoring key if
                omitted or set to :obj:`None`.
        """

        await super().construct(*args, **kwargs)

        self.__authoring_client = LUISAuthoringClient(
            endpoint, CognitiveServicesCredentials(authoring_key))

        self.__runtime_client = LUISRuntimeClient(
            endpoint,
            CognitiveServicesCredentials(
                authoring_key if runtime_key is None else runtime_key))
コード例 #5
0
ファイル: luis.py プロジェクト: totalhack/chatbot
 def __init__(self, config):
     super(LUISNLU, self).__init__(config)
     self.base_url = config['luis_base_url']
     self.subkey = config['luis_subkey']
     self.app_id = config['luis_app_id']
     self.app_version = config['luis_app_version']
     self.runtime_client = LUISRuntimeClient(self.base_url, CognitiveServicesCredentials(self.subkey))
     self.authoring_client = LUISAuthoringClient(self.base_url, CognitiveServicesCredentials(self.subkey))
コード例 #6
0
    def __init__(self):
        import os
        credential = os.getenv('LUIS_CREDENTIAL')
        with open(credential, "r") as file:
            self.credential = json.load(file)

        self.client = LUISRuntimeClient(
            self.credential['endpoint_url'],
            CognitiveServicesCredentials(self.credential['subscription_key']))
コード例 #7
0
 def __init__(self, servo, luis_app_id, luis_key, azure_speech_key):
     self.servo = servo
     self.recognizer = sr.Recognizer()
     self.mic = sr.Microphone(device_index=0)
     #self.mic = sr.Microphone(device_index=self.DEVICE_INDEX)
     self.luis_app_id = luis_app_id
     self.luis_client = LUISRuntimeClient(
         'https://westus.api.cognitive.microsoft.com',
         CognitiveServicesCredentials(luis_key))
     self.azure_speech_key = azure_speech_key
コード例 #8
0
class asistan():
    #Speech to text konfigurasyon
    speech_key, service_region = "<<Speech Key Buraya Gelecek>>", "<<Speech region Buraya Gelecek>>"
    speech_config = speechsdk.SpeechConfig(subscription=speech_key,
                                           region=service_region,
                                           speech_recognition_language="tr-TR")

    #LUIS konfigurasyon
    LUIS_RUNTIME_KEY = "<<Luis Key Buraya Gelecek>>"
    LUIS_RUNTIME_ENDPOINT = "<<Luis Endpoint Buraya Gelecek>>"
    LUIS_APP_ID = "<<Luis App Id buraya gelecek>>"
    LUIS_APP_SLOT_NAME = "<<Luis published model buraya gelecek. Secenekler: 'staging' ya da 'prodoction' >>"
    clientRuntime = LUISRuntimeClient(
        LUIS_RUNTIME_ENDPOINT, CognitiveServicesCredentials(LUIS_RUNTIME_KEY))

    def predict(self, query_text):
        request = {"query": query_text}
        response = self.clientRuntime.prediction.get_slot_prediction(
            app_id=self.LUIS_APP_ID,
            slot_name=self.LUIS_APP_SLOT_NAME,
            prediction_request=request)

        return {
            "Amac": response.prediction.top_intent,
            "Ozellikler": response.prediction.entities
        }

    def sesli_komut_isle(self):
        #STT islemi
        audio_filename = "outaudio.wav"
        audio_input = speechsdk.audio.AudioConfig(filename=audio_filename)
        speech_recognizer = speechsdk.SpeechRecognizer(
            speech_config=self.speech_config, audio_config=audio_input)
        result = speech_recognizer.recognize_once()

        if result.reason == speechsdk.ResultReason.RecognizedSpeech:
            print("Ses tanimlandi: {}".format(result.text))
            #LUIS Islemi
            print("LUIS'e gonderiliyor")
            luisresult = self.predict(result.text)
            return luisresult
        elif result.reason == speechsdk.ResultReason.NoMatch:
            print("Ses tanimlanamadi: {}".format(result.no_match_details))
            return {}
        elif result.reason == speechsdk.ResultReason.Canceled:
            cancellation_details = result.cancellation_details
            print("Ses tanima iptal edildi: {}".format(
                cancellation_details.reason))
            if cancellation_details.reason == speechsdk.CancellationReason.Error:
                print("Hata detaylari: {}".format(
                    cancellation_details.error_details))
            return {}
コード例 #9
0
 def __init__(
     self,
     luis_application: LuisApplication,
     luis_recognizer_options_v2: LuisRecognizerOptionsV2 = None,
 ):
     super().__init__(luis_application)
     credentials = CognitiveServicesCredentials(luis_application.endpoint_key)
     self._runtime = LUISRuntimeClient(luis_application.endpoint, credentials)
     self._runtime.config.add_user_agent(LuisUtil.get_user_agent())
     self._runtime.config.connection.timeout = (
         luis_recognizer_options_v2.timeout // 1000
     )
     self.luis_recognizer_options_v2 = (
         luis_recognizer_options_v2 or LuisRecognizerOptionsV2()
     )
     self._application = luis_application
コード例 #10
0
def get_prediction(subscription_key, query_in):
    """Resolve.

    This will execute LUIS prediction
    """
    client = LUISRuntimeClient(
        'https://westus.api.cognitive.microsoft.com',
        CognitiveServicesCredentials(subscription_key),
    )

    try:

        query = query_in

        print("Executing query: {}".format(query))
        result = client.prediction.resolve(
            "dc022f4c-ecbb-42cb-ba85-ce87ca42d0bd",  # LUIS Application ID
            query
        )

        # For tests

        # print("\nDetected intent: {} (score: {:d}%)".format(
        #     result.top_scoring_intent.intent,
        #     int(result.top_scoring_intent.score*100)
        # ))

        # print("Detected entities:")
        # for entity in result.entities:
        #     print("\t-> Entity '{}' (type: {}, score:{:d}%)".format(
        #         entity.entity,
        #         entity.type,
        #         int(entity.additional_properties['score']*100)
        #     ))
            
        # print("\nComplete result object as dictionary")
        # pprint(result.as_dict())

        return result

    except Exception as err:
        print("Encountered exception. {}".format(err))
コード例 #11
0
    def __init__(
        self,
        application: Union[LuisApplication, str],
        prediction_options: LuisPredictionOptions = None,
        include_api_results: bool = False,
    ):
        """Initializes a new instance of the <see cref="LuisRecognizer"/> class.
        
        :param application: The LUIS application to use to recognize text.
        :type application: LuisApplication
        :param prediction_options: The LUIS prediction options to use, defaults to None
        :param prediction_options: LuisPredictionOptions, optional
        :param include_api_results: True to include raw LUIS API response, defaults to False
        :param include_api_results: bool, optional
        :raises TypeError:
        """

        if isinstance(application, LuisApplication):
            self._application = application
        elif isinstance(application, str):
            self._application = LuisApplication.from_application_endpoint(
                application)
        else:
            raise TypeError(
                "LuisRecognizer.__init__(): application is not an instance of LuisApplication or str."
            )

        self._options = prediction_options or LuisPredictionOptions()

        self._include_api_results = include_api_results

        self.telemetry_client = self._options.telemetry_client
        self.log_personal_information = self._options.log_personal_information

        credentials = CognitiveServicesCredentials(
            self._application.endpoint_key)
        self._runtime = LUISRuntimeClient(self._application.endpoint,
                                          credentials)
        self._runtime.config.add_user_agent(LuisUtil.get_user_agent())
        self._runtime.config.connection.timeout = self._options.timeout // 1000
def quickstart():

    # <VariablesYouChange>
    authoringKey = 'PASTE_YOUR_LUIS_AUTHORING_SUBSCRIPTION_KEY_HERE'
    authoringEndpoint = 'PASTE_YOUR_LUIS_AUTHORING_ENDPOINT_HERE'
    predictionKey = 'PASTE_YOUR_LUIS_PREDICTION_SUBSCRIPTION_KEY_HERE'
    predictionEndpoint = 'PASTE_YOUR_LUIS_PREDICTION_ENDPOINT_HERE'
    # </VariablesYouChange>

    # <VariablesYouDontNeedToChangeChange>
    appName = "Contoso Pizza Company"
    versionId = "0.1"
    intentName = "OrderPizzaIntent"
    # </VariablesYouDontNeedToChangeChange>

    # <AuthoringCreateClient>
    client = LUISAuthoringClient(authoringEndpoint,
                                 CognitiveServicesCredentials(authoringKey))
    # </AuthoringCreateClient>

    # Create app
    app_id = create_app(client, appName, versionId)

    # <AddIntent>
    client.model.add_intent(app_id, versionId, intentName)
    # </AddIntent>

    # Add Entities
    add_entities(client, app_id, versionId)

    # Add labeled examples
    add_labeled_examples(client, app_id, versionId, intentName)

    # <TrainAppVersion>
    client.train.train_version(app_id, versionId)
    waiting = True
    while waiting:
        info = client.train.get_status(app_id, versionId)

        # get_status returns a list of training statuses, one for each model. Loop through them and make sure all are done.
        waiting = any(
            map(
                lambda x: 'Queued' == x.details.status or 'InProgress' == x.
                details.status, info))
        if waiting:
            print("Waiting 10 seconds for training to complete...")
            time.sleep(10)
        else:
            print("trained")
            waiting = False
    # </TrainAppVersion>

    # <PublishVersion>
    responseEndpointInfo = client.apps.publish(app_id,
                                               versionId,
                                               is_staging=False)
    # </PublishVersion>

    # <PredictionCreateClient>
    runtimeCredentials = CognitiveServicesCredentials(predictionKey)
    clientRuntime = LUISRuntimeClient(endpoint=predictionEndpoint,
                                      credentials=runtimeCredentials)
    # </PredictionCreateClient>

    # <QueryPredictionEndpoint>
    # Production == slot name
    predictionRequest = {
        "query": "I want two small pepperoni pizzas with more salsa"
    }

    predictionResponse = clientRuntime.prediction.get_slot_prediction(
        app_id, "Production", predictionRequest)
    print("Top intent: {}".format(predictionResponse.prediction.top_intent))
    print("Sentiment: {}".format(predictionResponse.prediction.sentiment))
    print("Intents: ")

    for intent in predictionResponse.prediction.intents:
        print("\t{}".format(json.dumps(intent)))
    print("Entities: {}".format(predictionResponse.prediction.entities))
コード例 #13
0
    def process_file(self, path):
        cache_path = path.replace('.wav', '.luis')

        if os.path.exists(cache_path):
            with open(cache_path) as f:
                return json.load(f)

        template = "wss://{}.stt.speech.microsoft.com/speech/recognition" \
                   "/conversation/cognitiveservices/v1?initialSilenceTimeoutMs={:d}"
        speech_config = speechsdk.SpeechConfig(
            subscription=self._speech_key,
            endpoint=template.format(self._region,
                                     self._initial_silence_timeout_ms))
        source_language_config = speechsdk.languageconfig.SourceLanguageConfig(
            "en-US", self._speech_endpoint_id)
        audio_config = speechsdk.audio.AudioConfig(filename=path)

        speech_recognizer = speechsdk.SpeechRecognizer(
            speech_config=speech_config,
            source_language_config=source_language_config,
            audio_config=audio_config)
        speech_response = speech_recognizer.recognize_once()

        if speech_response is None:
            return None

        if speech_response.reason == speechsdk.ResultReason.RecognizedSpeech:
            transcript = speech_response.text.lower()
        elif speech_response.reason == speechsdk.ResultReason.NoMatch:
            raise Exception(speech_response.no_match_details)
        elif speech_response.reason == speechsdk.ResultReason.Canceled:
            cancellation_details = speech_response.cancellation_details
            if cancellation_details.reason == speechsdk.CancellationReason.Error:
                print("Error details: {}".format(
                    cancellation_details.error_details))
            raise Exception(cancellation_details.reason)
        else:
            return None

        if not transcript:
            return None
        request = {"query": transcript}

        client_runtime = LUISRuntimeClient(
            self._endpoint_url,
            CognitiveServicesCredentials(self._prediction_key))
        nlu_response = client_runtime.prediction.get_slot_prediction(
            app_id=self._app_id,
            slot_name=self._slot_name,
            prediction_request=request)

        if nlu_response is None:
            return None

        intent = nlu_response.prediction.top_intent
        slots = dict()
        for k, v in nlu_response.prediction.entities.items():
            slots[k] = [e[0].strip() for e in v]

        result = dict(intent=intent, slots=slots, transcript=transcript)

        with open(cache_path, 'w') as f:
            json.dump(result, f, indent=2)

        return result
コード例 #14
0
 def __init__(self):
     self.credential_dict = loadJSON("./credentials/azure-keys.json")
     self.client = LUISRuntimeClient(
         endpoint=f'https://{self.credential_dict["predictionResourceName"]}.cognitiveservices.azure.com/',
         credentials=CognitiveServicesCredentials(self.credential_dict["predictionKey"])
     )
コード例 #15
0
ファイル: feedback10.py プロジェクト: wangsc522/linebot01
app = Flask(__name__)

line_bot_api = LineBotApi(
    'rNuJcLVeCoJwBooBW8AhsyoFTKWDN/15SdFP8ObH1SBMAbdtWK0tEQReHXE+8fRo1NtNxt1kX/6KKvqSzytsZy8RvuuFhpjmbi9a+V+eVqt+NJrYwrefxT31ckJGaZt6dtG66trfbDULq4f3bdd60QdB04t89/1O/w1cDnyilFU='
)
handler = WebhookHandler('a2107f4d8710940b1568c6ae14415089')

#luisAppId = "4fffa055-e22e-46a0-8416-a91ffa832944"
luisAppId = "7cf6b3f3-f3d5-49b8-90ea-ad773e5c8ac8"
#luisAppKey = "e0b8bd8d20c24c799e468488a1e3aa99"
luisAppKey = "0c27389e595549eca99514047420e278"
SLOTName = 'staging'
runtime_endpoint = 'https://wscluis01.cognitiveservices.azure.com/'
runtime_endpoint = 'https://line001-authoring.cognitiveservices.azure.com/'
clientRuntime = LUISRuntimeClient(runtime_endpoint,
                                  CognitiveServicesCredentials(luisAppKey))

# 引用必要套件
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

# 引用私密金鑰
# path/to/serviceAccount.json 請用自己存放的路徑
cred = credentials.Certificate('serviceAccountKey.json')

# 初始化firebase,注意不能重複初始化
firebase_admin.initialize_app(cred)

# 初始化firestore
db = firestore.client()
コード例 #16
0
def quickstart():

    authoringKey = '20dc03f3f35e418b9c38bb1553ad8b24'
    authoringEndpoint = 'https://jemdemo5.cognitiveservices.azure.com/'
    predictionKey = '20dc03f3f35e418b9c38bb1553ad8b24'
    predictionEndpoint = 'https://jemdemo5.cognitiveservices.azure.com/'

    appName = "Luis Demo v"
    versionId = "0.1"
    intentName = "OrderPizzaIntent"
    intentName2 = "OrderTaxiIntent"

    client = LUISAuthoringClient(authoringEndpoint,
                                 CognitiveServicesCredentials(authoringKey))

    # define app basics
    appDefinition = {
        "name": appName,
        "initial_version_id": versionId,
        "culture": "en-us"
    }

    # create app
    app_id = client.apps.add(appDefinition)

    # get app id - necessary for all other changes
    print("Created LUIS app with ID {}".format(app_id))

    # read training data
    with open('Intentsubset1.csv', 'r') as fd:
        reader = csv.DictReader(fd)
        labeledExampleUtteranceWithMLEntity = list(reader)


# Get unique intents
    all_intents = []
    for x in labeledExampleUtteranceWithMLEntity:
        all_intents.append(x['intentName'])
    unique_intents = list(set(all_intents))

    for x in unique_intents:
        client.model.add_intent(app_id, versionId, x)

    # Define labeled example

    print("Labeled Example Utterance:",
          labeledExampleUtteranceWithMLEntity[2:4])
    print(len(labeledExampleUtteranceWithMLEntity))
    df = pd.DataFrame(labeledExampleUtteranceWithMLEntity)
    X = df['text']
    Y = df['intentName']
    X_train, X_test, Y_train, Y_test = train_test_split(X,
                                                        Y,
                                                        test_size=0.3,
                                                        random_state=42,
                                                        stratify=Y)
    print('finished split')
    # Add an example for the entity.
    # Enable nested children to allow using multiple models with the same name.
    # The quantity subentity and the phraselist could have the same exact name if this is set to True
    chunks = (len(X_train) - 1) // 50 + 1
    Train_df = pd.concat([X_train, Y_train], axis=1, join="inner")
    Train_dict = Train_df.to_dict('records')
    print(len(Train_df))
    for i in range(chunks):
        client.examples.batch(app_id, versionId,
                              Train_dict[i * 50:(i + 1) * 50],
                              {"enableNestedChildren": True})

    print('added examples')
    client.train.train_version(app_id, versionId)
    waiting = True
    while waiting:
        info = client.train.get_status(app_id, versionId)

        # get_status returns a list of training statuses, one for each model. Loop through them and make sure all are done.
        waiting = any(
            map(
                lambda x: 'Queued' == x.details.status or 'InProgress' == x.
                details.status, info))
        if waiting:
            print("Waiting 10 seconds for training to complete...")
            time.sleep(10)
        else:
            print("trained")
            waiting = False

    responseEndpointInfo = client.apps.publish(app_id,
                                               versionId,
                                               is_staging=False)

    runtimeCredentials = CognitiveServicesCredentials(predictionKey)
    clientRuntime = LUISRuntimeClient(endpoint=predictionEndpoint,
                                      credentials=runtimeCredentials)

    # Production == slot name
    predictionRequest = {"query": "I forgot my password"}

    predictionResponse = clientRuntime.prediction.get_slot_prediction(
        app_id, "Production", predictionRequest)
    print("Top intent: {}".format(predictionResponse.prediction.top_intent))
    print("Sentiment: {}".format(predictionResponse.prediction.sentiment))
    print("Intents: ")

    for intent in predictionResponse.prediction.intents:
        print("\t{}".format(json.dumps(intent)))
    print("Entities: {}".format(predictionResponse.prediction.entities))
コード例 #17
0
if not runtime_key_var_name in os.environ:
    raise Exception('Please set/export the environment variable: {}'.format(
        runtime_key_var_name))
runtime_subscription_key = os.environ[runtime_key_var_name]

runtime_endpoint_var_name = 'LUIS_RUNTIME_ENDPOINT'
if not runtime_endpoint_var_name in os.environ:
    raise Exception('Please set/export the environment variable: {}'.format(
        runtime_endpoint_var_name))
runtime_endpoint = os.environ[runtime_endpoint_var_name]

# Instantiate LUIS clients
authoring_client = LUISAuthoringClient(
    authoring_endpoint,
    CognitiveServicesCredentials(authoring_subscription_key))
runtime_client = LUISRuntimeClient(
    runtime_endpoint, CognitiveServicesCredentials(runtime_subscription_key))


def create_app():
    app_id = authoring_client.apps.add_custom_prebuilt_domain(
        domain_name="HomeAutomation", culture="en-us")
    print("Created LUIS app with ID {}".format(app_id))
    return app_id


def train_app(app_id, app_version):
    response = authoring_client.train.train_version(app_id, app_version)
    waiting = True
    while waiting:
        info = authoring_client.train.get_status(app_id, app_version)
        # get_status returns a list of training statuses, one for each model. Loop through them and make sure all are done.
def quickstart(): 

	# <VariablesYouChange>
	authoringKey = 'PASTE_YOUR_LUIS_AUTHORING_SUBSCRIPTION_KEY_HERE'
	authoringEndpoint = 'PASTE_YOUR_LUIS_AUTHORING_ENDPOINT_HERE'
	predictionKey = 'PASTE_YOUR_LUIS_PREDICTION_SUBSCRIPTION_KEY_HERE'
	predictionEndpoint = 'PASTE_YOUR_LUIS_PREDICTION_ENDPOINT_HERE'
	# </VariablesYouChange>

	# <VariablesYouDontNeedToChangeChange>
	# We use a UUID to avoid name collisions.
	appName = "Contoso Pizza Company " + str(uuid.uuid4())
	versionId = "0.1"
	intentName = "OrderPizzaIntent"
	# </VariablesYouDontNeedToChangeChange>

	# <AuthoringCreateClient>
	client = LUISAuthoringClient(authoringEndpoint, CognitiveServicesCredentials(authoringKey))
	# </AuthoringCreateClient>

	# Create app
	app_id = create_app(client, appName, versionId)

	# <AddIntent>
	client.model.add_intent(app_id, versionId, intentName)
	# </AddIntent>
	
	# Add Entities
	add_entities(client, app_id, versionId)
	
	# Add labeled examples
	add_labeled_examples(client,app_id, versionId, intentName)

	# <TrainAppVersion>
	client.train.train_version(app_id, versionId)
	waiting = True
	while waiting:
		info = client.train.get_status(app_id, versionId)

		# get_status returns a list of training statuses, one for each model. Loop through them and make sure all are done.
		waiting = any(map(lambda x: 'Queued' == x.details.status or 'InProgress' == x.details.status, info))
		if waiting:
			print ("Waiting 10 seconds for training to complete...")
			time.sleep(10)
		else: 
			print ("trained")
			waiting = False
	# </TrainAppVersion>
	
	# <PublishVersion>
	# Mark the app as public so we can query it using any prediction endpoint.
	# Note: For production scenarios, you should instead assign the app to your own LUIS prediction endpoint. See:
	# https://docs.microsoft.com/en-gb/azure/cognitive-services/luis/luis-how-to-azure-subscription#assign-a-resource-to-an-app
	client.apps.update_settings(app_id, is_public=True)

	responseEndpointInfo = client.apps.publish(app_id, versionId, is_staging=False)
	# </PublishVersion>
	
	# <PredictionCreateClient>
	runtimeCredentials = CognitiveServicesCredentials(predictionKey)
	clientRuntime = LUISRuntimeClient(endpoint=predictionEndpoint, credentials=runtimeCredentials)
	# </PredictionCreateClient>

    # <QueryPredictionEndpoint>
    # Production == slot name
	predictionRequest = { "query" : "I want two small pepperoni pizzas with more salsa" }
	
	predictionResponse = clientRuntime.prediction.get_slot_prediction(app_id, "Production", predictionRequest)
	print("Top intent: {}".format(predictionResponse.prediction.top_intent))
	print("Sentiment: {}".format (predictionResponse.prediction.sentiment))
	print("Intents: ")

	for intent in predictionResponse.prediction.intents:
		print("\t{}".format (json.dumps (intent)))
	print("Entities: {}".format (predictionResponse.prediction.entities))
    # </QueryPredictionEndpoint>

	# Clean up resources.
	print ("Deleting app...")
	client.apps.delete(app_id)
	print ("App deleted.")
コード例 #19
0
ファイル: chatbot.py プロジェクト: Koinonos-Team/koinonos
luis_app_id = '20263b4d-b405-4c9b-8de8-e51663797c41' 
luis_key = 'b45490c8a83243f9a6320ec7e8e85a43'
luis_endpoint = 'https://koinonos-language-understanding.cognitiveservices.azure.com/'

# Configure speech recognizer
speech_key, service_region = "40a03ef9d3d44916bdcd1c4457b82c13", "eastus" 
speech_config = SpeechConfig(subscription=speech_key, region=service_region)
speech_recognizer = SpeechRecognizer(speech_config=speech_config)

# Configure speech synthesizer
audio_config = AudioOutputConfig(use_default_speaker=True)
synthesizer = SpeechSynthesizer(speech_config=speech_config)

runtimeCredentials = CognitiveServicesCredentials(luis_key)
clientRuntime = LUISRuntimeClient(endpoint=luis_endpoint, credentials=runtimeCredentials)

print("Start listening...")
speech = speech_recognizer.recognize_once()
try:   
    while speech.text != "Stop":
        # Production == slot name
        print("Your query is: ", speech.text)
        predictionRequest = { "query" : speech.text}

        predictionResponse = clientRuntime.prediction.get_slot_prediction(luis_app_id, "Production", predictionRequest)
        
        print("Top intent: {}".format(predictionResponse.prediction.top_intent))
        print("Sentiment: {}".format (predictionResponse.prediction.sentiment))
        print("Intents: ")
コード例 #20
0
def main():

    try:
        # Get Configuration Settings
        load_dotenv()
        lu_app_id = os.getenv('LU_APP_ID')
        lu_prediction_endpoint = os.getenv('LU_PREDICTION_ENDPOINT')
        lu_prediction_key = os.getenv('LU_PREDICTION_KEY')

        # Create a client for the LU app
        credentials = CognitiveServicesCredentials(lu_prediction_key)
        lu_client = LUISRuntimeClient(lu_prediction_endpoint, credentials)

        # Get user input (until they enter "quit")
        userText = ''
        while userText.lower() != 'quit':
            userText = input('\nEnter some text ("quit" to stop)\n')
            if userText.lower() != 'quit':

                # Call the LU app to get intent and entities
                request = {"query": userText}
                slot = 'Production'
                prediction_response = lu_client.prediction.get_slot_prediction(
                    lu_app_id, slot, request)
                top_intent = prediction_response.prediction.top_intent
                entities = prediction_response.prediction.entities
                print('Top Intent: {}'.format(top_intent))
                print('Entities: {}'.format(entities))
                print('-----------------\n{}'.format(
                    prediction_response.query))

                # Apply the appropriate action
                if top_intent == 'GetTime':
                    location = 'local'
                    # Check for entities
                    if len(entities) > 0:
                        # Check for a location entity
                        if 'Location' in entities:
                            # ML entities are strings, get the first one
                            location = entities['Location'][0]
                    # Get the time for the specified location
                    print(GetTime(location))

                elif top_intent == 'GetDay':
                    date_string = date.today().strftime("%m/%d/%Y")
                    # Check for entities
                    if len(entities) > 0:
                        # Check for a Date entity
                        if 'Date' in entities:
                            # Regex entities are strings, get the first one
                            date_string = entities['Date'][0]
                    # Get the day for the specified date
                    print(GetDay(date_string))

                elif top_intent == 'GetDate':
                    day = 'today'
                    # Check for entities
                    if len(entities) > 0:
                        # Check for a Weekday entity
                        if 'Weekday' in entities:
                            # List entities are lists
                            day = entities['Weekday'][0][0]
                    # Get the date for the specified day
                    print(GetDate(day))

                else:
                    # Some other intent (for example, "None") was predicted
                    print('Try asking me for the time, the day, or the date.')

    except Exception as ex:
        print(ex)
コード例 #21
0
client.model.add_intent(app_id, versionId, "security")

for i in intents:
    client.examples.add(app_id, versionId, i)

# Train the app
client.train.train_version(app_id, versionId)
waiting = True
while waiting:
    info = client.train.get_status(app_id, versionId)

    # get_status returns a list of training statuses, one for each model. Loop through them and make sure all are done.
    waiting = any(
        map(
            lambda x: 'Queued' == x.details.status or 'InProgress' == x.details
            .status, info))
    if waiting:
        print("Waiting 10 seconds for training to complete...")
        time.sleep(10)
    else:
        print("trained")
        waiting = False

# Publish a Language Understanding app
responseEndpointInfo = client.apps.publish(app_id, versionId, is_staging=False)

# Authenticate the prediction runtime client
runtimeCredentials = CognitiveServicesCredentials(authoringKey)
clientRuntime = LUISRuntimeClient(endpoint=predictionEndpoint,
                                  credentials=runtimeCredentials)
コード例 #22
0
from azure.cognitiveservices.language.luis.runtime import LUISRuntimeClient
from msrest.authentication import CognitiveServicesCredentials

#LUIS konfigurasyon
LUIS_RUNTIME_KEY = ""
LUIS_RUNTIME_ENDPOINT = ""
LUIS_APP_ID = ""
LUIS_APP_SLOT_NAME = ""
clientRuntime = LUISRuntimeClient(
    LUIS_RUNTIME_ENDPOINT, CognitiveServicesCredentials(LUIS_RUNTIME_KEY))


def predict(query_text):
    print("\nLuis'e gonderiliyor..\n")
    request = {"query": query_text}
    response = clientRuntime.prediction.get_slot_prediction(
        app_id=LUIS_APP_ID,
        slot_name=LUIS_APP_SLOT_NAME,
        prediction_request=request)

    print("Amac: {}".format(response.prediction.top_intent))
    print("Ozellikler: {}".format(response.prediction.entities))


phrase = "Elimizde hiç siyah tshirt var mı?"
predict(phrase)
コード例 #23
0
def quickstart():

    # Set variables ----------------------------------------------------

    appName = "BookFlight-Luis-model"
    versionId = "0.1"

    # Authenticate client------------------------------------------------

    client = LUISAuthoringClient(authoringEndpoint,
                                 CognitiveServicesCredentials(authoringKey))

    # Create LUIS application -------------------------------------------

    # define app basics
    appDefinition = {
        "name": appName,
        "initial_version_id": versionId,
        "culture": "en-us"
    }

    # Create app
    app_id = client.apps.add(appDefinition)

    # get app id - necessary for all other changes
    print(f"Created LUIS app with id {app_id}")

    # Create intention(s) ------------------------------------------------

    intentNames = ["BookFlight", "Confirm", "Greetings"]
    for intent in intentNames:
        client.model.add_intent(app_id, versionId, intent)

    # Create entity(ies) -------------------------------------------------

    # Add pre_built entity :
    client.model.add_prebuilt(
        app_id,
        versionId,
        prebuilt_extractor_names=["money", "geographyV2", "datetimeV2"])

    # Create Airport entity :
    airport_entity = {"name": "Airport"}

    # Add ML entity to app
    from_entity = client.model.add_entity(app_id,
                                          versionId,
                                          name="From",
                                          children=[airport_entity])
    to_entity = client.model.add_entity(app_id,
                                        versionId,
                                        name="To",
                                        children=[airport_entity])

    departure_date_id = client.model.add_entity(app_id,
                                                versionId,
                                                name="Departure_date")
    return_date_id = client.model.add_entity(app_id,
                                             versionId,
                                             name="Return_date")
    budget_id = client.model.add_entity(app_id, versionId, name="budget")

    # Get entity and sub-entities for nested entities:
    from_object = client.model.get_entity(app_id, versionId, from_entity)
    to_object = client.model.get_entity(app_id, versionId, to_entity)

    from_airport_id = get_child_id(from_object, "Airport")
    to_airport_id = get_child_id(to_object, "Airport")

    # Add model as feature to subentity model
    prebuiltFeaturedDefinition = {
        "model_name": "geographyV2",
        "is_required": False
    }
    client.features.add_entity_feature(app_id, versionId, from_airport_id,
                                       prebuiltFeaturedDefinition)
    client.features.add_entity_feature(app_id, versionId, to_airport_id,
                                       prebuiltFeaturedDefinition)
    prebuiltFeaturedDefinition = {
        "model_name": "datetimeV2",
        "is_required": False
    }
    client.features.add_entity_feature(app_id, versionId, departure_date_id,
                                       prebuiltFeaturedDefinition)
    client.features.add_entity_feature(app_id, versionId, return_date_id,
                                       prebuiltFeaturedDefinition)
    prebuiltFeaturedDefinition = {"model_name": "money", "is_required": False}
    client.features.add_entity_feature(app_id, versionId, budget_id,
                                       prebuiltFeaturedDefinition)

    # Add utterances examples to intents ----------------------------------------------

    # Define labeled examples :
    BookFlight_json_file = "./data/training_data_50_ex.json"
    BookFlight_utterance = load_json(BookFlight_json_file)
    print("\nBookFlight_utterance : ", BookFlight_utterance)

    other_utterances = [{
        "text": "right",
        "intentName": intentNames[1]
    }, {
        "text": "yes",
        "intentName": intentNames[1]
    }, {
        "text": "OK",
        "intentName": intentNames[1]
    }, {
        "text": "good",
        "intentName": intentNames[1]
    }, {
        "text": "Hello",
        "intentName": intentNames[2]
    }, {
        "text": "Hi",
        "intentName": intentNames[2]
    }, {
        "text": "Hey",
        "intentName": intentNames[2]
    }, {
        "text": "Good morning",
        "intentName": intentNames[2]
    }]

    # Add an example for the entity
    # Enable nested children to allow using multiple models with the same name
    # The "quantity" subentity and the phraselise could have the same exact name if this is set to True
    for utterance in BookFlight_utterance:
        print("\nutterance : ", utterance)
        client.examples.add(app_id, versionId, utterance,
                            {"enableNestedChildren": True})
    for utterance in other_utterances:
        client.examples.add(app_id, versionId, utterance,
                            {"enableNestedChildren": False})

    # Train the model ---------------------------------------------------------

    client.train.train_version(app_id, versionId)
    waiting = True
    while waiting:
        info = client.train.get_status(app_id, versionId)

        # get_status returns a list of training statuses , one for each model. Loop through them and make sure all are done.
        waiting = any(
            map(
                lambda x: "Queued" == x.details.status or "InProgess" == x.
                details.status, info))
        if waiting:
            print("Waiting 10 seconds for training to complete")
            time.sleep(10)
        else:
            print("Trained")
            waiting = False

    # Publish the app ---------------------------------------------------------

    responseEndpointInfo = client.apps.publish(app_id,
                                               versionId,
                                               is_staging=False)
    print("Model published to Production slot")

    # Authenticate prediction runtime client ----------------------------------

    runtimeCredentials = CognitiveServicesCredentials(
        authoringKey)  # for test only. For production, use prediction key
    clientRuntime = LUISRuntimeClient(endpoint=predictionEndpoint,
                                      credentials=runtimeCredentials)

    # Get a prediction from runtime --------------------------------------------

    # Production == slot name
    predictionRequest = {
        "query":
        "Hi. i'd like to fly from New-York to Las-Vegas on August 10, 2021"
    }

    predictionResponse = clientRuntime.prediction.get_slot_prediction(
        app_id, "Production", predictionRequest)
    print(f"Top intent : {predictionResponse.prediction.top_intent}")
    print(f"Sentiment : {predictionResponse.prediction.sentiment}")

    for intent in predictionResponse.prediction.intents:
        print(f"\t{json.dumps(intent)}")
    print(f"Entities : {predictionResponse.prediction.entities}")