-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalyze.ts
41 lines (35 loc) · 978 Bytes
/
analyze.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// deno-lint-ignore-file ban-ts-comment
import { MODEL_API } from "./constant.ts";
import {
SentimentAnalysisResponse,
SentimentAnalysisResult,
SentimentMap,
} from "./type.ts";
export async function analyzeSentiment(
review: string | string[],
HF_KEY: string
) {
const response = await fetch(MODEL_API, {
method: "POST",
headers: {
Authorization: `Bearer ${HF_KEY}`,
},
body: JSON.stringify({ inputs: review }),
});
const body: SentimentAnalysisResponse = await response.json();
// @ts-ignore
if (body.error) throw new Error(body.error);
// @ts-ignore
const mappedResult = body.map((result) => {
const item = result.reduce(
// @ts-ignore
(acc: Record<SentimentMap, number>, { label, score }) => {
acc[label.toLowerCase() as SentimentMap] = score;
return acc;
},
{} as Record<SentimentMap, number>
);
return item;
}) as SentimentAnalysisResult[];
return mappedResult;
}