Skip to content

Instantly share code, notes, and snippets.

@anjanesh
Last active February 28, 2023 07:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anjanesh/cc7417440584ac5cf3b92eb8d68e23cf to your computer and use it in GitHub Desktop.
Save anjanesh/cc7417440584ac5cf3b92eb8d68e23cf to your computer and use it in GitHub Desktop.
deno webserver returning JSON for tensorflowJS for toxicity model
import tfjs from "npm:@tensorflow/tfjs@4.2.0";
import * as toxicity from "npm:@tensorflow-models/toxicity@1.2.2";
const server = Deno.listen({ port: 8080 });
console.log(`HTTP webserver running. Access it at: http://localhost:8080/`);
const threshold = 0.5;
let t0 = performance.now();
let arrToxicity = {};
let counter = 0;
let toxicityF = async (sentence) =>
{
return await new Promise((resolve, reject) =>
{
console.log("Calling toxicity .. now");
toxicity.load(threshold).then((model: any) =>
{
const sentences = [sentence];
model.classify(sentences).then((predictions: Array<String>) =>
{
predictions.map((p) =>
{
arrToxicity[p.label] = p.results[0].match
});
}).then(() =>
{
let t1 = performance.now();
console.log("Call to toxicity took " + (t1 - t0) + " milliseconds.");
resolve(JSON.stringify(arrToxicity, null, 2));
}).catch(() => reject("error") );
});
});
};
for await (const conn of server)
{
serveHttp(conn);
}
async function serveHttp(conn: Deno.Conn)
{
const httpConn = Deno.serveHttp(conn);
for await (const requestEvent of httpConn)
{
counter++;
const url = new URL(requestEvent.request.url);
switch (url.pathname)
{
case "/toxicity":
let sentence = url.searchParams.get("sentence"); // Bad worded sentence
if (sentence)
{
const res = toxicityF(sentence).then((body) =>
{
requestEvent.respondWith(new Response(body, { status: 200, headers: { "content-type": "application/json",} }),);
});
}
else
{
requestEvent.respondWith(new Response("sentence is required in query", { status: 200 }),);
}
break;
default:
requestEvent.respondWith(new Response(counter, { status: 200, }),);
}
}
}
@anjanesh
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment