Merge branch 'feature-ssulbox-ado2-ds' into feature-ssulbox
This commit is contained in:
commit
8ba5546f85
29 files changed
+3236
-240
No files matched your search
@@ -0,0 +1,263 @@
|
||||
/**
|
||||
* Poster to Video (P2V) 클라이언트.
|
||||
*
|
||||
* castad 백엔드가 아니라 **별도 서버(:8010)** 를 직접 호출한다. 다른 파이프라인들
|
||||
* (ADO2·썰박스)이 `utils/api.ts` 로 castad 백엔드에 붙는 것과 대비된다.
|
||||
*
|
||||
* 왜 프록시를 두지 않았나 — P2V 서버는 검증된 `scripts/*.py` 를 subprocess 로 감싼
|
||||
* 단일 워커라 castad 백엔드에 흡수하려면 실행 환경(Higgsfield CLI·ffmpeg·모델 키)을
|
||||
* 통째로 이식해야 한다. **내부 시연 범위**에서는 직접 호출이 맞고, 대외 공개 단계에서
|
||||
* castad 백엔드에 `/p2v/*` 프록시를 세워 카카오 인증·크레딧 차감을 얹는 게 다음 수순이다.
|
||||
* 그때 갈아끼울 지점은 이 파일 하나다.
|
||||
*
|
||||
* 인증은 단일 팀 키(`P2V_ACCESS_KEY`). 서버는 3경로로 받는다:
|
||||
* - `X-P2V-Key` 헤더 → fetch 호출
|
||||
* - `p2v_key` 쿠키 → **여기서는 못 쓴다.** castad 와 P2V 는 다른 오리진이라
|
||||
* document.cookie 로 심어도 P2V 요청에 실리지 않는다.
|
||||
* - `?key=` 쿼리 → 헤더를 못 붙이는 <img>/<video>/<a download> 용 (p2vFile)
|
||||
*/
|
||||
|
||||
/** P2V 서버 오리진. 배포 시 `.env` 의 VITE_P2V_URL 로 덮는다 */
|
||||
export const P2V_URL = (import.meta.env.VITE_P2V_URL || 'http://localhost:8010').replace(/\/$/, '');
|
||||
|
||||
/**
|
||||
* 접근 키 저장소.
|
||||
*
|
||||
* storageKeys.K 에 넣지 않은 것은 의도적이다 — 그쪽 키들은 로그아웃·새 프로젝트에
|
||||
* 일괄 삭제되는데, 이건 서버 자격증명이라 지워지면 시연 중에 매번 다시 물어야 한다.
|
||||
*/
|
||||
const KEY_STORAGE = 'castad_p2v_key';
|
||||
|
||||
export const getP2vKey = (): string => localStorage.getItem(KEY_STORAGE) ?? '';
|
||||
export const setP2vKey = (key: string): void => localStorage.setItem(KEY_STORAGE, key.trim());
|
||||
export const clearP2vKey = (): void => localStorage.removeItem(KEY_STORAGE);
|
||||
|
||||
/** 401 — 화면이 키 입력을 띄워야 하는 상황. 일반 실패와 구분해야 해서 타입을 나눈다 */
|
||||
export class P2vAuthError extends Error {
|
||||
constructor() {
|
||||
super('P2V_AUTH_REQUIRED');
|
||||
this.name = 'P2vAuthError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 404 — 서버에 그 잡이 없다. 화면은 처음으로 되돌려야 한다.
|
||||
*
|
||||
* 상태 코드로 판정하는 이유: 서버 detail 문구("잡 없음")를 문자열로 맞추려다
|
||||
* 실제로 한 번 놓쳤다. 문구는 서버 사정으로 바뀌고 번역도 되지만 코드는 안 바뀐다.
|
||||
*/
|
||||
export class P2vNotFoundError extends Error {
|
||||
constructor(detail: string) {
|
||||
super(detail);
|
||||
this.name = 'P2vNotFoundError';
|
||||
}
|
||||
}
|
||||
|
||||
export async function p2vFetch<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const key = getP2vKey();
|
||||
const res = await fetch(`${P2V_URL}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
...(init?.headers ?? {}),
|
||||
...(key ? { 'X-P2V-Key': key } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
if (res.status === 401) throw new P2vAuthError();
|
||||
|
||||
if (!res.ok) {
|
||||
// FastAPI 는 {detail: ...} 로 준다. 본문이 없는 에러(502 등)도 있으므로 감싼다
|
||||
let detail = res.statusText;
|
||||
try {
|
||||
const body = await res.json();
|
||||
detail = typeof body.detail === 'string' ? body.detail : JSON.stringify(body);
|
||||
} catch {
|
||||
/* 본문 없음 — statusText 로 간다 */
|
||||
}
|
||||
if (res.status === 404) throw new P2vNotFoundError(detail);
|
||||
throw new Error(detail);
|
||||
}
|
||||
return res.json() as Promise<T>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 정적 산출물(영상·이미지) URL.
|
||||
*
|
||||
* 서버가 주는 artifacts 값은 `/files/render/x.mp4` 같은 **루트 상대 경로**라
|
||||
* 다른 오리진인 castad 에서는 그대로 쓸 수 없다. 오리진을 붙이고, 헤더를 실을 수 없는
|
||||
* 태그(<video src> 등)를 위해 키를 쿼리로 태운다.
|
||||
*/
|
||||
export const p2vFile = (path: string | null | undefined): string => {
|
||||
if (!path) return '';
|
||||
const key = getP2vKey();
|
||||
return `${P2V_URL}${path}${key ? `?key=${encodeURIComponent(key)}` : ''}`;
|
||||
};
|
||||
|
||||
// ── 타입 (서버 jobs.py / routers 와 1:1) ──────────────────────────────
|
||||
|
||||
export type P2vStageStatus = 'idle' | 'running' | 'done' | 'failed';
|
||||
|
||||
export interface P2vStageState {
|
||||
status: P2vStageStatus;
|
||||
started: number | null;
|
||||
ended: number | null;
|
||||
}
|
||||
|
||||
export interface PosterMeta {
|
||||
event_name: string;
|
||||
date_text: string;
|
||||
place: string;
|
||||
category: string;
|
||||
keywords: string[];
|
||||
region_guess?: string;
|
||||
}
|
||||
|
||||
export interface P2vJob {
|
||||
id: string;
|
||||
kind: 'f1' | 'f2';
|
||||
name: string;
|
||||
status: 'queued' | 'running' | 'awaiting_review' | 'failed' | 'done';
|
||||
stage: string | null;
|
||||
stages: Record<string, P2vStageState>;
|
||||
narration: string[] | null;
|
||||
motion_elements?: string[] | null;
|
||||
metadata: PosterMeta | null;
|
||||
error: { stage: string; detail: string } | null;
|
||||
artifacts: Record<string, string>;
|
||||
created_at: number;
|
||||
queue_size?: number;
|
||||
template_id?: string | null;
|
||||
}
|
||||
|
||||
/** 배포 등급. public-domain 만 외부 공개 가능 — 나머지는 내부 시연 한정 */
|
||||
export type P2vLicense = 'public-domain' | 'internal-only' | 'user-uploaded';
|
||||
|
||||
export interface F2Template {
|
||||
id: string;
|
||||
name_ko: string;
|
||||
thumb_url: string;
|
||||
category: string;
|
||||
license: P2vLicense;
|
||||
attribution: string;
|
||||
license_note: string;
|
||||
/** 사용자가 올린 레퍼런스인가 (삭제 가능) */
|
||||
removable: boolean;
|
||||
small_ref: boolean;
|
||||
}
|
||||
|
||||
export interface F2Category { id: string; label: string }
|
||||
export interface F2Format { id: string; label: string }
|
||||
export interface F2UploadHint { enabled: boolean; min_long_edge: number }
|
||||
|
||||
// ── F1 (포스터 → 영상) ────────────────────────────────────────────────
|
||||
|
||||
/** 포스터 업로드 → 잡 생성. 반환된 id 로 폴링한다 */
|
||||
export async function createPosterJob(poster: File, name: string): Promise<{ id: string }> {
|
||||
const fd = new FormData();
|
||||
fd.append('poster', poster);
|
||||
fd.append('name', name);
|
||||
return p2vFetch<{ id: string }>('/api/f1/jobs', { method: 'POST', body: fd });
|
||||
}
|
||||
|
||||
export const getPosterJob = (id: string): Promise<P2vJob> =>
|
||||
p2vFetch<P2vJob>(`/api/f1/jobs/${id}`);
|
||||
|
||||
export const updatePosterNarration = (id: string, narration: string[]): Promise<unknown> =>
|
||||
p2vFetch(`/api/f1/jobs/${id}/narration`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ narration }),
|
||||
});
|
||||
|
||||
export const updatePosterMetadata = (
|
||||
id: string,
|
||||
meta: { event_name: string; date_text: string; place: string },
|
||||
): Promise<unknown> =>
|
||||
p2vFetch(`/api/f1/jobs/${id}/metadata`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(meta),
|
||||
});
|
||||
|
||||
/** 검수 승인 → TTS·BGM·애니메이션·렌더가 이어진다. motions 를 넘기면 모션 선정을 덮어쓴다 */
|
||||
export const approvePosterJob = (id: string, motions?: string[] | null): Promise<unknown> =>
|
||||
p2vFetch(`/api/f1/jobs/${id}/approve`, {
|
||||
method: 'POST',
|
||||
...(motions
|
||||
? { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ motions }) }
|
||||
: {}),
|
||||
});
|
||||
|
||||
export const retryPosterJob = (id: string, motions?: string[] | null): Promise<unknown> =>
|
||||
p2vFetch(`/api/f1/jobs/${id}/retry`, {
|
||||
method: 'POST',
|
||||
...(motions
|
||||
? { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ motions }) }
|
||||
: {}),
|
||||
});
|
||||
|
||||
export const deletePosterJob = (id: string): Promise<unknown> =>
|
||||
p2vFetch(`/api/f1/jobs/${id}`, { method: 'DELETE' });
|
||||
|
||||
// ── F2 (포스터 스타일링) ──────────────────────────────────────────────
|
||||
|
||||
export const listF2Templates = (): Promise<F2Template[]> => p2vFetch<F2Template[]>('/api/f2/templates');
|
||||
export const listF2Categories = (): Promise<F2Category[]> => p2vFetch<F2Category[]>('/api/f2/categories');
|
||||
export const listF2Formats = (): Promise<F2Format[]> => p2vFetch<F2Format[]>('/api/f2/formats');
|
||||
export const getF2UploadHint = (): Promise<F2UploadHint> => p2vFetch<F2UploadHint>('/api/f2/upload-hint');
|
||||
|
||||
/** 레퍼런스 업로드 — 저장 + 화풍 분석까지 서버가 동기로 끝낸다(10초 안팎) */
|
||||
export async function createF2Template(reference: File, name: string): Promise<F2Template> {
|
||||
const fd = new FormData();
|
||||
fd.append('reference', reference);
|
||||
fd.append('name', name);
|
||||
return p2vFetch<F2Template>('/api/f2/templates', { method: 'POST', body: fd });
|
||||
}
|
||||
|
||||
export const deleteF2Template = (id: string): Promise<unknown> =>
|
||||
p2vFetch(`/api/f2/templates/${id}`, { method: 'DELETE' });
|
||||
|
||||
export async function createStylingJob(
|
||||
poster: File,
|
||||
templateId: string,
|
||||
format: string,
|
||||
): Promise<{ id: string }> {
|
||||
const fd = new FormData();
|
||||
fd.append('poster', poster);
|
||||
fd.append('template_id', templateId);
|
||||
fd.append('format', format);
|
||||
return p2vFetch<{ id: string }>('/api/f2/jobs', { method: 'POST', body: fd });
|
||||
}
|
||||
|
||||
export const getStylingJob = (id: string): Promise<P2vJob> =>
|
||||
p2vFetch<P2vJob>(`/api/f2/jobs/${id}`);
|
||||
|
||||
// ── 진행 계산 ────────────────────────────────────────────────────────
|
||||
|
||||
/** 아직 도는 중인가. 이 두 상태에서만 폴링을 계속한다 */
|
||||
export const isP2vActive = (job: P2vJob | null): boolean =>
|
||||
job !== null && (job.status === 'queued' || job.status === 'running');
|
||||
|
||||
/** 스테이지 진행률(%) — 선형 진행바용. 도는 중인 스테이지는 절반으로 친다 */
|
||||
export function p2vProgress(job: P2vJob | null): number {
|
||||
if (!job) return 0;
|
||||
const states = Object.values(job.stages);
|
||||
if (states.length === 0) return 0;
|
||||
const done = states.filter((s) => s.status === 'done').length;
|
||||
const running = states.some((s) => s.status === 'running') ? 0.5 : 0;
|
||||
return Math.round(((done + running) / states.length) * 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* 검수 게이트를 이미 지났는가.
|
||||
*
|
||||
* 스텝퍼가 "분석 → 검수 → 생성" 중 어디인지 알아야 하는데 status 만으로는
|
||||
* 검수 전 running 과 승인 후 running 이 구분되지 않는다. tts 는 승인 이후에만
|
||||
* 시작하므로 이게 게이트 통과의 신호다(스테이지 이름을 박는 대신 F1_STAGES 순서에
|
||||
* 의존하지 않도록 tts 하나만 본다 — 게이트가 옮겨가면 이 상수만 고친다).
|
||||
*/
|
||||
const POST_REVIEW_STAGE = 'tts';
|
||||
|
||||
export const isPastReview = (job: P2vJob | null): boolean =>
|
||||
!!job && job.stages[POST_REVIEW_STAGE]?.status !== undefined
|
||||
&& job.stages[POST_REVIEW_STAGE].status !== 'idle';
|
||||
@@ -32,10 +32,24 @@ export const K = {
|
||||
VIDEO_RATIO: 'castad_video_ratio',
|
||||
|
||||
// 썰박스 통합
|
||||
/** 현재 선택된 파이프라인 ('ado2' | 'ssul') */
|
||||
/** 현재 선택된 파이프라인 (PipelineTabs 의 Pipeline 값) */
|
||||
PIPELINE: 'castad_pipeline',
|
||||
/** 진행 중인 썰박스 생성 잡 ID. 권위는 서버(`/ssul/tasks/active`)이고 이건 복구 힌트다 */
|
||||
SSUL_TASK_ID: 'castad_ssul_task_id',
|
||||
|
||||
// Poster to Video 통합
|
||||
/**
|
||||
* 진행 중인 포스터 영상(F1) 잡 ID.
|
||||
*
|
||||
* 썰박스의 `/ssul/tasks/active` 같은 "내 활성 잡" 엔드포인트가 P2V 에는 없다
|
||||
* (단일 팀 키라 사용자 개념이 없다). 그래서 이 값이 새로고침 복구의 유일한 근거다 —
|
||||
* 지우면 진행 중인 잡을 화면에서 잃는다. 서버에서 잡이 사라졌으면 조회가 404 로
|
||||
* 떨어지고 GenerationFlow 가 이 키를 정리한다.
|
||||
*
|
||||
* 접근 키(castad_p2v_key)는 여기 두지 않는다 — 서버 자격증명이라 프로젝트 초기화·
|
||||
* 로그아웃으로 지워지면 시연 중 매번 다시 물어야 한다 (utils/p2vApi.ts 참조).
|
||||
*/
|
||||
POSTER_JOB_ID: 'castad_poster_job_id',
|
||||
} as const;
|
||||
|
||||
/**
|
||||
@@ -52,6 +66,7 @@ export const PROJECT_KEYS: readonly string[] = [
|
||||
K.VIDEO_RATIO,
|
||||
K.PIPELINE,
|
||||
K.SSUL_TASK_ID,
|
||||
K.POSTER_JOB_ID,
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user