diff --git a/Dockerfile b/Dockerfile index d3433fc..0c5a066 100644 --- a/Dockerfile +++ b/Dockerfile @@ -16,7 +16,7 @@ WORKDIR /app ARG NEXT_PUBLIC_BASE_PATH= ENV NEXT_PUBLIC_BASE_PATH=$NEXT_PUBLIC_BASE_PATH ENV NODE_ENV=production HOSTNAME=0.0.0.0 PORT=3000 NEXT_TELEMETRY_DISABLED=1 -RUN apt-get update && apt-get install -y --no-install-recommends openssl ca-certificates curl && rm -rf /var/lib/apt/lists/* +RUN apt-get update && apt-get install -y --no-install-recommends openssl ca-certificates curl fonts-noto-core && rm -rf /var/lib/apt/lists/* COPY --from=build /app/.next/standalone ./ # Standalone only traces what server.js imports — overlay the full node_modules # so the `prisma` CLI (invoked by name below, not imported) is present too. diff --git a/src/lib/ai/article-image.ts b/src/lib/ai/article-image.ts new file mode 100644 index 0000000..ccc5512 --- /dev/null +++ b/src/lib/ai/article-image.ts @@ -0,0 +1,32 @@ +import sharp from "sharp"; + +function escapeXml(value: string) { + return value.replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]!); +} + +function headlineLines(value: string, max = 24): string[] { + const words = value.trim().replace(/\s+/g, " ").split(" "); + const lines: string[] = []; + let line = ""; + for (const word of words) { + const candidate = line ? `${line} ${word}` : word; + if (candidate.length > max && line) { lines.push(line); line = word; } + else line = candidate; + } + if (line) lines.push(line); + return lines.slice(0, 3); +} + +/** Adds a reliable Thai editorial headline after image generation; image models do not typeset Thai safely. */ +export async function addArticleHeadline(image: Buffer, headline: string, accent = "#0077B6"): Promise { + const lines = headlineLines(headline); + if (!lines.length) return image; + const svg = ` + + + + AI UPDATE + ${lines.map((line, index) => `${escapeXml(line)}`).join("")} + `; + return sharp(image, { limitInputPixels: 40_000_000 }).resize(1024, 1024, { fit: "cover" }).composite([{ input: Buffer.from(svg) }]).jpeg({ quality: 90 }).toBuffer(); +} diff --git a/src/lib/ai/article-research.ts b/src/lib/ai/article-research.ts new file mode 100644 index 0000000..5a4c79c --- /dev/null +++ b/src/lib/ai/article-research.ts @@ -0,0 +1,38 @@ +import { searchNews } from "./news"; +import { websitePrompt } from "./website"; + +export type ArticleSource = { title: string; url: string; source: string; publishedAt: 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[] }> { + const results = await searchNews("artificial intelligence OpenAI Anthropic Claude Gemini Copilot", { language: "en-US", market: "US" }); + const topicPattern = /\b(AI|artificial intelligence|OpenAI|Anthropic|Claude|Gemini|Copilot|ChatGPT|machine learning)\b/i; + const trustedPattern = /Reuters|Associated Press|Bloomberg|Financial Times|BBC|The Verge|TechCrunch|Ars Technica|Wired|VentureBeat|MIT Technology Review|Microsoft|Google|OpenAI|Anthropic/i; + const ranked = results + .filter((article) => topicPattern.test(`${article.title} ${article.description}`)) + .sort((a, b) => Number(trustedPattern.test(b.source)) - Number(trustedPattern.test(a.source))); + const selected = [] as typeof results; + const hosts = new Set(); + for (const article of ranked) { + try { + const host = new URL(article.url).hostname.replace(/^www\./, ""); + if (/\.th$|tha/i.test(host) || hosts.has(host)) continue; + hosts.add(host); + selected.push(article); + 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); + 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) => ` +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."} +`).join("\n\n"); + return { prompt, sources }; +} diff --git a/src/lib/ai/news.ts b/src/lib/ai/news.ts index af57922..a3949b7 100644 --- a/src/lib/ai/news.ts +++ b/src/lib/ai/news.ts @@ -28,11 +28,12 @@ function field(item: string, name: string): string { } /** Search current public news through Bing's RSS endpoint; no credentials or page data leave the server. */ -export async function searchNews(query: string): Promise { +export async function searchNews(query: string, options: { language?: string; market?: string } = {}): Promise { const url = new URL("https://www.bing.com/news/search"); url.searchParams.set("q", query); url.searchParams.set("format", "rss"); - url.searchParams.set("setlang", "th-TH"); + url.searchParams.set("setlang", options.language ?? "th-TH"); + if (options.market) url.searchParams.set("cc", options.market); const response = await fetch(url, { cache: "no-store", signal: AbortSignal.timeout(SEARCH_TIMEOUT_MS), diff --git a/src/lib/ai/post-queue-shared.ts b/src/lib/ai/post-queue-shared.ts index 8f92e7a..9675950 100644 --- a/src/lib/ai/post-queue-shared.ts +++ b/src/lib/ai/post-queue-shared.ts @@ -8,6 +8,7 @@ export const POST_JOB_STATUS = { export const POST_JOB_STAGE: Record = { queued: "รอเริ่มสร้างโพสต์", + research: "กำลังค้นและอ่านข่าว AI จากต่างประเทศ", content: "Codex กำลังเขียนเนื้อหาและพรอมต์ภาพ", image: "ChatGPT กำลังสร้างภาพ", saving: "กำลังบันทึกฉบับร่าง", @@ -29,5 +30,5 @@ export interface PostJobView { export function postJobProgress(job: Pick): number { if (job.status === "COMPLETED") return 100; if (job.status === "QUEUED" || job.status === "CANCELLED") return 0; - return ({ content: 10, image: 50, saving: 90 } as Record)[job.stage] ?? 0; + return ({ research: 10, content: 25, image: 55, saving: 90 } as Record)[job.stage] ?? 0; } diff --git a/src/lib/ai/post-queue.ts b/src/lib/ai/post-queue.ts index 4267b1e..8aed747 100644 --- a/src/lib/ai/post-queue.ts +++ b/src/lib/ai/post-queue.ts @@ -10,6 +10,8 @@ import { CAPTION_RULES, IMAGE_ART_DIRECTION, platformRule } from "./prompts"; import { profilePrompt } from "./shared"; import { putBlob } from "@/lib/storage/blob"; import { logoPalettePrompt } from "./brand-palette"; +import { researchAiArticle, type ArticleSource } from "./article-research"; +import { addArticleHeadline } from "./article-image"; export const JOB_SELECT = { id: true, topic: true, status: true, stage: true, postId: true, error: true, @@ -21,6 +23,7 @@ const Draft = z.object({ title: z.string().min(1).max(120), caption: z.string().min(1).max(5000), imagePrompt: z.string().min(20).max(4000), + imageHeadline: z.string().max(100).default(""), }); const SYSTEM = `Create a complete draft Facebook/Instagram post for a small Thai business. A human will review and approve it before publication. @@ -74,16 +77,37 @@ export async function processNextPostJob(baseUrl: string) { await assertImageQuota(job.pageId); const profile = Profile.parse(job.profileSnapshot); const logoPalette = await logoPalettePrompt(page.pictureUrl); + const isAutomaticArticle = job.requestKey.startsWith("auto:") && job.topic.includes("ประเภทเนื้อหา: บทความ"); + let researchPrompt = ""; + let researchSources: ArticleSource[] = []; + if (isAutomaticArticle) { + await prisma.postGenerationJob.update({ where: { id: job.id }, data: { stage: "research" } }); + const research = await researchAiArticle(); + researchPrompt = research.prompt; + researchSources = research.sources; + await prisma.postGenerationJob.update({ where: { id: job.id }, data: { stage: "content" } }); + } + const articleRules = isAutomaticArticle ? ` +This automatic slot is a Thai editorial AI-news article grounded only in material below. +- Select one timely, useful story with enough confirmed detail. Prefer a primary announcement plus corroborating reporting when available. +- Write clear Thai for general business readers: an opening summary followed by 5-8 short paragraphs explaining what happened, how it works, why it matters, and important limits or human oversight. Explain technical terms on first use. +- 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. +- 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."; const content = await generateStructured({ kind: "post-generation", pageId: job.pageId, userId: job.requestedById, - system: SYSTEM + (job.requestKey.startsWith("auto:") ? "\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 slot is creation time, not a publication promise." : ""), effort: "medium", schema: Draft, waitForWorker: true, - prompt: `${profilePrompt(profile)}\n${logoPalette}\n\n${platformRule(job.targets.includes("INSTAGRAM"))}\n\n\n${job.topic}\n`, + system: SYSTEM + (job.requestKey.startsWith("auto:") ? "\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 slot is creation time, not a publication promise." : "") + articleRules, effort: "medium", schema: Draft, waitForWorker: true, + prompt: `${profilePrompt(profile)}\n${logoPalette}\n\n${platformRule(job.targets.includes("INSTAGRAM"))}\n\n\n${job.topic}\n${researchPrompt ? `\n\n\n${researchPrompt}\n` : ""}`, }); 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); const image = await generateImage(content.imagePrompt, "square", true); - const file = new File([new Uint8Array(image.bytes)], "ai-post.jpg", { type: image.contentType }); + 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 }); const blob = await putBlob(`posts/${job.pageId}/ai-post.jpg`, file, { contentType: image.contentType }, baseUrl); await prisma.$transaction(async (tx) => { await tx.postGenerationJob.update({ where: { id: job.id }, data: { imageBlobUrl: blob.url, stage: "saving" } }); @@ -99,7 +123,7 @@ export async function processNextPostJob(baseUrl: string) { const changed = await tx.postGenerationJob.updateMany({ where: { id: job.id, status: "RUNNING" }, data: { status: "COMPLETED", stage: "completed", postId: post.id, finishedAt: new Date(), error: null } }); if (changed.count !== 1) throw new Error("Queue job no longer owns its execution"); await audit({ action: "POST_CREATED", actorId: user.id, actorLabel: actorLabel(user), pageId: job.pageId, postId: post.id, detail: { aiAssisted: true, jobId: job.id } }, tx); - await audit({ action: "AI_POST_COMPLETED", actorId: user.id, actorLabel: actorLabel(user), pageId: job.pageId, postId: post.id, detail: { jobId: job.id } }, tx); + await audit({ action: "AI_POST_COMPLETED", actorId: user.id, actorLabel: actorLabel(user), pageId: job.pageId, postId: post.id, detail: { jobId: job.id, ...(researchSources.length ? { researchSources } : {}) } }, tx); }); return { processed: true, jobId: job.id, status: "COMPLETED" }; } catch (error) {