summaryrefslogtreecommitdiff
path: root/src/pages/api/nlp.ts
blob: 0e5eacb8b2188959ccdaec88cd5048aa95daee42 (plain)
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
// import db from "../../lib/db";
import { z } from "zod";
import { NLP } from "sortug-ai";

const schema = z.object({
  app: z.enum(["stanza", "spacy"]),
  text: z.string().min(3, "minimum 3 characters"),
  lang: z
    .custom<string>((val) => {
      const check = NLP.ISO.BCP47.parse(val);
      if (!check.language) return false;
      const twochars = Object.values(NLP.ISO.iso6393To1);
      return twochars.includes(check.language);
    })
    .optional(),
});

export const POST = async (request: Request): Promise<Response> => {
  const bod = await request.json();
  const { app, text, lang } = await schema.parseAsync(bod);

  try {
    const res =
      app === "stanza"
        ? NLP.Stanza.segmenter(text, lang)
        : NLP.Spacy.run(text, lang);
    const r = await res;
    return Response.json(r, { status: 200 });
  } catch (error) {
    return Response.json({ message: "Failure" }, { status: 500 });
  }
};