doraaaslogicspine / src /index.ts
Primearchive's picture
Update src/index.ts
77cf2e2 verified
Raw History Blame Contribute Delete
17.6 kB
import express, { Request, Response } from 'express';
import google from 'googlethis';
import swaggerUi from 'swagger-ui-express';
import {
AutoTokenizer,
AutoProcessor,
CLIPTextModelWithProjection,
CLIPVisionModelWithProjection,
RawImage
} from '@xenova/transformers';
const app = express();
app.use(express.json({ limit: '50mb' }));
const PORT = process.env.PORT || 7860;
const MODEL_NAME = 'Xenova/clip-vit-base-patch32';
const PIXABAY_API_KEY = process.env.PIXABAY_API || '';
let tokenizer: any = null;
let processor: any = null;
let textModel: any = null;
let visionModel: any = null;
const BLACKLISTED_SITES = [
"pinterest.com", "pinterest.co.uk", "youtube.com", "tiktok.com",
"facebook.com", "instagram.com", "quora.com", "9gag.com",
"netflix.com", "elements.envato.com", "123rf.com", "freepik.com",
"alamy.com", "istockphoto.com", "gettyimages.com", "gettyimages.fr",
"gettyimages.dk", "gettyimages.fi", "gettyimages.no", "gettyimages.ae",
"gettyimages.in", "gettyimages.com.au", "gettyimages.co.nz",
"gettyimages.ca", "gettyimages.co.uk", "gettyimages.ie",
"shutterstock.com", "adobe.com", "stocksnap.io", "stockvault.net",
"gratisography.com", "peopleimages.com", "demilked.com",
"negativespace.co", "coverr.co", "stockfresh.com",
"focusedcollection.com", "cxl.com", "startupstockphotos.com",
"blueprintdigital.com", "muniandahuaylas.gob.pe", "mixedasianmedia.com",
"shaalaa.com", "wordpress.com", "imgcdn.stablediffusionweb.com", "stablediffusionweb.com"
];
const swaggerDocument = {
openapi: '3.0.0',
info: {
title: 'DORAAA Asset Engine V2.0',
version: '2.0.0',
description: 'Real-time multi-anchor search & ranking API with ultra-fast deterministic asset metadata extraction.'
},
paths: {
'/generate-slide': {
post: {
summary: 'Search, Classify, Rank, and Extract Metadata',
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
properties: {
query: { type: 'string', example: 'Akbar sitting on a throne' },
type: { type: 'string', enum: ['person', 'organization', 'place', 'object'], default: 'object' },
searchLimit: { type: 'number', default: 8 },
returnCount: { type: 'number', default: 1 },
imageMode: { type: 'string', enum: ['normal', 'face', 'clipart', 'lineart'], default: 'clipart' },
transparentOnly: { type: 'boolean', default: true },
allowText: { type: 'boolean', default: false },
url: { type: 'boolean', default: true },
base64: { type: 'boolean', default: true }
},
required: ['query']
}
}
}
},
responses: { 200: { description: 'Success' } }
}
},
'/health': {
get: {
summary: 'Health Probe Status Check',
responses: { 200: { description: 'Alive' } }
}
}
}
};
app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
function cosineSimilarity(vecA: number[], vecB: number[]): number {
let dotProduct = 0;
let normA = 0;
let normB = 0;
for (let i = 0; i < vecA.length; i++) {
dotProduct += vecA[i] * vecB[i];
normA += vecA[i] * vecA[i];
normB += vecB[i] * vecB[i];
}
return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
}
function extractFilenameFromUrl(url: string): string {
try {
const cleanUrl = url.split('?')[0];
const parts = cleanUrl.split('/');
const lastPart = parts[parts.length - 1] || '';
const filenameNoExt = lastPart.replace(/\.(jpg|jpeg|png|gif|webp|svg|bmp)$/i, '');
const cleanText = filenameNoExt.replace(/[-_]/g, ' ').trim();
return cleanText.slice(0, 100);
} catch (e) {
return '';
}
}
function getTypeClassificationPrompt(type: string): string {
switch (type.toLowerCase()) {
case 'person':
return "a portrait photograph, character illustration, portrait painting, or human figure face";
case 'organization':
return "a corporate logo, brand emblem, crest insignia, vector icon stamp, or official company identity asset";
case 'place':
return "a landscape photograph, architecture landmark, outdoor scenery, or environmental background building view";
case 'object':
default:
return "a standalone physical item, isolated graphic object, product, or realistic tool item";
}
}
/**
* DORAAA Engine V2.0: Single-Pass Deterministic Fast Metadata Extractor
* Executes in a few milliseconds on the raw pixel buffer without ML models or extra passes.
*/
function extractImageMetadata(rawImg: any) {
const width = rawImg.width;
const height = rawImg.height;
const channels = rawImg.channels;
const data = rawImg.data; // Uint8Array or Uint8ClampedArray
const aspectRatio = Number((width / height).toFixed(6));
const totalPixels = width * height;
let transparentPixelCount = 0;
let minX = width;
let minY = height;
let maxX = -1;
let maxY = -1;
// Check if image possesses an alpha channel
const hasAlpha = channels === 4;
if (hasAlpha) {
// Single-Pass scan across the raw pixel array
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const index = (y * width + x) * 4;
const alpha = data[index + 3];
if (alpha < 10) { // Considered fully transparent pixel
transparentPixelCount++;
} else { // Non-transparent pixel
if (x < minX) minX = x;
if (x > maxX) maxX = x;
if (y < minY) minY = y;
if (y > maxY) maxY = y;
}
}
}
}
const hasTransparency = hasAlpha && transparentPixelCount > 0;
const transparencyPercentage = hasTransparency
? Number(((transparentPixelCount / totalPixels) * 100).toFixed(2))
: 0;
let contentBounds: { left: number; top: number; right: number; bottom: number; width: number; height: number };
if (hasTransparency && maxX >= minX && maxY >= minY) {
contentBounds = {
left: minX,
top: minY,
right: maxX,
bottom: maxY,
width: maxX - minX + 1,
height: maxY - minY + 1
};
} else {
// Default to full dimensions if no transparency exists or no fully clear boundaries
contentBounds = {
left: 0,
top: 0,
right: width - 1,
bottom: height - 1,
width: width,
height: height
};
}
const normalizedContentBounds = {
left: Number((contentBounds.left / width).toFixed(4)),
top: Number((contentBounds.top / height).toFixed(4)),
right: Number((contentBounds.right / width).toFixed(4)),
bottom: Number((contentBounds.bottom / height).toFixed(4))
};
let mimeType = 'image/png';
if (channels === 3) {
mimeType = 'image/jpeg';
} else if (hasTransparency) {
mimeType = 'image/png';
}
return {
width,
height,
aspectRatio,
mimeType,
fileSize: data.byteLength,
hasTransparency,
transparencyPercentage,
contentBounds,
normalizedContentBounds
};
}
async function fetchFromPixabay(query: string, imageMode: string, limit: number): Promise<Array<{ url: string; thumbnail?: string }>> {
if (!PIXABAY_API_KEY) {
console.log("[PIXABAY] No PIXABAY_API key provided in environment variables. Skipping to fallback...");
return [];
}
try {
let pixabayType = 'all';
if (imageMode === 'clipart') pixabayType = 'vector';
else if (imageMode === 'lineart') pixabayType = 'illustration';
else if (imageMode === 'face' || imageMode === 'normal') pixabayType = 'photo';
const encodedQuery = encodeURIComponent(query);
const apiUrl = `https://pixabay.com/api/?key=${PIXABAY_API_KEY}&q=${encodedQuery}&image_type=${pixabayType}&per_page=${Math.max(limit, 3)}&safesearch=true`;
console.log(`[PIXABAY] Fetching directly from Pixabay API: "${query}"...`);
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`Pixabay API responded with status ${response.status}`);
}
const data = await response.json();
if (!data.hits || data.hits.length === 0) {
console.log("[PIXABAY] 0 hits found for query.");
return [];
}
console.log(`[PIXABAY] Successfully retrieved ${data.hits.length} images from Pixabay.`);
return data.hits.map((hit: any) => ({
url: hit.largeImageURL || hit.webformatURL || hit.previewURL,
thumbnail: hit.webformatURL || hit.previewURL
}));
} catch (err: any) {
console.error(`[PIXABAY ERROR] ${err.message}. Falling back to Google...`);
return [];
}
}
async function fetchFromGoogle(query: string, imageMode: string, transparentOnly: boolean, limit: number): Promise<Array<{ url: string; thumbnail?: string }>> {
const MAX_SITE_EXCLUSIONS = 20;
const limitedBlacklist = BLACKLISTED_SITES.slice(0, MAX_SITE_EXCLUSIONS);
const siteExclusions = limitedBlacklist.map(site => `-site:${site}`).join(' ');
const finalGoogleQuery = `${query.trim()} ${siteExclusions}`;
const advancedTools: string[] = [];
if (imageMode !== 'normal') advancedTools.push(`itp:${imageMode}`);
if (transparentOnly) advancedTools.push('ic:trans');
advancedTools.push('ift:png');
const scraperOptions = {
safe: false,
page: 0,
additional_params: { tbs: advancedTools.join(',') }
};
console.log(`[GOOGLE SCRAPER] Fetching from Google Images...`);
const scrapedResults = await google.image(finalGoogleQuery, scraperOptions);
if (!scrapedResults || scrapedResults.length === 0) {
return [];
}
return scrapedResults.map((item: any) => ({
url: item.url,
thumbnail: item.thumbnail || item.url
}));
}
async function initModels() {
console.log("=== STARTING AI MODEL BOOTSTRAP ===");
tokenizer = await AutoTokenizer.from_pretrained(MODEL_NAME);
processor = await AutoProcessor.from_pretrained(MODEL_NAME);
textModel = await CLIPTextModelWithProjection.from_pretrained(MODEL_NAME, { quantized: true });
visionModel = await CLIPVisionModelWithProjection.from_pretrained(MODEL_NAME, { quantized: true });
console.log("=== MODEL LIFECYCLE INITIALIZED SUCCESSFULLY ===");
}
async function executionPipeline(config: {
query: string;
type: string;
searchLimit: number;
returnCount: number;
imageMode: 'normal' | 'face' | 'clipart' | 'lineart';
transparentOnly: boolean;
allowText: boolean;
includeUrl: boolean;
includeBase64: boolean;
}) {
console.log(`\n--- RUNNING HYBRID SEARCH PIPELINE FOR: "${config.query}" [Type: ${config.type}] ---`);
// 1. Primary: Pixabay API
let candidateImages = await fetchFromPixabay(config.query, config.imageMode, config.searchLimit);
// 2. Fallback: Google Search Scraper
if (candidateImages.length === 0) {
console.log("[FALLBACK] Switching to Google Scraper layer...");
try {
candidateImages = await fetchFromGoogle(config.query, config.imageMode, config.transparentOnly, config.searchLimit);
} catch (googleErr: any) {
throw new Error(`Both Pixabay and Google search failed: ${googleErr.message}`);
}
}
if (candidateImages.length === 0) {
console.log("[ERROR] Search providers returned 0 raw links.");
return [];
}
console.log(`[PROCESSING] Evaluating top ${Math.min(candidateImages.length, config.searchLimit)} image tensors with CLIP AI...`);
const limitedImages = candidateImages.slice(0, config.searchLimit);
// --- ASYNCHRONOUS ANCHOR TEXT EMBEDDINGS ---
const textInputs = tokenizer([config.query], { padding: true, truncation: true, max_length: 77 });
const p1 = textModel(textInputs);
const typePromptText = getTypeClassificationPrompt(config.type);
const typeInputs = tokenizer([typePromptText], { padding: true, truncation: true, max_length: 77 });
const p2 = textModel(typeInputs);
const negativePrompts = [
"text, typography, sentences, words, document, captions, labeling, letters",
"screenshot, website interface, software dashboard, login page, app window, computer user interface",
"geographic map, country map, land atlas, chart, diagram, infographic, timeline, family tree"
];
const negativePromises = negativePrompts.map(prompt => {
const negInputs = tokenizer([prompt], { padding: true, truncation: true, max_length: 77 });
return textModel(negInputs);
});
const [queryRes, typeRes, ...negResults] = await Promise.all([p1, p2, ...negativePromises]);
const positiveVector = Array.from(queryRes.text_embeds.data) as number[];
const typeVector = Array.from(typeRes.text_embeds.data) as number[];
const negativeVectors = negResults.map(res => Array.from(res.text_embeds.data) as number[]);
// Intermediate store to keep raw image instances for post-ranking metadata analysis
const evaluatedCandidates: Array<{
url: string;
rawImgInstance: any;
score: number;
}> = [];
const promises = limitedImages.map(async (img: any, idx: number) => {
const targetUrl = img.thumbnail || img.url;
try {
if (!targetUrl.startsWith('http')) return;
const sanitizedFilename = extractFilenameFromUrl(targetUrl);
let filenameBonus = 0;
if (sanitizedFilename && sanitizedFilename.length > 2) {
const fileInputs = tokenizer([sanitizedFilename], { padding: true, truncation: true, max_length: 77 });
const { text_embeds: fileEmbeds } = await textModel(fileInputs);
const fileVector = Array.from(fileEmbeds.data) as number[];
const fileMatchFactor = cosineSimilarity(fileVector, positiveVector);
if (fileMatchFactor > 0) {
filenameBonus = fileMatchFactor * 0.12;
}
}
const rawImgInstance = await RawImage.read(targetUrl);
const imageInputs = await processor(rawImgInstance);
const { image_embeds } = await visionModel(imageInputs);
const imageVector = Array.from(image_embeds.data) as number[];
const queryScore = cosineSimilarity(imageVector, positiveVector);
const typeScore = cosineSimilarity(imageVector, typeVector);
let maxNegativeImpact = 0;
if (!config.allowText) {
for (const negVec of negativeVectors) {
const currentNegScore = cosineSimilarity(imageVector, negVec);
if (currentNegScore > maxNegativeImpact) {
maxNegativeImpact = currentNegScore;
}
}
}
const finalScore = queryScore + (typeScore * 0.8) + filenameBonus - (maxNegativeImpact * 1.5);
console.log(` [Image ${idx + 1}] "${sanitizedFilename || 'unknown'}" -> Query: ${queryScore.toFixed(2)} | Type: ${typeScore.toFixed(2)} | File Bonus: +${filenameBonus.toFixed(2)} | Penalty: ${maxNegativeImpact.toFixed(2)} -> Total: ${finalScore.toFixed(3)}`);
evaluatedCandidates.push({
url: img.url,
rawImgInstance,
score: finalScore
});
} catch (e: any) {
console.log(` [Image ${idx + 1}] Processing issue skipped: ${e.message}`);
}
});
await Promise.all(promises);
console.log(`[RANKING] Sorting candidates and selecting top ${config.returnCount} asset(s)...`);
// Sort candidates by final score descending
const topCandidates = evaluatedCandidates
.sort((a, b) => b.score - a.score)
.slice(0, config.returnCount);
console.log(`[DORAAA ENGINE V2.0] Extracting deterministic metadata for ${topCandidates.length} selected asset(s)...`);
// Extract metadata ONLY for the surviving selected images
const finalResults = topCandidates.map((candidate) => {
const metadata = extractImageMetadata(candidate.rawImgInstance);
const resultItem: any = {
score: candidate.score,
metadata
};
if (config.includeUrl) {
resultItem.url = candidate.url;
}
if (config.includeBase64) {
resultItem.base64 = `data:image/png;base64,${Buffer.from(candidate.rawImgInstance.data.buffer).toString('base64')}`;
}
return resultItem;
});
return finalResults;
}
// --- API Endpoints ---
app.get('/', (req: Request, res: Response) => {
res.json({ status: true });
});
app.post('/generate-slide', async (req: Request, res: Response): Promise<any> => {
try {
const {
query,
type = 'object',
searchLimit = 8,
returnCount = 1,
imageMode = 'clipart',
transparentOnly = true,
allowText = false,
url = true,
base64 = true
} = req.body;
if (!query) {
return res.status(400).json({ error: "Missing required string 'query' inside payload body." });
}
const outputAssets = await executionPipeline({
query,
type,
searchLimit: Number(searchLimit),
returnCount: Number(returnCount),
imageMode,
transparentOnly: Boolean(transparentOnly),
allowText: Boolean(allowText),
includeUrl: Boolean(url),
includeBase64: Boolean(base64)
});
return res.json({
success: true,
query,
type,
results: outputAssets
});
} catch (err: any) {
console.error(`[API RUNTIME CRASH] ${err.message}`);
return res.status(500).json({ success: false, error: err.message });
}
});
app.get('/health', (req: Request, res: Response) => {
res.json({ status: "alive", model: MODEL_NAME, version: "2.0.0" });
});
initModels().then(() => {
app.listen(PORT, () => {
console.log(`DORAAA Asset Engine V2.0 server listening on port: ${PORT}`);
});
});