Last active
February 28, 2023 07:40
-
-
Save anjanesh/cc7417440584ac5cf3b92eb8d68e23cf to your computer and use it in GitHub Desktop.
deno webserver returning JSON for tensorflowJS for toxicity model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, }),); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Enter this in the browser : http://localhost:8080/toxicity?sentence=kiss%20my%20ass%20you%20piece%20of%20shit