brat-farel / server.js
FarelDeveloper's picture
Update server.js
c25b00f verified
Raw
History Blame Contribute Delete
1.54 kB
const express = require("express");
const cors = require("cors");
const { createCanvas } = require("canvas");
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.static("public"));
function generateBratImage(text) {
const width = 1000;
const height = 1400;
const canvas = createCanvas(width, height);
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = "#000000";
ctx.font = "60px Arial";
let x = 50;
let y = 120;
text.split(" ").forEach((word, i) => {
// RANDOM JITTER
const jitterX = Math.random() * 30 - 15;
const jitterY = Math.random() * 30 - 15;
// RANDOM LINE BREAK
if (Math.random() < 0.15) {
y += 110;
x = 50;
}
ctx.fillText(word, x + jitterX, y + jitterY);
x += ctx.measureText(word).width + 40;
// NEW LINE if too long
if (x > 800) {
y += 110;
x = 50;
}
});
return canvas.toBuffer("image/png");
}
app.post("/api/brat", (req, res) => {
const { text } = req.body;
if (!text) return res.json({ error: "Masukkan text" });
const img = generateBratImage(text);
res.set("Content-Type", "image/png");
res.send(img);
});
// Home page
app.get("/", (req, res) => {
res.sendFile(__dirname + "/public/index.html");
});
// HuggingFace uses port 7860
app.listen(7860, () => console.log("Running brat generator on 7860"));