Use source images as article references

This commit is contained in:
Loma Bot Ops
2026-11-28 20:37:11 +07:00
parent 58216d5263
commit 6f8f84f81f
8 changed files with 101 additions and 20 deletions
+7 -7
View File
@@ -1,7 +1,7 @@
import { searchNews } from "./news";
import { websitePrompt } from "./website";
import { websiteResearch } from "./website";
export type ArticleSource = { title: string; url: string; source: string; publishedAt: string | null };
export type ArticleSource = { title: string; url: string; source: string; publishedAt: string | null; imageUrl: string | null };
/** Collects current English-language AI reporting before the text model writes an automatic article. */
export async function researchAiArticle(): Promise<{ prompt: string; sources: ArticleSource[] }> {
@@ -22,17 +22,17 @@ export async function researchAiArticle(): Promise<{ prompt: string; sources: Ar
if (selected.length === 3) break;
} catch { /* Ignore malformed search results. */ }
}
const read = await Promise.all(selected.map(async (article) => ({ article, text: await websitePrompt(article.url) })));
const usable = read.filter(({ article, text }) => text || article.description);
const read = await Promise.all(selected.map(async (article) => ({ article, research: await websiteResearch(article.url) })));
const usable = read.filter(({ article, research }) => research.prompt || article.description);
if (!usable.length) throw new Error("No readable international AI articles");
const sources = usable.map(({ article }) => ({ title: article.title, url: article.url, source: article.source, publishedAt: article.publishedAt }));
const prompt = usable.map(({ article, text }, index) => `<foreign_source index="${index + 1}">
const sources = usable.map(({ article, research }) => ({ title: article.title, url: article.url, source: article.source, publishedAt: article.publishedAt, imageUrl: research.imageUrl ?? article.imageUrl }));
const prompt = usable.map(({ article, research }, index) => `<foreign_source index="${index + 1}" has_image="${Boolean(research.imageUrl ?? article.imageUrl)}">
Publisher: ${article.source}
Published: ${article.publishedAt ?? "unknown"}
Title: ${article.title}
Search excerpt: ${article.description || "none"}
Article text:
${text || "Page could not be read; use only the title and search excerpt cautiously."}
${research.prompt || "Page could not be read; use only the title and search excerpt cautiously."}
</foreign_source>`).join("\n\n");
return { prompt, sources };
}
+2 -2
View File
@@ -23,8 +23,8 @@ export async function assertImageQuota(pageId: string): Promise<void> {
}
/** Image bytes come from the dedicated ChatGPT browser worker. */
export async function generateImage(prompt: string, size: ImageSizeKey, waitForWorker = false): Promise<GeneratedImage> {
const result = await runAutomation({ kind: "image", prompt, size }, { waitForWorker });
export async function generateImage(prompt: string, size: ImageSizeKey, waitForWorker = false, referenceImageUrl?: string): Promise<GeneratedImage> {
const result = await runAutomation({ kind: "image", prompt, size, ...(referenceImageUrl ? { referenceImageUrl } : {}) }, { waitForWorker });
if (typeof result.b64 !== "string" || !result.b64) throw new UserFacingError("Worker ไม่ส่งรูปกลับมา ตรวจการ login ChatGPT แล้วลองใหม่");
return { bytes: Buffer.from(result.b64, "base64"), contentType: "image/jpeg", inputTokens: 0, outputTokens: 0 };
}
+2
View File
@@ -7,6 +7,7 @@ export interface NewsArticle {
source: string;
publishedAt: string | null;
description: string;
imageUrl: string | null;
}
function decodeXml(value: string): string {
@@ -52,6 +53,7 @@ export async function searchNews(query: string, options: { language?: string; ma
source: field(item, "News:Source") || field(item, "source") || "แหล่งข่าว",
publishedAt: Number.isNaN(timestamp) ? null : new Date(timestamp).toISOString(),
description: field(item, "description").slice(0, 600),
imageUrl: /^https?:\/\//.test(field(item, "News:Image")) ? field(item, "News:Image") : null,
} satisfies NewsArticle;
})
.filter((article) => article.title && /^https?:\/\//.test(article.url))
+7 -2
View File
@@ -25,6 +25,7 @@ const Draft = z.object({
caption: z.string().min(1).max(5000),
imagePrompt: z.string().min(20).max(4000),
imageHeadline: z.string().max(100).default(""),
sourceIndex: z.number().int().min(0).max(3).default(0),
});
const SYSTEM = `Create a complete draft Facebook/Instagram post for a small Thai business. A human will review and approve it before publication.
@@ -98,8 +99,9 @@ This automatic slot is a Thai editorial AI-news article grounded only in <foreig
- Paraphrase; never translate long passages or invent facts. If sources disagree or a detail is not confirmed, omit it.
- Do not put publisher names, URLs, a source list, citations, or "อ้างอิง" in the caption. Provenance is retained internally for reviewers.
- imageHeadline must be a compelling factual Thai headline, 45-85 characters, suitable for 2-3 large lines. No clickbait.
- sourceIndex must identify the foreign_source used for the article (1-3).
- The imagePrompt must request a premium square editorial news visual in the shop's exact brand palette and visual style. Keep the lower half visually quiet for a Thai headline overlay. Do not request any text, logos, UI screenshots, trademarks, or copied news artwork.
` : "\nSet imageHeadline to an empty string.";
` : "\nSet imageHeadline to an empty string and sourceIndex to 0.";
const content = await generateStructured({
kind: "post-generation", pageId: job.pageId, userId: job.requestedById,
system: SYSTEM + (automatic ? "\nThis is an automatic content slot. Choose a fresh, relevant topic from the shop profile and brief data. Avoid repeating the supplied recent topics. Never invent prices, promotions, availability or claims. The configured slot is its publication time." : "") + articleRules, effort: "medium", schema: Draft, waitForWorker: true,
@@ -108,7 +110,10 @@ This automatic slot is a Thai editorial AI-news article grounded only in <foreig
if (job.targets.includes("INSTAGRAM") && content.caption.length > 2200) throw new UserFacingError("Caption ที่ AI สร้างยาวเกินข้อจำกัด Instagram กรุณาลองใหม่");
await prisma.postGenerationJob.update({ where: { id: job.id }, data: { captionResult: content, imagePrompt: content.imagePrompt, stage: "image" } });
await assertJobAccess(job.pageId, job.requestedById, automatic ? "APPROVER" : "EDITOR");
const image = await generateImage(content.imagePrompt, "square", true);
const sourceImageUrl = isAutomaticArticle
? researchSources[content.sourceIndex - 1]?.imageUrl ?? researchSources.find((source) => source.imageUrl)?.imageUrl
: undefined;
const image = await generateImage(content.imagePrompt, "square", true, sourceImageUrl ?? undefined);
const accent = logoPalette.match(/#[0-9A-F]{6}/i)?.[0] ?? "#0077B6";
const imageBytes = isAutomaticArticle ? await addArticleHeadline(image.bytes, content.imageHeadline, accent) : image.bytes;
const file = new File([new Uint8Array(imageBytes)], "ai-post.jpg", { type: image.contentType });
+18 -6
View File
@@ -1,7 +1,8 @@
import { lookup } from "node:dns/promises";
import { isIP } from "node:net";
const cache = new Map<string, { expiresAt: number; value: string }>();
type WebsiteResearch = { prompt: string; imageUrl: string | null };
const cache = new Map<string, { expiresAt: number; value: WebsiteResearch }>();
const MAX_BYTES = 1_500_000;
const MAX_TEXT = 6_000;
const MAX_REDIRECTS = 3;
@@ -38,11 +39,11 @@ function metaContent(html: string, name: string): string {
return decodeEntities(tag?.match(/content=["']([^"']*)["']/i)?.[1] ?? "").trim();
}
/** Reads a shop's public website into short plain text (title, description, visible copy). Empty string if it cannot be read. */
export async function websitePrompt(website: string): Promise<string> {
/** Reads public page text and its declared social-preview image with SSRF protection. */
export async function websiteResearch(website: string): Promise<WebsiteResearch> {
const cached = cache.get(website);
if (cached && cached.expiresAt > Date.now()) return cached.value;
let value = "";
let value: WebsiteResearch = { prompt: "", imageUrl: null };
try {
let url = new URL(website);
let response: Response | null = null;
@@ -77,6 +78,12 @@ export async function websitePrompt(website: string): Promise<string> {
const html = Buffer.concat(chunks).toString("utf8");
const title = decodeEntities(html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1] ?? "").replace(/\s+/g, " ").trim();
const description = metaContent(html, "description") || metaContent(html, "og:description");
const rawImage = metaContent(html, "og:image") || metaContent(html, "twitter:image");
let imageUrl: string | null = null;
try {
const image = new URL(rawImage, url);
if (image.protocol === "https:" || image.protocol === "http:") imageUrl = image.toString();
} catch { /* A page image is optional. */ }
const body = decodeEntities(
html
.replace(/<(script|style|noscript|svg|template|iframe)[\s\S]*?<\/\1>/gi, " ")
@@ -90,12 +97,17 @@ export async function websitePrompt(website: string): Promise<string> {
.join("\n")
.slice(0, MAX_TEXT);
if (title || description || body) {
value = `<shop_website url="${website}">\nTitle: ${title}\nDescription: ${description}\n\n${body}\n</shop_website>`;
value = { prompt: `<shop_website url="${website}">\nTitle: ${title}\nDescription: ${description}\n\n${body}\n</shop_website>`, imageUrl };
}
}
} catch {
value = "";
value = { prompt: "", imageUrl: null };
}
cache.set(website, { expiresAt: Date.now() + 60 * 60_000, value });
return value;
}
/** Backward-compatible text-only helper for shop profile research. */
export async function websitePrompt(website: string): Promise<string> {
return (await websiteResearch(website)).prompt;
}