feat: Gemini·Creatomate 호출을 서버 함수로 옮긴다

브라우저가 키를 들고 외부 API 를 직접 부르던 구조를 api/gemini-image.js, api/creatomate-render.js 로 옮긴다.
브라우저는 채널·포맷·주제 선택값만 보내고, 서버가 허용 목록과 대조한 뒤 프롬프트·영상 구성을 만든다.
키는 서버 환경변수 GEMINI_API_KEY·CREATOMATE_API_KEY 에만 둔다. 출처는 infinith-demo·localhost 만 받는다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Haewon KamandClaude Opus 5.5 committed 2026-10-07 14:39:19 +09:00
1 parent 8667bf6e2e
commit 0b729759c3
5 files changed
+330 -239

No files matched your search

+33 -172
View File
@@ -1,202 +1,63 @@
import type { StudioState } from '../types/studio';
import { CHANNEL_OPTIONS } from '../types/studio';
const CREATOMATE_API_KEY = import.meta.env.VITE_CREATOMATE_API_KEY ?? '';
const API_BASE = 'https://api.creatomate.com/v1';
/**
* 콘텐츠 스튜디오 영상 생성. Creatomate 는 서버 함수(api/creatomate-render.js)에서만 호출한다.
* 브라우저는 키를 모르고 선택값만 보낸다. 렌더 시작 뒤 서버에 상태를 물어 완료를 기다린다 (2026-10-07).
*/
export interface VideoResult {
videoUrl: string;
prompt: string;
}
interface CreatomateRender {
id: string;
status: 'planned' | 'waiting' | 'transcribing' | 'rendering' | 'succeeded' | 'failed';
url?: string;
error_message?: string;
interface RenderState {
ok: boolean;
id?: string;
status?: 'planned' | 'waiting' | 'transcribing' | 'rendering' | 'succeeded' | 'failed';
url?: string | null;
error?: string | null;
}
const ASPECT_DIMENSIONS: Record<string, { width: number; height: number }> = {
'9:16': { width: 1080, height: 1920 },
'16:9': { width: 1920, height: 1080 },
'1:1': { width: 1080, height: 1080 },
'4:5': { width: 1080, height: 1350 },
};
const ENDPOINT = '/api/creatomate-render';
const PILLAR_TITLES: Record<string, { ko: string; en: string }> = {
safety: { ko: '안전한 수술 시스템', en: 'Safe Surgery System' },
expertise: { ko: '전문 의료진', en: 'Expert Medical Team' },
results: { ko: '자연스러운 결과', en: 'Natural Results' },
care: { ko: '환자 중심 케어', en: 'Patient-Centered Care' },
};
/**
* Build a Creatomate source object programmatically.
* This creates a simple branded slideshow video without needing
* a pre-built template — ideal for initial integration.
*/
function buildSource(state: StudioState) {
const channel = CHANNEL_OPTIONS.find(c => c.channel === state.channel);
const format = channel?.formats.find(f => f.key === state.format);
const dims = ASPECT_DIMENSIONS[format?.aspectRatio ?? '16:9'];
const pillar = state.pillarId ? PILLAR_TITLES[state.pillarId] : null;
return {
output_format: 'mp4',
width: dims.width,
height: dims.height,
duration: 10,
elements: [
// Background gradient
{
type: 'shape',
shape: 'rectangle',
width: '100%',
height: '100%',
fill_color: 'linear-gradient(180deg, #0A1128 0%, #1A2B5E 50%, #4F1DA1 100%)',
},
// Title text
{
type: 'text',
text: pillar?.ko || 'INFINITH Marketing',
font_family: 'Noto Sans KR',
font_weight: '700',
font_size: dims.width > dims.height ? '72px' : '56px',
fill_color: '#FFFFFF',
x: '50%',
y: '40%',
x_anchor: '50%',
y_anchor: '50%',
width: '80%',
text_align: 'center',
animations: [
{ type: 'text-appear', duration: 1, split: 'word' },
],
},
// Subtitle
{
type: 'text',
text: pillar?.en || 'Premium Medical Marketing',
font_family: 'Noto Sans KR',
font_weight: '400',
font_size: dims.width > dims.height ? '36px' : '28px',
fill_color: 'rgba(255,255,255,0.7)',
x: '50%',
y: '55%',
x_anchor: '50%',
y_anchor: '50%',
width: '80%',
text_align: 'center',
animations: [
{ type: 'fade', fade_in: true, duration: 0.8, start: 0.5 },
],
},
// Brand accent line
{
type: 'shape',
shape: 'rectangle',
width: '120px',
height: '4px',
fill_color: '#6C5CE7',
x: '50%',
y: '48%',
x_anchor: '50%',
y_anchor: '50%',
animations: [
{ type: 'wipe', duration: 0.6, start: 0.3 },
],
},
// Channel badge
{
type: 'text',
text: `${channel?.label || ''} · ${format?.label || ''}`,
font_family: 'Noto Sans KR',
font_weight: '500',
font_size: '20px',
fill_color: 'rgba(255,255,255,0.5)',
x: '50%',
y: '90%',
x_anchor: '50%',
y_anchor: '50%',
text_align: 'center',
},
],
};
}
async function pollRender(renderId: string, maxAttempts = 30): Promise<CreatomateRender> {
async function pollRender(renderId: string, maxAttempts = 30): Promise<RenderState> {
for (let i = 0; i < maxAttempts; i++) {
const res = await fetch(`${API_BASE}/renders/${renderId}`, {
headers: { Authorization: `Bearer ${CREATOMATE_API_KEY}` },
});
if (!res.ok) {
throw new Error(`렌더 상태 확인 실패 (${res.status})`);
}
const render: CreatomateRender = await res.json();
if (render.status === 'succeeded' && render.url) {
return render;
}
if (render.status === 'failed') {
throw new Error(render.error_message || '영상 렌더링에 실패했습니다');
}
// Wait 2 seconds before next poll
await new Promise(resolve => setTimeout(resolve, 2000));
const res = await fetch(`${ENDPOINT}?id=${encodeURIComponent(renderId)}`);
if (!res.ok) throw new Error(`렌더 상태 확인 실패 (${res.status})`);
const render: RenderState = await res.json();
if (render.status === 'succeeded' && render.url) return render;
if (render.status === 'failed') throw new Error(render.error || '영상 렌더링에 실패했습니다');
await new Promise((resolve) => setTimeout(resolve, 2000));
}
throw new Error('영상 렌더링 시간이 초과되었습니다 — 다시 시도해주세요');
}
export async function generateVideo(state: StudioState): Promise<VideoResult> {
if (!CREATOMATE_API_KEY) {
throw new Error('Creatomate API 키가 설정되지 않았습니다');
}
const source = buildSource(state);
const prompt = `${state.channel}/${state.format} — ${state.pillarId || 'general'}`;
let renderResponse;
let res: Response;
try {
renderResponse = await fetch(`${API_BASE}/renders`, {
res = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Authorization': `Bearer ${CREATOMATE_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ source }),
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ channel: state.channel, format: state.format, pillarId: state.pillarId }),
});
} catch (err) {
throw new Error('Creatomate 서버에 연결할 수 없습니다');
console.error('[generateVideo] 서버 연결 실패', err);
throw new Error('영상 생성 서버에 연결할 수 없습니다');
}
if (!renderResponse.ok) {
const status = renderResponse.status;
if (status === 401) throw new Error('Creatomate API 인증 실패 — 관리자에게 문의하세요');
if (status === 429) throw new Error('렌더 한도 초과 — 잠시 후 다시 시도해주세요');
if (status === 400) {
const body = await renderResponse.json().catch(() => ({}));
throw new Error(`영상 설정 오류: ${body.message || '잘못된 요청'}`);
}
throw new Error(`영상 생성 요청 실패 (${status})`);
const render: RenderState | null = await res.json().catch(() => null);
if (!res.ok || !render?.ok) {
if (res.status === 500) throw new Error('Creatomate API 키가 설정되지 않았습니다');
if (res.status === 401) throw new Error('Creatomate API 인증 실패 — 관리자에게 문의하세요');
if (res.status === 429) throw new Error('렌더 한도 초과 — 잠시 후 다시 시도해주세요');
if (res.status === 400) throw new Error('영상 설정 오류: 잘못된 요청');
throw new Error(`영상 생성 요청 실패 (${res.status})`);
}
if (!render.id) throw new Error('렌더 ID를 받지 못했습니다');
const renders: CreatomateRender[] = await renderResponse.json();
const render = renders[0];
if (!render?.id) {
throw new Error('렌더 ID를 받지 못했습니다');
}
// If already succeeded (fast render)
if (render.status === 'succeeded' && render.url) {
return { videoUrl: render.url, prompt };
}
// Poll for completion
if (render.status === 'succeeded' && render.url) return { videoUrl: render.url, prompt };
const completed = await pollRender(render.id);
return { videoUrl: completed.url!, prompt };
}
+20 -67
View File
@@ -1,44 +1,9 @@
import { GoogleGenAI } from '@google/genai';
import type { StudioState } from '../types/studio';
import { CHANNEL_OPTIONS } from '../types/studio';
const client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY ?? '' });
function buildPrompt(state: StudioState): string {
const channel = CHANNEL_OPTIONS.find(c => c.channel === state.channel);
const format = channel?.formats.find(f => f.key === state.format);
const pillarDescriptions: Record<string, string> = {
safety: 'hospital safety systems, clean surgical rooms, CCTV monitoring, professional medical team, trust and reliability',
expertise: 'medical expertise, advanced surgical equipment, professional doctors, medical certifications, precision and skill',
results: 'natural beautiful results, before and after transformation, patient satisfaction, subtle elegant outcomes',
care: 'patient-centered care, warm consultation, personalized treatment plan, caring medical staff, comfortable clinic interior',
};
const pillarContext = state.pillarId ? pillarDescriptions[state.pillarId] ?? '' : '';
const aspectRatio = format?.aspectRatio ?? '16:9';
const channelHints: Record<string, string> = {
youtube: 'YouTube thumbnail style, bold text overlay area, high contrast, eye-catching',
instagram: 'Instagram aesthetic, clean minimalist, lifestyle photography style, warm tones',
naver_blog: 'Korean blog header image, informative, medical illustration, clean layout',
tiktok: 'TikTok cover image, vertical format, trendy, dynamic, youthful',
facebook: 'Facebook ad creative, professional, compelling, clear messaging space',
};
const channelHint = state.channel ? channelHints[state.channel] ?? '' : '';
return [
'Generate a premium medical marketing image for a plastic surgery clinic.',
`Theme: ${pillarContext}`,
`Style: ${channelHint}`,
`Aspect ratio: ${aspectRatio}`,
'Color palette: soft purple (#7B2D8E), gold (#E8B931), warm white (#FAF8F5).',
'Premium, luxurious, trustworthy aesthetic.',
'No text or logos in the image.',
'Photorealistic, high quality, professional medical marketing.',
].filter(Boolean).join(' ');
}
/**
* 콘텐츠 스튜디오 이미지 생성. Gemini 는 서버 함수(api/gemini-image.js)에서만 호출한다.
* 브라우저는 키를 모르고 선택값(채널·포맷·주제)만 보낸다. 프롬프트도 서버에서 만든다 (2026-10-07).
*/
export interface GenerateResult {
imageDataUrl: string;
@@ -46,36 +11,24 @@ export interface GenerateResult {
}
export async function generateImage(state: StudioState): Promise<GenerateResult> {
const prompt = buildPrompt(state);
let response;
let res: Response;
try {
response = await client.models.generateContent({
model: 'gemini-2.5-flash-image',
contents: prompt,
config: {
responseModalities: ['Text', 'Image'],
},
res = await fetch('/api/gemini-image', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ channel: state.channel, format: state.format, pillarId: state.pillarId }),
});
} catch (err: any) {
const code = err?.status ?? err?.code ?? err?.message?.match(/"code":(\d+)/)?.[1];
if (String(code) === '429' || err?.message?.includes('RESOURCE_EXHAUSTED')) {
throw new Error('API 요청 한도 초과 — 잠시 후 다시 시도해주세요');
}
if (String(code) === '400' || err?.message?.includes('INVALID_ARGUMENT')) {
throw new Error('API 설정 오류 — 관리자에게 문의하세요');
}
throw new Error('이미지 생성 중 오류가 발생했습니다');
} catch (err) {
console.error('[generateImage] 서버 연결 실패', err);
throw new Error('이미지 생성 서버에 연결할 수 없습니다');
}
// Extract image from response parts
const parts = response.candidates?.[0]?.content?.parts;
if (!parts) throw new Error('AI 응답을 받지 못했습니다');
const imagePart = parts.find((p: any) => p.inlineData?.mimeType?.startsWith('image/'));
if (!imagePart?.inlineData) throw new Error('이미지가 생성되지 않았습니다 — 다시 시도해주세요');
const { mimeType, data } = imagePart.inlineData;
const imageDataUrl = `data:${mimeType};base64,${data}`;
return { imageDataUrl, prompt };
const data = await res.json().catch(() => null);
if (!res.ok || !data?.ok) {
if (res.status === 429) throw new Error('API 요청 한도 초과 — 잠시 후 다시 시도해주세요');
if (res.status === 400 || res.status === 500) throw new Error('API 설정 오류 — 관리자에게 문의하세요');
if (data?.error === 'no image') throw new Error('이미지가 생성되지 않았습니다 — 다시 시도해주세요');
throw new Error('이미지 생성 중 오류가 발생했습니다');
}
return { imageDataUrl: data.imageDataUrl, prompt: data.prompt };
}