wp-styler-ai
Version:
Generate WordPress theme.json color palettes from images using AI-powered OCR through the OpenRouter API and Gemini Flash 2.0.
62 lines (59 loc) • 2.89 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ocr = ocr;
const openai_1 = __importDefault(require("openai"));
const fs_1 = __importDefault(require("fs"));
async function ocr({ filePath, apiKey = process.env.OPENROUTER_API_KEY, model = "google/gemini-2.0-flash-exp:free", }) {
const openai = new openai_1.default({
apiKey: apiKey,
baseURL: "https://openrouter.ai/api/v1",
});
let finalResult = await getThemeJson({ openai, model, filePath });
return finalResult;
}
async function getThemeJson({ openai, model, filePath, }) {
const systemPrompt = `
Be strictly accurate and ensure every color in the attached image is included in the extracted palette. Follow these rules:
1. Extract the color palette from the image and return it as a JSON object matching the format of the "settings.color.palette" array in a WordPress theme.json file.
2. Each color must have these keys: "slug", "color" (hexadecimal), and "name".
3. Use best practices for naming conventions. If a section title is present, prefix it to the color name.
4. Ensure no colors are missed, duplicated, or misrepresented. Critically review the output to include all unique HEX codes from the image.
5. Return only the JSON object and no additional text.
**Example JSON format (do not directly copy these colors):**
{"$schema":"https://schemas.wp.org/trunk/theme.json","version":3,"settings":{"color":{"palette":[{"slug":"white","color":"#FFFFFF","name":"White"},{"slug":"black","color":"#000000","name":"Black"},{"slug":"primary","color":"#2D2DC7","name":"Primary"}]}}}
`;
const finalImageUrl = isRemoteFile(filePath)
? filePath
: `data:image/jpeg;base64,${encodeImage(filePath)}`;
const response = await openai.chat.completions.create({
model: model,
messages: [
{
role: "user",
content: [
{ type: "text", text: systemPrompt },
{
type: "image_url",
image_url: {
url: finalImageUrl,
},
},
],
},
],
});
// Cleanup response to remove backticks or markdown syntax
const rawContent = response.choices[0].message.content;
const cleanContent = rawContent.replace(/```(?:json)?\n?|\\n/g, "").trim();
return JSON.parse(cleanContent);
}
function encodeImage(imagePath) {
const imageFile = fs_1.default.readFileSync(imagePath);
return Buffer.from(imageFile).toString("base64");
}
function isRemoteFile(filePath) {
return filePath.startsWith("http://") || filePath.startsWith("https://");
}