Commit 7b8d9876 authored by dasharatha.vamshi's avatar dasharatha.vamshi

init

parent 0c7d24ff
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyChainedComparisonsInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoreConstantInTheMiddle" value="true" />
</inspection_tool>
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<value>
<list size="56">
<item index="0" class="java.lang.String" itemvalue="scikit-image" />
<item index="1" class="java.lang.String" itemvalue="scipy" />
<item index="2" class="java.lang.String" itemvalue="opencv-python" />
<item index="3" class="java.lang.String" itemvalue="torch" />
<item index="4" class="java.lang.String" itemvalue="torchvision" />
<item index="5" class="java.lang.String" itemvalue="absl-py" />
<item index="6" class="java.lang.String" itemvalue="protobuf" />
<item index="7" class="java.lang.String" itemvalue="rsa" />
<item index="8" class="java.lang.String" itemvalue="tensorflow-estimator" />
<item index="9" class="java.lang.String" itemvalue="opt-einsum" />
<item index="10" class="java.lang.String" itemvalue="python-dateutil" />
<item index="11" class="java.lang.String" itemvalue="cycler" />
<item index="12" class="java.lang.String" itemvalue="gast" />
<item index="13" class="java.lang.String" itemvalue="numpy" />
<item index="14" class="java.lang.String" itemvalue="pyasn1" />
<item index="15" class="java.lang.String" itemvalue="requests" />
<item index="16" class="java.lang.String" itemvalue="importlib-metadata" />
<item index="17" class="java.lang.String" itemvalue="pyasn1-modules" />
<item index="18" class="java.lang.String" itemvalue="requests-oauthlib" />
<item index="19" class="java.lang.String" itemvalue="tensorflow" />
<item index="20" class="java.lang.String" itemvalue="tensorboard-plugin-wit" />
<item index="21" class="java.lang.String" itemvalue="zipp" />
<item index="22" class="java.lang.String" itemvalue="oauthlib" />
<item index="23" class="java.lang.String" itemvalue="astunparse" />
<item index="24" class="java.lang.String" itemvalue="urllib3" />
<item index="25" class="java.lang.String" itemvalue="pyparsing" />
<item index="26" class="java.lang.String" itemvalue="Cython" />
<item index="27" class="java.lang.String" itemvalue="Markdown" />
<item index="28" class="java.lang.String" itemvalue="google-auth-oauthlib" />
<item index="29" class="java.lang.String" itemvalue="Werkzeug" />
<item index="30" class="java.lang.String" itemvalue="kiwisolver" />
<item index="31" class="java.lang.String" itemvalue="tqdm" />
<item index="32" class="java.lang.String" itemvalue="yolov5processor" />
<item index="33" class="java.lang.String" itemvalue="tensorboard" />
<item index="34" class="java.lang.String" itemvalue="future" />
<item index="35" class="java.lang.String" itemvalue="matplotlib" />
<item index="36" class="java.lang.String" itemvalue="cachetools" />
<item index="37" class="java.lang.String" itemvalue="grpcio" />
<item index="38" class="java.lang.String" itemvalue="Keras" />
<item index="39" class="java.lang.String" itemvalue="google-auth" />
<item index="40" class="java.lang.String" itemvalue="idna" />
<item index="41" class="java.lang.String" itemvalue="Pillow" />
<item index="42" class="java.lang.String" itemvalue="cython" />
<item index="43" class="java.lang.String" itemvalue="keras" />
<item index="44" class="java.lang.String" itemvalue="imgaug" />
<item index="45" class="java.lang.String" itemvalue="opencv-contrib-python" />
<item index="46" class="java.lang.String" itemvalue="paho-mqtt" />
<item index="47" class="java.lang.String" itemvalue="pymongo" />
<item index="48" class="java.lang.String" itemvalue="fbprophet" />
<item index="49" class="java.lang.String" itemvalue="scikit-learn" />
<item index="50" class="java.lang.String" itemvalue="sklearn" />
<item index="51" class="java.lang.String" itemvalue="statsmodels" />
<item index="52" class="java.lang.String" itemvalue="python-dotenv" />
<item index="53" class="java.lang.String" itemvalue="pystan" />
<item index="54" class="java.lang.String" itemvalue="Cerberus" />
<item index="55" class="java.lang.String" itemvalue="tenacity" />
</list>
</value>
</option>
</inspection_tool>
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="N802" />
<option value="N806" />
<option value="N801" />
<option value="N803" />
</list>
</option>
</inspection_tool>
<inspection_tool class="PyUnresolvedReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredIdentifiers">
<list>
<option value="cv2.imresize" />
<option value="detectron2.model_zoo.get_config_file" />
<option value="detectron2.model_zoo.get_checkpoint_url" />
</list>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/ilens-bot.iml" filepath="$PROJECT_DIR$/.idea/ilens-bot.iml" />
</modules>
</component>
</project>
\ No newline at end of file
u python:S2737["XAdd logic to this except clause or eliminate it and rethrow the exception automatically.(¬ÿžòúÿÿÿÿ
k python:S2208"GImport only needed names or import the module and then use its members.(–‡“§ýÿÿÿÿ8¯Ý篟/
\ No newline at end of file
= python:S125*"Remove this commented out code.(šÚ8¨ù¾Úž/
\ No newline at end of file
U python:S112">Replace this generic exception class with a more specific one.(̲
Z python:S112">Replace this generic exception class with a more specific one.(
U python:S112">Replace this generic exception class with a more specific one.(
\ No newline at end of file
u python:S3776Þ"URefactor this function to reduce its Cognitive Complexity from 130 to the 15 allowed.(‘ÕòÀ8ÂÄŠŸ/
H python:S108Œ")Either remove or fill this block of code.(ã‘Û¾8ÂÄŠŸ/
m python:S1192è"MDefine a constant instead of duplicating this literal 'Input.Toggle' 3 times.(ø¨¿ç8Õ䢟/
\ python:S5754Û"<Specify an exception class to catch or reraise the exception(ˆÊÉ·8ëÓÂÛž/
U python:S1481ˆ"0Remove the unused local variable "user_profile".(½õª˜ùÿÿÿÿ8ÂÄŠŸ/
y python:S3776—"TRefactor this function to reduce its Cognitive Complexity from 26 to the 15 allowed.(èˆöŒþÿÿÿÿ8Õ䢟/
 python:S1192¿"ZDefine a constant instead of duplicating this literal "My Luis is not configured" 3 times.(§Ú°Ôþÿÿÿÿ8€ÈŒŸ/
C python:S125ý"Remove this commented out code.(ö´Òíøÿÿÿÿ8ÂÄŠŸ/
O python:S1066§"/Merge this if statement with the enclosing one.(”“±‹8øóí¢Ÿ/
\ No newline at end of file
p python:S107"MMethod "__init__" has 15 parameters, which is greater than the 13 authorized.( Ðàþüÿÿÿÿ8ß½‹Ÿ/
\ No newline at end of file
Z Web:S5254"@Add "lang" and/or "xml:lang" attributes to this "<html>" element(œ÷Ãûÿÿÿÿ
\ No newline at end of file
B python:S125@"Remove this commented out code.(ʿ8ҩҞ/
\ No newline at end of file
JWeb:PageWithoutTitleCheck"Add a <title> tag to this page.(նM8/
a Web:S5254"@Add "lang" and/or "xml:lang" attributes to this "<html>" element(8԰/
\ No newline at end of file
9
README.md,8\e\8ec9a00bfd09b3190ac6b22251dbb1aa95a0579d
F
cards/welcomeCard.json,c\e\ceb799efbfae978ac560580847d723be33c77fe7
J
helpers/activity_helper.py,d\7\d7382871cefd6ede357ebb670fcb5859ce709072
Q
!dialogs/cancel_and_help_dialog.py,6\1\6140e9b9e511b5d6f440d5eca2528ee9627a1af6
9
config.py,1\a\1a1b9769344cb239f2e540e1e6ee1efa2d3034ea
O
cognitiveModels/ilens_luis.json,b\9\b941c8667415ebd820cc7c792e9baef29a56c6b0
?
cards/task.json,b\0\b0d96616dc72a17df804968fcc74cf65e1082d25
C
dialogs/__init__.py,5\f\5f8757606256e9f4337b404b7eb71e0390193b1f
B
bots/dialog_bot.py,2\0\201ee0952c37e7c687b77f5bd90d12185076a39b
6
app.py,1\3\13cce7fd076299c81b4986166f3d822791c9490e
?
user_profile.py,e\d\ed2ea576a0ee19445d85ae00adc50961e0f86d94
N
bots/dialog_and_welcome_bot.py,1\c\1ca5ae5500a8a0924c8bfcd0f448bf1eb2f384e3
M
adapter_with_error_handler.py,b\6\b6d46fb98b99de9c079df05b69f9c361e2fa4512
H
helpers/dialog_helper.py,f\7\f7ef765f9a76af08545b3be173d3edd722741e2a
F
helpers/luis_helper.py,f\5\f51fa6ddbfa2b03f4a8442b7f93900dfece1687a
=
ilens_luis.py,a\3\a31dbd6763a78ed1348dcca0229ea7f1e6efa8b3
G
dialogs/task_details.py,7\d\7d4e54aff6f819e92ac21575d3260f122b619301
>
dialogs/qna.py,5\d\5d8385a5636f759116abd05886fb3db62448e682
F
dialogs/main_dialog.py,3\e\3e76f1a41b8ae527f00ef5bbe8be28ac14ac8426
L
cards/safety_check_list.json,f\1\f16aab2812aef02f782bddbd9c799000ec500ee2
C
wwwroot/__init__.py,c\6\c6db38eb4e92d133de68fbd01c6ed1a230069af1
L
wwwroot/js/backup/botChat.js,6\7\67b74b3d773c7ee3cc811e34418a6d2c3f910d38
F
wwwroot/js/__init__.py,f\9\f9e43d0db45d6b63da8e4d4d5cd18d17e7d333fa
O
wwwroot/lib/jquery-3.5.1.min.js,3\f\3fb58afee7a8781e3f8bfc46834952943c749daa
G
wwwroot/css/botChat.css,4\3\43b0169f6c61f6dc62d431529442475d5d17e4ce
E
wwwroot/css/style.css,5\e\5ebf261c2426a8d5ab894a0d552a2800d1e205de
A
wwwroot/js/bot.js,e\a\ea574ad5a10191e627b81687a0d4b95e17c64839
C
wwwroot/default.htm,7\6\765a877d495ff2db198815165f2bfc06973bad56
@
requirements.txt,1\9\19359a61ae2446b51b549167b014da2fcf265768
M
wwwroot/.vscode/settings.json,2\1\217338edb9a3ce0f2a39fc8ec9affea8a86a98ee
:
index.html,f\6\f6013a00b362253c64368d6eebc50ea2131754e2
B
wwwroot/js/main.js,9\d\9d9d82d9b6158292a91a5cf4412a083566285fbd
E
cards/inspection.json,8\5\8504589fa1083d3841c5c34d288edadd5bd7dd72
8
new.html,f\1\f16a5a334d6b6322fb1bcf7a077cddc1b2b4c5a4
P
wwwroot_new/js/backup/botChat.js,1\4\14f9aa567819d214ab601a0fd20fb3dff6ea4fd8
F
wwwroot_new/js/main.js,5\0\50c38596db477a60108c60d23b7bfcf070330daa
G
wwwroot_new/default.htm,f\3\f3b0a8fb82703da7f1dd0cc72beb4e896e75042a
M
wwwroot_new/wwwroot/js/bot.js,4\0\4077460554bc04f7926e16face90ebb2301ef30d
O
wwwroot_new/wwwroot/default.htm,a\a\aaf4e990c7078d60066421ced5e4e4e3926d2396
S
#wwwroot_new/wwwroot/css/botChat.css,a\5\a539f9094c90a2cd39f2b0a182c4aac1f2a59eb9
S
#wwwroot_new/lib/jquery-3.5.1.min.js,e\f\efe12db9d8cbc675f31f482a71ef4b37c15346cb
E
wwwroot_new/js/bot.js,6\4\64add216e4bfcdc1bec40470d96e3b8e0f637b9f
\ No newline at end of file
# Setting up LUIS via CLI:
This README contains information on how to create and deploy a LUIS application. When the bot is ready to be deployed to production, we recommend creating a LUIS Endpoint Resource for usage with your LUIS App.
> _For instructions on how to create a LUIS Application via the LUIS portal, see these Quickstart steps:_
> 1. _[Quickstart: Create a new app in the LUIS portal][Quickstart-create]_
> 2. _[Quickstart: Deploy an app in the LUIS portal][Quickstart-deploy]_
[Quickstart-create]: https://docs.microsoft.com/azure/cognitive-services/luis/get-started-portal-build-app
[Quickstart-deploy]:https://docs.microsoft.com/azure/cognitive-services/luis/get-started-portal-deploy-app
## Table of Contents:
- [Prerequisites](#Prerequisites)
- [Import a new LUIS Application using a local LUIS application](#Import-a-new-LUIS-Application-using-a-local-LUIS-application)
- [How to create a LUIS Endpoint resource in Azure and pair it with a LUIS Application](#How-to-create-a-LUIS-Endpoint-resource-in-Azure-and-pair-it-with-a-LUIS-Application)
___
## [Prerequisites](#Table-of-Contents):
#### Install Azure CLI >=2.0.61:
Visit the following page to find the correct installer for your OS:
- https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest
#### Install LUIS CLI >=2.4.0:
Open a CLI of your choice and type the following:
```bash
npm i -g luis-apis@^2.4.0
```
#### LUIS portal account:
You should already have a LUIS account with either https://luis.ai, https://eu.luis.ai, or https://au.luis.ai. To determine where to create a LUIS account, consider where you will deploy your LUIS applications, and then place them in [the corresponding region][LUIS-Authoring-Regions].
After you've created your account, you need your [Authoring Key][LUIS-AKey] and a LUIS application ID.
[LUIS-Authoring-Regions]: https://docs.microsoft.com/azure/cognitive-services/luis/luis-reference-regions#luis-authoring-regions]
[LUIS-AKey]: https://docs.microsoft.com/azure/cognitive-services/luis/luis-concept-keys#authoring-key
___
## [Import a new LUIS Application using a local LUIS application](#Table-of-Contents)
### 1. Import the local LUIS application to luis.ai
```bash
luis import application --region "LuisAppAuthoringRegion" --authoringKey "LuisAuthoringKey" --appName "FlightBooking" --in "./cognitiveModels/FlightBooking.json"
```
Outputs the following JSON:
```json
{
"id": "########-####-####-####-############",
"name": "FlightBooking",
"description": "A LUIS model that uses intent and entities.",
"culture": "en-us",
"usageScenario": "",
"domain": "",
"versionsCount": 1,
"createdDateTime": "2019-03-29T18:32:02Z",
"endpoints": {},
"endpointHitsCount": 0,
"activeVersion": "0.1",
"ownerEmail": "bot@contoso.com",
"tokenizerVersion": "1.0.0"
}
```
For the next step, you'll need the `"id"` value for `--appId` and the `"activeVersion"` value for `--versionId`.
### 2. Train the LUIS Application
```bash
luis train version --region "LuisAppAuthoringRegion" --authoringKey "LuisAuthoringKey" --appId "LuisAppId" --versionId "LuisAppversion" --wait
```
### 3. Publish the LUIS Application
```bash
luis publish version --region "LuisAppAuthoringRegion" --authoringKey "LuisAuthoringKey" --appId "LuisAppId" --versionId "LuisAppversion" --publishRegion "LuisAppPublishRegion"
```
> `--region` corresponds to the region you _author_ your application in. The regions available for this are "westus", "westeurope" and "australiaeast". <br/>
> These regions correspond to the three available portals, https://luis.ai, https://eu.luis.ai, or https://au.luis.ai. <br/>
> `--publishRegion` corresponds to the region of the endpoint you're publishing to, (e.g. "westus", "southeastasia", "westeurope", "brazilsouth"). <br/>
> See the [reference docs][Endpoint-API] for a list of available publish/endpoint regions.
[Endpoint-API]: https://westus.dev.cognitive.microsoft.com/docs/services/5819c76f40a6350ce09de1ac/operations/5819c77140a63516d81aee78
Outputs the following:
```json
{
"versionId": "0.1",
"isStaging": false,
"endpointUrl": "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/########-####-####-####-############",
"region": "westus",
"assignedEndpointKey": null,
"endpointRegion": "westus",
"failedRegions": "",
"publishedDateTime": "2019-03-29T18:40:32Z",
"directVersionPublish": false
}
```
To see how to create an LUIS Cognitive Service Resource in Azure, please see [the next README][README-LUIS]. This Resource should be used when you want to move your bot to production. The instructions will show you how to create and pair the resource with a LUIS Application.
[README-LUIS]: ./README-LUIS.md
___
## [How to create a LUIS Endpoint resource in Azure and pair it with a LUIS Application](#Table-of-Contents)
### 1. Create a new LUIS Cognitive Services resource on Azure via Azure CLI
> _Note:_ <br/>
> _If you don't have a Resource Group in your Azure subscription, you can create one through the Azure portal or through using:_
> ```bash
> az group create --subscription "AzureSubscriptionGuid" --location "westus" --name "ResourceGroupName"
> ```
> _To see a list of valid locations, use `az account list-locations`_
```bash
# Use Azure CLI to create the LUIS Key resource on Azure
az cognitiveservices account create --kind "luis" --name "NewLuisResourceName" --sku "S0" --location "westus" --subscription "AzureSubscriptionGuid" -g "ResourceGroupName"
```
The command will output a response similar to the JSON below:
```json
{
"endpoint": "https://westus.api.cognitive.microsoft.com/luis/v2.0",
"etag": "\"########-####-####-####-############\"",
"id": "/subscriptions/########-####-####-####-############/resourceGroups/ResourceGroupName/providers/Microsoft.CognitiveServices/accounts/NewLuisResourceName",
"internalId": "################################",
"kind": "luis",
"location": "westus",
"name": "NewLuisResourceName",
"provisioningState": "Succeeded",
"resourceGroup": "ResourceGroupName",
"sku": {
"name": "S0",
"tier": null
},
"tags": null,
"type": "Microsoft.CognitiveServices/accounts"
}
```
Take the output from the previous command and create a JSON file in the following format:
```json
{
"azureSubscriptionId": "00000000-0000-0000-0000-000000000000",
"resourceGroup": "ResourceGroupName",
"accountName": "NewLuisResourceName"
}
```
### 2. Retrieve ARM access token via Azure CLI
```bash
az account get-access-token --subscription "AzureSubscriptionGuid"
```
This will return an object that looks like this:
```json
{
"accessToken": "eyJ0eXAiOiJKVtokentokentokentokentokeng1dCI6Ik4tbEMwbi05REFMcXdodUhZbkhRNjNHZUNYYyIsItokenI6Ik4tbEMwbi05REFMcXdodUhZbkhRNjNHZUNYYyJ9.eyJhdWQiOiJodHRwczovL21hbmFnZW1lbnQuY29yZS53aW5kb3dzLm5ldC8iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC83MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDcvIiwiaWF0IjoxNTUzODc3MTUwLCJuYmYiOjE1NTM4NzcxNTAsImV4cCI6MTU1Mzg4MTA1MCwiX2NsYWltX25hbWVzIjp7Imdyb3VwcyI6InNyYzEifSwiX2NsYWltX3NvdXJjZXMiOnsic3JjMSI6eyJlbmRwb2ludCI6Imh0dHBzOi8vZ3JhcGgud2luZG93cy5uZXQvNzJmOTg4YmYtODZmMS00MWFmLTkxYWItMmQ3Y2QwMTFkYjQ3L3VzZXJzL2ZmZTQyM2RkLWJhM2YtNDg0Ny04NjgyLWExNTI5MDA4MjM4Ny9nZXRNZW1iZXJPYmplY3RzIn19LCJhY3IiOiIxIiwiYWlvIjoiQVZRQXEvOEtBQUFBeGVUc201NDlhVHg4RE1mMFlRVnhGZmxxOE9RSC9PODR3QktuSmRqV1FqTkkwbmxLYzB0bHJEZzMyMFZ5bWZGaVVBSFBvNUFFUTNHL0FZNDRjdk01T3M0SEt0OVJkcE5JZW9WU0dzd0kvSkk9IiwiYW1yIjpbIndpYSIsIm1mYSJdLCJhcHBpZCI6IjA0YjA3Nzk1LThkZGItNDYxYS1iYmVlLTAyZjllMWJmN2I0NiIsImFwcGlkYWNyIjoiMCIsImRldmljZWlkIjoiNDhmNDVjNjEtMTg3Zi00MjUxLTlmZWItMTllZGFkZmMwMmE3IiwiZmFtaWx5X25hbWUiOiJHdW0iLCJnaXZlbl9uYW1lIjoiU3RldmVuIiwiaXBhZGRyIjoiMTY3LjIyMC4yLjU1IiwibmFtZSI6IlN0ZXZlbiBHdW0iLCJvaWQiOiJmZmU0MjNkZC1iYTNmLTQ4NDctODY4Mi1hMTUyOTAwODIzODciLCJvbnByZW1fc2lkIjoiUy0xLTUtMjEtMjEyNzUyMTE4NC0xNjA0MDEyOTIwLTE4ODc5Mjc1MjctMjYwOTgyODUiLCJwdWlkIjoiMTAwMzdGRkVBMDQ4NjlBNyIsInJoIjoiSSIsInNjcCI6InVzZXJfaW1wZXJzb25hdGlvbiIsInN1YiI6Ik1rMGRNMWszN0U5ckJyMjhieUhZYjZLSU85LXVFQVVkZFVhNWpkSUd1Nk0iLCJ0aWQiOiI3MmY5ODhiZi04NmYxLTQxYWYtOTFhYi0yZDdjZDAxMWRiNDciLCJ1bmlxdWVfbmFtZSI6InN0Z3VtQG1pY3Jvc29mdC5jb20iLCJ1cG4iOiJzdGd1bUBtaWNyb3NvZnQuY29tIiwidXRpIjoiT2w2NGN0TXY4RVNEQzZZQWRqRUFtokenInZlciI6IjEuMCJ9.kFAsEilE0mlS1pcpqxf4rEnRKeYsehyk-gz-zJHUrE__oad3QjgDSBDPrR_ikLdweynxbj86pgG4QFaHURNCeE6SzrbaIrNKw-n9jrEtokenlosOxg_0l2g1LeEUOi5Q4gQREAU_zvSbl-RY6sAadpOgNHtGvz3Rc6FZRITfkckSLmsKAOFoh-aWC6tFKG8P52rtB0qVVRz9tovBeNqkMYL49s9ypduygbXNVwSQhm5JszeWDgrFuVFHBUP_iENCQYGQpEZf_KvjmX1Ur1F9Eh9nb4yI2gFlKncKNsQl-tokenK7-tokentokentokentokentokentokenatoken",
"expiresOn": "2200-12-31 23:59:59.999999",
"subscription": "AzureSubscriptionGuid",
"tenant": "tenant-guid",
"tokenType": "Bearer"
}
```
The value needed for the next step is the `"accessToken"`.
### 3. Use `luis add appazureaccount` to pair your LUIS resource with a LUIS Application
```bash
luis add appazureaccount --in "path/to/created/requestBody.json" --appId "LuisAppId" --authoringKey "LuisAuthoringKey" --armToken "accessToken"
```
If successful, it should yield a response like this:
```json
{
"code": "Success",
"message": "Operation Successful"
}
```
### 4. See the LUIS Cognitive Services' keys
```bash
az cognitiveservices account keys list --name "NewLuisResourceName" --subscription "AzureSubscriptionGuid" -g "ResourceGroupName"
```
This will return an object that looks like this:
```json
{
"key1": "9a69####dc8f####8eb4####399f####",
"key2": "####f99e####4b1a####fb3b####6b9f"
}
```
\ No newline at end of file
# CoreBot
Bot Framework v4 core bot sample.
This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to:
- Use [LUIS](https://www.luis.ai) to implement core AI capabilities
- Implement a multi-turn conversation using Dialogs
- Handle user interruptions for such things as `Help` or `Cancel`
- Prompt for and validate requests for information from the user
## Prerequisites
This sample **requires** prerequisites in order to run.
### Overview
This bot uses [LUIS](https://www.luis.ai), an AI based cognitive service, to implement language understanding.
### Create a LUIS Application to enable language understanding
The LUIS model for this example can be found under `CognitiveModels/FlightBooking.json` and the LUIS language model setup, training, and application configuration steps can be found [here](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-v4-luis?view=azure-bot-service-4.0&tabs=cs).
Once you created the LUIS model, update `config.py` with your `LuisAppId`, `LuisAPIKey` and `LuisAPIHostName`.
```json
"LuisAppId": "Your LUIS App Id",
"LuisAPIKey": "Your LUIS Subscription key here",
"LuisAPIHostName": "Your LUIS App region here (i.e: westus.api.cognitive.microsoft.com)"
```
## To try this sample
- Clone the repository
```bash
git clone https://github.com/Microsoft/botbuilder-samples.git
```
- In a terminal, navigate to `botbuilder-samples\samples\python\13.core-bot` folder
- Activate your desired virtual environment
- In the terminal, type `pip install -r requirements.txt`
- Run your bot with `python app.py`
## Testing the bot using Bot Framework Emulator
[Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
- Install the latest Bot Framework Emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
### Connect to the bot using Bot Framework Emulator
- Launch Bot Framework Emulator
- File -> Open Bot
- Enter a Bot URL of `http://localhost:3978/api/messages`
## Deploy the bot to Azure
To learn more about deploying a bot to Azure, see [Deploy your bot to Azure](https://aka.ms/azuredeployment) for a complete list of deployment instructions.
## Further reading
- [Bot Framework Documentation](https://docs.botframework.com)
- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
- [Dialogs](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-dialog?view=azure-bot-service-4.0)
- [Gathering Input Using Prompts](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-prompts?view=azure-bot-service-4.0&tabs=csharp)
- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
- [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0)
- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0)
- [Azure CLI](https://docs.microsoft.com/cli/azure/?view=azure-cli-latest)
- [Azure Portal](https://portal.azure.com)
- [Language Understanding using LUIS](https://docs.microsoft.com/en-us/azure/cognitive-services/luis/)
- [Channels and Bot Connector Service](https://docs.microsoft.com/en-us/azure/bot-service/bot-concepts?view=azure-bot-service-4.0)
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import sys
import traceback
from datetime import datetime
from botbuilder.core import (
BotFrameworkAdapter,
BotFrameworkAdapterSettings,
ConversationState,
TurnContext,
)
from botbuilder.schema import ActivityTypes, Activity
class AdapterWithErrorHandler(BotFrameworkAdapter):
def __init__(
self,
settings: BotFrameworkAdapterSettings,
conversation_state: ConversationState,
):
super().__init__(settings)
self._conversation_state = conversation_state
# Catch-all for errors.
async def on_error(context: TurnContext, error: Exception):
# This check writes out errors to console log
# NOTE: In production environment, you should consider logging this to Azure
# application insights.
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
traceback.print_exc()
# Send a message to the user
await context.send_activity("The bot encountered an error or bug.")
await context.send_activity(
"To continue to run this bot, please fix the bot source code."
)
# Send a trace activity if we're talking to the Bot Framework Emulator
if context.activity.channel_id == "emulator":
# Create a trace activity that contains the error object
trace_activity = Activity(
label="TurnError",
name="on_turn_error Trace",
timestamp=datetime.utcnow(),
type=ActivityTypes.trace,
value=f"{error}",
value_type="https://www.botframework.com/schemas/error",
)
# Send a trace activity, which will be displayed in Bot Framework Emulator
await context.send_activity(trace_activity)
# Clear out state
nonlocal self
await self._conversation_state.delete(context)
self.on_turn_error = on_error
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""
This sample shows how to create a bot that demonstrates the following:
- Use [LUIS](https://www.luis.ai) to implement core AI capabilities.
- Implement a multi-turn conversation using Dialogs.
- Handle user interruptions for such things as `Help` or `Cancel`.
- Prompt for and validate requests for information from the user.
"""
from http import HTTPStatus
from aiohttp import web
from aiohttp.web import Request, Response, json_response
from botbuilder.core import (
BotFrameworkAdapterSettings,
ConversationState,
MemoryStorage,
UserState,
)
from botbuilder.core.integration import aiohttp_error_middleware
from botbuilder.schema import Activity
from adapter_with_error_handler import AdapterWithErrorHandler
from bots import DialogAndWelcomeBot
from config import DefaultConfig
from dialogs import MainDialog, faq, task_details
from ilens_luis import IlensLuis
from wwwroot import *
CONFIG = DefaultConfig()
# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
# Create MemoryStorage, UserState and ConversationState
MEMORY = MemoryStorage()
USER_STATE = UserState(MEMORY)
CONVERSATION_STATE = ConversationState(MEMORY)
# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
ADAPTER = AdapterWithErrorHandler(SETTINGS, CONVERSATION_STATE)
# Create dialogs and Bot
RECOGNIZER = IlensLuis(CONFIG)
task_details = task_details(RECOGNIZER, USER_STATE)
faq = faq()
DIALOG = MainDialog(RECOGNIZER, USER_STATE, task_details, faq)
BOT = DialogAndWelcomeBot(CONVERSATION_STATE, USER_STATE, DIALOG)
# Listen for incoming requests on /api/messages.
async def messages(req: Request) -> Response:
# Main bot message handler.
if "application/json" in req.headers["Content-Type"]:
body = await req.json()
else:
return Response(status=HTTPStatus.UNSUPPORTED_MEDIA_TYPE)
activity = Activity().deserialize(body)
auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""
response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
if response:
return json_response(data=response.body, status=response.status)
return Response(status=HTTPStatus.OK)
def html_response(document):
s = open(document, "r")
return web.Response(text=s.read(), content_type='text/html')
async def render(request):
import os
path = "new.html"
relative_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(relative_path, path)
return html_response(path)
APP = web.Application(middlewares=[aiohttp_error_middleware])
APP.router.add_post("/api/messages", messages)
APP.router.add_get("/", render)
if __name__ == "__main__":
try:
web.run_app(APP, host="localhost", port=CONFIG.PORT)
except Exception as error:
raise error
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .dialog_bot import DialogBot
from .dialog_and_welcome_bot import DialogAndWelcomeBot
__all__ = ["DialogBot", "DialogAndWelcomeBot"]
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import json
import os.path
from typing import List
from botbuilder.core import (
ConversationState,
MessageFactory,
UserState,
TurnContext,
)
from botbuilder.dialogs import Dialog
from botbuilder.schema import Attachment, ChannelAccount
from helpers.dialog_helper import DialogHelper
from user_profile import UserProfile
from .dialog_bot import DialogBot
class DialogAndWelcomeBot(DialogBot):
def __init__(
self,
conversation_state: ConversationState,
user_state: UserState,
dialog: Dialog,
):
super(DialogAndWelcomeBot, self).__init__(
conversation_state, user_state, dialog
)
self.user_state = user_state
self.user_profile_accessor = self.user_state.create_property("UserProfile")
async def on_members_added_activity(
self, members_added: List[ChannelAccount], turn_context: TurnContext
):
for member in members_added:
# Greet anyone that was not the target (recipient) of this message.
# To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
if member.id != turn_context.activity.recipient.id:
# welcome_card = self.create_adaptive_card_attachment()
# response = MessageFactory.attachment(welcome_card)
# await turn_context.send_activity(response)
user_profile = await self.user_profile_accessor.get(turn_context, UserProfile())
user_profile.start = False
await turn_context.send_activity("Hi! Welcome to Ilens Assistant…")
await DialogHelper.run_dialog(
self.dialog,
turn_context,
self.conversation_state.create_property("DialogState"),
)
# Load attachment from file.
def create_adaptive_card_attachment(self):
relative_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(relative_path, "../cards/welcomeCard.json")
with open(path) as in_file:
card = json.load(in_file)
return Attachment(
content_type="application/vnd.microsoft.card.adaptive", content=card
)
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.core import ActivityHandler, ConversationState, UserState, TurnContext
from botbuilder.dialogs import Dialog
from helpers.dialog_helper import DialogHelper
class DialogBot(ActivityHandler):
def __init__(
self,
conversation_state: ConversationState,
user_state: UserState,
dialog: Dialog,
):
if conversation_state is None:
raise Exception(
"[DialogBot]: Missing parameter. conversation_state is required"
)
if user_state is None:
raise Exception("[DialogBot]: Missing parameter. user_state is required")
if dialog is None:
raise Exception("[DialogBot]: Missing parameter. dialog is required")
self.conversation_state = conversation_state
self.user_state = user_state
self.dialog = dialog
async def on_turn(self, turn_context: TurnContext):
await super().on_turn(turn_context)
# Save any state changes that might have occurred during the turn.
await self.conversation_state.save_changes(turn_context, False)
await self.user_state.save_changes(turn_context, False)
async def on_message_activity(self, turn_context: TurnContext):
await DialogHelper.run_dialog(
self.dialog,
turn_context,
self.conversation_state.create_property("DialogState"),
)
{
"type": "AdaptiveCard",
"body": [
{
"type": "TextBlock",
"size": "Medium",
"weight": "Bolder",
"text": "Visual Inspection"
},
{
"type": "Container",
"items": [
{
"type": "TextBlock",
"text": "Observations",
"wrap": true,
"weight": "Bolder"
},
{
"type": "Input.Toggle",
"title": "Discoloration",
"value": "false",
"id": "discoloration"
},
{
"type": "Input.Toggle",
"title": "Change in Sound",
"value": "true",
"id": "change_in_sound"
},
{
"type": "Input.Toggle",
"title": "Visible Leak",
"value": "false",
"id": "leak"
}
]
},
{
"type": "Container",
"items": [
{
"type": "TextBlock",
"text": "Mechanical Seal for Leakage",
"wrap": true,
"weight": "Bolder"
},
{
"type": "Input.Toggle",
"title": "Safe",
"value": "true",
"id": "safe"
},
{
"type": "Input.Toggle",
"title": "Risk",
"value": "false",
"id": "risk"
},
{
"type": "Input.Toggle",
"title": "Not Applicable",
"value": "false",
"id": "not_applicable"
}
]
},
{
"type": "Container",
"items": [
{
"type": "TextBlock",
"text": "Bushing Conditions",
"wrap": true,
"weight": "Bolder"
},
{
"type": "Input.Toggle",
"title": "Good",
"value": "false",
"id": "good"
},
{
"type": "Input.Toggle",
"title": "Fair",
"value": "false",
"id": "fair"
},
{
"type": "Input.Toggle",
"title": "Poor",
"value": "true",
"id": "poor"
}
]
}
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.0"
}
\ No newline at end of file
{
"type": "AdaptiveCard",
"body": [
{
"type": "TextBlock",
"size": "Medium",
"weight": "Bolder",
"text": "Safety Check List"
},
{
"type": "Container",
"items": [
{
"type": "TextBlock",
"text": "Safety Hat",
"wrap": true,
"weight": "Bolder"
},
{
"type": "Input.Toggle",
"title": "Yes",
"value": "true",
"id": "hat_yes"
},
{
"type": "Input.Toggle",
"title": "No",
"value": "false",
"id": "hat_no"
}
]
},
{
"type": "Container",
"items": [
{
"type": "TextBlock",
"text": "Safety Vest",
"wrap": true,
"weight": "Bolder"
},
{
"type": "Input.Toggle",
"title": "Yes",
"value": "false",
"id": "vest_yes"
},
{
"type": "Input.Toggle",
"title": "No",
"value": "true",
"id": "vest_no"
}
]
},
{
"type": "Container",
"items": [
{
"type": "TextBlock",
"text": "Safety Goggles",
"wrap": true,
"weight": "Bolder"
},
{
"type": "Input.Toggle",
"title": "Yes",
"value": "false",
"id": "goggles_yes"
},
{
"type": "Input.Toggle",
"title": "No",
"value": "true",
"id": "goggles_no"
}
]
},
{
"type": "Container",
"items": [
{
"type": "TextBlock",
"text": "Safety Shoes",
"wrap": true,
"weight": "Bolder"
},
{
"type": "Input.Toggle",
"value": "true",
"id": "shoes_yes",
"title": "Yes"
},
{
"type": "Input.Toggle",
"title": "No",
"value": "false",
"id": "shoes_no"
}
]
}
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.0"
}
\ No newline at end of file
{
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.0",
"body": [
{
"type": "TextBlock",
"spacing": "Medium",
"size": "default",
"weight": "Bolder",
"text": "Task Details",
"wrap": true,
"maxLines": 0
},
{
"type": "TextBlock",
"size": "default",
"isSubtle": true,
"text": "STEPS TO COMPLETE THE TASK",
"wrap": true,
"maxLines": 0
},
{
"type": "TextBlock",
"size": "Medium",
"isSubtle": true,
"text": "a. Safety Checklist",
"wrap": true,
"maxLines": 1,
"fontType": "Monospace",
"weight": "Bolder"
},
{
"type": "TextBlock",
"size": "Medium",
"isSubtle": true,
"text": "b. Visual Inspection",
"wrap": true,
"maxLines": 1,
"fontType": "Monospace",
"weight": "Bolder"
}
]
}
\ No newline at end of file
{
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.0",
"body": [
{
"type": "Image",
"url": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU",
"size": "stretch"
},
{
"type": "TextBlock",
"spacing": "medium",
"size": "default",
"weight": "bolder",
"text": "Welcome to Bot Framework!",
"wrap": true,
"maxLines": 0
},
{
"type": "TextBlock",
"size": "default",
"isSubtle": "true",
"text": "Now that you have successfully run your bot, follow the links in this Adaptive Card to expand your knowledge of Bot Framework.",
"wrap": true,
"maxLines": 0
}
],
"actions": [
{
"type": "Action.OpenUrl",
"title": "Get an overview",
"url": "https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0"
},
{
"type": "Action.OpenUrl",
"title": "Ask a question",
"url": "https://stackoverflow.com/questions/tagged/botframework"
},
{
"type": "Action.OpenUrl",
"title": "Learn how to deploy",
"url": "https://docs.microsoft.com/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0"
}
]
}
\ No newline at end of file
{
"luis_schema_version": "7.0.0",
"intents": [
{
"name": "asset",
"features": []
},
{
"name": "change_in_sound",
"features": []
},
{
"name": "Discoloration",
"features": []
},
{
"name": "fair",
"features": []
},
{
"name": "good",
"features": []
},
{
"name": "leak",
"features": []
},
{
"name": "None",
"features": []
},
{
"name": "not_applicable",
"features": []
},
{
"name": "qna",
"features": []
},
{
"name": "quality",
"features": []
},
{
"name": "risk",
"features": []
},
{
"name": "safe",
"features": []
},
{
"name": "safety",
"features": []
},
{
"name": "similar_service",
"features": []
},
{
"name": "task",
"features": []
}
],
"entities": [],
"hierarchicals": [],
"composites": [],
"closedLists": [],
"prebuiltEntities": [
{
"name": "age",
"roles": []
},
{
"name": "datetimeV2",
"roles": []
},
{
"name": "dimension",
"roles": []
},
{
"name": "email",
"roles": []
},
{
"name": "geographyV2",
"roles": []
},
{
"name": "keyPhrase",
"roles": []
},
{
"name": "money",
"roles": []
},
{
"name": "number",
"roles": []
},
{
"name": "ordinal",
"roles": []
},
{
"name": "ordinalV2",
"roles": []
},
{
"name": "percentage",
"roles": []
},
{
"name": "personName",
"roles": []
},
{
"name": "phonenumber",
"roles": []
},
{
"name": "temperature",
"roles": []
},
{
"name": "url",
"roles": []
}
],
"utterances": [
{
"text": "assest details",
"intent": "asset",
"entities": []
},
{
"text": "can you answer some of my questions",
"intent": "qna",
"entities": []
},
{
"text": "change in the sound",
"intent": "change_in_sound",
"entities": []
},
{
"text": "dicoloration",
"intent": "Discoloration",
"entities": []
},
{
"text": "discoloration",
"intent": "Discoloration",
"entities": []
},
{
"text": "discolored",
"intent": "Discoloration",
"entities": []
},
{
"text": "fair",
"intent": "fair",
"entities": []
},
{
"text": "faq",
"intent": "qna",
"entities": []
},
{
"text": "give me the asset details",
"intent": "asset",
"entities": []
},
{
"text": "good",
"intent": "good",
"entities": []
},
{
"text": "i am not",
"intent": "None",
"entities": []
},
{
"text": "i am not wearing",
"intent": "None",
"entities": []
},
{
"text": "i can hear some noise",
"intent": "change_in_sound",
"entities": []
},
{
"text": "i can see a leak here",
"intent": "leak",
"entities": []
},
{
"text": "i have few questions",
"intent": "qna",
"entities": []
},
{
"text": "i want to check my safety gear",
"intent": "safety",
"entities": []
},
{
"text": "i want to do a quality inspection",
"intent": "quality",
"entities": []
},
{
"text": "i want to fill my task details",
"intent": "task",
"entities": []
},
{
"text": "i want to take a safety inspection",
"intent": "safety",
"entities": []
},
{
"text": "it is at risky position",
"intent": "risk",
"entities": []
},
{
"text": "it is better",
"intent": "good",
"entities": []
},
{
"text": "it is discolored",
"intent": "Discoloration",
"entities": []
},
{
"text": "it is fair",
"intent": "fair",
"entities": []
},
{
"text": "it is fair enough",
"intent": "fair",
"entities": []
},
{
"text": "it is good",
"intent": "good",
"entities": []
},
{
"text": "it is nice",
"intent": "good",
"entities": []
},
{
"text": "it is not applicable",
"intent": "not_applicable",
"entities": []
},
{
"text": "it is not at all aplicable",
"intent": "not_applicable",
"entities": []
},
{
"text": "it is ok",
"intent": "good",
"entities": []
},
{
"text": "it is safe",
"intent": "safe",
"entities": []
},
{
"text": "it look safe",
"intent": "safe",
"entities": []
},
{
"text": "it looks good",
"intent": "good",
"entities": []
},
{
"text": "it looks like discolored",
"intent": "Discoloration",
"entities": []
},
{
"text": "my task details",
"intent": "task",
"entities": []
},
{
"text": "my tasks",
"intent": "task",
"entities": []
},
{
"text": "not applicable",
"intent": "not_applicable",
"entities": []
},
{
"text": "qna",
"intent": "qna",
"entities": []
},
{
"text": "quality inspection",
"intent": "quality",
"entities": []
},
{
"text": "questions",
"intent": "qna",
"entities": []
},
{
"text": "risk",
"intent": "risk",
"entities": []
},
{
"text": "safe",
"intent": "safe",
"entities": []
},
{
"text": "safety inspection",
"intent": "safety",
"entities": []
},
{
"text": "service records",
"intent": "similar_service",
"entities": []
},
{
"text": "show me asset details",
"intent": "asset",
"entities": []
},
{
"text": "show me my task details",
"intent": "task",
"entities": []
},
{
"text": "show me similar service records",
"intent": "similar_service",
"entities": []
},
{
"text": "similar service records",
"intent": "similar_service",
"entities": []
},
{
"text": "sound change",
"intent": "change_in_sound",
"entities": []
},
{
"text": "sound is different",
"intent": "change_in_sound",
"entities": []
},
{
"text": "task",
"intent": "task",
"entities": []
},
{
"text": "task details",
"intent": "task",
"entities": []
},
{
"text": "task instructions",
"intent": "task",
"entities": []
},
{
"text": "there is a leak",
"intent": "leak",
"entities": []
},
{
"text": "there is a risk",
"intent": "risk",
"entities": []
},
{
"text": "there is a visible leak",
"intent": "leak",
"entities": []
},
{
"text": "there is some kind of risk",
"intent": "risk",
"entities": []
},
{
"text": "visible leak",
"intent": "leak",
"entities": []
},
{
"text": "what are assest details",
"intent": "asset",
"entities": []
}
],
"versionId": "0.1",
"name": "ilens-assistant-luis",
"desc": "ilens-assistant-luis",
"culture": "en-us",
"tokenizerVersion": "1.0.0",
"patternAnyEntities": [],
"regex_entities": [],
"phraselists": [],
"regex_features": [],
"patterns": [],
"settings": []
}
\ No newline at end of file
#!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
""" Bot Configuration """
class DefaultConfig:
""" Bot Configuration """
PORT = 3978
APP_ID = os.environ.get("MicrosoftAppId", "98630f4e-e545-4bc4-8c51-88deb74d7bcc")
APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "Ilens_Assistant_v1")
LUIS_APP_ID = os.environ.get("LuisAppId", "45646243-2016-4f0a-9145-e93a7f58e355")
LUIS_API_KEY = os.environ.get("LuisAPIKey", "f19be164fbfc49a3972f940835820d7e")
# LUIS endpoint host name, ie "westus.api.cognitive.microsoft.com"
LUIS_API_HOST_NAME = os.environ.get("LuisAPIHostName", "westus.api.cognitive.microsoft.com")
This diff is collapsed.
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"appId": {
"type": "string",
"metadata": {
"description": "Active Directory App ID, set as MicrosoftAppId in the Web App's Application Settings."
}
},
"appSecret": {
"type": "string",
"metadata": {
"description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings."
}
},
"botId": {
"type": "string",
"metadata": {
"description": "The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable."
}
},
"botSku": {
"defaultValue": "F0",
"type": "string",
"metadata": {
"description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1."
}
},
"newAppServicePlanName": {
"type": "string",
"defaultValue": "",
"metadata": {
"description": "The name of the new App Service Plan."
}
},
"newAppServicePlanSku": {
"type": "object",
"defaultValue": {
"name": "S1",
"tier": "Standard",
"size": "S1",
"family": "S",
"capacity": 1
},
"metadata": {
"description": "The SKU of the App Service Plan. Defaults to Standard values."
}
},
"appServicePlanLocation": {
"type": "string",
"metadata": {
"description": "The location of the App Service Plan."
}
},
"existingAppServicePlan": {
"type": "string",
"defaultValue": "",
"metadata": {
"description": "Name of the existing App Service Plan used to create the Web App for the bot."
}
},
"newWebAppName": {
"type": "string",
"defaultValue": "",
"metadata": {
"description": "The globally unique name of the Web App. Defaults to the value passed in for \"botId\"."
}
}
},
"variables": {
"defaultAppServicePlanName": "[if(empty(parameters('existingAppServicePlan')), 'createNewAppServicePlan', parameters('existingAppServicePlan'))]",
"useExistingAppServicePlan": "[not(equals(variables('defaultAppServicePlanName'), 'createNewAppServicePlan'))]",
"servicePlanName": "[if(variables('useExistingAppServicePlan'), parameters('existingAppServicePlan'), parameters('newAppServicePlanName'))]",
"publishingUsername": "[concat('$', parameters('newWebAppName'))]",
"resourcesLocation": "[parameters('appServicePlanLocation')]",
"webAppName": "[if(empty(parameters('newWebAppName')), parameters('botId'), parameters('newWebAppName'))]",
"siteHost": "[concat(variables('webAppName'), '.azurewebsites.net')]",
"botEndpoint": "[concat('https://', variables('siteHost'), '/api/messages')]"
},
"resources": [
{
"comments": "Create a new Linux App Service Plan if no existing App Service Plan name was passed in.",
"type": "Microsoft.Web/serverfarms",
"apiVersion": "2016-09-01",
"name": "[variables('servicePlanName')]",
"location": "[variables('resourcesLocation')]",
"sku": "[parameters('newAppServicePlanSku')]",
"kind": "linux",
"properties": {
"name": "[variables('servicePlanName')]",
"perSiteScaling": false,
"reserved": true,
"targetWorkerCount": 0,
"targetWorkerSizeId": 0
}
},
{
"comments": "Create a Web App using a Linux App Service Plan",
"type": "Microsoft.Web/sites",
"apiVersion": "2016-08-01",
"name": "[variables('webAppName')]",
"location": "[variables('resourcesLocation')]",
"dependsOn": [
"[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]"
],
"kind": "app,linux",
"properties": {
"enabled": true,
"hostNameSslStates": [
{
"name": "[concat(parameters('newWebAppName'), '.azurewebsites.net')]",
"sslState": "Disabled",
"hostType": "Standard"
},
{
"name": "[concat(parameters('newWebAppName'), '.scm.azurewebsites.net')]",
"sslState": "Disabled",
"hostType": "Repository"
}
],
"serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('servicePlanName'))]",
"reserved": true,
"scmSiteAlsoStopped": false,
"clientAffinityEnabled": false,
"clientCertEnabled": false,
"hostNamesDisabled": false,
"containerSize": 0,
"dailyMemoryTimeQuota": 0,
"httpsOnly": false,
"siteConfig": {
"appSettings": [
{
"name": "MicrosoftAppId",
"value": "[parameters('appId')]"
},
{
"name": "MicrosoftAppPassword",
"value": "[parameters('appSecret')]"
},
{
"name": "SCM_DO_BUILD_DURING_DEPLOYMENT",
"value": "true"
}
],
"cors": {
"allowedOrigins": [
"https://botservice.hosting.portal.azure.net",
"https://hosting.onecloud.azure-test.net/"
]
}
}
}
},
{
"type": "Microsoft.Web/sites/config",
"apiVersion": "2016-08-01",
"name": "[concat(variables('webAppName'), '/web')]",
"location": "[variables('resourcesLocation')]",
"dependsOn": [
"[resourceId('Microsoft.Web/sites', variables('webAppName'))]"
],
"properties": {
"numberOfWorkers": 1,
"defaultDocuments": [
"Default.htm",
"Default.html",
"Default.asp",
"index.htm",
"index.html",
"iisstart.htm",
"default.aspx",
"index.php",
"hostingstart.html"
],
"netFrameworkVersion": "v4.0",
"phpVersion": "",
"pythonVersion": "",
"nodeVersion": "",
"linuxFxVersion": "PYTHON|3.7",
"requestTracingEnabled": false,
"remoteDebuggingEnabled": false,
"remoteDebuggingVersion": "VS2017",
"httpLoggingEnabled": true,
"logsDirectorySizeLimit": 35,
"detailedErrorLoggingEnabled": false,
"publishingUsername": "[variables('publishingUsername')]",
"scmType": "None",
"use32BitWorkerProcess": true,
"webSocketsEnabled": false,
"alwaysOn": false,
"appCommandLine": "gunicorn --bind 0.0.0.0 --worker-class aiohttp.worker.GunicornWebWorker --timeout 600 app:APP",
"managedPipelineMode": "Integrated",
"virtualApplications": [
{
"virtualPath": "/",
"physicalPath": "site\\wwwroot",
"preloadEnabled": false,
"virtualDirectories": null
}
],
"winAuthAdminState": 0,
"winAuthTenantState": 0,
"customAppPoolIdentityAdminState": false,
"customAppPoolIdentityTenantState": false,
"loadBalancing": "LeastRequests",
"routingRules": [],
"experiments": {
"rampUpRules": []
},
"autoHealEnabled": false,
"vnetName": "",
"minTlsVersion": "1.2",
"ftpsState": "AllAllowed",
"reservedInstanceCount": 0
}
},
{
"apiVersion": "2017-12-01",
"type": "Microsoft.BotService/botServices",
"name": "[parameters('botId')]",
"location": "global",
"kind": "bot",
"sku": {
"name": "[parameters('botSku')]"
},
"properties": {
"name": "[parameters('botId')]",
"displayName": "[parameters('botId')]",
"endpoint": "[variables('botEndpoint')]",
"msaAppId": "[parameters('appId')]",
"developerAppInsightsApplicationId": null,
"developerAppInsightKey": null,
"publishingCredentials": null,
"storageResourceId": null
},
"dependsOn": [
"[resourceId('Microsoft.Web/sites/', variables('webAppName'))]"
]
}
]
}
\ No newline at end of file
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .cancel_and_help_dialog import CancelAndHelpDialog
from .main_dialog import MainDialog
from .task_details import task_details
from .qna import faq
__all__ = ["CancelAndHelpDialog","MainDialog","task_details",'faq']
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.dialogs import (
ComponentDialog,
DialogContext,
DialogTurnResult,
DialogTurnStatus,
)
from botbuilder.schema import ActivityTypes, InputHints
from botbuilder.core import MessageFactory
class CancelAndHelpDialog(ComponentDialog):
def __init__(self, dialog_id: str):
super(CancelAndHelpDialog, self).__init__(dialog_id)
async def on_continue_dialog(self, inner_dc: DialogContext) -> DialogTurnResult:
result = await self.interrupt(inner_dc)
if result is not None:
return result
return await super(CancelAndHelpDialog, self).on_continue_dialog(inner_dc)
async def interrupt(self, inner_dc: DialogContext) -> DialogTurnResult:
if inner_dc.context.activity.type == ActivityTypes.message:
text = inner_dc.context.activity.text.lower()
help_message_text = "Show Help..."
help_message = MessageFactory.text(
help_message_text, help_message_text, InputHints.expecting_input
)
if text in ("help", "?"):
await inner_dc.context.send_activity(help_message)
return DialogTurnResult(DialogTurnStatus.Waiting)
cancel_message_text = "Cancelling"
cancel_message = MessageFactory.text(
cancel_message_text, cancel_message_text, InputHints.ignoring_input
)
if text in ("cancel", "quit"):
await inner_dc.context.send_activity(cancel_message)
return await inner_dc.cancel_all_dialogs()
return None
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.dialogs import (
ComponentDialog,
WaterfallDialog,
WaterfallStepContext,
DialogTurnResult,
)
from botbuilder.dialogs.prompts import TextPrompt, PromptOptions
from botbuilder.core import MessageFactory, TurnContext
from botbuilder.schema import InputHints
from user_profile import UserProfile
from ilens_luis import IlensLuis
from helpers.luis_helper import LuisHelper, Intent
from botbuilder.schema import ChannelAccount, CardAction, ActionTypes, SuggestedActions
from botbuilder.dialogs.prompts import ConfirmPrompt, ChoicePrompt, PromptOptions
from botbuilder.dialogs.choices import Choice
from .task_details import task_details
from .qna import faq
from botbuilder.core import ActivityHandler, ConversationState, UserState, TurnContext
class MainDialog(ComponentDialog):
def __init__(
self, luis_recognizer: IlensLuis,user_state: UserState, task_details: task_details, faq: faq
):
super(MainDialog, self).__init__(MainDialog.__name__)
self.task_details_id = task_details.id
self.faq_id = faq.id
self.add_dialog(task_details)
self.add_dialog(faq)
self.add_dialog(ChoicePrompt(ChoicePrompt.__name__))
self.add_dialog(ConfirmPrompt(ConfirmPrompt.__name__))
self._luis_recognizer = luis_recognizer
self.add_dialog(TextPrompt(TextPrompt.__name__))
self.add_dialog(
WaterfallDialog(
"WFDialog", [self.welcome_step, self.options_step, self.final_step]
)
)
self.user_state = user_state
self.user_profile_accessor = self.user_state.create_property("UserProfile")
self.initial_dialog_id = "WFDialog"
async def welcome_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
if not self._luis_recognizer.is_configured:
await step_context.context.send_activity(
MessageFactory.text(
"NOTE: LUIS is not configured. To enable all capabilities, add 'LuisAppId', 'LuisAPIKey' and "
"'LuisAPIHostName' to the appsettings.json file.",
input_hint=InputHints.ignoring_input,
)
)
return await step_context.next(None)
# prompt_options = PromptOptions( prompt=MessageFactory.text("In order to proceed forward please choose any
# option to continue"), retry_prompt=MessageFactory.text("Please choose an option from the list."),
# choices=[Choice("Task Details"), Choice("Asset Details"), Choice("Similar service records"), Choice("FAQ")]
# ) return await step_context.prompt(ChoicePrompt.__name__, prompt_options)
user_profile = await self.user_profile_accessor.get(step_context.context, UserProfile())
if not user_profile.start:
reply = MessageFactory.text("In order to proceed forward please choose any option to continue")
user_profile.start = True
else:
reply = MessageFactory.text("Is there anything else I can help you with?")
reply.suggested_actions = SuggestedActions(
actions=[
CardAction(
title="Task Details",
type=ActionTypes.im_back,
value="Task Details"
), CardAction(
title="Asset Details",
type=ActionTypes.im_back,
value="Asset Details"
), CardAction(
title="Similar service records",
type=ActionTypes.im_back,
value="Similar service records"
),
CardAction(
title="FAQ's",
type=ActionTypes.im_back,
value="FAQ's"
)
]
)
return await step_context.prompt(
TextPrompt.__name__, PromptOptions(prompt=reply)
)
async def options_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
if not self._luis_recognizer.is_configured:
await step_context.context.send_activity("My Luis is not configured")
return await step_context.end_dialog()
intent, luis_result = await LuisHelper.execute_luis_query(self._luis_recognizer, step_context.context)
if intent == Intent.task.value:
return await step_context.begin_dialog(self.task_details_id, UserProfile())
elif intent == Intent.qna.value:
return await step_context.begin_dialog(self.faq_id, UserProfile())
elif intent == Intent.asset.value:
await step_context.context.send_activity("asset")
elif intent == Intent.similar_service.value:
await step_context.context.send_activity("similar_service")
else:
didnt_understand_text = (
"Sorry, I didn't get that. Please try asking in a different way"
)
await step_context.context.send_activity(didnt_understand_text)
return await step_context.next(None)
async def final_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
prompt_message = "What else can I do for you?"
return await step_context.replace_dialog(self.initial_dialog_id, prompt_message)
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from datatypes_date_time.timex import Timex
from botbuilder.dialogs import WaterfallDialog, WaterfallStepContext, DialogTurnResult
from botbuilder.dialogs.prompts import ConfirmPrompt, TextPrompt, PromptOptions
from botbuilder.core import MessageFactory
from botbuilder.schema import InputHints
from .cancel_and_help_dialog import CancelAndHelpDialog
from botbuilder.schema import ChannelAccount, CardAction, ActionTypes, SuggestedActions
class faq(CancelAndHelpDialog):
def __init__(self, dialog_id: str = None):
super(faq, self).__init__(dialog_id or faq.__name__)
self.add_dialog(TextPrompt(TextPrompt.__name__))
self.add_dialog(ConfirmPrompt(ConfirmPrompt.__name__))
self.add_dialog(
WaterfallDialog(
WaterfallDialog.__name__,
[
self.first_step, self.final_step, self.end_step
],
)
)
self.initial_dialog_id = WaterfallDialog.__name__
async def first_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
"""
Complete the interaction and end the dialog.
:param step_context:
:return DialogTurnResult:
"""
reply = MessageFactory.text("please ask your question")
return await step_context.prompt(
TextPrompt.__name__, PromptOptions(prompt=reply)
)
async def final_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
"""
Complete the interaction and end the dialog.
:param step_context:
:return DialogTurnResult:
"""
await step_context.context.send_activity(self.api_hit(str(step_context.result)))
reply = MessageFactory.text("Are there any other questions I should answer?")
reply.suggested_actions = SuggestedActions(
actions=[
CardAction(
title="Yes",
type=ActionTypes.im_back,
value='yes'
),
CardAction(
title="No",
type=ActionTypes.im_back,
value='no'
)
]
)
return await step_context.prompt(
TextPrompt.__name__, PromptOptions(prompt=reply)
)
async def end_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
"""
Complete the interaction and end the dialog.
:param step_context:
:return DialogTurnResult:
"""
if str(step_context.result).lower() == 'yes':
return await step_context.replace_dialog(self.id)
await step_context.context.send_activity("hope I was able to answer all your questions")
return await step_context.end_dialog()
def is_ambiguous(self, timex: str) -> bool:
timex_property = Timex(timex)
return "definite" not in timex_property.types
def api_hit(self, question):
import requests
url = "https://ilens-assistant-qna.azurewebsites.net/qnamaker/knowledgebases/0697399a-4050-4f19-80ce-4ad8dae41b6a/generateAnswer"
payload = "{\"question\":\"" + question + "\"}"
print(payload)
headers = {
'Authorization': 'EndpointKey 031de099-2a8b-4b27-af84-2a5e15b35413',
'Content-Type': 'application/json',
'Cookie': 'ARRAffinity=05b4cef5a3f30849a8768536ff665c720ef1b15f35ff9c5d7fa3f54b9d6f9375; ARRAffinitySameSite=05b4cef5a3f30849a8768536ff665c720ef1b15f35ff9c5d7fa3f54b9d6f9375'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
my_ans = response.json()
print(my_ans["answers"][0]["answer"])
return str(my_ans["answers"][0]["answer"])
This diff is collapsed.
import json
f = open("../cards/safety_check_list.json","r")
data = json.loads(f.read())
for i in data['body']:
if i['type'] == 'Container':
for j in i['items']:
if j['type'] == 'Input.Toggle':
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from . import activity_helper, luis_helper, dialog_helper
__all__ = ["activity_helper", "dialog_helper", "luis_helper"]
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from datetime import datetime
from botbuilder.schema import (
Activity,
ActivityTypes,
ChannelAccount,
ConversationAccount,
)
def create_activity_reply(activity: Activity, text: str = None, locale: str = None):
return Activity(
type=ActivityTypes.message,
timestamp=datetime.utcnow(),
from_property=ChannelAccount(
id=getattr(activity.recipient, "id", None),
name=getattr(activity.recipient, "name", None),
),
recipient=ChannelAccount(
id=activity.from_property.id, name=activity.from_property.name
),
reply_to_id=activity.id,
service_url=activity.service_url,
channel_id=activity.channel_id,
conversation=ConversationAccount(
is_group=activity.conversation.is_group,
id=activity.conversation.id,
name=activity.conversation.name,
),
text=text or "",
locale=locale or "",
attachments=[],
entities=[],
)
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.core import StatePropertyAccessor, TurnContext
from botbuilder.dialogs import Dialog, DialogSet, DialogTurnStatus
class DialogHelper:
@staticmethod
async def run_dialog(
dialog: Dialog, turn_context: TurnContext, accessor: StatePropertyAccessor
):
dialog_set = DialogSet(accessor)
dialog_set.add(dialog)
dialog_context = await dialog_set.create_context(turn_context)
results = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
await dialog_context.begin_dialog(dialog.id)
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from enum import Enum
from typing import Dict
from botbuilder.ai.luis import LuisRecognizer
from botbuilder.core import IntentScore, TopIntent, TurnContext
class Intent(Enum):
NONE_INTENT = "None"
safety = "safety"
qna = "qna"
task = "task"
similar_service = "similar_service"
asset = "asset"
change_in_sound = 'change_in_sound'
discoloration = "Discoloration"
fair = "fair"
good = "good"
leak = "leak"
not_applicable = "not_applicable"
risk = "risk"
safe = "safe"
quality = 'quality'
poor = "poor"
def top_intent(intents: Dict[Intent, dict]) -> TopIntent:
max_intent = Intent.NONE_INTENT
max_value = 0.0
for intent, value in intents:
intent_score = IntentScore(value)
if intent_score.score > max_value:
max_intent, max_value = intent, intent_score.score
return TopIntent(max_intent, max_value)
class LuisHelper:
@staticmethod
async def execute_luis_query(
luis_recognizer: LuisRecognizer, turn_context: TurnContext
) -> (Intent, object):
"""
Returns an object with preformatted LUIS results for the bot's dialogs to consume.
"""
result = None
intent = None
try:
recognizer_result = await luis_recognizer.recognize(turn_context)
intent = (
sorted(
recognizer_result.intents,
key=recognizer_result.intents.get,
reverse=True,
)[:1][0]
if recognizer_result.intents
else None
)
# if intent == Intent.BOOK_FLIGHT.value:
# result = BookingDetails()
#
# # We need to get the result from the LUIS JSON which at every level returns an array.
# to_entities = recognizer_result.entities.get("$instance", {}).get(
# "To", []
# )
# if len(to_entities) > 0:
# if recognizer_result.entities.get("To", [{"$instance": {}}])[0][
# "$instance"
# ]:
# result.destination = to_entities[0]["text"].capitalize()
# else:
# result.unsupported_airports.append(
# to_entities[0]["text"].capitalize()
# )
#
# from_entities = recognizer_result.entities.get("$instance", {}).get(
# "From", []
# )
# if len(from_entities) > 0:
# if recognizer_result.entities.get("From", [{"$instance": {}}])[0][
# "$instance"
# ]:
# result.origin = from_entities[0]["text"].capitalize()
# else:
# result.unsupported_airports.append(
# from_entities[0]["text"].capitalize()
# )
#
# # This value will be a TIMEX. And we are only interested in a Date so grab the first result and drop
# # the Time part. TIMEX is a format that represents DateTime expressions that include some ambiguity.
# # e.g. missing a Year.
# date_entities = recognizer_result.entities.get("datetime", [])
# if date_entities:
# timex = date_entities[0]["timex"]
#
# if timex:
# datetime = timex[0].split("T")[0]
#
# result.travel_date = datetime
#
# else:
# result.travel_date = None
except Exception as exception:
print(exception)
return intent, result
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.ai.luis import LuisApplication, LuisRecognizer
from botbuilder.core import Recognizer, RecognizerResult, TurnContext
from config import DefaultConfig
class IlensLuis(Recognizer):
def __init__(self, configuration: DefaultConfig):
self._recognizer = None
luis_is_configured = (
configuration.LUIS_APP_ID
and configuration.LUIS_API_KEY
and configuration.LUIS_API_HOST_NAME
)
if luis_is_configured:
# Set the recognizer options depending on which endpoint version you want to use e.g v2 or v3.
# More details can be found in https://docs.microsoft.com/azure/cognitive-services/luis/luis-migration-api-v3
luis_application = LuisApplication(
configuration.LUIS_APP_ID,
configuration.LUIS_API_KEY,
"https://" + configuration.LUIS_API_HOST_NAME,
)
self._recognizer = LuisRecognizer(luis_application)
@property
def is_configured(self) -> bool:
# Returns true if luis is configured in the config.py and initialized.
return self._recognizer is not None
async def recognize(self, turn_context: TurnContext) -> RecognizerResult:
return await self._recognizer.recognize(turn_context)
<!DOCTYPE html>
<html>
<head>
<script
crossorigin="anonymous"
src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"
></script>
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
}
#webchat {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({
token: '64vf8UAFkAU.3ATP9ObutL7bEnKzrhB5UU2pUQPqRVHDydpm_7vnM5c'
}),
userID: 'YOUR_USER_ID',
username: 'Web Chat User',
locale: 'en-US'
},
document.getElementById('webchat')
);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>
ILens-Assistant
</title>
<meta charset="UTF-8">
<link href="https://cdn.botframework.com/botframework-webchat/latest/botchat.css" rel="stylesheet" />
</head>
<body>
<div id="bot" />
<script src="https://cdn.botframework.com/botframework-webchat/latest/botchat.js"></script>
<script src="https://cdn.botframework.com/botframework-webchat/latest/CognitiveServices.js"></script>
<script>
function guid() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
var userId = guid().toUpperCase();
var userName = 'User-' + Math.floor((1 + Math.random()) * 10000);
var secret = 'JAf_VV4dubo.v3qoxVXaQXqDtRoDsxF-J7zcvXT0qKgI8V6-dWLCcDk';
var user = {
id: userId,
name: userName
};
var bot = {
id: 'Demo-WebAppBot',
name: ' Demo ChatBot'
};
var botConnection = new BotChat.DirectLine({
secret: secret,
webSocket: true
});
console.log(botConnection);
const speechOptions = {
speechRecognizer: new BotChat.Speech.BrowserSpeechRecognizer(),
speechSynthesizer: new BotChat.Speech.BrowserSpeechSynthesizer()
};
BotChat.App({
botConnection: botConnection,
user: user,
bot: bot,
resize: 'detect',
speechOptions: speechOptions
}, document.getElementById("bot"));
console.log("hiii");
<!-- Conversation is initiated here by sending a dummy message to the bot -->
botConnection.postActivity({ type: "event", from: user, name: "firstMessage", value: "ping" }).subscribe(id => console.log("Conversation updated"));
// botConnection.postActivity({ type: "endActivity", from: { id: 'Bot' }, name: 'endActivity', value: "The user has closed the session", }).subscribe(id => console.log("Conversation sent"));
//botConnection.endActivity;
//botConnection.endConversation;
window.addEventListener('beforeunload', (event) => {
event.returnValue = `Are you sure you want to leave?`;
});
</script>
</body>
</html>
\ No newline at end of file
botbuilder-integration-aiohttp>=4.13.0
botbuilder-dialogs>=4.13.0
botbuilder-ai>=4.13.0
datatypes-date-time>=1.0.0.a2
requests
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class UserProfile:
def __init__(
self,
hat: bool = None,
vest: bool = None,
boots: bool = None,
goggles: bool = None,
start: bool = False,
card: bool = False,
change_in_sound: bool = False,
discoloration: bool = False,
fair: bool = False,
good: bool = False,
leak: bool = False,
not_applicable: bool = False,
risk: bool = False,
safe: bool = False,
quality: bool = False,
):
self.hat = hat
self.vest = vest
self.boots = boots
self.goggles = goggles
self.start = start
self.card = card
self.change_in_sound = change_in_sound
self.discoloration = discoloration
self.fair = fair
self.good = good
self.leak = leak
self.not_applicable = not_applicable
self.risk = risk
self.safe = safe
self.quality = quality
{
"liveServer.settings.port": 5501
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment