diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index 8600166fe0f3..98a2a961393d 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -1357,10 +1357,6 @@ packages: resolution: {integrity: sha512-DxOSLua+NdpWoSqULhjDyAZTXFdP/LKkqtYuxxz1SCN289zk3OG8UOpnCQAz/tygyACBtWp/BoO72ptK7msY8g==} engines: {node: '>=18.0.0'} - '@azure/core-xml@1.4.5': - resolution: {integrity: sha512-gT4H8mTaSXRz7eGTuQyq1aIJnJqeXzpOe9Ay7Z3FrCouer14CbV3VzjnJrNrQfbBpGBLO9oy8BmrY75A0p53cA==} - engines: {node: '>=18.0.0'} - '@azure/functions@3.5.1': resolution: {integrity: sha512-6UltvJiuVpvHSwLcK/Zc6NfUwlkDLOFFx97BHCJzlWNsfiWwzwmTsxJXg4kE/LemKTHxPpfoPE+kOJ8hAdiKFQ==} @@ -1440,10 +1436,6 @@ packages: resolution: {integrity: sha512-IzD+hfqGqFtXymHXm4RzrZW2MsSH2M7RLmZsKaKVi7SUxbeYTUeX+ALk8gVzkM8ykb7EzlDLWCNErKfAa57rYQ==} engines: {node: '>=18.0.0'} - '@azure/storage-file-share@12.26.0': - resolution: {integrity: sha512-o/cvWx+904JqK1OjG4/lrnDXZMwSsnPEnlKtJVcx1XntTsthCejA6ZMHJMCEU0yiu4wJ8Q+Bp5a8zEdzkRZIVQ==} - engines: {node: '>=18.0.0'} - '@azure/template@1.0.13-beta.1': resolution: {integrity: sha512-dn0mqAC4jPUbqAOUxdkVNihu1rV6Na7rX8xtwU2LI0JKlZJXOULxzDR4Zyc02s5aUdLpRkyxGoGStdkc+dJC4w==} engines: {node: '>=18.0.0'} @@ -2434,7 +2426,7 @@ packages: version: 0.0.0 '@rush-temp/ai-vision-face@file:projects/ai-vision-face.tgz': - resolution: {integrity: sha512-+04d00UxdRr7CBMBVQze1z+6nMoCXnXDGeatQ21+Y1zHaFXBghTfiXGyEV2fs4tBjAxirn55a0WK7CheUTeWcQ==, tarball: file:projects/ai-vision-face.tgz} + resolution: {integrity: sha512-rsDgElH/xNJzHinjNO6E5ia27/qtVow92qsRyRXnupQq8FH8hEyU/XPV12knyrH9/CtiD7bAwcA/CAgCfJcmKg==, tarball: file:projects/ai-vision-face.tgz} version: 0.0.0 '@rush-temp/ai-vision-image-analysis@file:projects/ai-vision-image-analysis.tgz': @@ -3866,7 +3858,7 @@ packages: version: 0.0.0 '@rush-temp/perf-storage-file-share@file:projects/perf-storage-file-share.tgz': - resolution: {integrity: sha512-8wCFKHwG4f1OaVLGPs1ZHUoBpHnbOmtqyvFSDVKCtnpuy3bnxTdK+wdjE6uWuvHOxOv9xSJyTS2ekQhcvFs6Aw==, tarball: file:projects/perf-storage-file-share.tgz} + resolution: {integrity: sha512-0EmfhpZnjn3yxng5UYDMwxKPkiHYwkeNJFHwLPxayGzJhiiRgd5cNIM4Pvh5UNSIHIcSJVXltoazvBY/Pmrh1w==, tarball: file:projects/perf-storage-file-share.tgz} version: 0.0.0 '@rush-temp/perf-template@file:projects/perf-template.tgz': @@ -3926,7 +3918,7 @@ packages: version: 0.0.0 '@rush-temp/storage-file-datalake@file:projects/storage-file-datalake.tgz': - resolution: {integrity: sha512-cjeUa7EgqQ1nhsJYVM/yhMUosEinE++tWwgkm5DpeZ7j1M2phPqKE/M5auu209emar9WER/UgBIB/A350a9GpA==, tarball: file:projects/storage-file-datalake.tgz} + resolution: {integrity: sha512-AwMwBu+HEpNMO73vrFi36Li/brUqekXTJr5yVgYm2NX9FD1OsROC6Za3ChVTfzaotO8hEmCvrnBklm0n/QT24w==, tarball: file:projects/storage-file-datalake.tgz} version: 0.0.0 '@rush-temp/storage-file-share@file:projects/storage-file-share.tgz': @@ -8298,11 +8290,6 @@ snapshots: '@azure/abort-controller': 2.1.2 tslib: 2.8.1 - '@azure/core-xml@1.4.5': - dependencies: - fast-xml-parser: 5.0.9 - tslib: 2.8.1 - '@azure/functions@3.5.1': dependencies: iconv-lite: 0.6.3 @@ -8490,23 +8477,6 @@ snapshots: transitivePeerDependencies: - supports-color - '@azure/storage-file-share@12.26.0': - dependencies: - '@azure/abort-controller': 2.1.2 - '@azure/core-auth': 1.9.0 - '@azure/core-client': 1.9.3 - '@azure/core-http-compat': 2.2.0 - '@azure/core-paging': 1.6.2 - '@azure/core-rest-pipeline': 1.19.1 - '@azure/core-tracing': 1.2.0 - '@azure/core-util': 1.11.0 - '@azure/core-xml': 1.4.5 - '@azure/logger': 1.1.4 - events: 3.3.0 - tslib: 2.8.1 - transitivePeerDependencies: - - supports-color - '@azure/template@1.0.13-beta.1': dependencies: '@azure/core-auth': 1.9.0 @@ -10105,14 +10075,13 @@ snapshots: '@rush-temp/ai-vision-face@file:projects/ai-vision-face.tgz(@types/debug@4.1.12)(msw@2.7.3(@types/node@22.7.9)(typescript@5.8.2))(tsx@4.19.3)(vite@6.2.2(@types/node@22.7.9)(tsx@4.19.3)(yaml@2.7.0))(yaml@2.7.0)': dependencies: '@types/node': 18.19.80 - '@vitest/browser': 3.0.9(@types/node@18.19.80)(playwright@1.51.1)(typescript@5.8.2)(vite@6.2.2(@types/node@22.7.9)(tsx@4.19.3)(yaml@2.7.0))(vitest@3.0.9) + '@vitest/browser': 3.0.9(@types/node@18.19.80)(playwright@1.51.1)(typescript@5.6.3)(vite@6.2.2(@types/node@22.7.9)(tsx@4.19.3)(yaml@2.7.0))(vitest@3.0.9) '@vitest/coverage-istanbul': 3.0.9(vitest@3.0.9) dotenv: 16.4.7 eslint: 9.22.0 playwright: 1.51.1 - prettier: 3.5.3 tslib: 2.8.1 - typescript: 5.8.2 + typescript: 5.6.3 vitest: 3.0.9(@types/debug@4.1.12)(@types/node@18.19.80)(@vitest/browser@3.0.9)(msw@2.7.3(@types/node@22.7.9)(typescript@5.8.2))(tsx@4.19.3)(yaml@2.7.0) transitivePeerDependencies: - '@edge-runtime/vm' @@ -22227,7 +22196,6 @@ snapshots: '@rush-temp/perf-storage-file-share@file:projects/perf-storage-file-share.tgz': dependencies: - '@azure/storage-file-share': 12.26.0 '@types/node': 18.19.80 dotenv: 16.4.7 eslint: 9.22.0 diff --git a/sdk/face/ai-vision-face-rest/CHANGELOG.md b/sdk/face/ai-vision-face-rest/CHANGELOG.md index 50b2f383e26f..a6129d696d05 100644 --- a/sdk/face/ai-vision-face-rest/CHANGELOG.md +++ b/sdk/face/ai-vision-face-rest/CHANGELOG.md @@ -1,46 +1,7 @@ # Release History - -## 1.0.0-beta.3 (2025-02-03) - -### Breaking Changes - -- Added support for latest Detect Liveness Session API - - Revised the naming of the liveness session operation paths. - - Revised the response schema of the liveness session operations. - - Removed the `audit` and `list` liveness session operations as they are not supported in the v1.2 versions of the API. - - Revise the `CreateLivenessWithVerify` session call request schema to remove the `Parameters` JSON body and replace with individual parameters instead. -- Removed Person Directory APIs as they are not GAed. - -## 1.0.0-beta.2 (2024-10-14) - -This library now supports the Azure AI Face v1.2-preview.1 API. - -### Features Added - -- Added support for latest Detect Liveness Session API - - New face detection operation: [Detect From Session Image Id](https://learn.microsoft.com/rest/api/face/face-detection-operations/detect-from-session-image-id?view=rest-face-v1.2-preview.1) using `DetectFromSessionImageIdParameters`. - - New liveness session operation: [Get Session Image](https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-session-image?view=rest-face-v1.2-preview.1). - - New properties `enableSessionImage?: boolean`, `livenessSingleModalModel?: LivenessModel` to `CreateLivenessSessionContent`. - - New model `CreateLivenessWithVerifySessionJsonContent` for liveness session operations [Create Liveness With Verify Session](https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-with-verify-session?view=rest-face-v1.2-preview.1) and [Create Liveness With Verify Session With Verify Image](https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-with-verify-session-with-verify-image?view=rest-face-v1.2-preview.1). - -## 1.0.0-beta.1 (2024-05-23) - -This is the first preview of the Azure Face Service client library `@azure-rest/ai-vision-face` that follows the [TypeScript Azure SDK Design Guidelines](https://azure.github.io/azure-sdk/typescript_introduction.html). -This library replaces the package [@azure/cognitiveservices-face](https://www.npmjs.com/package/@azure/cognitiveservices-face). - -This package's [documentation](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/face/ai-vision-face-rest/README.md) and [samples](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/face/ai-vision-face-rest/samples) demonstrate the new API. + +## 1.0.0 (2025-03-18) ### Features Added -These are the new features not supported by the old package [@azure/cognitiveservices-face](https://www.npmjs.com/package/@azure/cognitiveservices-face). - -- Added support for Liveness Detection. -- Added support for `Person` and `DynamicPersonGroup` operations. -- Added support for face recognition with `PersonDirectory` by passing `IdentifyFromPersonDirectoryParameters` or `IdentifyFromDynamicPersonGroupParameters` to `/identify`. -- Added support for authentication with Microsoft Entra ID using `DefaultAzureCredential` from `@azure/identity`. - -### Breaking Changes - -- This library supports only the Azure AI Face v1.1-preview.1 API, whose data models are not compatible with the v1.0 API used by [@azure/cognitiveservices-face](https://www.npmjs.com/package/@azure/cognitiveservices-face). -- This library follows the design of [REST client](https://devblogs.microsoft.com/azure-sdk/azure-rest-libraries-for-javascript/), which is essentially different from [@azure/cognitiveservices-face](https://www.npmjs.com/package/@azure/cognitiveservices-face). -- The Snapshot operations are all removed as [the Snapshot API is no longer supported](https://azure.microsoft.com/updates/facelimitedaccess/). +The package of @azure-rest/ai-vision-face is using our next generation design principles. To learn more, please refer to our documentation [Quick Start](https://aka.ms/azsdk/js/mgmt/quickstart). diff --git a/sdk/face/ai-vision-face-rest/LICENSE b/sdk/face/ai-vision-face-rest/LICENSE index b2f52a2bad4e..63447fd8bbbf 100644 --- a/sdk/face/ai-vision-face-rest/LICENSE +++ b/sdk/face/ai-vision-face-rest/LICENSE @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +SOFTWARE. \ No newline at end of file diff --git a/sdk/face/ai-vision-face-rest/README.md b/sdk/face/ai-vision-face-rest/README.md index 61729b7cb0d7..5bc6eb93a234 100644 --- a/sdk/face/ai-vision-face-rest/README.md +++ b/sdk/face/ai-vision-face-rest/README.md @@ -1,20 +1,14 @@ -# Azure AI Face client library for JavaScript +# Azure Face REST client library for JavaScript -The Azure AI Face service provides AI algorithms that detect, recognize, and analyze human faces in images. It includes the following main features: +Face API REST Client -- Face detection and analysis -- Liveness detection -- Face recognition - - Face verification ("one-to-one" matching) - - Face identification ("one-to-many" matching) -- Find similar faces -- Group faces +**Please rely heavily on our [REST client docs](https://github.com/Azure/azure-sdk-for-js/blob/main/documentation/rest-clients.md) to use this library** -[Product documentation](https://learn.microsoft.com/azure/ai-services/computer-vision/overview-identity) -| [Source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/face/ai-vision-face-rest) -| [Package (NPM)](https://www.npmjs.com/package/@azure-rest/ai-vision-face) -| [Samples](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/face/ai-vision-face-rest/samples) -| [API reference documentation](https://aka.ms/azsdk-javascript-face-ref) +Key links: + +- [Source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/face/ai-vision-face-rest) +- [Package (NPM)](https://www.npmjs.com/package/@azure-rest/ai-vision-face) +- [API reference documentation](https://learn.microsoft.com/javascript/api/@azure-rest/ai-vision-face?view=azure-node-preview) ## Getting started @@ -22,450 +16,32 @@ The Azure AI Face service provides AI algorithms that detect, recognize, and ana - LTS versions of Node.js -See our [support policy](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) for more details. - ### Prerequisites -- An [Azure subscription](https://azure.microsoft.com/free/). -- Your Azure account must have a `Cognitive Services Contributor` role assigned in order for you to agree to the responsible AI terms and create a resource. To get this role assigned to your account, follow the steps in the [Assign roles](https://learn.microsoft.com/azure/role-based-access-control/role-assignments-steps) documentation, or contact your administrator. -- Once you have sufficient permissions to control your Azure subscription, you need either - - an [Azure Face account](https://portal.azure.com/#blade/Microsoft_Azure_ProjectOxford/CognitiveServicesHub/Face) or - - an [Azure AI services multi-service account](https://portal.azure.com/#view/Microsoft_Azure_ProjectOxford/CognitiveServicesHub/~/AllInOne) - -### Create a Face or an Azure AI services multi-service account - -Azure AI Face supports both [multi-service](https://learn.microsoft.com/azure/ai-services/multi-service-resource?tabs=windows&pivots=azportal#supported-services-with-a-multi-service-resource) and single-service access. Create an Azure AI services multi-service account if you plan to access multiple Azure AI services under a single endpoint/key. For Face access only, create a Face resource. +- You must have an [Azure subscription](https://azure.microsoft.com/free/) to use this package. -- To create a new Face or Azure AI services multi-service account, you can use [Azure Portal](https://ms.portal.azure.com/#create/Microsoft.CognitiveServicesFace), [Azure PowerShell](https://learn.microsoft.com/azure/ai-services/multi-service-resource?tabs=windows&pivots=azpowershell), or [Azure CLI](https://learn.microsoft.com/azure/ai-services/multi-service-resource?tabs=windows&pivots=azcli). +### Install the `@azure-rest/ai-vision-face` package -### Install the package - -Install the Azure Face REST client library for JavaScript with `npm`: +Install the Azure Face REST client REST client library for JavaScript with `npm`: ```bash npm install @azure-rest/ai-vision-face ``` -### Authenticate the client - -In order to interact with the Face service, you will need to create an instance of a client. -An **endpoint** and **credential** are necessary to instantiate the client object. - -Both key credential and Microsoft Entra ID credential are supported to authenticate the client. -For enhanced security, we strongly recommend utilizing Microsoft Entra ID credential for authentication in the production environment, while AzureKeyCredential should be reserved exclusively for the testing environment. - -#### Get the endpoint - -You can find the endpoint for your Face resource using the Azure Portal or Azure CLI: - -```bash -# Get the endpoint for the Face resource -az cognitiveservices account show --name "resource-name" --resource-group "resource-group-name" --query "properties.endpoint" -``` - -Either a regional endpoint or a custom subdomain can be used for authentication. They are formatted as follows: - -``` -Regional endpoint: https://.api.cognitive.microsoft.com/ -Custom subdomain: https://.cognitiveservices.azure.com/ -``` - -A regional endpoint is the same for every resource in a region. A complete list of supported regional endpoints can be consulted [here](https://azure.microsoft.com/global-infrastructure/services/?products=cognitive-services). Please note that regional endpoints do not support Microsoft Entra ID authentication. If you'd like migrate your resource to use custom subdomain, follow the instructions [here](https://learn.microsoft.com/azure/ai-services/cognitive-services-custom-subdomains#how-does-this-impact-existing-resources). - -A custom subdomain, on the other hand, is a name that is unique to the resource. Once created and linked to a resource, it cannot be modified. - -#### Create the client with a Microsoft Entra ID credential - -`AzureKeyCredential` authentication is used in the examples in this getting started guide, but you can also authenticate with Microsoft Entra ID using the [@azure/identity](https://learn.microsoft.com/javascript/api/@azure/identity/?view=azure-node-latest) library. -Note that regional endpoints do not support Microsoft Entra ID authentication. Create a [custom subdomain](https://learn.microsoft.com/azure/cognitive-services/authentication#create-a-resource-with-a-custom-subdomain) name for your resource in order to use this type of authentication. - -To use the [DefaultAzureCredential](https://learn.microsoft.com/javascript/api/@azure/identity/defaultazurecredential?view=azure-node-latest) type shown below, or other credential types provided with the Azure SDK, please install the `@azure/identity` package: - -``` -npm install --save @azure/identity -``` - -You will also need to [register a new Microsoft Entra ID application and grant access](https://learn.microsoft.com/azure/cognitive-services/authentication#assign-a-role-to-a-service-principal) to Face by assigning the `"Cognitive Services User"` role to your service principal. - -Once completed, set the values of the client ID, tenant ID, and client secret of the Microsoft Entra ID application as environment variables: -`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET`. - -```ts snippet:ReadmeSampleCreateClient_Entra -import { DefaultAzureCredential } from "@azure/identity"; -import FaceClient from "@azure-rest/ai-vision-face"; - -const endpoint = process.env["FACE_ENDPOINT"] || ""; -const credential = new DefaultAzureCredential(); -const client = FaceClient(endpoint, credential); -``` - -#### Create the client with AzureKeyCredential - -To use an API key as the `credential` parameter, pass the key as a string into an instance of [AzureKeyCredential](https://learn.microsoft.com/javascript/api/@azure/core-auth/azurekeycredential?view=azure-node-latest). -You can get the API key for your Face resource using the [Azure Portal](https://learn.microsoft.com/azure/ai-services/multi-service-resource?tabs=windows&pivots=azportal#get-the-keys-for-your-resource) or [Azure CLI](https://learn.microsoft.com/azure/ai-services/multi-service-resource?tabs=windows&pivots=azcli#get-the-keys-for-your-resource): - -```bash -# Get the API keys for the Face resource -az cognitiveservices account keys list --name "" --resource-group "" -``` - -```ts snippet:ReadmeSampleCreateClient_KeyCredential -import { AzureKeyCredential } from "@azure/core-auth"; -import FaceClient from "@azure-rest/ai-vision-face"; - -const endpoint = process.env["FACE_ENDPOINT"] || ""; -const apikey = process.env["FACE_APIKEY"] || ""; -const credential = new AzureKeyCredential(apikey); -const client = FaceClient(endpoint, credential); -``` - -## Key concepts - -### FaceClient - -The `FaceClient` is the primary interface for developers interacting with the Azure AI Face service. It follows the design of [REST client](https://devblogs.microsoft.com/azure-sdk/azure-rest-libraries-for-javascript/) and serves as the gateway from which all interaction with the library will occur. - -### Long-running operations - -Long-running operations are operations which consist of an initial request sent to the service to start an operation, followed by polling the service at intervals to determine whether the operation has completed or failed, and if it has succeeded, to get the result. For more information, please refer to the "Long-running operations" section in this [blog post](https://devblogs.microsoft.com/azure-sdk/azure-rest-libraries-for-javascript/). - -Current long-running face operations: - -- Face list operations - - [Train large face list](https://learn.microsoft.com/rest/api/face/face-list-operations/train-large-face-list?view=rest-face-v1.1-preview.1&tabs=HTTP) -- Person group operations - - [Train large person group](https://learn.microsoft.com/rest/api/face/person-group-operations/update-large-person-group?view=rest-face-v1.1-preview.1&tabs=HTTP) - - [Train person group](https://learn.microsoft.com/rest/api/face/person-group-operations/train-person-group?view=rest-face-v1.1-preview.1&tabs=HTTP) - -## Examples - -The following section provides several code snippets covering some of the most common Face tasks, including: - -- [Detecting faces in an image](#face-detection "Face Detection") -- [Identifing the specific face from a LargePersonGroup](#face-recognition-from-largepersongroup "Face Recognition from LargePersonGroup") -- [Determining if a face in an video is real (live) or fake (spoof)](#liveness-detection "Liveness Detection") - -### Face Detection - -Detect faces and analyze them from an binary data. - -```ts snippet:ReadmeSampleFaceDetection -import { DefaultAzureCredential } from "@azure/identity"; -import FaceClient, { isUnexpected } from "@azure-rest/ai-vision-face"; -import { readFileSync } from "node:fs"; - -const endpoint = process.env["FACE_ENDPOINT"] || ""; -const credential = new DefaultAzureCredential(); -const client = FaceClient(endpoint, credential); - -const response = await client.path("/detect").post({ - contentType: "application/octet-stream", - queryParameters: { - detectionModel: "detection_03", - recognitionModel: "recognition_04", - returnFaceLandmarks: true, - returnRecognitionModel: true, - faceIdTimeToLive: 120, - returnFaceAttributes: ["headPose", "mask", "qualityForRecognition"], - returnFaceId: false, - }, - body: readFileSync("path/to/test/image"), -}); - -if (isUnexpected(response)) { - throw new Error(response.body.error.message); -} - -console.log(response.body); -``` - -### Face Recognition from LargePersonGroup - -Identify a face against a defined LargePersonGroup. - -First, we have to create a LargePersonGroup, add a few Persons to it, and then register faces with these Persons. - -```ts snippet:ReadmeSampleFaceRecognitionFromLargePersonGroup -import { DefaultAzureCredential } from "@azure/identity"; -import FaceClient, { isUnexpected } from "@azure-rest/ai-vision-face"; -import { readFileSync } from "node:fs"; - -const endpoint = process.env["FACE_ENDPOINT"] || ""; -const credential = new DefaultAzureCredential(); -const client = FaceClient(endpoint, credential); - -const largePersonGroupId = "lpg_family"; - -console.log(`Create a large person group with id: ${largePersonGroupId}`); -const createLargePersonGroupResponse = await client - .path("/largepersongroups/{largePersonGroupId}", largePersonGroupId) - .put({ - body: { - name: "My Family", - recognitionModel: "recognition_04", - }, - }); - -console.log("Create a Person Bill and add a face to him."); -const createLargePersonGroupPersonResponse_bill = await client - .path("/largepersongroups/{largePersonGroupId}/persons", largePersonGroupId) - .post({ - body: { - name: "Bill", - userData: "Dad", - }, - }); - -if (isUnexpected(createLargePersonGroupPersonResponse_bill)) { - throw new Error(createLargePersonGroupPersonResponse_bill.body.error.message); -} - -const personId_bill = createLargePersonGroupPersonResponse_bill.body.personId; -await client - .path( - "/largepersongroups/{largePersonGroupId}/persons/{personId}/persistedfaces", - largePersonGroupId, - personId_bill, - ) - .post({ - queryParameters: { - userData: "Dad-0001", - detectionModel: "detection_03", - }, - contentType: "application/octet-stream", - body: readFileSync("path/to/bill/image"), - }); - -console.log("Create a Person Clare and add a face to her."); -const createLargePersonGroupPersonResponse_clare = await client - .path("/largepersongroups/{largePersonGroupId}/persons", largePersonGroupId) - .post({ - body: { - name: "Clare", - userData: "Mom", - }, - }); - -if (isUnexpected(createLargePersonGroupPersonResponse_clare)) { - throw new Error(createLargePersonGroupPersonResponse_clare.body.error.message); -} - -const personId_clare = createLargePersonGroupPersonResponse_clare.body.personId; -await client - .path( - "/largepersongroups/{largePersonGroupId}/persons/{personId}/persistedfaces", - largePersonGroupId, - personId_clare, - ) - .post({ - queryParameters: { - userData: "Mom-0001", - detectionModel: "detection_03", - }, - contentType: "application/octet-stream", - body: readFileSync("path/to/clare/image"), - }); -``` - -Before doing the identification, we must train the LargePersonGroup first. - -```ts snippet:ReadmeSampleFaceRecognitionFromLargePersonGroup_Train -import { DefaultAzureCredential } from "@azure/identity"; -import FaceClient, { getLongRunningPoller } from "@azure-rest/ai-vision-face"; - -const endpoint = process.env["FACE_ENDPOINT"] || ""; -const credential = new DefaultAzureCredential(); -const client = FaceClient(endpoint, credential); - -const largePersonGroupId = "lpg_family"; - -console.log(`Start to train the large person group: ${largePersonGroupId}`); -const trainResponse = await client - .path("/largepersongroups/{largePersonGroupId}/train", largePersonGroupId) - .post(); -const trainPoller = await getLongRunningPoller(client, trainResponse); -await trainPoller.pollUntilDone(); -``` - -When the training operation is completed successfully, we can identify the faces in this LargePersonGroup throught. - -```ts snippet:ReadmeSampleFaceRecognitionFromLargePersonGroup_Identify -import { DefaultAzureCredential } from "@azure/identity"; -import FaceClient, { isUnexpected } from "@azure-rest/ai-vision-face"; -import { readFileSync } from "node:fs"; - -const endpoint = process.env["FACE_ENDPOINT"] || ""; -const credential = new DefaultAzureCredential(); -const client = FaceClient(endpoint, credential); - -const largePersonGroupId = "lpg_family"; - -console.log("Detect faces from the target image."); -const detectResponse = await client.path("/detect").post({ - contentType: "application/octet-stream", - queryParameters: { - detectionModel: "detection_03", - recognitionModel: "recognition_04", - returnFaceId: true, - }, - body: readFileSync("path/to/target/image"), -}); - -if (isUnexpected(detectResponse)) { - throw new Error(detectResponse.body.error.message); -} - -const faceIds = detectResponse.body.map((face) => face.faceId as string); - -console.log("Identify the faces in the large person group."); - -const identifyResponse = await client.path("/identify").post({ - body: { faceIds, largePersonGroupId }, -}); - -if (isUnexpected(identifyResponse)) { - throw new Error(identifyResponse.body.error.message); -} - -console.log(identifyResponse.body); -``` - -Finally, remove the large person group if you don't need it anymore. - -```ts snippet:ReadmeSampleFaceRecognitionFromLargePersonGroup_Delete -import { DefaultAzureCredential } from "@azure/identity"; -import FaceClient from "@azure-rest/ai-vision-face"; - -const endpoint = process.env["FACE_ENDPOINT"] || ""; -const credential = new DefaultAzureCredential(); -const client = FaceClient(endpoint, credential); - -const largePersonGroupId = "lpg_family"; - -console.log(`Delete the large person group: ${largePersonGroupId}`); -await client.path("/largepersongroups/{largePersonGroupId}", largePersonGroupId).delete(); -``` - -### Liveness detection - -Face Liveness detection can be used to determine if a face in an input video stream is real (live) or fake (spoof). -The goal of liveness detection is to ensure that the system is interacting with a physically present live person at -the time of authentication. The whole process of authentication is called a session. - -There are two different components in the authentication: a frontend application and an app server/orchestrator. -Before uploading the video stream, the app server has to create a session, and then the frontend client could upload -the payload with a `session authorization token` to call the liveness detection. The app server can query for the -liveness detection result and audit logs anytime until the session is deleted. - -The Liveness detection operation can not only confirm if the input is live or spoof, but also verify whether the input -belongs to the expected person's face, which is called **liveness detection with face verification**. For the detail -information, please refer to the [tutorial](https://learn.microsoft.com/azure/ai-services/computer-vision/tutorials/liveness). - -This package is only responsible for app server to create, query, delete a session and get audit logs. For how to -integrate the UI and the code into your native frontend application, please follow instructions in the [tutorial](https://learn.microsoft.com/azure/ai-services/computer-vision/tutorials/liveness). - -Here is an example to create and get the liveness detection result of a session. - -```ts snippet:ReadmeSampleLivenessDetection -import { DefaultAzureCredential } from "@azure/identity"; -import FaceClient, { isUnexpected } from "@azure-rest/ai-vision-face"; -import { randomUUID } from "node:crypto"; - -const endpoint = process.env["FACE_ENDPOINT"] || ""; -const credential = new DefaultAzureCredential(); -const client = FaceClient(endpoint, credential); - -console.log("Create a new liveness session."); -const createLivenessSessionResponse = await client - .path("/detectLiveness-sessions") - .post({ - body: { - livenessOperationMode: "Passive", - deviceCorrelationId: randomUUID(), - enableSessionImage: true, - }, - }); - -if (isUnexpected(createLivenessSessionResponse)) { - throw new Error(createLivenessSessionResponse.body.error.message); -} -console.log(createLivenessSessionResponse.body); - -const { sessionId } = createLivenessSessionResponse.body; - -console.log("Get liveness detection results."); -const getLivenessSessionResponse = await client - .path("/detectLiveness-sessions/{sessionId}", sessionId) - .get(); - -if (isUnexpected(getLivenessSessionResponse)) { - throw new Error(getLivenessSessionResponse.body.error.message); -} -console.log(getLivenessSessionResponse.body); -``` - -Here is another example for the liveness detection with face verification. - -```ts snippet:ReadmeSampleLivenessDetectionWithVerify -import { DefaultAzureCredential } from "@azure/identity"; -import FaceClient, { isUnexpected } from "@azure-rest/ai-vision-face"; -import { readFileSync } from "node:fs"; -import { randomUUID } from "node:crypto"; +### Create and authenticate a `FaceClient` -const endpoint = process.env["FACE_ENDPOINT"] || ""; -const credential = new DefaultAzureCredential(); -const client = FaceClient(endpoint, credential); +To use an [Azure Active Directory (AAD) token credential](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-with-a-pre-fetched-access-token), +provide an instance of the desired credential type obtained from the +[@azure/identity](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#credentials) library. -console.log("Create a new liveness with verify session with verify image."); -const createLivenessSessionResponse = await client - .path("/detectLivenessWithVerify-sessions") - .post({ - contentType: "multipart/form-data", - body: [ - { - name: "verifyImage", - body: readFileSync("path/to/verify/image"), - filename: "verifyImage.jpg", - }, - { - name: "livenessOperationMode", - body: "Passive", - }, - { - name: "deviceCorrelationId", - body: randomUUID(), - }, - { - name: "enableSessionImage", - body: true, - }, - ], - }); +To authenticate with AAD, you must first `npm` install [`@azure/identity`](https://www.npmjs.com/package/@azure/identity) -if (isUnexpected(createLivenessSessionResponse)) { - throw new Error(createLivenessSessionResponse.body.error.message); -} -console.log(createLivenessSessionResponse.body); - -const { sessionId } = createLivenessSessionResponse.body; - -console.log("Get the liveness detection and verification result."); -const getLivenessSessionResultResponse = await client - .path("/detectLivenessWithVerify-sessions/{sessionId}", sessionId) - .get(); - -if (isUnexpected(getLivenessSessionResultResponse)) { - throw new Error(getLivenessSessionResultResponse.body.error.message); -} -console.log(getLivenessSessionResultResponse.body); -``` +After setup, you can choose which type of [credential](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#credentials) from `@azure/identity` to use. +As an example, [DefaultAzureCredential](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#defaultazurecredential) +can be used to authenticate the client. ## Troubleshooting -### General - -Error codes and messages raised by the Face service can be found in the [service documentation](https://aka.ms/face-error-codes-and-messages). - ### Logging Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the `AZURE_LOG_LEVEL` environment variable to `info`. Alternatively, logging can be enabled at runtime by calling `setLogLevel` in the `@azure/logger`: @@ -477,30 +53,3 @@ setLogLevel("info"); ``` For more detailed instructions on how to enable logs, you can look at the [@azure/logger package docs](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/logger). - -## Next steps - -### More sample code - -See the [Sample README](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/face/ai-vision-face-rest/samples) for several code snippets illustrating common patterns used in the Face JavaScript API. - -### Additional documentation - -For more extensive documentation on Azure AI Face, see the [Face documentation](https://learn.microsoft.com/azure/ai-services/computer-vision/overview-identity) on learn.microsoft.com. - -## Contributing - -This project welcomes contributions and suggestions. Most contributions require -you to agree to a Contributor License Agreement (CLA) declaring that you have -the right to, and actually do, grant us the rights to use your contribution. -For details, visit https://cla.microsoft.com. - -When you submit a pull request, a CLA-bot will automatically determine whether -you need to provide a CLA and decorate the PR appropriately (e.g., label, -comment). Simply follow the instructions provided by the bot. You will only -need to do this once across all repos using our CLA. - -This project has adopted the -[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information, -see the Code of Conduct FAQ or contact opencode@microsoft.com with any -additional questions or comments. diff --git a/sdk/face/ai-vision-face-rest/api-extractor.json b/sdk/face/ai-vision-face-rest/api-extractor.json index 7df8f550ad22..f45cda543122 100644 --- a/sdk/face/ai-vision-face-rest/api-extractor.json +++ b/sdk/face/ai-vision-face-rest/api-extractor.json @@ -1,6 +1,6 @@ { "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", - "mainEntryPointFilePath": "dist/esm/index.d.ts", + "mainEntryPointFilePath": "./dist/esm/index.d.ts", "docModel": { "enabled": true }, @@ -11,7 +11,7 @@ "dtsRollup": { "enabled": true, "untrimmedFilePath": "", - "publicTrimmedFilePath": "dist/ai-vision-face.d.ts" + "publicTrimmedFilePath": "./types/ai-vision-face.d.ts" }, "messages": { "tsdocMessageReporting": { @@ -28,4 +28,4 @@ } } } -} +} \ No newline at end of file diff --git a/sdk/face/ai-vision-face-rest/assets.json b/sdk/face/ai-vision-face-rest/assets.json deleted file mode 100644 index 0547d1444645..000000000000 --- a/sdk/face/ai-vision-face-rest/assets.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "AssetsRepo": "Azure/azure-sdk-assets", - "AssetsRepoPrefixPath": "js", - "TagPrefix": "js/face/ai-vision-face-rest", - "Tag": "js/face/ai-vision-face-rest_2e18119368" -} diff --git a/sdk/face/ai-vision-face-rest/eslint.config.mjs b/sdk/face/ai-vision-face-rest/eslint.config.mjs index d7dafe8e8d4d..6d2f8a5914c3 100644 --- a/sdk/face/ai-vision-face-rest/eslint.config.mjs +++ b/sdk/face/ai-vision-face-rest/eslint.config.mjs @@ -3,8 +3,12 @@ import azsdkEslint from "@azure/eslint-plugin-azure-sdk"; export default azsdkEslint.config([ { rules: { - "tsdoc/syntax": "warn", "@azure/azure-sdk/ts-modules-only-named": "warn", + "@azure/azure-sdk/ts-package-json-types": "warn", + "@azure/azure-sdk/ts-package-json-engine-is-present": "warn", + "@azure/azure-sdk/ts-package-json-files-required": "off", + "@azure/azure-sdk/ts-package-json-main-is-cjs": "off", + "tsdoc/syntax": "warn", }, }, ]); diff --git a/sdk/face/ai-vision-face-rest/package.json b/sdk/face/ai-vision-face-rest/package.json index b679f637aad5..8548fcb82de3 100644 --- a/sdk/face/ai-vision-face-rest/package.json +++ b/sdk/face/ai-vision-face-rest/package.json @@ -1,6 +1,6 @@ { "name": "@azure-rest/ai-vision-face", - "version": "1.0.0-beta.3", + "version": "1.0.0", "description": "Face API REST Client", "engines": { "node": ">=18.0.0" @@ -55,11 +55,11 @@ ] }, "dependencies": { - "@azure-rest/core-client": "^2.1.0", + "@azure-rest/core-client": "^2.3.1", "@azure/abort-controller": "^2.1.2", "@azure/core-auth": "^1.9.0", - "@azure/core-lro": "^3.0.0", - "@azure/core-rest-pipeline": "^1.19.0", + "@azure/core-lro": "^3.1.0", + "@azure/core-rest-pipeline": "^1.19.1", "@azure/logger": "^1.1.4", "tslib": "^2.8.1" }, @@ -69,15 +69,14 @@ "@azure-tools/test-utils-vitest": "^1.0.0", "@azure/dev-tool": "^1.0.0", "@azure/eslint-plugin-azure-sdk": "^3.0.0", - "@azure/identity": "^4.6.0", + "@azure/identity": "^4.8.0", "@types/node": "^18.0.0", "@vitest/browser": "^3.0.9", "@vitest/coverage-istanbul": "^3.0.9", "dotenv": "^16.0.0", "eslint": "^9.9.0", - "playwright": "^1.50.1", - "prettier": "^3.2.5", - "typescript": "~5.8.2", + "playwright": "^1.51.1", + "typescript": "~5.6.2", "vitest": "^3.0.9" }, "scripts": { @@ -92,7 +91,7 @@ "generate:client": "echo skipped", "integration-test": "npm run integration-test:node && npm run integration-test:browser", "integration-test:browser": "echo skipped", - "integration-test:node": "dev-tool run test:vitest --esm", + "integration-test:node": "echo skipped", "lint": "eslint package.json api-extractor.json src test", "lint:fix": "eslint package.json api-extractor.json src test --fix --fix-type [problem,suggestion]", "minify": "dev-tool run vendored uglifyjs -c -m --comments --source-map \"content='./dist/index.js.map'\" -o ./dist/index.min.js ./dist/index.js", @@ -101,60 +100,33 @@ "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser && npm run integration-test:browser", "test:node": "npm run clean && dev-tool run build-package && npm run unit-test:node && npm run integration-test:node", "unit-test": "npm run unit-test:node && npm run unit-test:browser", - "unit-test:browser": "echo skipped", + "unit-test:browser": "npm run clean && dev-tool run build-package && dev-tool run build-test && dev-tool run test:vitest --browser", "unit-test:node": "dev-tool run test:vitest", "update-snippets": "dev-tool run update-snippets" }, - "//sampleConfiguration": { - "productName": "Face API", - "productSlugs": [ - "azure" - ], - "disableDocsMs": true, - "apiRefLink": "https://aka.ms/azsdk-javascript-face-ref", - "extraFiles": { - "./samples-dev/data/detection1.jpg": [ - "javascript/data/detection1.jpg", - "typescript/src/data/detection1.jpg" - ], - "./samples-dev/data/detection5.jpg": [ - "javascript/data/detection5.jpg", - "typescript/src/data/detection5.jpg" - ], - "./samples-dev/data/nine-faces.png": [ - "javascript/data/nine-faces.png", - "typescript/src/data/nine-faces.png" - ] - } - }, + "browser": "./dist/browser/index.js", + "react-native": "./dist/react-native/index.js", "exports": { "./package.json": "./package.json", ".": { "browser": { - "source": "./src/index.ts", "types": "./dist/browser/index.d.ts", "default": "./dist/browser/index.js" }, "react-native": { - "source": "./src/index.ts", "types": "./dist/react-native/index.d.ts", "default": "./dist/react-native/index.js" }, "import": { - "source": "./src/index.ts", "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { - "source": "./src/index.ts", "types": "./dist/commonjs/index.d.ts", "default": "./dist/commonjs/index.js" } } }, "main": "./dist/commonjs/index.js", - "types": "./dist/commonjs/index.d.ts", - "module": "./dist/esm/index.js", - "browser": "./dist/browser/index.js", - "react-native": "./dist/react-native/index.js" -} + "types": "./dist/commonjs/index.d.ts" +} \ No newline at end of file diff --git a/sdk/face/ai-vision-face-rest/sample.env b/sdk/face/ai-vision-face-rest/sample.env index 07ea63f6c25d..508439fc7d62 100644 --- a/sdk/face/ai-vision-face-rest/sample.env +++ b/sdk/face/ai-vision-face-rest/sample.env @@ -1,2 +1 @@ -FACE_ENDPOINT="" -FACE_APIKEY="" +# Feel free to add your own environment variables. \ No newline at end of file diff --git a/sdk/face/ai-vision-face-rest/samples-dev/aadAuth.ts b/sdk/face/ai-vision-face-rest/samples-dev/aadAuth.ts deleted file mode 100644 index d0aa234e5ede..000000000000 --- a/sdk/face/ai-vision-face-rest/samples-dev/aadAuth.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { readFileSync } from "node:fs"; -import { DefaultAzureCredential } from "@azure/identity"; -import createFaceClient, { isUnexpected } from "@azure-rest/ai-vision-face"; -import "dotenv/config"; - -/** - * This sample demonstrates how to authenticate FaceClient using Microsoft Entra ID. - * - * @summary Microsoft Entra ID authentication. - */ - -async function main(): Promise { - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const credential = new DefaultAzureCredential(); - const client = createFaceClient(endpoint, credential); - - const fileName = "data/detection1.jpg"; - const detectResponse = await client.path("/detect").post({ - contentType: "application/octet-stream", - queryParameters: { - detectionModel: "detection_03", - recognitionModel: "recognition_04", - returnFaceId: false, - }, - body: readFileSync(fileName), - }); - if (isUnexpected(detectResponse)) { - throw new Error(detectResponse.body.error.message); - } - console.log(`Detect: ${fileName}`); - console.log(JSON.stringify(detectResponse.body, null, 2)); -} - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples-dev/data/detection1.jpg b/sdk/face/ai-vision-face-rest/samples-dev/data/detection1.jpg deleted file mode 100644 index 8e80a0b71fbc..000000000000 Binary files a/sdk/face/ai-vision-face-rest/samples-dev/data/detection1.jpg and /dev/null differ diff --git a/sdk/face/ai-vision-face-rest/samples-dev/data/detection5.jpg b/sdk/face/ai-vision-face-rest/samples-dev/data/detection5.jpg deleted file mode 100644 index 919d2ad3296c..000000000000 Binary files a/sdk/face/ai-vision-face-rest/samples-dev/data/detection5.jpg and /dev/null differ diff --git a/sdk/face/ai-vision-face-rest/samples-dev/data/nine-faces.png b/sdk/face/ai-vision-face-rest/samples-dev/data/nine-faces.png deleted file mode 100644 index 9ce0fc21d0d0..000000000000 Binary files a/sdk/face/ai-vision-face-rest/samples-dev/data/nine-faces.png and /dev/null differ diff --git a/sdk/face/ai-vision-face-rest/samples-dev/detect.ts b/sdk/face/ai-vision-face-rest/samples-dev/detect.ts deleted file mode 100644 index 14c66fa5f602..000000000000 --- a/sdk/face/ai-vision-face-rest/samples-dev/detect.ts +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { readFileSync } from "node:fs"; -import { AzureKeyCredential } from "@azure/core-auth"; -import createFaceClient, { isUnexpected } from "@azure-rest/ai-vision-face"; -import "dotenv/config"; - -/** - * This sample demonstrates how to detect faces in an image through local file or URL. - * - * @summary Face detection. - */ - -async function detectFromImage(): Promise { - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const apikey = process.env["FACE_APIKEY"] ?? ""; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - const filename = "data/detection5.jpg"; - const response = await client.path("/detect").post({ - contentType: "application/octet-stream", - queryParameters: { - detectionModel: "detection_03", - recognitionModel: "recognition_04", - returnFaceLandmarks: true, - returnRecognitionModel: true, - faceIdTimeToLive: 120, - returnFaceAttributes: ["headPose", "mask", "qualityForRecognition"], - returnFaceId: false, - }, - body: readFileSync(filename), - }); - if (isUnexpected(response)) { - throw new Error(response.body.error.message); - } - console.log(`Detect from image: ${filename}`); - console.log(JSON.stringify(response.body, null, 2)); -} - -async function detectFromUrl(): Promise { - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const apikey = process.env["FACE_APIKEY"] ?? ""; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - const url = "https://aka.ms/facesampleurl"; - const response = await client.path("/detect").post({ - contentType: "application/json", - queryParameters: { - detectionModel: "detection_01", - recognitionModel: "recognition_04", - returnFaceLandmarks: true, - returnRecognitionModel: true, - faceIdTimeToLive: 120, - returnFaceAttributes: ["accessories", "glasses", "exposure", "noise"], - returnFaceId: false, - }, - body: { url }, - }); - if (isUnexpected(response)) { - throw new Error(response.body.error.message); - } - console.log(`Detect from URL: ${url}`); - console.log(JSON.stringify(response.body, null, 2)); -} - -async function main(): Promise { - await detectFromImage(); - await detectFromUrl(); -} - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples-dev/group.ts b/sdk/face/ai-vision-face-rest/samples-dev/group.ts deleted file mode 100644 index f346a0c3ecc0..000000000000 --- a/sdk/face/ai-vision-face-rest/samples-dev/group.ts +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { readFileSync } from "node:fs"; -import { AzureKeyCredential } from "@azure/core-auth"; -import createFaceClient, { isUnexpected } from "@azure-rest/ai-vision-face"; -import "dotenv/config"; - -/** - * This sample demonstrates how to group similar faces. - * - * @summary Face grouping. - */ - -async function main(): Promise { - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const apikey = process.env["FACE_APIKEY"] ?? ""; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - // Detect faces from image. - const filename = "data/nine-faces.png"; - const detectResponse = await client.path("/detect").post({ - contentType: "application/octet-stream", - queryParameters: { - detectionModel: "detection_03", - recognitionModel: "recognition_04", - returnFaceId: true, - }, - body: readFileSync(filename), - }); - if (isUnexpected(detectResponse)) { - throw new Error(detectResponse.body.error.message); - } - console.log(`Detect: ${filename}`); - console.log(JSON.stringify(detectResponse.body, null, 2)); - - // Group the faces. - const groupResponse = await client.path("/group").post({ - body: { - faceIds: detectResponse.body.map((face) => face.faceId as string), - }, - }); - if (isUnexpected(groupResponse)) { - throw new Error(groupResponse.body.error.message); - } - console.log("Group:"); - console.log(JSON.stringify(groupResponse.body, null, 2)); -} - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples-dev/livenessSession.ts b/sdk/face/ai-vision-face-rest/samples-dev/livenessSession.ts deleted file mode 100644 index acff28284e5c..000000000000 --- a/sdk/face/ai-vision-face-rest/samples-dev/livenessSession.ts +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { randomUUID } from "node:crypto"; -import { AzureKeyCredential } from "@azure/core-auth"; -import createFaceClient, { isUnexpected } from "@azure-rest/ai-vision-face"; -import "dotenv/config"; - -/** - * This sample demonstrates how to create a liveness detection session. - * - * @summary Liveness detection. - */ - -function pressAnyKeyToContinue(): Promise { - return new Promise((resolve) => { - const { stdin } = process; - const { isRaw } = stdin; - stdin.setRawMode(true); - stdin.resume(); - stdin.once("data", () => { - stdin.pause(); - stdin.setRawMode(isRaw); - resolve(); - }); - }); -} - -async function waitForLivenessRequest(): Promise { - // Wait for request from client device. -} - -async function sendTokenToClientDevices(_token: string): Promise { - // Send the token to client devices. -} - -async function waitForLivenessSessionComplete(): Promise { - console.log( - "Please refer to https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness and use the mobile client SDK to perform liveness detection on your mobile application.", - ); - console.log( - "Press any key to continue when you complete these steps to run sample to get session results...", - ); - await pressAnyKeyToContinue(); -} - -async function main(): Promise { - // This sample follows the documentation: https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness - // We will follow the steps in https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness#orchestrate-the-liveness-solution to demo the sample code in app server. - - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const apikey = process.env["FACE_APIKEY"] ?? ""; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - // 1. A client device will send a request to start liveness check to us. - await waitForLivenessRequest(); - - // 2.Send a request to Face API to create a liveness detection session. - const createLivenessSessionResponse = await client - .path("/detectLiveness-sessions") - .post({ - body: { - livenessOperationMode: "Passive", - deviceCorrelationId: randomUUID(), - }, - }); - if (isUnexpected(createLivenessSessionResponse)) { - throw new Error(createLivenessSessionResponse.body.error.message); - } - console.log("Create liveness session:"); - console.log(JSON.stringify(createLivenessSessionResponse.body, null, 2)); - - const { sessionId, authToken } = createLivenessSessionResponse.body; - - // 3. Pass the AuthToken to client device. - // Client device will process the step 4, 5, 6 in the documentation 'Orchestrate the liveness solution' - await sendTokenToClientDevices(authToken); - - // 7. wait for client device notifyus us that liveness session completed. - await waitForLivenessSessionComplete(); - - // 8. After client devices perform the action, we can get the result from the following APIs. - // Get session results. - const getLivenessSessionResultResponse = await client - .path("/detectLiveness-sessions/{sessionId}", sessionId) - .get(); - if (isUnexpected(getLivenessSessionResultResponse)) { - throw new Error(getLivenessSessionResultResponse.body.error.message); - } - console.log("Get liveness detection results:"); - console.log(JSON.stringify(getLivenessSessionResultResponse.body, null, 2)); - - // Delete session. - const deleteLivenessSessionResponse = await client - .path("/detectLiveness-sessions/{sessionId}", sessionId) - .delete(); - if (isUnexpected(deleteLivenessSessionResponse)) { - throw new Error(deleteLivenessSessionResponse.body.error.message); - } - console.log("Delete liveness session:"); - console.log(JSON.stringify(deleteLivenessSessionResponse.body, null, 2)); -} - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples-dev/livenessSessionWithVerify.ts b/sdk/face/ai-vision-face-rest/samples-dev/livenessSessionWithVerify.ts deleted file mode 100644 index cb0a5547b50b..000000000000 --- a/sdk/face/ai-vision-face-rest/samples-dev/livenessSessionWithVerify.ts +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { randomUUID } from "node:crypto"; -import { AzureKeyCredential } from "@azure/core-auth"; -import createFaceClient, { isUnexpected } from "@azure-rest/ai-vision-face"; -import "dotenv/config"; - -/** - * This sample demonstrates how to create a liveness detection with face verification session. - * - * @summary Liveness detection with face verification. - */ - -function pressAnyKeyToContinue(): Promise { - return new Promise((resolve) => { - const { stdin } = process; - const { isRaw } = stdin; - stdin.setRawMode(true); - stdin.resume(); - stdin.once("data", () => { - stdin.pause(); - stdin.setRawMode(isRaw); - resolve(); - }); - }); -} - -async function waitForLivenessRequest(): Promise { - // Wait for request from client device. -} - -async function sendTokenToClientDevices(_token: string): Promise { - // Send the token to client devices. -} - -async function waitForLivenessSessionComplete(): Promise { - console.log( - "Please refer to https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness and use the mobile client SDK to perform liveness detection on your mobile application.", - ); - console.log( - "Press any key to continue when you complete these steps to run sample to get session results...", - ); - await pressAnyKeyToContinue(); -} - -async function main(): Promise { - // This sample follows the documentation: https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness - // We will follow the steps in https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness#perform-liveness-detection-with-face-verification to demo the sample code in app server. - - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const apikey = process.env["FACE_APIKEY"] ?? ""; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - // 1. A client device will send a request to start liveness check to us. - await waitForLivenessRequest(); - - // 2.Send a request to Face API to create a liveness detection session. - const createLivenessSessionResponse = await client - .path("/detectLivenessWithVerify-sessions") - .post({ - contentType: "multipart/form-data", - body: [ - { - name: "livenessOperationMode", - body: "Passive", - }, - { - name: "deviceCorrelationId", - body: randomUUID(), - }, - { - name: "enableSessionImage", - body: true, - }, - ], - }); - if (isUnexpected(createLivenessSessionResponse)) { - throw new Error(createLivenessSessionResponse.body.error.message); - } - console.log("Create liveness session:"); - console.log(JSON.stringify(createLivenessSessionResponse.body, null, 2)); - - const { sessionId, authToken } = createLivenessSessionResponse.body; - - // 3. Pass the AuthToken to client device. - // Client device will process the step 4, 5, 6 in the documentation 'Orchestrate the liveness solution' - await sendTokenToClientDevices(authToken); - - // 7. wait for client device notifyus us that liveness session completed. - await waitForLivenessSessionComplete(); - - // 8. After client devices perform the action, we can get the result from the following APIs. - // Get session results. - const getLivenessSessionResultResponse = await client - .path("/detectLivenessWithVerify-sessions/{sessionId}", sessionId) - .get(); - if (isUnexpected(getLivenessSessionResultResponse)) { - throw new Error(getLivenessSessionResultResponse.body.error.message); - } - console.log("Get liveness detection results:"); - console.log(JSON.stringify(getLivenessSessionResultResponse.body, null, 2)); - - // Delete session. - const deleteLivenessSessionResponse = await client - .path("/detectLivenessWithVerify-sessions/{sessionId}", sessionId) - .delete(); - if (isUnexpected(deleteLivenessSessionResponse)) { - throw new Error(deleteLivenessSessionResponse.body.error.message); - } - console.log("Delete liveness session:"); - console.log(JSON.stringify(deleteLivenessSessionResponse.body, null, 2)); -} - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples-dev/livenessSessionWithVerifyWithVerifyImage.ts b/sdk/face/ai-vision-face-rest/samples-dev/livenessSessionWithVerifyWithVerifyImage.ts deleted file mode 100644 index e3d6944b74d9..000000000000 --- a/sdk/face/ai-vision-face-rest/samples-dev/livenessSessionWithVerifyWithVerifyImage.ts +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { randomUUID } from "node:crypto"; -import { AzureKeyCredential } from "@azure/core-auth"; -import createFaceClient, { isUnexpected } from "@azure-rest/ai-vision-face"; -import { readFileSync } from "node:fs"; -import "dotenv/config"; - -/** - * This sample demonstrates how to create a liveness detection with face verification session with a verification image. - * - * @summary Liveness detection with face verification with verification image. - */ - -function pressAnyKeyToContinue(): Promise { - return new Promise((resolve) => { - const { stdin } = process; - const { isRaw } = stdin; - stdin.setRawMode(true); - stdin.resume(); - stdin.once("data", () => { - stdin.pause(); - stdin.setRawMode(isRaw); - resolve(); - }); - }); -} - -async function waitForLivenessRequest(): Promise { - // Wait for request from client device. -} - -async function sendTokenToClientDevices(_token: string): Promise { - // Send the token to client devices. -} - -async function waitForLivenessSessionComplete(): Promise { - console.log( - "Please refer to https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness and use the mobile client SDK to perform liveness detection on your mobile application.", - ); - console.log( - "Press any key to continue when you complete these steps to run sample to get session results...", - ); - await pressAnyKeyToContinue(); -} - -async function main(): Promise { - // This sample follows the documentation: https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness - // We will follow the steps in https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness#perform-liveness-detection-with-face-verification to demo the sample code in app server. - - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const apikey = process.env["FACE_APIKEY"] ?? ""; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - // 1. A client device will send a request to start liveness check to us. - await waitForLivenessRequest(); - - // 2.Send a request to Face API to create a liveness detection session. - const createLivenessSessionResponse = await client - .path("/detectLivenessWithVerify-sessions") - .post({ - contentType: "multipart/form-data", - body: [ - { - name: "livenessOperationMode", - body: "Passive", - }, - { - name: "deviceCorrelationId", - body: randomUUID(), - }, - { - name: "enableSessionImage", - body: true, - }, - { - name: "verifyImage", - body: readFileSync("samples-dev/data/detection1.jpg"), - filename: "verifyImage.jpg", - }, - ], - }); - if (isUnexpected(createLivenessSessionResponse)) { - throw new Error(createLivenessSessionResponse.body.error.message); - } - console.log("Create liveness session:"); - console.log(JSON.stringify(createLivenessSessionResponse.body, null, 2)); - - const { sessionId, authToken } = createLivenessSessionResponse.body; - - // 3. Pass the AuthToken to client device. - // Client device will process the step 4, 5, 6 in the documentation 'Orchestrate the liveness solution' - await sendTokenToClientDevices(authToken); - - // 7. wait for client device notifyus us that liveness session completed. - await waitForLivenessSessionComplete(); - - // 8. After client devices perform the action, we can get the result from the following APIs. - // Get session results. - const getLivenessSessionResultResponse = await client - .path("/detectLivenessWithVerify-sessions/{sessionId}", sessionId) - .get(); - if (isUnexpected(getLivenessSessionResultResponse)) { - throw new Error(getLivenessSessionResultResponse.body.error.message); - } - console.log("Get liveness detection results:"); - console.log(JSON.stringify(getLivenessSessionResultResponse.body, null, 2)); - - // Delete session. - const deleteLivenessSessionResponse = await client - .path("/detectLivenessWithVerify-sessions/{sessionId}", sessionId) - .delete(); - if (isUnexpected(deleteLivenessSessionResponse)) { - throw new Error(deleteLivenessSessionResponse.body.error.message); - } - console.log("Delete liveness session:"); - console.log(JSON.stringify(deleteLivenessSessionResponse.body, null, 2)); -} - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/README.md b/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/README.md deleted file mode 100644 index 9fc0d32d60fe..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/README.md +++ /dev/null @@ -1,60 +0,0 @@ -# Face API client library samples for JavaScript (Beta) - -These sample programs show how to use the JavaScript client libraries for Face API in some common scenarios. - -| **File Name** | **Description** | -| --------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | -| [aadAuth.js][aadauth] | Microsoft Entra ID authentication. | -| [detect.js][detect] | Face detection. | -| [group.js][group] | Face grouping. | -| [livenessSession.js][livenesssession] | Liveness detection. | -| [livenessSessionWithVerify.js][livenesssessionwithverify] | Liveness detection with face verification. | -| [livenessSessionWithVerifyWithVerifyImage.js][livenesssessionwithverifywithverifyimage] | Liveness detection with face verification with verification image. | - -## Prerequisites - -The sample programs are compatible with [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule). - -You need [an Azure subscription][freesub] to run these sample programs. - -Samples retrieve credentials to access the service endpoint from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function. - -Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. - -## Setup - -To run the samples using the published version of the package: - -1. Install the dependencies using `npm`: - -```bash -npm install -``` - -2. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. - -3. Run whichever samples you like (note that some samples may require additional setup, see the table above): - -```bash -node aadAuth.js -``` - -Alternatively, run a single sample with the correct environment variables set (setting up the `.env` file is not required if you do this), for example (cross-platform): - -```bash -npx dev-tool run vendored cross-env FACE_ENDPOINT="" node aadAuth.js -``` - -## Next Steps - -Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. - -[aadauth]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/aadAuth.js -[detect]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/detect.js -[group]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/group.js -[livenesssession]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/livenessSession.js -[livenesssessionwithverify]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/livenessSessionWithVerify.js -[livenesssessionwithverifywithverifyimage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/livenessSessionWithVerifyWithVerifyImage.js -[apiref]: https://aka.ms/azsdk-javascript-face-ref -[freesub]: https://azure.microsoft.com/free/ -[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/face/ai-vision-face-rest/README.md diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/aadAuth.js b/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/aadAuth.js deleted file mode 100644 index 02e8f45de756..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/aadAuth.js +++ /dev/null @@ -1,37 +0,0 @@ -const { readFileSync } = require("fs"); -const { DefaultAzureCredential } = require("@azure/identity"); - -const createFaceClient = require("@azure-rest/ai-vision-face").default, - { isUnexpected } = require("@azure-rest/ai-vision-face"); - -require("dotenv/config"); - -/** - * This sample demonstrates how to authenticate FaceClient using Microsoft Entra ID. - * - * @summary Microsoft Entra ID authentication. - */ - -const main = async () => { - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const credential = new DefaultAzureCredential(); - const client = createFaceClient(endpoint, credential); - - const fileName = "data/detection1.jpg"; - const detectResponse = await client.path("/detect").post({ - contentType: "application/octet-stream", - queryParameters: { - detectionModel: "detection_03", - recognitionModel: "recognition_04", - returnFaceId: false, - }, - body: readFileSync(fileName), - }); - if (isUnexpected(detectResponse)) { - throw new Error(detectResponse.body.error.message); - } - console.log(`Detect: ${fileName}`); - console.log(JSON.stringify(detectResponse.body, null, 2)); -}; - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/data/detection1.jpg b/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/data/detection1.jpg deleted file mode 100644 index 8e80a0b71fbc..000000000000 Binary files a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/data/detection1.jpg and /dev/null differ diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/data/detection5.jpg b/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/data/detection5.jpg deleted file mode 100644 index 919d2ad3296c..000000000000 Binary files a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/data/detection5.jpg and /dev/null differ diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/data/nine-faces.png b/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/data/nine-faces.png deleted file mode 100644 index 9ce0fc21d0d0..000000000000 Binary files a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/data/nine-faces.png and /dev/null differ diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/detect.js b/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/detect.js deleted file mode 100644 index d73796f75325..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/detect.js +++ /dev/null @@ -1,74 +0,0 @@ -const { readFileSync } = require("fs"); -const { AzureKeyCredential } = require("@azure/core-auth"); - -const createFaceClient = require("@azure-rest/ai-vision-face").default, - { isUnexpected } = require("@azure-rest/ai-vision-face"); - -require("dotenv/config"); - -/** - * This sample demonstrates how to detect faces in an image through local file or URL. - * - * @summary Face detection. - */ - -const detectFromImage = async () => { - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const apikey = process.env["FACE_APIKEY"] ?? ""; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - const filename = "data/detection5.jpg"; - const response = await client.path("/detect").post({ - contentType: "application/octet-stream", - queryParameters: { - detectionModel: "detection_03", - recognitionModel: "recognition_04", - returnFaceLandmarks: true, - returnRecognitionModel: true, - faceIdTimeToLive: 120, - returnFaceAttributes: ["headPose", "mask", "qualityForRecognition"], - returnFaceId: false, - }, - body: readFileSync(filename), - }); - if (isUnexpected(response)) { - throw new Error(response.body.error.message); - } - console.log(`Detect from image: ${filename}`); - console.log(JSON.stringify(response.body, null, 2)); -}; - -const detectFromUrl = async () => { - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const apikey = process.env["FACE_APIKEY"] ?? ""; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - const url = "https://aka.ms/facesampleurl"; - const response = await client.path("/detect").post({ - contentType: "application/json", - queryParameters: { - detectionModel: "detection_01", - recognitionModel: "recognition_04", - returnFaceLandmarks: true, - returnRecognitionModel: true, - faceIdTimeToLive: 120, - returnFaceAttributes: ["accessories", "glasses", "exposure", "noise"], - returnFaceId: false, - }, - body: { url }, - }); - if (isUnexpected(response)) { - throw new Error(response.body.error.message); - } - console.log(`Detect from URL: ${url}`); - console.log(JSON.stringify(response.body, null, 2)); -}; - -const main = async () => { - await detectFromImage(); - await detectFromUrl(); -}; - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/group.js b/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/group.js deleted file mode 100644 index 9f253393250b..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/group.js +++ /dev/null @@ -1,51 +0,0 @@ -const { readFileSync } = require("fs"); -const { AzureKeyCredential } = require("@azure/core-auth"); - -const createFaceClient = require("@azure-rest/ai-vision-face").default, - { isUnexpected } = require("@azure-rest/ai-vision-face"); - -require("dotenv/config"); - -/** - * This sample demonstrates how to group similar faces. - * - * @summary Face grouping. - */ - -const main = async () => { - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const apikey = process.env["FACE_APIKEY"] ?? ""; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - // Detect faces from image. - const filename = "data/nine-faces.png"; - const detectResponse = await client.path("/detect").post({ - contentType: "application/octet-stream", - queryParameters: { - detectionModel: "detection_03", - recognitionModel: "recognition_04", - returnFaceId: true, - }, - body: readFileSync(filename), - }); - if (isUnexpected(detectResponse)) { - throw new Error(detectResponse.body.error.message); - } - console.log(`Detect: ${filename}`); - console.log(JSON.stringify(detectResponse.body, null, 2)); - - // Group the faces. - const groupResponse = await client.path("/group").post({ - body: { - faceIds: detectResponse.body.map((face) => face.faceId), - }, - }); - if (isUnexpected(groupResponse)) { - throw new Error(groupResponse.body.error.message); - } - console.log("Group:"); - console.log(JSON.stringify(groupResponse.body, null, 2)); -}; - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/livenessSession.js b/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/livenessSession.js deleted file mode 100644 index b503f6da25f5..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/livenessSession.js +++ /dev/null @@ -1,103 +0,0 @@ -const { randomUUID } = require("crypto"); - -const { AzureKeyCredential } = require("@azure/core-auth"); - -const createFaceClient = require("@azure-rest/ai-vision-face").default, - { isUnexpected } = require("@azure-rest/ai-vision-face"); - -require("dotenv/config"); - -/** - * This sample demonstrates how to create a liveness detection session. - * - * @summary Liveness detection. - */ - -const pressAnyKeyToContinue = () => - new Promise((resolve) => { - const { stdin } = process; - const { isRaw } = stdin; - stdin.setRawMode(true); - stdin.resume(); - stdin.once("data", () => { - stdin.pause(); - stdin.setRawMode(isRaw); - resolve(); - }); - }); - -const waitForLivenessRequest = async () => { - // Wait for request from client device. -}; - -const sendTokenToClientDevices = async (_token) => { - // Send the token to client devices. -}; - -const waitForLivenessSessionComplete = async () => { - console.log( - "Please refer to https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness and use the mobile client SDK to perform liveness detection on your mobile application.", - ); - console.log( - "Press any key to continue when you complete these steps to run sample to get session results...", - ); - await pressAnyKeyToContinue(); -}; - -async function main() { - // This sample follows the documentation: https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness - // We will follow the steps in https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness#orchestrate-the-liveness-solution to demo the sample code in app server. - - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const apikey = process.env["FACE_APIKEY"] ?? ""; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - // 1. A client device will send a request to start liveness check to us. - await waitForLivenessRequest(); - - // 2.Send a request to Face API to create a liveness detection session. - const createLivenessSessionResponse = await client.path("/detectLiveness-sessions").post({ - body: { - livenessOperationMode: "Passive", - deviceCorrelationId: randomUUID(), - }, - }); - if (isUnexpected(createLivenessSessionResponse)) { - throw new Error(createLivenessSessionResponse.body.error.message); - } - console.log("Create liveness session:"); - console.log(JSON.stringify(createLivenessSessionResponse.body, null, 2)); - - const { sessionId, authToken } = createLivenessSessionResponse.body; - - // 3. Pass the AuthToken to client device. - // Client device will process the step 4, 5, 6 in the documentation 'Orchestrate the liveness solution' - await sendTokenToClientDevices(authToken); - - // 7. wait for client device notifyus us that liveness session completed. - await waitForLivenessSessionComplete(); - - // 8. After client devices perform the action, we can get the result from the following APIs. - // Get session results. - const getLivenessSessionResultResponse = await client - .path("/detectLiveness-sessions/{sessionId}", sessionId) - .get(); - if (isUnexpected(getLivenessSessionResultResponse)) { - throw new Error(getLivenessSessionResultResponse.body.error.message); - } - console.log("Get liveness detection results:"); - console.log(JSON.stringify(getLivenessSessionResultResponse.body, null, 2)); - - // Delete session. - const deleteLivenessSessionResponse = await client - .path("/detectLiveness-sessions/{sessionId}", sessionId) - .delete(); - if (isUnexpected(deleteLivenessSessionResponse)) { - throw new Error(deleteLivenessSessionResponse.body.error.message); - } - console.log("Delete liveness session:"); - console.log(JSON.stringify(deleteLivenessSessionResponse.body, null, 2)); -} - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/livenessSessionWithVerify.js b/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/livenessSessionWithVerify.js deleted file mode 100644 index c79a2cc02108..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/livenessSessionWithVerify.js +++ /dev/null @@ -1,116 +0,0 @@ -const { randomUUID } = require("crypto"); - -const { AzureKeyCredential } = require("@azure/core-auth"); - -const createFaceClient = require("@azure-rest/ai-vision-face").default, - { isUnexpected } = require("@azure-rest/ai-vision-face"); - -require("dotenv/config"); - -/** - * This sample demonstrates how to create a liveness detection with face verification session. - * - * @summary Liveness detection with face verification. - */ - -const pressAnyKeyToContinue = () => - new Promise((resolve) => { - const { stdin } = process; - const { isRaw } = stdin; - stdin.setRawMode(true); - stdin.resume(); - stdin.once("data", () => { - stdin.pause(); - stdin.setRawMode(isRaw); - resolve(); - }); - }); - -const waitForLivenessRequest = async () => { - // Wait for request from client device. -}; - -const sendTokenToClientDevices = async (_token) => { - // Send the token to client devices. -}; - -const waitForLivenessSessionComplete = async () => { - console.log( - "Please refer to https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness and use the mobile client SDK to perform liveness detection on your mobile application.", - ); - console.log( - "Press any key to continue when you complete these steps to run sample to get session results...", - ); - await pressAnyKeyToContinue(); -}; - -async function main() { - // This sample follows the documentation: https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness - // We will follow the steps in https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness#perform-liveness-detection-with-face-verification to demo the sample code in app server. - - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const apikey = process.env["FACE_APIKEY"] ?? ""; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - // 1. A client device will send a request to start liveness check to us. - await waitForLivenessRequest(); - - // 2.Send a request to Face API to create a liveness detection session. - const createLivenessSessionResponse = await client - .path("/detectLivenessWithVerify-sessions") - .post({ - contentType: "multipart/form-data", - body: [ - { - name: "livenessOperationMode", - body: "Passive", - }, - { - name: "deviceCorrelationId", - body: randomUUID(), - }, - { - name: "enableSessionImage", - body: true, - }, - ], - }); - if (isUnexpected(createLivenessSessionResponse)) { - throw new Error(createLivenessSessionResponse.body.error.message); - } - console.log("Create liveness session:"); - console.log(JSON.stringify(createLivenessSessionResponse.body, null, 2)); - - const { sessionId, authToken } = createLivenessSessionResponse.body; - - // 3. Pass the AuthToken to client device. - // Client device will process the step 4, 5, 6 in the documentation 'Orchestrate the liveness solution' - await sendTokenToClientDevices(authToken); - - // 7. wait for client device notifyus us that liveness session completed. - await waitForLivenessSessionComplete(); - - // 8. After client devices perform the action, we can get the result from the following APIs. - // Get session results. - const getLivenessSessionResultResponse = await client - .path("/detectLivenessWithVerify-sessions/{sessionId}", sessionId) - .get(); - if (isUnexpected(getLivenessSessionResultResponse)) { - throw new Error(getLivenessSessionResultResponse.body.error.message); - } - console.log("Get liveness detection results:"); - console.log(JSON.stringify(getLivenessSessionResultResponse.body, null, 2)); - - // Delete session. - const deleteLivenessSessionResponse = await client - .path("/detectLivenessWithVerify-sessions/{sessionId}", sessionId) - .delete(); - if (isUnexpected(deleteLivenessSessionResponse)) { - throw new Error(deleteLivenessSessionResponse.body.error.message); - } - console.log("Delete liveness session:"); - console.log(JSON.stringify(deleteLivenessSessionResponse.body, null, 2)); -} - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/livenessSessionWithVerifyWithVerifyImage.js b/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/livenessSessionWithVerifyWithVerifyImage.js deleted file mode 100644 index 6de7bda4f278..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/livenessSessionWithVerifyWithVerifyImage.js +++ /dev/null @@ -1,122 +0,0 @@ -const { randomUUID } = require("crypto"); - -const { AzureKeyCredential } = require("@azure/core-auth"); - -const createFaceClient = require("@azure-rest/ai-vision-face").default, - { isUnexpected } = require("@azure-rest/ai-vision-face"); -const { readFileSync } = require("fs"); - -require("dotenv/config"); - -/** - * This sample demonstrates how to create a liveness detection with face verification session with a verification image. - * - * @summary Liveness detection with face verification with verification image. - */ - -const pressAnyKeyToContinue = () => - new Promise((resolve) => { - const { stdin } = process; - const { isRaw } = stdin; - stdin.setRawMode(true); - stdin.resume(); - stdin.once("data", () => { - stdin.pause(); - stdin.setRawMode(isRaw); - resolve(); - }); - }); - -const waitForLivenessRequest = async () => { - // Wait for request from client device. -}; - -const sendTokenToClientDevices = async (_token) => { - // Send the token to client devices. -}; - -const waitForLivenessSessionComplete = async () => { - console.log( - "Please refer to https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness and use the mobile client SDK to perform liveness detection on your mobile application.", - ); - console.log( - "Press any key to continue when you complete these steps to run sample to get session results...", - ); - await pressAnyKeyToContinue(); -}; - -async function main() { - // This sample follows the documentation: https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness - // We will follow the steps in https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness#perform-liveness-detection-with-face-verification to demo the sample code in app server. - - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const apikey = process.env["FACE_APIKEY"] ?? ""; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - // 1. A client device will send a request to start liveness check to us. - await waitForLivenessRequest(); - - // 2.Send a request to Face API to create a liveness detection session. - const createLivenessSessionResponse = await client - .path("/detectLivenessWithVerify-sessions") - .post({ - contentType: "multipart/form-data", - body: [ - { - name: "livenessOperationMode", - body: "Passive", - }, - { - name: "deviceCorrelationId", - body: randomUUID(), - }, - { - name: "enableSessionImage", - body: true, - }, - { - name: "verifyImage", - body: readFileSync("samples-dev/data/detection1.jpg"), - filename: "verifyImage.jpg", - }, - ], - }); - if (isUnexpected(createLivenessSessionResponse)) { - throw new Error(createLivenessSessionResponse.body.error.message); - } - console.log("Create liveness session:"); - console.log(JSON.stringify(createLivenessSessionResponse.body, null, 2)); - - const { sessionId, authToken } = createLivenessSessionResponse.body; - - // 3. Pass the AuthToken to client device. - // Client device will process the step 4, 5, 6 in the documentation 'Orchestrate the liveness solution' - await sendTokenToClientDevices(authToken); - - // 7. wait for client device notifyus us that liveness session completed. - await waitForLivenessSessionComplete(); - - // 8. After client devices perform the action, we can get the result from the following APIs. - // Get session results. - const getLivenessSessionResultResponse = await client - .path("/detectLivenessWithVerify-sessions/{sessionId}", sessionId) - .get(); - if (isUnexpected(getLivenessSessionResultResponse)) { - throw new Error(getLivenessSessionResultResponse.body.error.message); - } - console.log("Get liveness detection results:"); - console.log(JSON.stringify(getLivenessSessionResultResponse.body, null, 2)); - - // Delete session. - const deleteLivenessSessionResponse = await client - .path("/detectLivenessWithVerify-sessions/{sessionId}", sessionId) - .delete(); - if (isUnexpected(deleteLivenessSessionResponse)) { - throw new Error(deleteLivenessSessionResponse.body.error.message); - } - console.log("Delete liveness session:"); - console.log(JSON.stringify(deleteLivenessSessionResponse.body, null, 2)); -} - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/package.json b/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/package.json deleted file mode 100644 index 75b060c342c8..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "@azure-samples/ai-vision-face-js-beta", - "private": true, - "version": "1.0.0", - "description": "Face API client library samples for JavaScript (Beta)", - "engines": { - "node": ">=18.0.0" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/Azure/azure-sdk-for-js.git", - "directory": "sdk/face/ai-vision-face-rest" - }, - "keywords": [ - "node", - "azure", - "cloud", - "typescript", - "browser", - "isomorphic" - ], - "author": "Microsoft Corporation", - "license": "MIT", - "bugs": { - "url": "https://github.com/Azure/azure-sdk-for-js/issues" - }, - "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/face/ai-vision-face-rest", - "dependencies": { - "@azure-rest/ai-vision-face": "next", - "dotenv": "latest", - "@azure/identity": "^4.2.1", - "@azure/core-auth": "^1.6.0" - } -} diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/sample.env b/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/sample.env deleted file mode 100644 index 07ea63f6c25d..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/javascript/sample.env +++ /dev/null @@ -1,2 +0,0 @@ -FACE_ENDPOINT="" -FACE_APIKEY="" diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/README.md b/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/README.md deleted file mode 100644 index a59644f09f92..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# Face API client library samples for TypeScript (Beta) - -These sample programs show how to use the TypeScript client libraries for Face API in some common scenarios. - -| **File Name** | **Description** | -| --------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | -| [aadAuth.ts][aadauth] | Microsoft Entra ID authentication. | -| [detect.ts][detect] | Face detection. | -| [group.ts][group] | Face grouping. | -| [livenessSession.ts][livenesssession] | Liveness detection. | -| [livenessSessionWithVerify.ts][livenesssessionwithverify] | Liveness detection with face verification. | -| [livenessSessionWithVerifyWithVerifyImage.ts][livenesssessionwithverifywithverifyimage] | Liveness detection with face verification with verification image. | - -## Prerequisites - -The sample programs are compatible with [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule). - -Before running the samples in Node, they must be compiled to JavaScript using the TypeScript compiler. For more information on TypeScript, see the [TypeScript documentation][typescript]. Install the TypeScript compiler using: - -```bash -npm install -g typescript -``` - -You need [an Azure subscription][freesub] to run these sample programs. - -Samples retrieve credentials to access the service endpoint from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function. - -Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. - -## Setup - -To run the samples using the published version of the package: - -1. Install the dependencies using `npm`: - -```bash -npm install -``` - -2. Compile the samples: - -```bash -npm run build -``` - -3. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. - -4. Run whichever samples you like (note that some samples may require additional setup, see the table above): - -```bash -node dist/aadAuth.js -``` - -Alternatively, run a single sample with the correct environment variables set (setting up the `.env` file is not required if you do this), for example (cross-platform): - -```bash -npx dev-tool run vendored cross-env FACE_ENDPOINT="" node dist/aadAuth.js -``` - -## Next Steps - -Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. - -[aadauth]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/aadAuth.ts -[detect]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/detect.ts -[group]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/group.ts -[livenesssession]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/livenessSession.ts -[livenesssessionwithverify]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/livenessSessionWithVerify.ts -[livenesssessionwithverifywithverifyimage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/livenessSessionWithVerifyWithVerifyImage.ts -[apiref]: https://aka.ms/azsdk-javascript-face-ref -[freesub]: https://azure.microsoft.com/free/ -[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/face/ai-vision-face-rest/README.md -[typescript]: https://www.typescriptlang.org/docs/home.html diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/package.json b/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/package.json deleted file mode 100644 index 3669e354292a..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/package.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "@azure-samples/ai-vision-face-ts-beta", - "private": true, - "version": "1.0.0", - "description": "Face API client library samples for TypeScript (Beta)", - "engines": { - "node": ">=18.0.0" - }, - "scripts": { - "build": "tsc", - "prebuild": "rimraf dist/" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/Azure/azure-sdk-for-js.git", - "directory": "sdk/face/ai-vision-face-rest" - }, - "keywords": [ - "node", - "azure", - "cloud", - "typescript", - "browser", - "isomorphic" - ], - "author": "Microsoft Corporation", - "license": "MIT", - "bugs": { - "url": "https://github.com/Azure/azure-sdk-for-js/issues" - }, - "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/face/ai-vision-face-rest", - "dependencies": { - "@azure-rest/ai-vision-face": "next", - "dotenv": "latest", - "@azure/identity": "^4.2.1", - "@azure/core-auth": "^1.6.0" - }, - "devDependencies": { - "@types/node": "^18.0.0", - "typescript": "~5.8.2", - "rimraf": "latest" - } -} diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/sample.env b/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/sample.env deleted file mode 100644 index 07ea63f6c25d..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/sample.env +++ /dev/null @@ -1,2 +0,0 @@ -FACE_ENDPOINT="" -FACE_APIKEY="" diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/aadAuth.ts b/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/aadAuth.ts deleted file mode 100644 index 2a218bdaa808..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/aadAuth.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { readFileSync } from 'node:fs'; -import { DefaultAzureCredential } from '@azure/identity'; - -import createFaceClient, { - isUnexpected, -} from '@azure-rest/ai-vision-face'; - -import "dotenv/config"; - -/** - * This sample demonstrates how to authenticate FaceClient using Microsoft Entra ID. - * - * @summary Microsoft Entra ID authentication. - */ - -const main = async () => { - const endpoint = process.env['FACE_ENDPOINT'] ?? ''; - const credential = new DefaultAzureCredential(); - const client = createFaceClient(endpoint, credential); - - const fileName = 'data/detection1.jpg'; - const detectResponse = await client.path('/detect').post({ - contentType: 'application/octet-stream', - queryParameters: { - detectionModel: 'detection_03', - recognitionModel: 'recognition_04', - returnFaceId: false, - }, - body: readFileSync(fileName), - }); - if (isUnexpected(detectResponse)) { - throw new Error(detectResponse.body.error.message); - } - console.log(`Detect: ${fileName}`); - console.log(JSON.stringify(detectResponse.body, null, 2)); -}; - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/data/detection1.jpg b/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/data/detection1.jpg deleted file mode 100644 index 8e80a0b71fbc..000000000000 Binary files a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/data/detection1.jpg and /dev/null differ diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/data/detection5.jpg b/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/data/detection5.jpg deleted file mode 100644 index 919d2ad3296c..000000000000 Binary files a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/data/detection5.jpg and /dev/null differ diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/data/nine-faces.png b/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/data/nine-faces.png deleted file mode 100644 index 9ce0fc21d0d0..000000000000 Binary files a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/data/nine-faces.png and /dev/null differ diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/detect.ts b/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/detect.ts deleted file mode 100644 index cd46dca962c6..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/detect.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { readFileSync } from 'node:fs'; -import { AzureKeyCredential } from '@azure/core-auth'; - -import createFaceClient, { - isUnexpected, -} from '@azure-rest/ai-vision-face'; - -import "dotenv/config"; - -/** - * This sample demonstrates how to detect faces in an image through local file or URL. - * - * @summary Face detection. - */ - -const detectFromImage = async () => { - const endpoint = process.env['FACE_ENDPOINT'] ?? ''; - const apikey = process.env['FACE_APIKEY'] ?? ''; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - const filename = 'data/detection5.jpg'; - const response = await client.path('/detect').post({ - contentType: 'application/octet-stream', - queryParameters: { - detectionModel: 'detection_03', - recognitionModel: 'recognition_04', - returnFaceLandmarks: true, - returnRecognitionModel: true, - faceIdTimeToLive: 120, - returnFaceAttributes: ['headPose', 'mask', 'qualityForRecognition'], - returnFaceId: false, - }, - body: readFileSync(filename), - }); - if (isUnexpected(response)) { - throw new Error(response.body.error.message); - } - console.log(`Detect from image: ${filename}`); - console.log(JSON.stringify(response.body, null, 2)); -}; - -const detectFromUrl = async () => { - const endpoint = process.env['FACE_ENDPOINT'] ?? ''; - const apikey = process.env['FACE_APIKEY'] ?? ''; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - const url = 'https://aka.ms/facesampleurl'; - const response = await client.path('/detect').post({ - contentType: 'application/json', - queryParameters: { - detectionModel: 'detection_01', - recognitionModel: 'recognition_04', - returnFaceLandmarks: true, - returnRecognitionModel: true, - faceIdTimeToLive: 120, - returnFaceAttributes: ['accessories', 'glasses', 'exposure', 'noise'], - returnFaceId: false, - }, - body: { url }, - }); - if (isUnexpected(response)) { - throw new Error(response.body.error.message); - } - console.log(`Detect from URL: ${url}`); - console.log(JSON.stringify(response.body, null, 2)); -}; - -const main = async () => { - await detectFromImage(); - await detectFromUrl(); -}; - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/group.ts b/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/group.ts deleted file mode 100644 index c0851d40b363..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/group.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { readFileSync } from 'node:fs'; -import { AzureKeyCredential } from '@azure/core-auth'; - -import createFaceClient, { - isUnexpected, -} from '@azure-rest/ai-vision-face'; - -import "dotenv/config"; - -/** - * This sample demonstrates how to group similar faces. - * - * @summary Face grouping. - */ - -const main = async () => { - const endpoint = process.env['FACE_ENDPOINT'] ?? ''; - const apikey = process.env['FACE_APIKEY'] ?? ''; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - // Detect faces from image. - const filename = 'data/nine-faces.png'; - const detectResponse = await client.path('/detect').post({ - contentType: 'application/octet-stream', - queryParameters: { - detectionModel: 'detection_03', - recognitionModel: 'recognition_04', - returnFaceId: true, - }, - body: readFileSync(filename), - }); - if (isUnexpected(detectResponse)) { - throw new Error(detectResponse.body.error.message); - } - console.log(`Detect: ${filename}`); - console.log(JSON.stringify(detectResponse.body, null, 2)); - - // Group the faces. - const groupResponse = await client.path('/group').post({ - body: { - faceIds: detectResponse.body.map((face) => face.faceId as string), - } - }); - if (isUnexpected(groupResponse)) { - throw new Error(groupResponse.body.error.message); - } - console.log('Group:'); - console.log(JSON.stringify(groupResponse.body, null, 2)); -}; - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/livenessSession.ts b/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/livenessSession.ts deleted file mode 100644 index 8563c8e6676f..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/livenessSession.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { randomUUID } from 'node:crypto'; - -import { AzureKeyCredential } from "@azure/core-auth"; - -import createFaceClient, { isUnexpected } from "@azure-rest/ai-vision-face"; - -import "dotenv/config"; - -/** - * This sample demonstrates how to create a liveness detection session. - * - * @summary Liveness detection. - */ - -const pressAnyKeyToContinue = () => - new Promise((resolve) => { - const { stdin } = process; - const { isRaw } = stdin; - stdin.setRawMode(true); - stdin.resume(); - stdin.once("data", () => { - stdin.pause(); - stdin.setRawMode(isRaw); - resolve(); - }); - }); - -const waitForLivenessRequest = async () => { - // Wait for request from client device. -}; - -const sendTokenToClientDevices = async (_token: string) => { - // Send the token to client devices. -}; - -const waitForLivenessSessionComplete = async () => { - console.log( - "Please refer to https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness and use the mobile client SDK to perform liveness detection on your mobile application.", - ); - console.log( - "Press any key to continue when you complete these steps to run sample to get session results...", - ); - await pressAnyKeyToContinue(); -}; - -async function main(): Promise { - // This sample follows the documentation: https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness - // We will follow the steps in https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness#orchestrate-the-liveness-solution to demo the sample code in app server. - - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const apikey = process.env["FACE_APIKEY"] ?? ""; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - // 1. A client device will send a request to start liveness check to us. - await waitForLivenessRequest(); - - // 2.Send a request to Face API to create a liveness detection session. - const createLivenessSessionResponse = await client - .path("/detectLiveness-sessions") - .post({ - body: { - livenessOperationMode: "Passive", - deviceCorrelationId: randomUUID(), - }, - }); - if (isUnexpected(createLivenessSessionResponse)) { - throw new Error(createLivenessSessionResponse.body.error.message); - } - console.log("Create liveness session:"); - console.log(JSON.stringify(createLivenessSessionResponse.body, null, 2)); - - const { sessionId, authToken } = createLivenessSessionResponse.body; - - // 3. Pass the AuthToken to client device. - // Client device will process the step 4, 5, 6 in the documentation 'Orchestrate the liveness solution' - await sendTokenToClientDevices(authToken); - - // 7. wait for client device notifies us that liveness session completed. - await waitForLivenessSessionComplete(); - - // 8. After client devices perform the action, we can get the result from the following APIs. - // Get session results. - const getLivenessSessionResultResponse = await client - .path("/detectLiveness-sessions/{sessionId}", sessionId) - .get(); - if (isUnexpected(getLivenessSessionResultResponse)) { - throw new Error(getLivenessSessionResultResponse.body.error.message); - } - console.log("Get liveness detection results:"); - console.log(JSON.stringify(getLivenessSessionResultResponse.body, null, 2)); - - // Delete session. - const deleteLivenessSessionResponse = await client - .path("/detectLiveness-sessions/{sessionId}", sessionId) - .delete(); - if (isUnexpected(deleteLivenessSessionResponse)) { - throw new Error(deleteLivenessSessionResponse.body.error.message); - } - console.log("Delete liveness session:"); - console.log(JSON.stringify(deleteLivenessSessionResponse.body, null, 2)); -} - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/livenessSessionWithVerify.ts b/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/livenessSessionWithVerify.ts deleted file mode 100644 index 61b0de15556c..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/livenessSessionWithVerify.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { randomUUID } from 'node:crypto'; - -import { AzureKeyCredential } from "@azure/core-auth"; - -import createFaceClient, { isUnexpected } from "@azure-rest/ai-vision-face"; - -import "dotenv/config"; - -/** - * This sample demonstrates how to create a liveness detection with face verification session. - * - * @summary Liveness detection with face verification. - */ - -const pressAnyKeyToContinue = () => - new Promise((resolve) => { - const { stdin } = process; - const { isRaw } = stdin; - stdin.setRawMode(true); - stdin.resume(); - stdin.once("data", () => { - stdin.pause(); - stdin.setRawMode(isRaw); - resolve(); - }); - }); - -const waitForLivenessRequest = async () => { - // Wait for request from client device. -}; - -const sendTokenToClientDevices = async (_token: string) => { - // Send the token to client devices. -}; - -const waitForLivenessSessionComplete = async () => { - console.log( - "Please refer to https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness and use the mobile client SDK to perform liveness detection on your mobile application.", - ); - console.log( - "Press any key to continue when you complete these steps to run sample to get session results...", - ); - await pressAnyKeyToContinue(); -}; - -async function main(): Promise { - // This sample follows the documentation: https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness - // We will follow the steps in https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness#perform-liveness-detection-with-face-verification to demo the sample code in app server. - - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const apikey = process.env["FACE_APIKEY"] ?? ""; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - // 1. A client device will send a request to start liveness check to us. - await waitForLivenessRequest(); - - // 2.Send a request to Face API to create a liveness detection session. - const createLivenessSessionResponse = await client - .path("/detectLivenessWithVerify-sessions") - .post({ - contentType: "multipart/form-data", - body: [ - { - name: "livenessOperationMode", - body: "Passive", - }, - { - name: "deviceCorrelationId", - body: randomUUID(), - }, - { - name: "enableSessionImage", - body: true, - }, - ], - }); - if (isUnexpected(createLivenessSessionResponse)) { - throw new Error(createLivenessSessionResponse.body.error.message); - } - console.log("Create liveness session:"); - console.log(JSON.stringify(createLivenessSessionResponse.body, null, 2)); - - const { sessionId, authToken } = createLivenessSessionResponse.body; - - // 3. Pass the AuthToken to client device. - // Client device will process the step 4, 5, 6 in the documentation 'Orchestrate the liveness solution' - await sendTokenToClientDevices(authToken); - - // 7. wait for client device notifies us that liveness session completed. - await waitForLivenessSessionComplete(); - - // 8. After client devices perform the action, we can get the result from the following APIs. - // Get session results. - const getLivenessSessionResultResponse = await client - .path("/detectLivenessWithVerify-sessions/{sessionId}", sessionId) - .get(); - if (isUnexpected(getLivenessSessionResultResponse)) { - throw new Error(getLivenessSessionResultResponse.body.error.message); - } - console.log("Get liveness detection results:"); - console.log(JSON.stringify(getLivenessSessionResultResponse.body, null, 2)); - - // Delete session. - const deleteLivenessSessionResponse = await client - .path("/detectLivenessWithVerify-sessions/{sessionId}", sessionId) - .delete(); - if (isUnexpected(deleteLivenessSessionResponse)) { - throw new Error(deleteLivenessSessionResponse.body.error.message); - } - console.log("Delete liveness session:"); - console.log(JSON.stringify(deleteLivenessSessionResponse.body, null, 2)); -} - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/livenessSessionWithVerifyWithVerifyImage.ts b/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/livenessSessionWithVerifyWithVerifyImage.ts deleted file mode 100644 index 014009b0e9c3..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/src/livenessSessionWithVerifyWithVerifyImage.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { randomUUID } from 'node:crypto'; - -import { AzureKeyCredential } from "@azure/core-auth"; - -import createFaceClient, { - isUnexpected, -} from '@azure-rest/ai-vision-face'; -import { readFileSync } from 'node:fs'; - -import "dotenv/config"; - -/** - * This sample demonstrates how to create a liveness detection with face verification session with a verification image. - * - * @summary Liveness detection with face verification with verification image. - */ - -const pressAnyKeyToContinue = () => - new Promise((resolve) => { - const { stdin } = process; - const { isRaw } = stdin; - stdin.setRawMode(true); - stdin.resume(); - stdin.once("data", () => { - stdin.pause(); - stdin.setRawMode(isRaw); - resolve(); - }); - }); - -const waitForLivenessRequest = async () => { - // Wait for request from client device. -}; - -const sendTokenToClientDevices = async (_token: string) => { - // Send the token to client devices. -}; - -const waitForLivenessSessionComplete = async () => { - console.log( - "Please refer to https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness and use the mobile client SDK to perform liveness detection on your mobile application.", - ); - console.log( - "Press any key to continue when you complete these steps to run sample to get session results...", - ); - await pressAnyKeyToContinue(); -}; - -async function main(): Promise { - // This sample follows the documentation: https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness - // We will follow the steps in https://learn.microsoft.com/en-us/azure/ai-services/computer-vision/tutorials/liveness#perform-liveness-detection-with-face-verification to demo the sample code in app server. - - const endpoint = process.env["FACE_ENDPOINT"] ?? ""; - const apikey = process.env["FACE_APIKEY"] ?? ""; - const credential = new AzureKeyCredential(apikey); - const client = createFaceClient(endpoint, credential); - - // 1. A client device will send a request to start liveness check to us. - await waitForLivenessRequest(); - - // 2.Send a request to Face API to create a liveness detection session. - const createLivenessSessionResponse = await client - .path("/detectLivenessWithVerify-sessions") - .post({ - contentType: "multipart/form-data", - body: [ - { - name: "livenessOperationMode", - body: "Passive", - }, - { - name: "deviceCorrelationId", - body: randomUUID(), - }, - { - name: "enableSessionImage", - body: true, - }, - { - name: "verifyImage", - body: readFileSync("samples-dev/data/detection1.jpg"), - filename: "verifyImage.jpg", - }, - ], - }); - if (isUnexpected(createLivenessSessionResponse)) { - throw new Error(createLivenessSessionResponse.body.error.message); - } - console.log("Create liveness session:"); - console.log(JSON.stringify(createLivenessSessionResponse.body, null, 2)); - - const { sessionId, authToken } = createLivenessSessionResponse.body; - - // 3. Pass the AuthToken to client device. - // Client device will process the step 4, 5, 6 in the documentation 'Orchestrate the liveness solution' - await sendTokenToClientDevices(authToken); - - // 7. wait for client device notifies us that liveness session completed. - await waitForLivenessSessionComplete(); - - // 8. After client devices perform the action, we can get the result from the following APIs. - // Get session results. - const getLivenessSessionResultResponse = await client - .path("/detectLivenessWithVerify-sessions/{sessionId}", sessionId) - .get(); - if (isUnexpected(getLivenessSessionResultResponse)) { - throw new Error(getLivenessSessionResultResponse.body.error.message); - } - console.log("Get liveness detection results:"); - console.log(JSON.stringify(getLivenessSessionResultResponse.body, null, 2)); - - // Delete session. - const deleteLivenessSessionResponse = await client - .path("/detectLivenessWithVerify-sessions/{sessionId}", sessionId) - .delete(); - if (isUnexpected(deleteLivenessSessionResponse)) { - throw new Error(deleteLivenessSessionResponse.body.error.message); - } - console.log("Delete liveness session:"); - console.log(JSON.stringify(deleteLivenessSessionResponse.body, null, 2)); -} - -main().catch(console.error); diff --git a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/tsconfig.json b/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/tsconfig.json deleted file mode 100644 index 400db87cf648..000000000000 --- a/sdk/face/ai-vision-face-rest/samples/v1-beta/typescript/tsconfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2023", - "module": "commonjs", - "lib": [], - "importHelpers": true, - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "noImplicitReturns": true, - "noFallthroughCasesInSwitch": true, - "moduleResolution": "node10", - "esModuleInterop": true, - "outDir": "./dist", - "resolveJsonModule": true - }, - "include": [ - "./src" - ] -} diff --git a/sdk/face/ai-vision-face-rest/src/faceClient.ts b/sdk/face/ai-vision-face-rest/src/faceClient.ts index a08ff3c987e0..052504a4e201 100644 --- a/sdk/face/ai-vision-face-rest/src/faceClient.ts +++ b/sdk/face/ai-vision-face-rest/src/faceClient.ts @@ -27,7 +27,7 @@ export default function createClient( { apiVersion = "v1.2", ...options }: FaceClientOptions = {}, ): FaceClient { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}/face/${apiVersion}`; - const userAgentInfo = `azsdk-js-ai-vision-face-rest/1.0.0-beta.3`; + const userAgentInfo = `azsdk-js-ai-vision-face-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` @@ -49,22 +49,5 @@ export default function createClient( client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); - client.pipeline.addPolicy({ - name: "VerifyImageFilenamePolicy", - sendRequest: (request, next) => { - for (const part of request.multipartBody?.parts ?? []) { - const contentDisposition = part.headers.get("content-disposition"); - if ( - contentDisposition && - contentDisposition.includes(`name="VerifyImage"`) && - !contentDisposition.includes("filename=") - ) { - part.headers.set("content-disposition", `form-data; name="VerifyImage"; filename="blob"`); - } - } - return next(request); - }, - }); - return client; } diff --git a/sdk/face/ai-vision-face-rest/test/public/livenessSession.spec.ts b/sdk/face/ai-vision-face-rest/test/public/livenessSession.spec.ts deleted file mode 100644 index e8ef3ae95381..000000000000 --- a/sdk/face/ai-vision-face-rest/test/public/livenessSession.spec.ts +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { createRecorder, createClient } from "./utils/recordedClient.js"; -import { assert, beforeEach, afterEach, it, describe } from "vitest"; -import type { Recorder } from "@azure-tools/test-recorder"; -import { isPlaybackMode } from "@azure-tools/test-recorder"; - -import type { FaceClient } from "../../src/index.js"; -import { isUnexpected } from "../../src/index.js"; - -// The crypto module is not available in browser environment, so implement a simple randomUUID function. -const randomUUID = (): string => - "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".replace(/x/g, () => - Math.floor(Math.random() * 16).toString(16), - ); - -describe("LivenessSession", () => { - let recorder: Recorder; - let client: FaceClient; - - beforeEach(async (context) => { - recorder = await createRecorder(context); - client = await createClient(recorder); - }); - - afterEach(async () => { - if (recorder?.recordingId) { - await recorder.stop(); - } - }); - - it.runIf(isPlaybackMode())("TestLivenessSession", async () => { - const deviceCorrelationId = recorder.variable("deviceCorrelationId", randomUUID()); - - const createLivenessSessionResponse = await client.path("/detectLiveness-sessions").post({ - body: { - livenessOperationMode: "Passive", - deviceCorrelationId, - enableSessionImage: true, - }, - }); - if (isUnexpected(createLivenessSessionResponse)) { - throw new Error(createLivenessSessionResponse.body.error.message); - } - assert.equal(createLivenessSessionResponse.body.status, "NotStarted"); - assert.equal(createLivenessSessionResponse.body.results.attempts.length, 0); - - const { sessionId /* authToken */ } = createLivenessSessionResponse.body; - - // start session - - const getLivenessSessionResultResponse1 = await client - .path("/detectLiveness-sessions/{sessionId}", sessionId) - .get(); - if (isUnexpected(getLivenessSessionResultResponse1)) { - throw new Error(getLivenessSessionResultResponse1.body.error.message); - } - assert.equal(getLivenessSessionResultResponse1.body.status, "Running"); - assert.equal(getLivenessSessionResultResponse1.body.results.attempts.length, 0); - - // send payloads - - const getLivenessSessionResultResponse2 = await client - .path("/detectLiveness-sessions/{sessionId}", sessionId) - .get(); - if (isUnexpected(getLivenessSessionResultResponse2)) { - throw new Error(getLivenessSessionResultResponse2.body.error.message); - } - assert.equal(getLivenessSessionResultResponse2.body.status, "Succeeded"); - assert.equal(getLivenessSessionResultResponse2.body.results.attempts.length, 1); - assert.equal( - getLivenessSessionResultResponse2.body.results.attempts[0].attemptStatus, - "Succeeded", - ); - assert.equal( - getLivenessSessionResultResponse2.body.results.attempts[0].result?.livenessDecision, - "realface", - ); - assert.isNotNull( - getLivenessSessionResultResponse2.body.results.attempts[0].result?.sessionImageId, - ); - - const sessionImageId = getLivenessSessionResultResponse2.body.results.attempts[0].result - ?.sessionImageId as string; - const getSessionImageResponse = await client - .path("/sessionImages/{sessionImageId}", sessionImageId) - .get(); - if (isUnexpected(getSessionImageResponse)) { - throw new Error(getSessionImageResponse.body.error.message); - } - assert.equal(getSessionImageResponse.body.length, 639232); - - const deleteLivenessSessionResponse = await client - .path("/detectLiveness-sessions/{sessionId}", sessionId) - .delete(); - if (isUnexpected(deleteLivenessSessionResponse)) { - throw new Error(deleteLivenessSessionResponse.body.error.message); - } - }); -}); diff --git a/sdk/face/ai-vision-face-rest/test/public/node/livenessSession.spec.ts b/sdk/face/ai-vision-face-rest/test/public/node/livenessSession.spec.ts deleted file mode 100644 index de6ae402fa54..000000000000 --- a/sdk/face/ai-vision-face-rest/test/public/node/livenessSession.spec.ts +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -import { randomUUID } from "node:crypto"; -import { readFileSync } from "node:fs"; - -import { createRecorder, createClient } from "../utils/recordedClient.js"; -import { assert, beforeEach, afterEach, it, describe } from "vitest"; -import type { Recorder } from "@azure-tools/test-recorder"; -import { isPlaybackMode } from "@azure-tools/test-recorder"; - -import type { FaceClient } from "../../../src/index.js"; -import { isUnexpected } from "../../../src/index.js"; - -describe("LivenessWithVerifySession", () => { - let recorder: Recorder; - let client: FaceClient; - - beforeEach(async (context) => { - recorder = await createRecorder(context); - client = await createClient(recorder); - }); - - afterEach(async () => { - if (recorder?.recordingId) { - await recorder.stop(); - } - }); - - it.runIf(isPlaybackMode())("TestLivenessWithVerifySession", async () => { - const deviceCorrelationId = recorder.variable("deviceCorrelationId", randomUUID()); - - const createLivenessSessionResponse = await client - .path("/detectLivenessWithVerify-sessions") - .post({ - contentType: "multipart/form-data", - body: [ - { - name: "livenessOperationMode", - body: "Passive", - }, - { - name: "deviceCorrelationId", - body: deviceCorrelationId, - }, - { - name: "enableSessionImage", - body: true, - }, - { - name: "verifyImage", - body: readFileSync("samples-dev/data/detection1.jpg"), - filename: "verifyImage.jpg", - }, - ], - }); - if (isUnexpected(createLivenessSessionResponse)) { - throw new Error(createLivenessSessionResponse.body.error.message); - } - assert.equal(createLivenessSessionResponse.body.status, "NotStarted"); - assert.equal(createLivenessSessionResponse.body.results.attempts.length, 0); - - const { sessionId /* authToken */ } = createLivenessSessionResponse.body; - - // start session - - const getLivenessSessionResultResponse1 = await client - .path("/detectLivenessWithVerify-sessions/{sessionId}", sessionId) - .get(); - if (isUnexpected(getLivenessSessionResultResponse1)) { - throw new Error(getLivenessSessionResultResponse1.body.error.message); - } - assert.equal(getLivenessSessionResultResponse1.body.status, "Running"); - assert.equal(getLivenessSessionResultResponse1.body.results.attempts.length, 0); - - // send payloads - - const getLivenessSessionResultResponse2 = await client - .path("/detectLivenessWithVerify-sessions/{sessionId}", sessionId) - .get(); - if (isUnexpected(getLivenessSessionResultResponse2)) { - throw new Error(getLivenessSessionResultResponse2.body.error.message); - } - assert.equal(getLivenessSessionResultResponse2.body.status, "Succeeded"); - assert.equal(getLivenessSessionResultResponse2.body.results.attempts.length, 1); - assert.equal( - getLivenessSessionResultResponse2.body.results.attempts[0].attemptStatus, - "Succeeded", - ); - assert.equal( - getLivenessSessionResultResponse2.body.results.attempts[0].result?.livenessDecision, - "realface", - ); - assert.equal( - getLivenessSessionResultResponse2.body.results.attempts[0].result?.verifyResult?.isIdentical, - false, - ); - assert.isNotNull( - getLivenessSessionResultResponse2.body.results.attempts[0].result?.sessionImageId, - ); - - const sessionImageId = getLivenessSessionResultResponse2.body.results.attempts[0].result - ?.sessionImageId as string; - const getSessionImageResponse = await client - .path("/sessionImages/{sessionImageId}", sessionImageId) - .get(); - if (isUnexpected(getSessionImageResponse)) { - throw new Error(getSessionImageResponse.body.error.message); - } - assert.equal(getSessionImageResponse.body.length, 639232); - - const deleteLivenessSessionResponse = await client - .path("/detectLivenessWithVerify-sessions/{sessionId}", sessionId) - .delete(); - if (isUnexpected(deleteLivenessSessionResponse)) { - throw new Error(deleteLivenessSessionResponse.body.error.message); - } - }); -}); diff --git a/sdk/face/ai-vision-face-rest/test/public/sampleTest.spec.ts b/sdk/face/ai-vision-face-rest/test/public/sampleTest.spec.ts new file mode 100644 index 000000000000..e4591bbad342 --- /dev/null +++ b/sdk/face/ai-vision-face-rest/test/public/sampleTest.spec.ts @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { assert, beforeEach, afterEach, it, describe } from "vitest"; + +describe("My test", () => { + // let recorder: Recorder; + + beforeEach(async () => { + // recorder = await createRecorder(this); + }); + + afterEach(async () => { + // await recorder.stop(); + }); + + it("sample test", async function () { + assert.equal(1, 1); + }); +}); diff --git a/sdk/face/ai-vision-face-rest/test/public/utils/recordedClient.ts b/sdk/face/ai-vision-face-rest/test/public/utils/recordedClient.ts index f9bb38994601..14dcd9fa397c 100644 --- a/sdk/face/ai-vision-face-rest/test/public/utils/recordedClient.ts +++ b/sdk/face/ai-vision-face-rest/test/public/utils/recordedClient.ts @@ -1,26 +1,14 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import type { RecorderStartOptions, VitestTestContext } from "@azure-tools/test-recorder"; -import { Recorder, assertEnvironmentVariable } from "@azure-tools/test-recorder"; -import { AzureKeyCredential } from "@azure/core-auth"; +import { Recorder, RecorderStartOptions, VitestTestContext } from "@azure-tools/test-recorder"; -import type { FaceClient, FaceClientOptions } from "../../../src/index.js"; -import createFaceClient from "../../../src/index.js"; - -const envSetupForPlayback: Record = { - FACE_ENDPOINT: "https://faceendpoint.cognitiveservices.azure.com/", - FACE_APIKEY: "faceapikey", +const replaceableVariables: Record = { + SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, - // Ref: https://github.com/Azure/azure-sdk-tools/blob/main/tools/test-proxy/Azure.Sdk.Tools.TestProxy/Common/SanitizerDictionary.cs - removeCentralSanitizers: [ - "AZSDK2030", // HeaderRegexSanitizer("operation-location", value: "https://example.com") - "AZSDK3430", // BodyKeySanitizer("$..id") - "AZSDK3496", // BodyKeySanitizer("$..resourceLocation") - ], + envSetupForPlayback: replaceableVariables, }; /** @@ -31,29 +19,5 @@ const recorderEnvSetup: RecorderStartOptions = { export async function createRecorder(context: VitestTestContext): Promise { const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); - await recorder.addSanitizers( - { - removeHeaderSanitizer: { headersForRemoval: ["Ocp-Apim-Subscription-Key"] }, - generalSanitizers: [ - { - regex: true, - target: "https://[a-zA-Z0-9-]*\\.cognitiveservices\\.azure\\.com/", - value: "https://fakeendpoint.cognitiveservices.azure.com/", - }, - ], - bodyKeySanitizers: [{ jsonPath: "authToken", value: "fakeauthtoken" }], - }, - ["record", "playback"], - ); return recorder; } - -export async function createClient( - recorder?: Recorder, - options?: FaceClientOptions, -): Promise { - const endpoint = assertEnvironmentVariable("FACE_ENDPOINT"); - const apikey = assertEnvironmentVariable("FACE_APIKEY"); - const credential = new AzureKeyCredential(apikey); - return createFaceClient(endpoint, credential, recorder?.configureClientOptions(options ?? {})); -} diff --git a/sdk/face/ai-vision-face-rest/test/snippets.spec.ts b/sdk/face/ai-vision-face-rest/test/snippets.spec.ts index acaf9fc1138e..7a4bd4f7bdb9 100644 --- a/sdk/face/ai-vision-face-rest/test/snippets.spec.ts +++ b/sdk/face/ai-vision-face-rest/test/snippets.spec.ts @@ -1,276 +1,13 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { AzureKeyCredential } from "@azure/core-auth"; -import FaceClient, { getLongRunningPoller, isUnexpected } from "../src/index.js"; -import { DefaultAzureCredential } from "@azure/identity"; +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + import { setLogLevel } from "@azure/logger"; import { describe, it } from "vitest"; -import { readFileSync } from "node:fs"; -import { randomUUID } from "node:crypto"; describe("snippets", () => { - it("ReadmeSampleCreateClient_Entra", async () => { - const endpoint = process.env["FACE_ENDPOINT"] || ""; - const credential = new DefaultAzureCredential(); - const client = FaceClient(endpoint, credential); - }); - - it("ReadmeSampleCreateClient_KeyCredential", async () => { - const endpoint = process.env["FACE_ENDPOINT"] || ""; - const apikey = process.env["FACE_APIKEY"] || ""; - const credential = new AzureKeyCredential(apikey); - const client = FaceClient(endpoint, credential); - }); - - it("ReadmeSampleFaceDetection", async () => { - const endpoint = process.env["FACE_ENDPOINT"] || ""; - const credential = new DefaultAzureCredential(); - const client = FaceClient(endpoint, credential); - // @ts-preserve-whitespace - const response = await client.path("/detect").post({ - contentType: "application/octet-stream", - queryParameters: { - detectionModel: "detection_03", - recognitionModel: "recognition_04", - returnFaceLandmarks: true, - returnRecognitionModel: true, - faceIdTimeToLive: 120, - returnFaceAttributes: ["headPose", "mask", "qualityForRecognition"], - returnFaceId: false, - }, - body: readFileSync("path/to/test/image"), - }); - // @ts-preserve-whitespace - if (isUnexpected(response)) { - throw new Error(response.body.error.message); - } - // @ts-preserve-whitespace - console.log(response.body); - }); - - it("ReadmeSampleFaceRecognitionFromLargePersonGroup", async () => { - const endpoint = process.env["FACE_ENDPOINT"] || ""; - const credential = new DefaultAzureCredential(); - const client = FaceClient(endpoint, credential); - // @ts-preserve-whitespace - const largePersonGroupId = "lpg_family"; - // @ts-preserve-whitespace - console.log(`Create a large person group with id: ${largePersonGroupId}`); - const createLargePersonGroupResponse = await client - .path("/largepersongroups/{largePersonGroupId}", largePersonGroupId) - .put({ - body: { - name: "My Family", - recognitionModel: "recognition_04", - }, - }); - // @ts-preserve-whitespace - console.log("Create a Person Bill and add a face to him."); - const createLargePersonGroupPersonResponse_bill = await client - .path("/largepersongroups/{largePersonGroupId}/persons", largePersonGroupId) - .post({ - body: { - name: "Bill", - userData: "Dad", - }, - }); - // @ts-preserve-whitespace - if (isUnexpected(createLargePersonGroupPersonResponse_bill)) { - throw new Error(createLargePersonGroupPersonResponse_bill.body.error.message); - } - // @ts-preserve-whitespace - const personId_bill = createLargePersonGroupPersonResponse_bill.body.personId; - await client - .path( - "/largepersongroups/{largePersonGroupId}/persons/{personId}/persistedfaces", - largePersonGroupId, - personId_bill, - ) - .post({ - queryParameters: { - userData: "Dad-0001", - detectionModel: "detection_03", - }, - contentType: "application/octet-stream", - body: readFileSync("path/to/bill/image"), - }); - // @ts-preserve-whitespace - console.log("Create a Person Clare and add a face to her."); - const createLargePersonGroupPersonResponse_clare = await client - .path("/largepersongroups/{largePersonGroupId}/persons", largePersonGroupId) - .post({ - body: { - name: "Clare", - userData: "Mom", - }, - }); - // @ts-preserve-whitespace - if (isUnexpected(createLargePersonGroupPersonResponse_clare)) { - throw new Error(createLargePersonGroupPersonResponse_clare.body.error.message); - } - // @ts-preserve-whitespace - const personId_clare = createLargePersonGroupPersonResponse_clare.body.personId; - await client - .path( - "/largepersongroups/{largePersonGroupId}/persons/{personId}/persistedfaces", - largePersonGroupId, - personId_clare, - ) - .post({ - queryParameters: { - userData: "Mom-0001", - detectionModel: "detection_03", - }, - contentType: "application/octet-stream", - body: readFileSync("path/to/clare/image"), - }); - }); - - it("ReadmeSampleFaceRecognitionFromLargePersonGroup_Train", async () => { - const endpoint = process.env["FACE_ENDPOINT"] || ""; - const credential = new DefaultAzureCredential(); - const client = FaceClient(endpoint, credential); - // @ts-preserve-whitespace - const largePersonGroupId = "lpg_family"; - // @ts-preserve-whitespace - console.log(`Start to train the large person group: ${largePersonGroupId}`); - const trainResponse = await client - .path("/largepersongroups/{largePersonGroupId}/train", largePersonGroupId) - .post(); - const trainPoller = await getLongRunningPoller(client, trainResponse); - await trainPoller.pollUntilDone(); - // Check if poller.getOperationState().status is 'succeeded'. - }); - - it("ReadmeSampleFaceRecognitionFromLargePersonGroup_Identify", async () => { - const endpoint = process.env["FACE_ENDPOINT"] || ""; - const credential = new DefaultAzureCredential(); - const client = FaceClient(endpoint, credential); - // @ts-preserve-whitespace - const largePersonGroupId = "lpg_family"; - // @ts-preserve-whitespace - console.log("Detect faces from the target image."); - const detectResponse = await client.path("/detect").post({ - contentType: "application/octet-stream", - queryParameters: { - detectionModel: "detection_03", - recognitionModel: "recognition_04", - returnFaceId: true, - }, - body: readFileSync("path/to/target/image"), - }); - // @ts-preserve-whitespace - if (isUnexpected(detectResponse)) { - throw new Error(detectResponse.body.error.message); - } - // @ts-preserve-whitespace - const faceIds = detectResponse.body.map((face) => face.faceId as string); - // @ts-preserve-whitespace - console.log("Identify the faces in the large person group."); - // @ts-preserve-whitespace - const identifyResponse = await client.path("/identify").post({ - body: { faceIds, largePersonGroupId }, - }); - // @ts-preserve-whitespace - if (isUnexpected(identifyResponse)) { - throw new Error(identifyResponse.body.error.message); - } - // @ts-preserve-whitespace - console.log(identifyResponse.body); - }); - - it("ReadmeSampleFaceRecognitionFromLargePersonGroup_Delete", async () => { - const endpoint = process.env["FACE_ENDPOINT"] || ""; - const credential = new DefaultAzureCredential(); - const client = FaceClient(endpoint, credential); - // @ts-preserve-whitespace - const largePersonGroupId = "lpg_family"; - // @ts-preserve-whitespace - console.log(`Delete the large person group: ${largePersonGroupId}`); - await client.path("/largepersongroups/{largePersonGroupId}", largePersonGroupId).delete(); - }); - - it("ReadmeSampleLivenessDetection", async () => { - const endpoint = process.env["FACE_ENDPOINT"] || ""; - const credential = new DefaultAzureCredential(); - const client = FaceClient(endpoint, credential); - // @ts-preserve-whitespace - console.log("Create a new liveness session."); - const createLivenessSessionResponse = await client - .path("/detectLiveness/singleModal/sessions") - .post({ - body: { - livenessOperationMode: "Passive", - deviceCorrelationId: randomUUID(), - sendResultsToClient: false, - authTokenTimeToLiveInSeconds: 60, - }, - }); - // @ts-preserve-whitespace - if (isUnexpected(createLivenessSessionResponse)) { - throw new Error(createLivenessSessionResponse.body.error.message); - } - console.log(createLivenessSessionResponse.body); - // @ts-preserve-whitespace - const { sessionId } = createLivenessSessionResponse.body; - // @ts-preserve-whitespace - console.log("Get liveness detection results."); - const getLivenessSessionResponse = await client - .path("/detectLiveness/singleModal/sessions/{sessionId}", sessionId) - .get(); - // @ts-preserve-whitespace - if (isUnexpected(getLivenessSessionResponse)) { - throw new Error(getLivenessSessionResponse.body.error.message); - } - console.log(getLivenessSessionResponse.body); - }); - - it("ReadmeSampleLivenessDetectionWithVerify", async () => { - const endpoint = process.env["FACE_ENDPOINT"] || ""; - const credential = new DefaultAzureCredential(); - const client = FaceClient(endpoint, credential); - // @ts-preserve-whitespace - console.log("Create a new liveness with verify session with verify image."); - const createLivenessSessionResponse = await client - .path("/detectLivenessWithVerify/singleModal/sessions") - .post({ - contentType: "multipart/form-data", - body: [ - { - name: "VerifyImage", - body: readFileSync("path/to/verify/image"), - }, - { - name: "Parameters", - body: { - livenessOperationMode: "Passive", - sendResultsToClient: false, - authTokenTimeToLiveInSeconds: 60, - deviceCorrelationId: randomUUID(), - }, - }, - ], - }); - // @ts-preserve-whitespace - if (isUnexpected(createLivenessSessionResponse)) { - throw new Error(createLivenessSessionResponse.body.error.message); - } - console.log(createLivenessSessionResponse.body); - // @ts-preserve-whitespace - const { sessionId } = createLivenessSessionResponse.body; - // @ts-preserve-whitespace - console.log("Get the liveness detection and verification result."); - const getLivenessSessionResultResponse = await client - .path("/detectLivenessWithVerify/singleModal/sessions/{sessionId}", sessionId) - .get(); - // @ts-preserve-whitespace - if (isUnexpected(getLivenessSessionResultResponse)) { - throw new Error(getLivenessSessionResultResponse.body.error.message); - } - console.log(getLivenessSessionResultResponse.body); - }); - it("SetLogLevel", async () => { setLogLevel("info"); }); diff --git a/sdk/face/ai-vision-face-rest/tsconfig.json b/sdk/face/ai-vision-face-rest/tsconfig.json index 19ceb382b521..71858ab903e4 100644 --- a/sdk/face/ai-vision-face-rest/tsconfig.json +++ b/sdk/face/ai-vision-face-rest/tsconfig.json @@ -1,13 +1,16 @@ { - "references": [ - { - "path": "./tsconfig.src.json" - }, - { - "path": "./tsconfig.samples.json" - }, - { - "path": "./tsconfig.test.json" - } + "extends": "../../../tsconfig", + "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext", + "rootDir": ".", + "skipLibCheck": true + }, + "include": [ + "src/**/*.ts", + "src/**/*.mts", + "src/**/*.cts", + "test/**/*.ts", + "test/**/*.ts" ] -} +} \ No newline at end of file diff --git a/sdk/face/ai-vision-face-rest/tsp-location.yaml b/sdk/face/ai-vision-face-rest/tsp-location.yaml index 5af5f5bd2d9a..50f6950ef243 100644 --- a/sdk/face/ai-vision-face-rest/tsp-location.yaml +++ b/sdk/face/ai-vision-face-rest/tsp-location.yaml @@ -1,5 +1,4 @@ -additionalDirectories: [] directory: specification/ai/Face -commit: 24d856b33d49b5ac6227a51c610b7d8b0f289458 -repo: Azure/azure-rest-api-specs - +commit: a3dcf1c9eb0324a1e4e9a12ec4655f54ba1f44f5 +repo: /mnt/vss/_work/1/s/azure-rest-api-specs +additionalDirectories: