숏폼생성 기능 추가

This commit is contained in:
skkim committed 2026-06-12 09:44:02 +09:00
1 parent cb68b2da97
commit 530416026d
45 files changed
+5398 -960

No files matched your search

+1 -31
View File
@@ -358,32 +358,6 @@ const App: React.FC = () => {
}
};
// 테스트 데이터로 브랜드 분석 페이지 이동
const handleTestData = (data: CrawlingResponse) => {
const tagged = { ...data, _isTestData: true };
setAnalysisData(tagged);
localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(tagged));
setViewMode('analysis');
};
// 언어 변경 시 테스트 데이터 다시 로드
useEffect(() => {
const saved = localStorage.getItem(ANALYSIS_DATA_KEY);
if (!saved) return;
try {
const parsed = JSON.parse(saved);
if (!parsed._isTestData) return;
const jsonFile = i18n.language === 'en' ? '/example_analysis_en.json' : '/example_analysis.json';
fetch(jsonFile)
.then(res => res.json())
.then((data: CrawlingResponse) => {
const tagged = { ...data, _isTestData: true };
setAnalysisData(tagged);
localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(tagged));
})
.catch(err => console.error('Failed to reload test data:', err));
} catch { /* ignore */ }
}, [i18n.language]);
const handleToLogin = async () => {
// 이미 로그인된 상태면 바로 generation_flow로 이동
@@ -504,12 +478,8 @@ const App: React.FC = () => {
<Header onStartClick={handleHeaderStart} />
<section className="landing-section">
<HeroSection
onAnalyze={handleStartAnalysis}
onAutocomplete={handleAutocomplete}
onManualInput={handleManualInput}
onTestData={handleTestData}
onLogin={handleToLogin}
onNext={() => scrollToSection(1)}
error={error}
scrollProgress={scrollProgress}
/>
</section>
+21 -4
View File
@@ -24,6 +24,7 @@ interface SearchInputFormProps {
onManualInput?: (businessName: string, address: string) => void;
/** 직접입력 버튼 클릭 시 기본 동작(모달 열기)을 대체합니다. 제공 시 모달을 직접 관리해야 합니다. */
onManualButtonClick?: () => void;
onShortform?: () => void;
error?: string | null;
}
@@ -32,6 +33,7 @@ const SearchInputForm: React.FC<SearchInputFormProps> = ({
onAutocomplete,
onManualInput,
onManualButtonClick,
onShortform,
error: externalError,
}) => {
const { t } = useTranslation();
@@ -68,6 +70,7 @@ const SearchInputForm: React.FC<SearchInputFormProps> = ({
const searchTypeOptions = [
{ value: 'url' as SearchType, label: 'URL' },
{ value: 'name' as SearchType, label: t('landing.hero.searchTypeBusinessName') },
{ value: 'manual' as SearchType, label: t('landing.hero.searchTypeManual') },
];
const getPlaceholder = () =>
@@ -196,8 +199,12 @@ const SearchInputForm: React.FC<SearchInputFormProps> = ({
type="button"
className={`hero-dropdown-item ${searchType === option.value ? 'active' : ''}`}
onClick={() => {
setSearchType(option.value);
setIsDropdownOpen(false);
if (option.value === 'manual') {
handleManualButtonClick();
} else {
setSearchType(option.value);
}
}}
>
{option.label}
@@ -321,9 +328,19 @@ const SearchInputForm: React.FC<SearchInputFormProps> = ({
{t('landing.hero.analyzeButton')}
</button>
<button type="button" className="hero-manual-button" onClick={handleManualButtonClick}>
{t('landing.hero.searchTypeManual')}
</button>
{onShortform && (
<button
type="button"
className="url-input-shortform-btn"
onClick={onShortform}
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polygon points="23 7 16 12 23 17 23 7" />
<rect x="1" y="5" width="15" height="14" rx="2" ry="2" />
</svg>
숏폼 영상 만들기
</button>
)}
{/* onManualButtonClick 미제공 시 모달을 내부에서 관리 */}
{!onManualButtonClick && isManualModalOpen && (
+4
View File
@@ -157,6 +157,7 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
const [uploadVideoTitle, setUploadVideoTitle] = useState<string>('');
const [uploadChannelName, setUploadChannelName] = useState<string>('');
const [uploadIsScheduled, setUploadIsScheduled] = useState(false);
const [uploadScheduledAt, setUploadScheduledAt] = useState<string | null>(null);
// 드롭다운 외부 클릭 시 닫기
useEffect(() => {
@@ -373,6 +374,7 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
// 예약 업로드: 폴링 없이 바로 완료 처리
setUploadStatus('completed');
setUploadProgress(100);
setUploadScheduledAt(uploadResponse.scheduled_at ?? null);
onClose();
resetForm();
} else {
@@ -432,6 +434,7 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
setUploadVideoTitle('');
setUploadChannelName('');
setUploadIsScheduled(false);
setUploadScheduledAt(null);
};
const handleClose = () => {
@@ -461,6 +464,7 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
youtubeUrl={uploadYoutubeUrl}
errorMessage={uploadErrorMessage}
isScheduled={uploadIsScheduled}
scheduledAt={uploadScheduledAt}
onGoToCalendar={onGoToCalendar}
/>
);
+1 -38
View File
@@ -45,44 +45,7 @@ export const TUTORIAL_PAGE_GROUPS: string[][] = [
export const tutorialSteps: TutorialStepDef[] = [
{
key: TUTORIAL_KEYS.LANDING,
hints: [
{
targetSelector: '.hero-dropdown-trigger',
titleKey: 'tutorial.landing.dropdown.title',
descriptionKey: 'tutorial.landing.dropdown.desc',
position: 'top',
clickToAdvance: false,
noSpotlight: true,
variant: 'bubble',
},
{
targetSelector: '.hero-input-wrapper',
titleKey: 'tutorial.landing.field.title',
descriptionKey: 'tutorial.landing.field.desc',
position: 'top',
clickToAdvance: false,
noSpotlight: true,
variant: 'bubble',
},
{
targetSelector: '.hero-manual-button',
titleKey: 'tutorial.landing.manual.title',
descriptionKey: 'tutorial.landing.manual.desc',
position: 'bottom',
clickToAdvance: false,
noSpotlight: true,
variant: 'bubble',
},
{
targetSelector: '.hero-button',
titleKey: 'tutorial.landing.button.title',
descriptionKey: 'tutorial.landing.button.desc',
position: 'bottom',
clickToAdvance: true,
noSpotlight: true,
variant: 'bubble',
},
],
hints: [],
},
{
key: TUTORIAL_KEYS.ASSET,
+24
View File
@@ -14,6 +14,7 @@ interface UploadProgressModalProps {
youtubeUrl?: string;
errorMessage?: string;
isScheduled?: boolean;
scheduledAt?: string | null;
onGoToCalendar?: () => void;
}
@@ -27,6 +28,7 @@ const UploadProgressModal: React.FC<UploadProgressModalProps> = ({
youtubeUrl,
errorMessage,
isScheduled = false,
scheduledAt,
onGoToCalendar,
}) => {
const { t } = useTranslation();
@@ -148,6 +150,28 @@ const UploadProgressModal: React.FC<UploadProgressModalProps> = ({
{t('upload.viewOnYoutube')}
</a>
)}
{/* Scheduled conflict notice */}
{status === 'completed' && isScheduled && scheduledAt && (
<div className="upload-progress-schedule-notice">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="12" cy="12" r="10" />
<line x1="12" y1="8" x2="12" y2="12" />
<line x1="12" y1="16" x2="12.01" y2="16" />
</svg>
<span>
{t('upload.scheduleConflict', {
time: new Date(scheduledAt).toLocaleString('ko-KR', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}),
})}
</span>
</div>
)}
</div>
{/* Footer */}
+2 -1
View File
@@ -154,7 +154,8 @@
"confirm": "OK",
"close": "Close",
"doNotClose": "Upload is in progress. Do not close this window.",
"goToCalendar": "View in Calendar"
"goToCalendar": "View in Calendar",
"scheduleConflict": "Schedule adjusted to {{time}} due to a conflict."
},
"landing": {
"hero": {
+2 -1
View File
@@ -154,7 +154,8 @@
"confirm": "확인",
"close": "닫기",
"doNotClose": "업로드가 진행 중입니다. 창을 닫지 마세요.",
"goToCalendar": "캘린더에서 확인"
"goToCalendar": "캘린더에서 확인",
"scheduleConflict": "예약 시간이 충돌하여 {{time}}으로 조정되었습니다."
},
"landing": {
"hero": {
+17 -35
View File
@@ -2,6 +2,7 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import Sidebar from '../../components/Sidebar';
import ShortformContent from './ShortformContent';
import AssetManagementContent from './AssetManagementContent';
import SoundStudioContent from './SoundStudioContent';
import CompletionContent from './CompletionContent';
@@ -54,6 +55,7 @@ interface GenerationFlowProps {
initialImageList?: string[];
businessInfo?: BusinessInfo;
initialAnalysisData?: CrawlingResponse | null;
initialShortform?: boolean;
}
// 위저드 단계:
@@ -69,7 +71,8 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
initialActiveItem = '대시보드',
initialImageList = [],
businessInfo,
initialAnalysisData
initialAnalysisData,
initialShortform = false,
}) => {
const { t, i18n } = useTranslation();
// localStorage에서 저장된 상태 복원
@@ -94,6 +97,9 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
// 초기 위저드 단계 결정
const getInitialWizardStep = (): number => {
// 숏폼 진입 플래그가 있으면 숏폼 화면(-3)으로 바로
if (initialShortform) return -3;
if (savedWizardStep !== null) {
const step = parseInt(savedWizardStep, 10);
// 분석 데이터가 있는데 URL 입력(-2) 또는 로딩(-1) 단계로 저장된 경우:
@@ -289,37 +295,6 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
};
// 테스트용 랜덤 m_id 생성 (99 ~ 300)
const generateRandomMId = (): number => {
return Math.floor(Math.random() * (300 - 99 + 1)) + 99;
};
// 테스트 데이터로 브랜드 분석 페이지 이동
const handleTestData = (data: CrawlingResponse) => {
const tagged = { ...data, m_id: generateRandomMId(), _isTestData: true };
setAnalysisData(tagged);
localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(tagged));
goToWizardStep(0); // 브랜드 분석 결과로
};
// 언어 변경 시 테스트 데이터 다시 로드
useEffect(() => {
const saved = localStorage.getItem(ANALYSIS_DATA_KEY);
if (!saved) return;
try {
const parsed = JSON.parse(saved);
if (!parsed._isTestData) return;
const jsonFile = i18n.language === 'en' ? '/example_analysis_en.json' : '/example_analysis.json';
fetch(jsonFile)
.then(res => res.json())
.then((data: CrawlingResponse) => {
// 언어 변경 시에는 기존 m_id 유지
const tagged = { ...data, m_id: parsed.m_id || generateRandomMId(), _isTestData: true };
setAnalysisData(tagged);
localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(tagged));
})
.catch(err => console.error('Failed to reload test data:', err));
} catch { /* ignore */ }
}, [i18n.language]);
// URL 분석 시작
const handleStartAnalysis = async (url: string) => {
@@ -432,6 +407,13 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
// 새 프로젝트 만들기 - 단계별 컨텐츠 렌더링
const renderWizardContent = () => {
switch (wizardStep) {
case -3:
// 숏폼 생성 단계
return (
<ShortformContent
onComplete={refreshCredits}
/>
);
case -2:
// URL 입력 단계
return (
@@ -439,7 +421,7 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
onAnalyze={handleStartAnalysis}
onAutocomplete={handleAutocomplete}
onManualInput={handleManualInput}
onTestData={handleTestData}
onShortform={() => goToWizardStep(-3)}
error={analysisError}
/>
);
@@ -551,8 +533,8 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
case '내 정보':
return <MyInfoContent initialTab={myInfoInitialTab} />;
case '새 프로젝트 만들기':
// 브랜드 분석(0)과 로딩(-1)은 전체 화면으로 표시
if (wizardStep === 0 || wizardStep === -1) {
// 브랜드 분석(0), 로딩(-1), 숏폼(-3)은 전체 화면으로 표시
if (wizardStep === 0 || wizardStep === -1 || wizardStep === -3) {
return renderWizardContent();
}
return (
+478
View File
@@ -0,0 +1,478 @@
import React, { useRef, useState } from 'react';
import { uploadImages, generateShortform, waitForShortformComplete, previewShortform } from '../../utils/api';
import { ShortformStatusResponse, VideoSpec } from '../../types/api';
type Kind = 'place' | 'product' | 'message';
type Step = 1 | 2 | 3 | 4;
interface ShortformContentProps {
onComplete?: () => void;
}
const KIND_OPTIONS: { value: Kind; label: string; desc: string }[] = [
{ value: 'place', label: '장소', desc: '펜션·카페·식당·매장 등 공간' },
{ value: 'product', label: '물건', desc: '제품, 음식 등 시각적인 아이템' },
{ value: 'message', label: '메시지', desc: '축하·안부·홍보 등' },
];
const STEP_META = [
{ label: '사진 업로드', sub: '4~5장' },
{ label: '정보 입력', sub: '몇 가지만 답하기' },
{ label: '영상 생성', sub: 'AI 카메라 + 자막' },
{ label: '완성', sub: '다운로드' },
];
const MIN_PHOTOS = 4;
const MIN_PHOTOS_LABEL = `${MIN_PHOTOS}장`;
const ShortformContent: React.FC<ShortformContentProps> = ({ onComplete }) => {
const fileInputRef = useRef<HTMLInputElement>(null);
const dropRef = useRef<HTMLDivElement>(null);
// 단계
const [step, setStep] = useState<Step>(1);
// Step 1 — 사진
const [files, setFiles] = useState<File[]>([]);
const [previews, setPreviews] = useState<string[]>([]);
// Step 2 — 폼
const [kind, setKind] = useState<Kind>('place');
const [bizName, setBizName] = useState('');
const [selling, setSelling] = useState('');
const [addr, setAddr] = useState('');
const [price, setPrice] = useState('');
// Step 3/4 — 생성 상태
const [statusMsg, setStatusMsg] = useState('');
const [result, setResult] = useState<ShortformStatusResponse | null>(null);
const [errorMsg, setErrorMsg] = useState('');
// 자막 미리보기
const [preview, setPreview] = useState<VideoSpec | null>(null);
const [previewLoading, setPreviewLoading] = useState(false);
const [previewError, setPreviewError] = useState('');
// --- 사진 관리 ---
const addFiles = (newFiles: File[]) => {
const images = newFiles.filter(f => f.type.startsWith('image/'));
if (!images.length) return;
const newUrls = images.map(f => URL.createObjectURL(f));
setFiles(prev => [...prev, ...images]);
setPreviews(prev => [...prev, ...newUrls]);
};
const removeFile = (index: number) => {
URL.revokeObjectURL(previews[index]);
setFiles(prev => prev.filter((_, i) => i !== index));
setPreviews(prev => prev.filter((_, i) => i !== index));
};
const handleDragOver = (e: React.DragEvent) => { e.preventDefault(); };
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
addFiles(Array.from(e.dataTransfer.files));
};
// --- 미리보기 필드 수정 ---
const patchPreview = (updater: (prev: NonNullable<typeof preview>) => NonNullable<typeof preview>) => {
setPreview(prev => prev ? updater(prev) : prev);
};
// --- 자막 미리보기 ---
const handlePreview = async () => {
if (!selling.trim()) return;
setPreviewLoading(true);
setPreviewError('');
try {
const spec = await previewShortform({
kind,
biz_name: bizName.trim(),
selling: selling.trim(),
addr: addr.trim() || undefined,
price: price.trim() || undefined,
});
setPreview(spec);
} catch (err) {
setPreviewError(err instanceof Error ? err.message : '미리보기 생성에 실패했습니다.');
} finally {
setPreviewLoading(false);
}
};
// --- 다운로드 ---
const [isDownloading, setIsDownloading] = useState(false);
const handleDownload = async (url: string) => {
if (isDownloading) return;
setIsDownloading(true);
try {
const resp = await fetch(url);
const blob = await resp.blob();
const blobUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = blobUrl;
link.download = `${bizName || 'shortform'}.mp4`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(blobUrl);
} catch {
const link = document.createElement('a');
link.href = url;
link.download = `${bizName || 'shortform'}.mp4`;
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} finally {
setIsDownloading(false);
}
};
// --- 생성 실행 ---
const handleGenerate = async () => {
setStep(3);
setErrorMsg('');
setResult(null);
try {
setStatusMsg('사진 업로드 중...');
const uploadResp = await uploadImages([], files);
setStatusMsg('영상 생성 요청 중...');
await generateShortform({
task_id: uploadResp.task_id,
kind,
biz_name: bizName.trim(),
addr: addr.trim() || undefined,
price: price.trim() || undefined,
selling: selling.trim(),
spec: preview ?? undefined,
dry_run: true,
});
setStatusMsg('AI 카메라 무브·자막 렌더링 중...');
const statusResp = await waitForShortformComplete(uploadResp.task_id, s => {
setStatusMsg(s === 'processing' ? 'AI 카메라 무브·자막 렌더링 중...' : s);
});
setResult(statusResp);
setStep(4);
onComplete?.();
} catch (err) {
setErrorMsg(err instanceof Error ? err.message : '생성 중 오류가 발생했습니다.');
setStep(2);
}
};
const step1Valid = files.length >= MIN_PHOTOS;
const step2Valid = bizName.trim() && selling.trim();
// ===================== 렌더 =====================
// 스텝 인디케이터
const StepBar = () => (
<div className="sf-step-bar">
{STEP_META.map((s, i) => {
const n = (i + 1) as Step;
const done = step > n;
const active = step === n;
return (
<div key={n} className={`sf-step-item ${active ? 'active' : ''} ${done ? 'done' : ''}`}>
<div className="sf-step-circle">
{done
? <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><polyline points="20 6 9 17 4 12"/></svg>
: n}
</div>
<div className="sf-step-label">
<span className="sf-step-name">{s.label}</span>
<span className="sf-step-sub">{s.sub}</span>
</div>
</div>
);
})}
</div>
);
// ---- Step 1: 사진 업로드 ----
if (step === 1) return (
<main className="sf-page">
<div className="sf-scroll-area">
<div className="sf-hero">
<h1 className="sf-hero-title">사진 몇 장과 한마디면, <span className="sf-hero-accent">8초 홍보 영상</span>이 됩니다</h1>
<p className="sf-hero-desc">복잡한 분석 없이 — 사진을 올리고 몇 가지만 답하면, AI 카메라 무브와 자막을 입힌 세로형 숏폼이 완성됩니다.</p>
</div>
<StepBar />
<div className="sf-card">
<h2 className="sf-card-title">사진 업로드</h2>
<p className="sf-card-desc">홍보할 장소나 물건 사진 4~5장. 전경 1장·디테일 2~3장을 섞으면 영상의 서사가 살아납니다.</p>
<div
ref={dropRef}
className="sf-drop-zone"
onClick={() => fileInputRef.current?.click()}
onDragOver={handleDragOver}
onDrop={handleDrop}
>
<div className="sf-drop-icon">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
</div>
<p className="sf-drop-text">여기로 사진을 끌어다 놓거나 클릭</p>
<p className="sf-drop-hint">JPG·PNG·{MIN_PHOTOS_LABEL} 이상</p>
</div>
<input ref={fileInputRef} type="file" accept="image/*" multiple style={{ display: 'none' }} onChange={e => { addFiles(Array.from(e.target.files || [])); e.target.value = ''; }} />
{previews.length > 0 && (
<div className="sf-photo-grid">
{previews.map((url, i) => (
<div key={i} className="sf-photo-item">
<span className="sf-photo-num">{i + 1}</span>
<img src={url} alt={`사진 ${i + 1}`} />
<button className="sf-photo-remove" onClick={() => removeFile(i)}>×</button>
</div>
))}
</div>
)}
</div>
</div>
<div className="sf-footer">
<div className="sf-footer-info">
<span className="sf-footer-count">{files.length}장</span>
{step1Valid
? <span className="sf-footer-status ok">업로드됨·준비 완료</span>
: <span className="sf-footer-status">{MIN_PHOTOS - files.length}장 더 추가해주세요</span>}
</div>
<button
className="sf-btn-next"
disabled={!step1Valid}
onClick={() => setStep(2)}
>
다음: 정보 입력 →
</button>
</div>
</main>
);
// ---- Step 2: 정보 입력 ----
if (step === 2) return (
<main className="sf-page">
<div className="sf-scroll-area">
<StepBar />
<div className="sf-card">
<h2 className="sf-card-title">몇 가지만 알려주세요</h2>
<p className="sf-card-desc">사장님·마케터가 가장 잘 아는 정보로 카피를 만듭니다.</p>
{/* Kind */}
<div className="sf-field">
<label className="sf-label">영상의 목적이 무엇인가요? <span className="sf-required">*</span></label>
<div className="sf-kind-grid">
{KIND_OPTIONS.map(opt => (
<button
key={opt.value}
type="button"
className={`sf-kind-card ${kind === opt.value ? 'active' : ''}`}
onClick={() => setKind(opt.value)}
>
<span className="sf-kind-label">{opt.label}</span>
<span className="sf-kind-desc">{opt.desc}</span>
</button>
))}
</div>
</div>
{/* 업체명 */}
<div className="sf-field">
<label className="sf-label">업체·상품·메시지 제목 <span className="sf-required">*</span></label>
<input
className="sf-input"
type="text"
placeholder="예: 스테이 머뭄"
value={bizName}
onChange={e => setBizName(e.target.value)}
maxLength={50}
/>
</div>
{/* 셀링포인트 */}
<div className="sf-field">
<label className="sf-label">가장 자랑하고 싶은 한 가지 <span className="sf-required">*</span></label>
<textarea
className="sf-textarea"
placeholder="예: 열방 손님 없는 완전한 독채, 개별 정원까지"
value={selling}
onChange={e => setSelling(e.target.value)}
maxLength={100}
rows={3}
/>
<p className="sf-field-hint">이 한마디가 영상의 후킹 타이틀·핵심 메시지가 됩니다. 구체적일수록 좋아요.</p>
</div>
{/* 자막 미리보기 */}
<div className="sf-field">
<div className="sf-subtitle-header">
<label className="sf-label">영상 자막·스크립트</label>
<button
className="sf-subtitle-btn"
disabled={!selling.trim() || previewLoading}
onClick={handlePreview}
>
{previewLoading ? '생성 중...' : preview ? '재생성하기' : '자막 생성하기'}
</button>
</div>
<p className="sf-field-hint">위 한 가지를 적은 뒤 누르면, AI가 인트로·셀링포인트·감성 스토리·CTA 4가지를 만들어줍니다.</p>
{previewError && <p className="sf-field-error">{previewError}</p>}
{preview && (
<div className="sf-preview-spec">
<div className="sf-preview-block">
<span className="sf-preview-tag">인트로</span>
<input className="sf-preview-input" value={preview.hook.eyebrow}
onChange={e => patchPreview(p => ({ ...p, hook: { ...p.hook, eyebrow: e.target.value } }))} />
<input className="sf-preview-input sf-preview-input-bold" value={preview.hook.title}
onChange={e => patchPreview(p => ({ ...p, hook: { ...p.hook, title: e.target.value } }))} />
</div>
<div className="sf-preview-block">
<span className="sf-preview-tag">셀링포인트</span>
<div className="sf-preview-badge-inputs">
{preview.selling_point.items.slice(0, 3).map((item, i) => (
<input key={i} className="sf-preview-badge-input" value={item}
onChange={e => patchPreview(p => {
const items = [...p.selling_point.items];
items[i] = e.target.value;
return { ...p, selling_point: { items } };
})} />
))}
</div>
</div>
<div className="sf-preview-block">
<span className="sf-preview-tag">감성 스토리</span>
{preview.brand_lines.slice(0, 2).map((line, i) => (
<input key={i} className="sf-preview-input" value={line}
onChange={e => patchPreview(p => {
const brand_lines = [...p.brand_lines];
brand_lines[i] = e.target.value;
return { ...p, brand_lines };
})} />
))}
</div>
<div className="sf-preview-block">
<span className="sf-preview-tag">CTA</span>
<input className="sf-preview-input" value={preview.end_card.brand}
onChange={e => patchPreview(p => ({ ...p, end_card: { ...p.end_card, brand: e.target.value } }))} />
<input className="sf-preview-input" value={preview.end_card.location}
onChange={e => patchPreview(p => ({ ...p, end_card: { ...p.end_card, location: e.target.value } }))} />
</div>
</div>
)}
</div>
{/* 주소 */}
<div className="sf-field">
<label className="sf-label">주소 또는 판매 사이트 URL <span className="sf-optional">(선택)</span></label>
<input
className="sf-input"
type="text"
placeholder="예: 전북 군산시 절골길 18"
value={addr}
onChange={e => setAddr(e.target.value)}
maxLength={100}
/>
<p className="sf-field-hint">영상 엔드카드·해시태그에 활용됩니다.</p>
</div>
{/* 가격 */}
<div className="sf-field">
<label className="sf-label">가격 정보 <span className="sf-optional">(선택)</span></label>
<input
className="sf-input"
type="text"
placeholder="예: 1박 19만원~"
value={price}
onChange={e => setPrice(e.target.value)}
maxLength={50}
/>
</div>
</div>
</div>
<div className="sf-footer sf-footer-two">
<button className="sf-btn-prev" onClick={() => setStep(1)}>← 사진 다시</button>
<button className="sf-btn-generate" disabled={!step2Valid} onClick={handleGenerate}>
영상 생성 →
</button>
</div>
{errorMsg && (
<div className="sf-error-toast">{errorMsg}</div>
)}
</main>
);
// ---- Step 3: 생성 중 ----
if (step === 3) return (
<main className="sf-page">
<div className="sf-scroll-area">
<StepBar />
<div className="sf-generating">
<div className="sf-gen-orb-ring">
<div className="sf-gen-spinner-lg" />
<div className="sf-gen-icon">
<svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<path d="M15 10l4.553-2.069A1 1 0 0121 8.87V15.13a1 1 0 01-1.447.899L15 14M3 8a2 2 0 012-2h10a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V8z"/>
</svg>
</div>
</div>
<h2 className="sf-gen-title">AI가 영상을 만들고 있어요</h2>
<p className="sf-gen-msg">{statusMsg || 'AI 카메라 무브·자막 렌더링 중...'}</p>
<p className="sf-gen-sub">보통 1~3분 정도 소요됩니다. 잠시만 기다려주세요.</p>
<div className="sf-gen-steps">
<div className={`sf-gen-step ${statusMsg.includes('업로드') ? 'active' : statusMsg ? 'done' : ''}`}>
<span className="sf-gen-step-dot" />사진 업로드
</div>
<div className={`sf-gen-step ${statusMsg.includes('요청') ? 'active' : statusMsg.includes('렌더링') || statusMsg.includes('완성') ? 'done' : ''}`}>
<span className="sf-gen-step-dot" />영상 생성 요청
</div>
<div className={`sf-gen-step ${statusMsg.includes('렌더링') ? 'active' : ''}`}>
<span className="sf-gen-step-dot" />AI 렌더링
</div>
</div>
</div>
</div>
</main>
);
// ---- Step 4: 완성 ----
return (
<main className="sf-page">
<div className="sf-scroll-area">
<StepBar />
<div className="sf-result">
<p className="sf-result-label">✓ 영상이 완성됐습니다!</p>
{result?.result_url && (
<div className="sf-result-video-wrap">
<video className="sf-result-video" src={result.result_url} controls playsInline />
</div>
)}
<div className="sf-result-actions">
{result?.result_url && (
<button
className="sf-download-btn"
disabled={isDownloading}
onClick={() => handleDownload(result.result_url!)}
>
{isDownloading ? '다운로드 중...' : '다운로드'}
</button>
)}
<button className="sf-btn-prev" onClick={() => { setStep(1); setFiles([]); setPreviews([]); setBizName(''); setSelling(''); setAddr(''); setPrice(''); }}>
새 영상 만들기
</button>
</div>
</div>
</div>
</main>
);
};
export default ShortformContent;
+4 -37
View File
@@ -1,39 +1,16 @@
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import React from 'react';
import { AutocompleteRequest } from '../../utils/api';
import { CrawlingResponse } from '../../types/api';
import SearchInputForm, { SearchType } from '../../components/SearchInputForm';
// 환경변수에서 테스트 모드 확인
const isTestPage = import.meta.env.VITE_IS_TESTPAGE === 'true';
interface UrlInputContentProps {
onAnalyze: (value: string, type?: SearchType) => void;
onAutocomplete?: (data: AutocompleteRequest) => void;
onManualInput?: (businessName: string, address: string) => void;
onTestData?: (data: CrawlingResponse) => void;
onShortform?: () => void;
error: string | null;
}
const UrlInputContent: React.FC<UrlInputContentProps> = ({ onAnalyze, onAutocomplete, onManualInput, onTestData, error }) => {
const { t, i18n } = useTranslation();
const [isLoadingTest, setIsLoadingTest] = useState(false);
const handleTestData = async () => {
if (!onTestData) return;
setIsLoadingTest(true);
try {
const jsonFile = i18n.language === 'en' ? '/example_analysis_en.json' : '/example_analysis.json';
const response = await fetch(jsonFile);
const data: CrawlingResponse = await response.json();
onTestData(data);
} catch (err) {
console.error('테스트 데이터 로드 실패:', err);
} finally {
setIsLoadingTest(false);
}
};
const UrlInputContent: React.FC<UrlInputContentProps> = ({ onAnalyze, onAutocomplete, onManualInput, onShortform, error }) => {
return (
<div className="url-input-container">
<div className="url-input-content">
@@ -46,20 +23,10 @@ const UrlInputContent: React.FC<UrlInputContentProps> = ({ onAnalyze, onAutocomp
onAnalyze={onAnalyze}
onAutocomplete={onAutocomplete}
onManualInput={onManualInput}
onShortform={onShortform}
error={error}
/>
</div>
{/* 테스트 버튼 (VITE_IS_TESTPAGE=true일 때만 표시) */}
{isTestPage && onTestData && (
<button
onClick={handleTestData}
disabled={isLoadingTest}
className="test-data-button"
>
{isLoadingTest ? t('urlInput.testDataLoading') : t('urlInput.testData')}
</button>
)}
</div>
);
};
+7 -100
View File
@@ -1,18 +1,4 @@
import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { AutocompleteRequest, isLoggedIn } from '../../utils/api';
import { CrawlingResponse } from '../../types/api';
import { useTutorial } from '../../components/Tutorial/useTutorial';
import { TUTORIAL_KEYS } from '../../components/Tutorial/tutorialSteps';
import TutorialOverlay from '../../components/Tutorial/TutorialOverlay';
import BusinessNameInputModal from '../../components/BusinessNameInputModal';
import LoginPromptModal from '../../components/LoginPromptModal';
import SearchInputForm from '../../components/SearchInputForm';
import { SearchType } from '../../components/SearchInputForm';
// 환경변수에서 테스트 모드 확인
const isTestPage = import.meta.env.VITE_IS_TESTPAGE === 'true';
import React, { useEffect, useRef } from 'react';
// Orb configuration with movement zones to prevent overlap
interface OrbConfig {
@@ -37,50 +23,14 @@ const orbConfigs: OrbConfig[] = [
];
interface HeroSectionProps {
onAnalyze?: (value: string, type?: SearchType) => void;
onAutocomplete?: (data: AutocompleteRequest) => void;
onManualInput?: (businessName: string, address: string) => void;
onTestData?: (data: CrawlingResponse) => void;
onLogin?: () => void;
onNext?: () => void;
error?: string | null;
scrollProgress?: number;
}
const HeroSection: React.FC<HeroSectionProps> = ({ onAnalyze, onAutocomplete, onManualInput, onTestData, onNext, error: externalError, scrollProgress = 0 }) => {
const { t, i18n } = useTranslation();
const [isManualModalOpen, setIsManualModalOpen] = useState(false);
const [isLoginPromptOpen, setIsLoginPromptOpen] = useState(false);
const [testError, setTestError] = useState('');
const [isLoadingTest, setIsLoadingTest] = useState(false);
const HeroSection: React.FC<HeroSectionProps> = ({ onLogin, onNext, scrollProgress = 0 }) => {
const orbRefs = useRef<(HTMLDivElement | null)[]>([]);
const animationRefs = useRef<number[]>([]);
const tutorial = useTutorial();
// 첫 방문 시 랜딩 튜토리얼 시작
useEffect(() => {
if (!tutorial.hasSeen(TUTORIAL_KEYS.LANDING)) {
const timer = setTimeout(() => {
tutorial.startTutorial(TUTORIAL_KEYS.LANDING);
}, 800);
return () => clearTimeout(timer);
}
}, []);
// 테스트 데이터 로드 핸들러
const handleTestData = async () => {
if (!onTestData) return;
setIsLoadingTest(true);
try {
const jsonFile = i18n.language === 'en' ? '/example_analysis_en.json' : '/example_analysis.json';
const response = await fetch(jsonFile);
const data: CrawlingResponse = await response.json();
onTestData(data);
} catch {
setTestError(t('landing.hero.testDataLoadFailed'));
} finally {
setIsLoadingTest(false);
}
};
// Orb 랜덤 이동 애니메이션
useEffect(() => {
@@ -168,63 +118,20 @@ const HeroSection: React.FC<HeroSectionProps> = ({ onAnalyze, onAutocomplete, on
className="hero-logo"
/>
<SearchInputForm
onAnalyze={onAnalyze}
onAutocomplete={onAutocomplete}
onManualInput={onManualInput}
onManualButtonClick={() => {
if (isLoggedIn()) {
setIsManualModalOpen(true);
} else {
setIsLoginPromptOpen(true);
}
}}
error={externalError || testError || null}
/>
<button className="hero-login-btn" onClick={onLogin}>
로그인
</button>
</div>
{/* Footer Indicator */}
<button onClick={onNext} className="scroll-indicator">
<span className="scroll-indicator-text">{t('landing.hero.scrollMore')}</span>
<span className="scroll-indicator-text">더 알아보기</span>
<div className="scroll-indicator-icon">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round">
<path d="M7 10l5 5 5-5" />
</svg>
</div>
</button>
{/* 테스트 버튼 */}
{isTestPage && onTestData && (
<button onClick={handleTestData} disabled={isLoadingTest} className="test-data-button">
{isLoadingTest ? t('landing.hero.testDataLoading') : t('landing.hero.testData')}
</button>
)}
{tutorial.isActive && !isManualModalOpen && (
<TutorialOverlay
hints={tutorial.hints}
currentIndex={tutorial.currentHintIndex}
onNext={tutorial.nextHint}
onPrev={tutorial.prevHint}
onSkip={tutorial.skipTutorial}
groupProgress={tutorial.groupProgress}
/>
)}
{isManualModalOpen && (
<BusinessNameInputModal
onClose={() => setIsManualModalOpen(false)}
onSubmit={(businessName, address) => {
if (tutorial.isActive) tutorial.nextHint();
setIsManualModalOpen(false);
onManualInput?.(businessName, address);
}}
/>
)}
{isLoginPromptOpen && (
<LoginPromptModal onClose={() => setIsLoginPromptOpen(false)} />
)}
</div>
);
};
+56 -2
View File
@@ -207,6 +207,58 @@ export interface ImageUploadResponse {
}>;
}
// 숏폼 생성 요청
export interface ShortformGenerateRequest {
task_id: string;
kind: string;
biz_name: string;
addr?: string;
price?: string;
selling: string;
spec?: VideoSpec;
dry_run?: boolean;
}
// 숏폼 생성 응답
export interface ShortformGenerateResponse {
task_id: string;
video_id: number;
status: string;
}
// 숏폼 상태 조회 응답
export interface ShortformStatusResponse {
task_id: string;
status: 'processing' | 'completed' | 'failed';
result_url: string | null;
}
// 숏폼 미리보기 요청
export interface ShortformPreviewRequest {
kind: string;
biz_name: string;
selling: string;
addr?: string;
price?: string;
}
// 숏폼 미리보기 응답 (VideoSpec)
export interface VideoSpec {
hook: {
eyebrow: string;
title: string;
};
selling_point: {
items: string[];
};
brand_lines: string[];
end_card: {
brand: string;
location: string;
};
caption: string;
}
// 언어 매핑
export const LANGUAGE_MAP: Record<string, string> = {
'한국어': 'Korean',
@@ -412,9 +464,11 @@ export interface SocialUploadRequest {
// 소셜 업로드 응답
export interface SocialUploadResponse {
success: boolean;
upload_id: string;
status: 'pending' | 'uploading' | 'completed' | 'failed';
upload_id: number;
platform: string;
status: string;
message: string;
scheduled_at?: string | null; // 예약 업로드 충돌 시 실제 예약 시간 반환
}
// 소셜 업로드 상태 조회 응답
+84
View File
@@ -34,6 +34,11 @@ import {
CommentsResponse,
CommentItem,
LikeToggleResponse,
ShortformGenerateRequest,
ShortformGenerateResponse,
ShortformStatusResponse,
ShortformPreviewRequest,
VideoSpec,
} from '../types/api';
export const API_URL = import.meta.env.VITE_API_URL || 'http://40.82.133.44';
@@ -557,6 +562,85 @@ export async function waitForVideoComplete(
return poll();
}
// ============================================
// 숏폼 생성 API
// ============================================
// 숏폼 생성 요청 (POST /shortform/generate, 202 Accepted)
export async function generateShortform(req: ShortformGenerateRequest): Promise<ShortformGenerateResponse> {
const response = await authenticatedFetch(`${API_URL}/shortform/generate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(req),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
// 숏폼 상태 조회 (GET /shortform/status/{task_id})
export async function getShortformStatus(taskId: string): Promise<ShortformStatusResponse> {
const response = await authenticatedFetch(`${API_URL}/shortform/status/${taskId}`, {
method: 'GET',
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
// 숏폼 완료까지 폴링 (10분 타임아웃, 3초 간격)
const SHORTFORM_POLL_TIMEOUT = 10 * 60 * 1000;
const SHORTFORM_POLL_INTERVAL = 3000;
export async function waitForShortformComplete(
taskId: string,
onStatusChange?: (status: string) => void
): Promise<ShortformStatusResponse> {
const startTime = Date.now();
const poll = async (): Promise<ShortformStatusResponse> => {
if (Date.now() - startTime > SHORTFORM_POLL_TIMEOUT) {
throw new Error('TIMEOUT');
}
const statusResponse = await getShortformStatus(taskId);
onStatusChange?.(statusResponse.status);
if (statusResponse.status === 'completed') {
return statusResponse;
} else if (statusResponse.status === 'failed') {
throw new Error('Shortform generation failed');
}
await new Promise(resolve => setTimeout(resolve, SHORTFORM_POLL_INTERVAL));
return poll();
};
return poll();
}
// 숏폼 자막 미리보기 (POST /shortform/preview)
export async function previewShortform(req: ShortformPreviewRequest): Promise<VideoSpec> {
const response = await authenticatedFetch(`${API_URL}/shortform/preview`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(req),
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error((err as { detail?: string }).detail || '미리보기 생성에 실패했습니다.');
}
return response.json();
}
// ============================================
// 카카오 인증 API
// ============================================