Spaces:
Sleeping

olokaflow / apps /server /src /services /promptAssetScraperService.ts
phucsd's picture
Deploy OlokaFlow Studio (Fliki Light UI + HyperFrames + OlokaTTS + Modal Cloud)
9713441 verified
Raw History Blame Contribute Delete
9.81 kB
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { UPLOADS_DIR } from '../db/database.js';
import type { AssetSourceType } from '@olokaflow/shared';
export interface ScrapedRawFile {
id: string;
name: string;
type: 'image' | 'svg' | 'video' | 'audio';
source: AssetSourceType;
sourceUrl: string;
relativePath: string;
publicUrl: string;
mimeType: string;
sizeBytes: number;
width: number;
height: number;
brandHint?: string;
pageTitle?: string;
}
export interface WebpageScrapeResult {
url: string;
pageTitle: string;
pageDescription: string;
visibleTextExcerpt: string;
extractedColors: string[];
brandNameHint: string;
files: ScrapedRawFile[];
}
export function extractUrlsFromPrompt(prompt: string): string[] {
if (!prompt) return [];
const regex = /https?:\/\/[^\s"'<>)\]]+/gi;
const matches = prompt.match(regex) || [];
return Array.from(new Set(matches.map((u) => u.replace(/[.,;!?]+$/, ''))));
}
/**
* Inspects Magic Bytes of a buffer to detect true file format and prevent HTML/corrupt image bugs.
*/
export function inspectBinaryMagicBytes(buf: Buffer): {
ext: string;
mimeType: string;
kind: 'image' | 'svg' | 'video' | 'audio' | 'html' | 'unknown';
width?: number;
height?: number;
} {
if (!buf || buf.length < 8) {
return { ext: '.bin', mimeType: 'application/octet-stream', kind: 'unknown' };
}
// PNG: 89 50 4E 47 0D 0A 1A 0A
if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {
const width = buf.length >= 24 ? buf.readUInt32BE(16) : 1080;
const height = buf.length >= 24 ? buf.readUInt32BE(20) : 1080;
return { ext: '.png', mimeType: 'image/png', kind: 'image', width, height };
}
// JPEG: FF D8 FF
if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
return { ext: '.jpg', mimeType: 'image/jpeg', kind: 'image', width: 1280, height: 720 };
}
// GIF: GIF87a or GIF89a
if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46) {
const width = buf.readUInt16LE(6);
const height = buf.readUInt16LE(8);
return { ext: '.gif', mimeType: 'image/gif', kind: 'image', width, height };
}
// WEBP: RIFF....WEBP
if (
buf.toString('ascii', 0, 4) === 'RIFF' &&
buf.toString('ascii', 8, 12) === 'WEBP'
) {
return { ext: '.webp', mimeType: 'image/webp', kind: 'image', width: 1280, height: 720 };
}
// MP4: ....ftyp
if (buf.toString('ascii', 4, 8) === 'ftyp') {
return { ext: '.mp4', mimeType: 'video/mp4', kind: 'video', width: 1920, height: 1080 };
}
// MP3: ID3 or FF FB
if (
buf.toString('ascii', 0, 3) === 'ID3' ||
(buf[0] === 0xff && (buf[1] & 0xe0) === 0xe0)
) {
return { ext: '.mp3', mimeType: 'audio/mpeg', kind: 'audio' };
}
const headText = buf.subarray(0, 512).toString('utf8').trim().toLowerCase();
if (headText.startsWith('<!doctype html') || headText.startsWith('<html')) {
return { ext: '.html', mimeType: 'text/html', kind: 'html' };
}
if (headText.includes('<svg')) {
return { ext: '.svg', mimeType: 'image/svg+xml', kind: 'svg', width: 512, height: 512 };
}
return { ext: '.bin', mimeType: 'application/octet-stream', kind: 'unknown' };
}
export async function downloadAndValidateMediaUrl(
url: string,
source: AssetSourceType = 'prompt_scraped',
brandHint = ''
): Promise<ScrapedRawFile | null> {
try {
const resp = await fetch(url, {
headers: {
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
Accept: 'image/*,video/*,audio/*,*/*;q=0.8',
},
signal: AbortSignal.timeout(12000),
});
if (!resp.ok) return null;
const buf = Buffer.from(await resp.arrayBuffer());
if (buf.length < 256) return null; // Skip 1x1 tracking pixels
const magic = inspectBinaryMagicBytes(buf);
if (magic.kind === 'html' || magic.kind === 'unknown') {
return null;
}
const id = `ast-${crypto.randomUUID().slice(0, 8)}`;
const urlPathName = new URL(url).pathname.split('/').pop() || 'scraped-media';
const baseCleanName = urlPathName
.replace(/\.[a-z0-9]+$/i, '')
.replace(/[^a-zA-Z0-9_-]/g, '_')
.slice(0, 48);
const fileName = `${id}-${baseCleanName || 'asset'}${magic.ext}`;
const fullPath = path.join(UPLOADS_DIR, fileName);
fs.writeFileSync(fullPath, buf);
return {
id,
name: baseCleanName || fileName,
type: magic.kind,
source,
sourceUrl: url,
relativePath: `uploads/${fileName}`,
publicUrl: `/media/uploads/${fileName}`,
mimeType: magic.mimeType,
sizeBytes: buf.length,
width: magic.width || 1080,
height: magic.height || 1080,
brandHint,
};
} catch {
return null;
}
}
/**
* Scrapes a webpage URL for high-res images (og:image, twitter:image, <img>, SVG logos, <video>),
* brand colors, and visible text copy.
*/
export async function scrapeWebpageUrl(url: string): Promise<WebpageScrapeResult | null> {
try {
// First check if the URL itself is a direct media file
const directMedia = await downloadAndValidateMediaUrl(url, 'prompt_scraped');
if (directMedia) {
return {
url,
pageTitle: directMedia.name,
pageDescription: '',
visibleTextExcerpt: '',
extractedColors: [],
brandNameHint: '',
files: [directMedia],
};
}
const resp = await fetch(url, {
headers: {
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
Accept: 'text/html,application/xhtml+xml',
},
signal: AbortSignal.timeout(12000),
});
if (!resp.ok) return null;
const html = await resp.text();
const baseObj = new URL(url);
const titleMatch = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
const pageTitle = titleMatch ? titleMatch[1].replace(/\s+/g, ' ').trim() : baseObj.hostname;
const descMatch =
html.match(/<meta[^>]+name=["']description["'][^>]+content=["']([^"']+)["']/i) ||
html.match(/<meta[^>]+property=["']og:description["'][^>]+content=["']([^"']+)["']/i);
const pageDescription = descMatch ? descMatch[1].trim() : '';
const siteNameMatch = html.match(
/<meta[^>]+property=["']og:site_name["'][^>]+content=["']([^"']+)["']/i
);
const brandNameHint = siteNameMatch
? siteNameMatch[1].trim()
: baseObj.hostname.replace(/^www\./, '').split('.')[0];
// Extract Hex colors from HTML/CSS
const hexMatches = html.match(/#[0-9a-fA-F]{6}\b/g) || [];
const extractedColors = Array.from(new Set(hexMatches)).slice(0, 6);
// Collect candidate image & video URLs
const candidateMediaUrls: string[] = [];
const ogImgMatches = html.matchAll(
/<meta[^>]+(?:property|name)=["'](?:og:image|twitter:image)["'][^>]+content=["']([^"']+)["']/gi
);
for (const m of ogImgMatches) {
if (m[1]) candidateMediaUrls.push(m[1]);
}
const imgMatches = html.matchAll(/<img[^>]+src=["']([^"']+)["'][^>]*>/gi);
for (const m of imgMatches) {
const src = m[1];
if (!src || src.startsWith('data:')) continue;
if (/pixel|tracker|analytics|1x1|blank\.gif/i.test(src)) continue;
candidateMediaUrls.push(src);
}
const resolvedUrls = Array.from(
new Set(
candidateMediaUrls
.map((u) => {
try {
return new URL(u, url).toString();
} catch {
return '';
}
})
.filter(Boolean)
)
).slice(0, 8);
const downloadedFiles: ScrapedRawFile[] = [];
for (const mediaUrl of resolvedUrls) {
const file = await downloadAndValidateMediaUrl(
mediaUrl,
'prompt_scraped',
brandNameHint
);
if (file) {
file.pageTitle = pageTitle;
downloadedFiles.push(file);
}
if (downloadedFiles.length >= 5) break;
}
// Extract clean visible text excerpt
const visibleTextExcerpt = html
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
.replace(/<[^>]+>/g, ' ')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 1200);
return {
url,
pageTitle,
pageDescription,
visibleTextExcerpt,
extractedColors,
brandNameHint,
files: downloadedFiles,
};
} catch {
return null;
}
}
/**
* Searches Wikimedia Commons open media API for fallback real-world reference images.
*/
export async function searchWebFallbackImages(
query: string,
limit = 2
): Promise<ScrapedRawFile[]> {
try {
const cleanQuery = query.trim();
if (!cleanQuery) return [];
const apiUrl = `https://commons.wikimedia.org/w/api.php?action=query&generator=search&gsrsearch=${encodeURIComponent(
`filetype:bitmap ${cleanQuery}`
)}&gsrlimit=${limit + 2}&prop=imageinfo&iiprop=url|dimensions|mime&iiurlwidth=1280&format=json&origin=*`;
const resp = await fetch(apiUrl, { signal: AbortSignal.timeout(8000) });
if (!resp.ok) return [];
const data = (await resp.json()) as any;
const pages = data?.query?.pages ? Object.values(data.query.pages) : [];
const results: ScrapedRawFile[] = [];
for (const p of pages as any[]) {
const info = p?.imageinfo?.[0];
const thumbUrl = info?.thumburl || info?.url;
if (!thumbUrl) continue;
const downloaded = await downloadAndValidateMediaUrl(thumbUrl, 'web_fallback');
if (downloaded) {
results.push(downloaded);
}
if (results.length >= limit) break;
}
return results;
} catch {
return [];
}
}