Skip to content

Commit 8b31480

Browse files
authored
[anomaly-detector] Update projects to use snippets (#32472)
### Packages impacted by this PR - @azure-rest/ai-anomaly-detector ### Issues associated with this PR - #32416 ### Describe the problem that is addressed by this PR Updates snippets for all projects under the `anomalydetector` folder. ### What are the possible designs available to address the problem? If there are more than one possible design, why was the one in this PR chosen? ### Are there test cases added in this PR? _(If not, why?)_ ### Provide a list of related PRs _(if any)_ ### Command used to generate this PR:**_(Applicable only to SDK release request PRs)_ ### Checklists - [ ] Added impacted package name to the issue description - [ ] Does this PR needs any fixes in the SDK Generator?** _(If so, create an Issue in the [Autorest/typescript](https://github.com/Azure/autorest.typescript) repository and link it here)_ - [ ] Added a changelog (if necessary)
1 parent 814b725 commit 8b31480

9 files changed

+345
-181
lines changed

sdk/anomalydetector/ai-anomaly-detector-rest/README.md

+127-103
Original file line numberDiff line numberDiff line change
@@ -89,148 +89,172 @@ The following section provides several code snippets covering some of the most c
8989

9090
### Batch detection
9191

92-
```typescript
92+
```ts snippet:batch_detection
93+
import {
94+
TimeSeriesPoint,
95+
AnomalyDetector,
96+
DetectUnivariateEntireSeriesParameters,
97+
isUnexpected,
98+
} from "@azure-rest/ai-anomaly-detector";
99+
import { parse } from "csv-parse/sync";
100+
import { AzureKeyCredential } from "@azure/core-auth";
101+
93102
const apiKey = process.env["ANOMALY_DETECTOR_API_KEY"] || "";
94103
const endpoint = process.env["ANOMALY_DETECTOR_ENDPOINT"] || "";
95104
const timeSeriesDataPath = "./samples-dev/example-data/request-data.csv";
96105

97106
function read_series_from_file(path: string): Array<TimeSeriesPoint> {
98-
let result = Array<TimeSeriesPoint>();
99-
let input = fs.readFileSync(path).toString();
100-
let parsed = parse(input, { skip_empty_lines: true });
107+
const result = Array<TimeSeriesPoint>();
108+
const input = fs.readFileSync(path).toString();
109+
const parsed = parse(input, { skip_empty_lines: true });
101110
parsed.forEach(function (e: Array<string>) {
102111
result.push({ timestamp: new Date(e[0]), value: Number(e[1]) });
103112
});
104113
return result;
105114
}
106115

107-
export async function main() {
108-
// create client
109-
const credential = new AzureKeyCredential(apiKey);
110-
const client = AnomalyDetector(endpoint, credential);
111-
112-
// construct request
113-
const options: DetectUnivariateEntireSeriesParameters = {
114-
body: {
115-
granularity: "daily",
116-
imputeMode: "auto",
117-
maxAnomalyRatio: 0.25,
118-
sensitivity: 95,
119-
series: read_series_from_file(timeSeriesDataPath),
120-
},
121-
headers: { "Content-Type": "application/json" },
122-
};
123-
124-
// get last detect result
125-
const result = await client.path("/timeseries/entire/detect").post(options);
126-
if (isUnexpected(result)) {
127-
throw result;
128-
}
129-
130-
if (result.body.isAnomaly) {
131-
result.body.isAnomaly.forEach(function (anomaly, index) {
132-
if (anomaly === true) {
133-
console.log(index);
134-
}
135-
});
136-
} else {
137-
console.log("There is no anomaly detected from the series.");
138-
}
116+
// create client
117+
const credential = new AzureKeyCredential(apiKey);
118+
const client = AnomalyDetector(endpoint, credential);
119+
120+
// construct request
121+
const options: DetectUnivariateEntireSeriesParameters = {
122+
body: {
123+
granularity: "daily",
124+
imputeMode: "auto",
125+
maxAnomalyRatio: 0.25,
126+
sensitivity: 95,
127+
series: read_series_from_file(timeSeriesDataPath),
128+
},
129+
headers: { "Content-Type": "application/json" },
130+
};
131+
132+
// get last detect result
133+
const result = await client.path("/timeseries/entire/detect").post(options);
134+
if (isUnexpected(result)) {
135+
throw result;
136+
}
137+
138+
if (result.body.isAnomaly) {
139+
result.body.isAnomaly.forEach(function (anomaly, index) {
140+
if (anomaly === true) {
141+
console.log(index);
142+
}
143+
});
144+
} else {
145+
console.log("There is no anomaly detected from the series.");
146+
}
139147
```
140148

141149
### Streaming Detection
142150

143-
```typescript
151+
```ts snippet:streaming_detection
152+
import {
153+
TimeSeriesPoint,
154+
AnomalyDetector,
155+
DetectUnivariateLastPointParameters,
156+
isUnexpected,
157+
} from "@azure-rest/ai-anomaly-detector";
158+
import { parse } from "csv-parse/sync";
159+
import { AzureKeyCredential } from "@azure/core-auth";
160+
144161
const apiKey = process.env["ANOMALY_DETECTOR_API_KEY"] || "";
145162
const endpoint = process.env["ANOMALY_DETECTOR_ENDPOINT"] || "";
146163
const timeSeriesDataPath = "./samples-dev/example-data/request-data.csv";
147164

148165
function read_series_from_file(path: string): Array<TimeSeriesPoint> {
149-
let result = Array<TimeSeriesPoint>();
150-
let input = fs.readFileSync(path).toString();
151-
let parsed = parse(input, { skip_empty_lines: true });
166+
const result = Array<TimeSeriesPoint>();
167+
const input = fs.readFileSync(path).toString();
168+
const parsed = parse(input, { skip_empty_lines: true });
152169
parsed.forEach(function (e: Array<string>) {
153170
result.push({ timestamp: new Date(e[0]), value: Number(e[1]) });
154171
});
155172
return result;
156173
}
157174

158-
export async function main() {
159-
// create client
160-
const credential = new AzureKeyCredential(apiKey);
161-
const client = AnomalyDetector(endpoint, credential);
162-
163-
// construct request
164-
const options: DetectUnivariateLastPointParameters = {
165-
body: {
166-
granularity: "daily",
167-
imputeFixedValue: 800,
168-
imputeMode: "fixed",
169-
maxAnomalyRatio: 0.25,
170-
sensitivity: 95,
171-
series: read_series_from_file(timeSeriesDataPath),
172-
},
173-
headers: { "Content-Type": "application/json" },
174-
};
175-
176-
// get last detect result
177-
const result = await client.path("/timeseries/last/detect").post(options);
178-
if (isUnexpected(result)) {
179-
throw result;
180-
}
181-
182-
if (result.body.isAnomaly) {
183-
console.log("The latest point is detected as anomaly.");
184-
} else {
185-
console.log("The latest point is not detected as anomaly.");
186-
}
175+
// create client
176+
const credential = new AzureKeyCredential(apiKey);
177+
const client = AnomalyDetector(endpoint, credential);
178+
179+
// construct request
180+
const options: DetectUnivariateLastPointParameters = {
181+
body: {
182+
granularity: "daily",
183+
imputeFixedValue: 800,
184+
imputeMode: "fixed",
185+
maxAnomalyRatio: 0.25,
186+
sensitivity: 95,
187+
series: read_series_from_file(timeSeriesDataPath),
188+
},
189+
headers: { "Content-Type": "application/json" },
190+
};
191+
192+
// get last detect result
193+
const result = await client.path("/timeseries/last/detect").post(options);
194+
if (isUnexpected(result)) {
195+
throw result;
196+
}
197+
198+
if (result.body.isAnomaly) {
199+
console.log("The latest point is detected as anomaly.");
200+
} else {
201+
console.log("The latest point is not detected as anomaly.");
202+
}
187203
```
188204

189205
### Detect change points
190206

191-
```typescript
207+
```ts snippet:detect_change_points
208+
import {
209+
TimeSeriesPoint,
210+
AnomalyDetector,
211+
DetectUnivariateChangePointParameters,
212+
isUnexpected,
213+
} from "@azure-rest/ai-anomaly-detector";
214+
import { parse } from "csv-parse/sync";
215+
import { AzureKeyCredential } from "@azure/core-auth";
216+
192217
const apiKey = process.env["ANOMALY_DETECTOR_API_KEY"] || "";
193218
const endpoint = process.env["ANOMALY_DETECTOR_ENDPOINT"] || "";
194219
const timeSeriesDataPath = "./samples-dev/example-data/request-data.csv";
195220

196221
function read_series_from_file(path: string): Array<TimeSeriesPoint> {
197-
let result = Array<TimeSeriesPoint>();
198-
let input = fs.readFileSync(path).toString();
199-
let parsed = parse(input, { skip_empty_lines: true });
222+
const result = Array<TimeSeriesPoint>();
223+
const input = fs.readFileSync(path).toString();
224+
const parsed = parse(input, { skip_empty_lines: true });
200225
parsed.forEach(function (e: Array<string>) {
201226
result.push({ timestamp: new Date(e[0]), value: Number(e[1]) });
202227
});
203228
return result;
204229
}
205230

206-
export async function main() {
207-
const credential = new AzureKeyCredential(apiKey);
208-
const client = AnomalyDetector(endpoint, credential);
209-
const options: DetectUnivariateChangePointParameters = {
210-
body: {
211-
granularity: "daily",
212-
series: read_series_from_file(timeSeriesDataPath),
213-
},
214-
headers: { "Content-Type": "application/json" },
215-
};
216-
const result = await client.path("/timeseries/changepoint/detect").post(options);
217-
if (isUnexpected(result)) {
218-
throw result;
219-
}
220-
221-
if (result.body.isChangePoint === undefined) throw new Error("Empty isChangePoint");
222-
if (
223-
result.body.isChangePoint.some(function (changePoint) {
224-
return changePoint === true;
225-
})
226-
) {
227-
console.log("Change points were detected from the series at index:");
228-
result.body.isChangePoint.forEach(function (changePoint, index) {
229-
if (changePoint === true) console.log(index);
230-
});
231-
} else {
232-
console.log("There is no change point detected from the series.");
233-
}
231+
const credential = new AzureKeyCredential(apiKey);
232+
const client = AnomalyDetector(endpoint, credential);
233+
const options: DetectUnivariateChangePointParameters = {
234+
body: {
235+
granularity: "daily",
236+
series: read_series_from_file(timeSeriesDataPath),
237+
},
238+
headers: { "Content-Type": "application/json" },
239+
};
240+
const result = await client.path("/timeseries/changepoint/detect").post(options);
241+
if (isUnexpected(result)) {
242+
throw result;
243+
}
244+
245+
if (result.body.isChangePoint === undefined) throw new Error("Empty isChangePoint");
246+
if (
247+
result.body.isChangePoint.some(function (changePoint) {
248+
return changePoint === true;
249+
})
250+
) {
251+
console.log("Change points were detected from the series at index:");
252+
result.body.isChangePoint.forEach(function (changePoint, index) {
253+
if (changePoint === true) console.log(index);
254+
});
255+
} else {
256+
console.log("There is no change point detected from the series.");
257+
}
234258
```
235259

236260
### Multivariate Anomaly Detection Sample
@@ -245,8 +269,8 @@ To see how to use Anomaly Detector library to conduct Multivariate Anomaly Detec
245269

246270
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`:
247271

248-
```javascript
249-
const { setLogLevel } = require("@azure/logger");
272+
```ts snippet:SetLogLevel
273+
import { setLogLevel } from "@azure/logger";
250274

251275
setLogLevel("info");
252276
```

sdk/anomalydetector/ai-anomaly-detector-rest/package.json

+8-8
Original file line numberDiff line numberDiff line change
@@ -50,18 +50,18 @@
5050
"unit-test": "npm run unit-test:node && npm run unit-test:browser",
5151
"unit-test:browser": "npm run clean && dev-tool run build-package && dev-tool run build-test && dev-tool run test:vitest --browser",
5252
"unit-test:node": "dev-tool run test:vitest",
53-
"update-snippets": "echo skipped"
53+
"update-snippets": "dev-tool run update-snippets"
5454
},
5555
"sideEffects": false,
5656
"autoPublish": false,
5757
"dependencies": {
58-
"@azure-rest/core-client": "^1.0.0",
59-
"@azure/core-auth": "^1.3.0",
60-
"@azure/core-lro": "^2.2.0",
61-
"@azure/core-paging": "^1.2.0",
62-
"@azure/core-rest-pipeline": "^1.8.0",
63-
"@azure/logger": "^1.0.0",
64-
"tslib": "^2.2.0"
58+
"@azure-rest/core-client": "^2.3.1",
59+
"@azure/core-auth": "^1.9.0",
60+
"@azure/core-lro": "^2.7.2",
61+
"@azure/core-paging": "^1.6.2",
62+
"@azure/core-rest-pipeline": "^1.18.1",
63+
"@azure/logger": "^1.1.4",
64+
"tslib": "^2.8.1"
6565
},
6666
"devDependencies": {
6767
"@azure-tools/test-credential": "^2.0.0",

sdk/anomalydetector/ai-anomaly-detector-rest/samples-dev/sample_detect_change_point.ts

+7-8
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,18 @@
77
* @summary detects change points.
88
*/
99

10-
import AnomalyDetector, {
10+
import type {
1111
DetectUnivariateChangePointParameters,
12-
isUnexpected,
1312
TimeSeriesPoint,
1413
} from "@azure-rest/ai-anomaly-detector";
14+
import AnomalyDetector, { isUnexpected } from "@azure-rest/ai-anomaly-detector";
1515
import { AzureKeyCredential } from "@azure/core-auth";
1616

1717
import { parse } from "csv-parse/sync";
1818
import * as fs from "node:fs";
1919

2020
// Load the .env file if it exists
21-
import * as dotenv from "dotenv";
22-
dotenv.config();
21+
import "dotenv/config";
2322

2423
// You will need to set this environment variables or edit the following values
2524

@@ -28,16 +27,16 @@ const endpoint = process.env["ANOMALY_DETECTOR_ENDPOINT"] || "";
2827
const timeSeriesDataPath = "./samples-dev/example-data/request-data.csv";
2928

3029
function read_series_from_file(path: string): Array<TimeSeriesPoint> {
31-
let result = Array<TimeSeriesPoint>();
32-
let input = fs.readFileSync(path).toString();
33-
let parsed = parse(input, { skip_empty_lines: true });
30+
const result = Array<TimeSeriesPoint>();
31+
const input = fs.readFileSync(path).toString();
32+
const parsed = parse(input, { skip_empty_lines: true });
3433
parsed.forEach(function (e: Array<string>) {
3534
result.push({ timestamp: new Date(e[0]), value: Number(e[1]) });
3635
});
3736
return result;
3837
}
3938

40-
export async function main() {
39+
export async function main(): Promise<void> {
4140
const credential = new AzureKeyCredential(apiKey);
4241
const client = AnomalyDetector(endpoint, credential);
4342
const options: DetectUnivariateChangePointParameters = {

sdk/anomalydetector/ai-anomaly-detector-rest/samples-dev/sample_detect_entire_series_anomaly.ts

+7-8
Original file line numberDiff line numberDiff line change
@@ -7,36 +7,35 @@
77
* @summary detects anomaly points on entire series.
88
*/
99

10-
import AnomalyDetector, {
10+
import type {
1111
DetectUnivariateEntireSeriesParameters,
12-
isUnexpected,
1312
TimeSeriesPoint,
1413
} from "@azure-rest/ai-anomaly-detector";
14+
import AnomalyDetector, { isUnexpected } from "@azure-rest/ai-anomaly-detector";
1515
import { AzureKeyCredential } from "@azure/core-auth";
1616

1717
import { parse } from "csv-parse/sync";
1818
import * as fs from "node:fs";
1919

2020
// Load the .env file if it exists
21-
import * as dotenv from "dotenv";
22-
dotenv.config();
21+
import "dotenv/config";
2322

2423
// You will need to set this environment variables or edit the following values
2524
const apiKey = process.env["ANOMALY_DETECTOR_API_KEY"] || "";
2625
const endpoint = process.env["ANOMALY_DETECTOR_ENDPOINT"] || "";
2726
const timeSeriesDataPath = "./samples-dev/example-data/request-data.csv";
2827

2928
function read_series_from_file(path: string): Array<TimeSeriesPoint> {
30-
let result = Array<TimeSeriesPoint>();
31-
let input = fs.readFileSync(path).toString();
32-
let parsed = parse(input, { skip_empty_lines: true });
29+
const result = Array<TimeSeriesPoint>();
30+
const input = fs.readFileSync(path).toString();
31+
const parsed = parse(input, { skip_empty_lines: true });
3332
parsed.forEach(function (e: Array<string>) {
3433
result.push({ timestamp: new Date(e[0]), value: Number(e[1]) });
3534
});
3635
return result;
3736
}
3837

39-
export async function main() {
38+
export async function main(): Promise<void> {
4039
// create client
4140
const credential = new AzureKeyCredential(apiKey);
4241
const client = AnomalyDetector(endpoint, credential);

0 commit comments

Comments
 (0)