init commit from ado4

This commit is contained in:
jaehwang committed 2025-12-08 13:27:07 +09:00
commit d820394ccc
126 files changed
+51929

No files matched your search

+144
View File
@@ -0,0 +1,144 @@
/// <reference lib="dom" />
/**
* Base64로 인코딩된 오디오 데이터를 Uint8Array로 디코딩하는 유틸리티 함수입니다.
* @param {string} base64 - Base64 인코딩된 문자열 (data URI 접두사 없이 순수 데이터)
* @returns {Uint8Array} - 디코딩된 바이트 배열
*/
export function decodeBase64(base64: string): Uint8Array {
// `atob` 함수를 사용하여 Base64 문자열을 이진 문자열로 디코딩합니다.
const binaryString = atob(base64);
const len = binaryString.length;
// 디코딩된 바이트를 저장할 Uint8Array를 생성합니다.
const bytes = new Uint8Array(len);
// 각 문자의 ASCII 코드를 바이트 배열에 저장합니다.
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes;
}
/**
* PCM 오디오 데이터를 AudioBuffer 객체로 디코딩하는 비동기 함수입니다.
* 웹 오디오 API를 사용하여 브라우저에서 오디오를 재생하거나 처리하기 위해 사용됩니다.
*
* @param {Uint8Array} data - 디코딩할 PCM 오디오 데이터 (Uint8Array 형식)
* @param {AudioContext} ctx - 현재 사용 중인 AudioContext 인스턴스
* @param {number} sampleRate - 오디오 샘플 레이트 (기본값: 24000 Hz)
* @param {number} numChannels - 오디오 채널 수 (기본값: 1, 모노)
* @returns {Promise<AudioBuffer>} - 디코딩된 AudioBuffer 객체
*/
export async function decodeAudioData(
data: Uint8Array,
ctx: AudioContext,
sampleRate: number = 24000,
numChannels: number = 1,
): Promise<AudioBuffer> {
// 16비트 정렬을 확인하고 필요한 경우 버퍼 크기를 조정합니다.
// (createBuffer는 짝수 길이의 버퍼를 선호할 수 있습니다.)
let buffer = data.buffer;
if (buffer.byteLength % 2 !== 0) {
const newBuffer = new ArrayBuffer(buffer.byteLength + 1);
new Uint8Array(newBuffer).set(data);
buffer = newBuffer;
}
// Int16Array로 데이터를 해석하여 16비트 PCM 데이터를 처리합니다.
const dataInt16 = new Int16Array(buffer);
// 총 프레임 수를 계산합니다 (샘플 수 / 채널 수).
const frameCount = dataInt16.length / numChannels;
// AudioBuffer를 생성합니다. (채널 수, 프레임 수, 샘플 레이트)
const audioBuffer = ctx.createBuffer(numChannels, frameCount, sampleRate);
// 각 오디오 채널에 대해 데이터를 처리합니다.
for (let channel = 0; channel < numChannels; channel++) {
// 현재 채널의 데이터를 가져옵니다 (Float32Array).
const channelData = audioBuffer.getChannelData(channel);
for (let i = 0; i < frameCount; i++) {
// Int16 값을 Float32 범위 [-1.0, 1.0]으로 변환합니다.
// 16비트 부호 있는 정수(short)의 최대값은 32767이므로 이 값으로 나눕니다.
channelData[i] = dataInt16[i * numChannels + channel] / 32768.0;
}
}
return audioBuffer;
}
/**
* AudioBuffer 객체를 WAV 형식의 Blob으로 변환하는 함수입니다.
* 이렇게 생성된 Blob은 HTML <audio> 태그에서 직접 재생할 수 있습니다.
*
* @param {AudioBuffer} abuffer - WAV로 변환할 AudioBuffer 객체
* @param {number} len - AudioBuffer의 총 샘플 길이 (프레임 수)
* @returns {Blob} - WAV 형식의 오디오 데이터를 담은 Blob 객체
*/
export function bufferToWaveBlob(abuffer: AudioBuffer, len: number): Blob {
const numOfChan = abuffer.numberOfChannels; // 채널 수 (예: 1=모노, 2=스테레오)
// WAV 파일의 총 길이를 계산합니다. (데이터 길이 + 헤더 길이)
// (샘플 수 * 채널 수 * 2 바이트/샘플 (16비트) + 44 바이트 (WAV 헤더))
const length = len * numOfChan * 2 + 44;
const buffer = new ArrayBuffer(length); // 전체 WAV 파일 크기의 ArrayBuffer
const view = new DataView(buffer); // 데이터를 쓰기 위한 DataView
const channels = []; // 각 채널의 데이터를 저장할 배열
let i;
let sample;
let offset = 0; // 현재 읽고 있는 샘플 오프셋
let pos = 0; // DataView에 쓰는 현재 위치
// 16비트 정수를 DataView에 쓰는 헬퍼 함수
function setUint16(data: number) {
view.setUint16(pos, data, true); // little-endian
pos += 2;
}
// 32비트 정수를 DataView에 쓰는 헬퍼 함수
function setUint32(data: number) {
view.setUint32(pos, data, true); // little-endian
pos += 4;
}
// --- WAV 헤더 작성 ---
setUint32(0x46464952); // "RIFF" chunk ID
setUint32(length - 8); // ChunkSize (파일 길이 - 8 바이트)
setUint32(0x45564157); // "WAVE" format
setUint32(0x20746d66); // "fmt " sub-chunk ID
setUint32(16); // Subchunk1Size (fmt 서브 청크 길이 = 16 바이트)
setUint16(1); // AudioFormat (PCM = 1)
setUint16(numOfChan); // NumChannels
setUint32(abuffer.sampleRate); // SampleRate
setUint32(abuffer.sampleRate * 2 * numOfChan); // ByteRate (SampleRate * NumChannels * BitsPerSample/8)
setUint16(numOfChan * 2); // BlockAlign (NumChannels * BitsPerSample/8)
setUint16(16); // BitsPerSample (현재 예제에서는 16비트로 고정)
setUint32(0x61746164); // "data" sub-chunk ID
setUint32(length - pos - 4); // Subchunk2Size (데이터 길이)
// --- 인터리브된 오디오 데이터 작성 ---
// 각 채널의 오디오 데이터를 배열에 저장
for (i = 0; i < abuffer.numberOfChannels; i++)
channels.push(abuffer.getChannelData(i));
// 각 샘플을 순회하며 채널 데이터를 인터리브하여 DataView에 작성
while (offset < len) {
for (i = 0; i < numOfChan; i++) {
// DataView에 쓰기 전 안전한 경계 검사
if (pos + 2 > length) break;
// 채널 인터리브 (예: 좌, 우, 좌, 우 ...)
const channel = channels[i];
// 채널 데이터에서 현재 오프셋의 샘플을 가져옵니다. (안전하게 접근)
const s = channel && offset < channel.length ? channel[offset] : 0;
// 샘플 값을 -1에서 1 사이로 클램프(clamp)합니다.
sample = Math.max(-1, Math.min(1, s));
// 16비트 부호 있는 정수(-32768 ~ 32767) 스케일로 변환합니다.
sample = (sample < 0 ? sample * 0x8000 : sample * 0x7FFF) | 0;
view.setInt16(pos, sample, true); // 16비트 샘플 작성 (little-endian)
pos += 2;
}
offset++; // 다음 원본 샘플로 이동
}
// 최종적으로 WAV Blob을 생성하여 반환합니다.
return new Blob([buffer], { type: 'audio/wav' });
}
+137
View File
@@ -0,0 +1,137 @@
import { FFmpeg } from '@ffmpeg/ffmpeg';
import { fetchFile, toBlobURL } from '@ffmpeg/util';
let ffmpeg: FFmpeg | null = null; // FFmpeg 인스턴스를 저장할 변수
/**
* FFmpeg WASM 모듈을 로드하는 함수입니다.
* 한 번 로드된 FFmpeg 인스턴스는 재사용됩니다.
* FFmpeg worker 스크립트의 상대 경로 문제를 해결하기 위한 패치 로직을 포함합니다.
* @returns {Promise<FFmpeg>} - 로드된 FFmpeg 인스턴스
*/
const loadFFmpeg = async () => {
if (ffmpeg) return ffmpeg; // 이미 로드되어 있다면 기존 인스턴스 반환
ffmpeg = new FFmpeg(); // 새로운 FFmpeg 인스턴스 생성
// FFmpeg 코어 및 관련 파일의 CDN 기본 URL
const coreBaseURL = 'https://unpkg.com/@ffmpeg/core@0.12.6/dist/esm';
const ffmpegBaseURL = 'https://unpkg.com/@ffmpeg/ffmpeg@0.12.10/dist/esm';
/**
* FFmpeg worker 스크립트의 상대 경로 import를 절대 경로로 패치하는 헬퍼 함수입니다.
* `@ffmpeg/ffmpeg` 라이브러리의 worker.js 파일은 내부적으로 `./classes.js`와 같은 상대 경로를 사용하는데,
* Blob URL로 로드될 경우 이 상대 경로를 해석하지 못하는 문제가 발생합니다.
* 따라서 worker.js 내용을 동적으로 가져와 절대 경로로 수정한 후 Blob URL로 만들어 사용합니다.
* @returns {Promise<string>} - 패치된 worker 스크립트의 Blob URL
*/
const getPatchedWorkerBlob = async () => {
try {
// 원본 worker.js 스크립트를 CDN에서 가져옵니다.
const response = await fetch(`${ffmpegBaseURL}/worker.js`);
let text = await response.text();
console.log("원본 Worker 스크립트 길이:", text.length);
// 상대 경로 임포트(예: from "./classes.js")를 절대 경로로 교체합니다.
// 정규식을 사용하여 "./classes.js" 또는 './classes.js' 패턴을 찾아 교체합니다.
const patchedText = text.replace(
/from\s*["']\.\/classes\.js["']/g,
`from "${ffmpegBaseURL}/classes.js"`
);
console.log("패치된 Worker 스크립트 길이:", patchedText.length);
// 패치된 스크립트 내용을 Blob으로 만들고, 이를 위한 URL을 생성합니다.
const blob = new Blob([patchedText], { type: 'text/javascript' });
const blobUrl = URL.createObjectURL(blob);
console.log("생성된 Worker Blob URL:", blobUrl);
return blobUrl;
} catch (e) {
console.error("Worker 스크립트 패치 실패:", e);
throw e;
}
};
// FFmpeg의 코어, WASM, worker 스크립트를 로드합니다.
// workerURL은 위에서 패치된 Blob URL을 사용합니다.
const workerBlobUrl = await getPatchedWorkerBlob(); // 패치된 worker 스크립트 URL을 먼저 생성
await ffmpeg.load({
coreURL: await toBlobURL(`${coreBaseURL}/ffmpeg-core.js`, 'text/javascript'),
wasmURL: await toBlobURL(`${coreBaseURL}/ffmpeg-core.wasm`, 'application/wasm'),
workerURL: workerBlobUrl, // 패치된 worker URL 사용
});
return ffmpeg;
};
/**
* 비디오와 오디오 파일을 클라이언트 사이드에서 FFmpeg WASM을 이용하여 병합합니다.
* 이 함수는 주로 미리보기 기능의 '빠른 저장'에 사용됩니다.
* @param {string} videoUrl - 병합할 비디오 파일의 URL
* @param {string} audioUrl - 병합할 오디오 파일의 URL
* @param {(msg: string) => void} onProgress - 진행 상황을 업데이트하는 콜백 함수
* @returns {Promise<string>} - 병합된 비디오의 Blob URL
*/
export const mergeVideoAndAudio = async (
videoUrl: string,
audioUrl: string,
onProgress: (msg: string) => void
): Promise<string> => {
try {
onProgress("FFmpeg 엔진 로딩 중...");
const ffmpeg = await loadFFmpeg(); // FFmpeg 인스턴스 로드
onProgress("비디오/오디오 파일 다운로드 중...");
// 비디오와 오디오 파일을 FFmpeg의 가상 파일 시스템(MEMFS)에 씁니다.
await ffmpeg.writeFile('input_video.mp4', await fetchFile(videoUrl));
// 오디오 파일의 확장자를 감지하여 올바른 파일명으로 저장합니다.
const isWav = audioUrl.endsWith('wav') || audioUrl.startsWith('blob:'); // Blob URL은 대부분 WAV임
const audioExt = isWav ? 'wav' : 'mp3';
const audioFilename = `input_audio.${audioExt}`;
await ffmpeg.writeFile(audioFilename, await fetchFile(audioUrl));
onProgress("비디오/오디오 병합 및 렌더링 중 (무한 루프 & 오디오 길이 맞춤)...");
// FFmpeg 명령어 실행
// -stream_loop -1 : 비디오를 무한 반복 재생합니다. (오디오가 끝나면 멈추도록 -shortest와 함께 사용)
// -i input_video.mp4 : 첫 번째 입력 파일 (비디오)
// -i input_audio.wav : 두 번째 입력 파일 (오디오)
// -shortest : 가장 짧은 스트림(여기서는 오디오)의 길이에 맞춰 출력을 중단합니다.
// -map 0:v:0 : 첫 번째 입력(비디오)의 비디오 스트림을 출력에 매핑합니다.
// -map 1:a:0 : 두 번째 입력(오디오)의 오디오 스트림을 출력에 매핑합니다.
// -c:v libx264 : 비디오 코덱을 H.264로 재인코딩합니다 (호환성 및 압축).
// -preset ultrafast : 인코딩 속도를 최우선으로 설정합니다 (빠른 미리보기용).
// -c:a aac : 오디오 코덱을 AAC로 재인코딩합니다 (MP4 표준 오디오 코덱).
// -strict experimental : 실험적인 기능(예: AAC 인코더) 사용을 허용합니다.
await ffmpeg.exec([
'-stream_loop', '-1',
'-i', 'input_video.mp4',
'-i', audioFilename,
'-shortest',
'-map', '0:v:0',
'-map', '1:a:0',
'-c:v', 'libx264',
'-preset', 'ultrafast',
'-c:a', 'aac',
'-strict', 'experimental',
'output.mp4'
]);
onProgress("최종 파일 생성 중...");
// FFmpeg 가상 파일 시스템에서 결과 파일(output.mp4)을 읽어옵니다.
const data = await ffmpeg.readFile('output.mp4');
// 읽어온 데이터를 Blob으로 만들고, 이를 위한 URL을 생성하여 반환합니다.
const blob = new Blob([data], { type: 'video/mp4' });
return URL.createObjectURL(blob);
} catch (error: any) {
console.error("FFmpeg 병합 오류 발생:", error);
throw new Error(`영상 합성 중 오류가 발생했습니다: ${error.message}`);
}
};
+327
View File
@@ -0,0 +1,327 @@
import { BusinessInfo, TTSConfig, AspectRatio, Language } from '../types';
import { decodeBase64, decodeAudioData, bufferToWaveBlob } from './audioUtils';
const SUPPORTED_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/heic', 'image/heif'];
// Helper to convert File object to base64 Data URL (MIME type 포함)
export const fileToBase64 = (file: File): Promise<{ base64: string; mimeType: string }> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const result = reader.result as string;
const [header, base64] = result.split(',');
const mimeType = header.split(':')[1].split(';')[0];
resolve({ base64, mimeType });
};
reader.onerror = error => reject(error);
});
};
/**
* 비즈니스 정보 검색 (Gemini 2.5 Flash + Google Maps Tool) - 백엔드 프록시 이용
* @param {string} query - 검색어 (업체명 또는 주소)
* @returns {Promise<{name: string, description: string, mapLink?: string}>}
*/
export const searchBusinessInfo = async (
query: string
): Promise<{ name: string; description: string; mapLink?: string }> => {
try {
const response = await fetch('/api/gemini/search-business', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}` // 인증 토큰 포함
},
body: JSON.stringify({ query })
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || `Server error: ${response.statusText}`);
}
const data = await response.json();
return data;
} catch (e: any) {
console.error("Search Business (Frontend) Failed:", e);
throw new Error(e.message || "업체 정보 검색에 실패했습니다.");
}
};
/**
* 창의적 콘텐츠 생성 (광고 카피 & 가사/스크립트) - 백엔드 프록시 이용
* @param {BusinessInfo} info - 비즈니스 정보 객체
* @returns {Promise<{adCopy: string[], lyrics: string}>}
*/
export const generateCreativeContent = async (
info: BusinessInfo
): Promise<{ adCopy: string[]; lyrics: string }> => {
try {
// 이미지 File 객체를 Base64로 변환하여 백엔드로 전달
const imagesForBackend = await Promise.all(
info.images.map(async (file) => await fileToBase64(file))
);
const payload = { ...info, images: imagesForBackend };
const response = await fetch('/api/gemini/creative-content', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || `Server error: ${response.statusText}`);
}
const data = await response.json();
return data;
} catch (e: any) {
console.error("Generate Creative Content (Frontend) Failed:", e);
throw new Error(e.message || "창의적 콘텐츠 생성에 실패했습니다.");
}
};
// 사용자 설정(성별/톤)을 Gemini 미리 정의된 목소리 이름으로 매핑 (이 함수는 백엔드에서 사용)
// const getVoiceName = (config: TTSConfig): string => { ... };
/**
* 고급 음성 합성 (TTS) - 백엔드 프록시 이용
* @param {string} text - 음성으로 변환할 텍스트
* @param {TTSConfig} config - TTS 설정
* @returns {Promise<string>} - Base64 인코딩된 오디오 데이터 URL
*/
export const generateAdvancedSpeech = async (
text: string,
config: TTSConfig
): Promise<string> => {
try {
const response = await fetch('/api/gemini/speech', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify({ text, config })
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || `Server error: ${response.statusText}`);
}
const data = await response.json();
// Base64 오디오 데이터를 Blob URL로 변환하여 반환
const audioContext = new ((window as any).AudioContext || (window as any).webkitAudioContext)({ sampleRate: 24000 });
const audioBytes = decodeBase64(data.base64Audio);
const audioBuffer = await decodeAudioData(audioBytes, audioContext, 24000, 1);
const wavBlob = bufferToWaveBlob(audioBuffer, audioBuffer.length);
return URL.createObjectURL(wavBlob);
} catch (e: any) {
console.error("Generate Advanced Speech (Frontend) Failed:", e);
throw new Error(e.message || "성우 음성 생성에 실패했습니다.");
}
};
/**
* 광고 포스터 생성 - 백엔드 프록시 이용
* @param {BusinessInfo} info - 비즈니스 정보 객체
* @returns {Promise<{ blobUrl: string; base64: string; mimeType: string }>}
*/
export const generateAdPoster = async (
info: BusinessInfo
): Promise<{ blobUrl: string; base64: string; mimeType: string }> => {
try {
const imagesForBackend = await Promise.all(
info.images.map(async (file) => await fileToBase64(file))
);
const payload = { ...info, images: imagesForBackend };
const response = await fetch('/api/gemini/ad-poster', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify({ info: payload })
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || `Server error: ${response.statusText}`);
}
const data = await response.json();
// Base64를 Blob URL로 변환
const byteCharacters = atob(data.base64);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], { type: data.mimeType });
const blobUrl = URL.createObjectURL(blob);
return { blobUrl, base64: data.base64, mimeType: data.mimeType };
} catch (e: any) {
console.error("Generate Ad Poster (Frontend) Failed:", e);
throw new Error(e.message || "광고 포스터 생성에 실패했습니다.");
}
};
/**
* 다수의 비즈니스 관련 이미지 생성 (갤러리/슬라이드쇼용) - 백엔드 프록시 이용
* @param {BusinessInfo} info - 비즈니스 정보 객체
* @param {number} count - 생성할 이미지 개수
* @returns {Promise<string[]>} - Base64 Data URL 배열
*/
export const generateImageGallery = async (
info: BusinessInfo,
count: number
): Promise<string[]> => {
try {
const response = await fetch('/api/gemini/image-gallery', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify({ info, count })
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || `Server error: ${response.statusText}`);
}
const data = await response.json();
return data.images;
} catch (e: any) {
console.error("Generate Image Gallery (Frontend) Failed:", e);
throw new Error(e.message || "이미지 갤러리 생성에 실패했습니다.");
}
};
/**
* 비디오 배경 생성 - 백엔드 프록시 이용
* @param {string} posterBase64 - Base64 인코딩된 포스터 이미지 데이터
* @param {string} posterMimeType - 포스터 이미지 MIME 타입
* @param {AspectRatio} aspectRatio - 비디오 화면 비율
* @returns {Promise<string>} - 생성된 비디오의 원격 URL
*/
export const generateVideoBackground = async (
posterBase64: string,
posterMimeType: string,
aspectRatio: AspectRatio = '16:9'
): Promise<string> => {
try {
const response = await fetch('/api/gemini/video-background', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify({ posterBase64, posterMimeType, aspectRatio })
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || `Server error: ${response.statusText}`);
}
const data = await response.json();
// 서버에서 받은 비디오 URL에 API 키를 붙이지 않고 그대로 반환
return data.videoUrl;
} catch (e: any) {
console.error("Generate Video Background (Frontend) Failed:", e);
throw new Error(e.message || "비디오 배경 생성에 실패했습니다.");
}
};
/**
* AI 이미지 검수 (Gemini Vision) - 백엔드 프록시 이용
* @param {Array<object>} imagesData - Base64 인코딩된 이미지 데이터 배열 ({ mimeType, base64 })
* @returns {Promise<Array<object>>} - 선별된 Base64 이미지 데이터 배열
*/
export const filterBestImages = async (
imagesData: { base64: string; mimeType: string }[]
): Promise<{ base64: string; mimeType: string }[]> => {
try {
const response = await fetch('/api/gemini/filter-images', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify({ imagesData })
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || `Server error: ${response.statusText}`);
}
const data = await response.json();
return data.filteredImages;
} catch (e: any) {
console.error("Filter Best Images (Frontend) Failed:", e);
throw new Error(e.message || "이미지 검수에 실패했습니다.");
}
};
/**
* 리뷰 기반 마케팅 설명 생성 - 백엔드 프록시 이용
* @param {string} name - 업체명
* @param {string} rawDescription - 기본 설명
* @param {string[]} reviews - 고객 리뷰 배열
* @param {number} rating - 평균 별점
* @returns {Promise<string>} - 생성된 설명
*/
export const enrichDescriptionWithReviews = async (
name: string,
rawDescription: string,
reviews: string[],
rating: number
): Promise<string> => {
try {
const response = await fetch('/api/gemini/enrich-description', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify({ name, rawDescription, reviews, rating })
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || `Server error: ${response.statusText}`);
}
const data = await response.json();
return data.enrichedDescription;
} catch (e: any) {
console.error("Enrich Description (Frontend) Failed:", e);
throw new Error(e.message || "마케팅 설명 생성에 실패했습니다.");
}
};
/**
* 이미지에서 텍스트 스타일(CSS) 추출 - 백엔드 프록시 이용
* @param {File} imageFile - 이미지 File 객체
* @returns {Promise<string>} - 생성된 CSS 코드
*/
export const extractTextEffectFromImage = async (
imageFile: File
): Promise<string> => {
try {
const imageForBackend = await fileToBase64(imageFile);
const response = await fetch('/api/gemini/text-effect', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify({ imageFile: imageForBackend })
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || `Server error: ${response.statusText}`);
}
const data = await response.json();
return data.cssCode;
} catch (e: any) {
console.error("Extract Text Effect (Frontend) Failed:", e);
throw new Error(e.message || "텍스트 스타일 분석에 실패했습니다.");
}
};
+259
View File
@@ -0,0 +1,259 @@
import { BusinessInfo } from '../types';
/**
* 이미지 파일의 간단한 해시를 생성합니다 (파일 크기 + 첫 바이트).
*/
const getImageFingerprint = async (file: File): Promise<string> => {
const size = file.size;
const slice = file.slice(0, 1024);
const buffer = await slice.arrayBuffer();
const bytes = new Uint8Array(buffer);
let sum = 0;
for (let i = 0; i < bytes.length; i++) {
sum = (sum + bytes[i]) % 65536;
}
return `${size}-${sum}`;
};
export interface CrawlOptions {
maxImages?: number;
existingFingerprints?: Set<string>;
}
/**
* Google Maps URL에서 장소 정보를 추출합니다.
* 지원 URL 형식:
* - https://maps.google.com/maps?q=장소이름
* - https://www.google.com/maps/place/장소이름
* - https://goo.gl/maps/...
* - https://maps.app.goo.gl/...
*/
export const parseGoogleMapsUrl = (url: string): string | null => {
try {
// maps.google.com 또는 google.com/maps 형식
if (url.includes('google.com/maps') || url.includes('maps.google.com')) {
// /place/장소이름 형식
const placeMatch = url.match(/\/place\/([^\/\?]+)/);
if (placeMatch) {
return decodeURIComponent(placeMatch[1].replace(/\+/g, ' '));
}
// ?q=장소이름 형식
const urlObj = new URL(url);
const query = urlObj.searchParams.get('q');
if (query) {
return decodeURIComponent(query.replace(/\+/g, ' '));
}
}
return null;
} catch {
return null;
}
};
/**
* Google Maps URL 또는 검색어로 장소 정보를 가져옵니다.
*/
export const crawlGooglePlace = async (
urlOrQuery: string,
onProgress?: (msg: string) => void,
options?: CrawlOptions
): Promise<Partial<BusinessInfo>> => {
const maxImages = options?.maxImages ?? 15;
const existingFingerprints = options?.existingFingerprints ?? new Set<string>();
onProgress?.("Google 지도 정보 가져오는 중...");
try {
// URL에서 검색어 추출 시도
let query = parseGoogleMapsUrl(urlOrQuery);
// URL 파싱 실패 시 직접 검색어로 사용
if (!query) {
// URL 형식이 아니면 검색어로 간주
if (!urlOrQuery.startsWith('http')) {
query = urlOrQuery;
} else {
throw new Error("지원되지 않는 Google Maps URL 형식입니다.");
}
}
onProgress?.(`'${query}' 검색 중...`);
// Google Places API로 검색
const placeDetails = await searchPlaceDetails(query);
if (!placeDetails) {
throw new Error("Google Places에서 해당 장소를 찾을 수 없습니다.");
}
const totalPhotos = placeDetails.photos?.length || 0;
onProgress?.(`'${placeDetails.displayName.text}' 정보 수신 완료. 이미지 다운로드 중... (총 ${totalPhotos}장 중 최대 ${maxImages}장)`);
// 사진을 랜덤하게 섞기
const photos = placeDetails.photos || [];
const shuffledPhotos = [...photos].sort(() => Math.random() - 0.5);
// 사진 다운로드 (중복 검사 포함)
const imageFiles: File[] = [];
let skippedDuplicates = 0;
for (let i = 0; i < shuffledPhotos.length && imageFiles.length < maxImages; i++) {
try {
onProgress?.(`이미지 다운로드 중 (${imageFiles.length + 1}/${maxImages})...`);
const file = await fetchPlacePhoto(shuffledPhotos[i].name);
if (file) {
const newFile = new File([file], `google_${i}.jpg`, { type: 'image/jpeg' });
// 중복 검사
const fingerprint = await getImageFingerprint(newFile);
if (existingFingerprints.has(fingerprint)) {
console.log(`중복 이미지 발견, 건너뜁니다`);
skippedDuplicates++;
continue;
}
imageFiles.push(newFile);
}
} catch (e) {
console.warn("이미지 다운로드 실패:", e);
}
}
if (skippedDuplicates > 0) {
console.log(`총 ${skippedDuplicates}장의 중복 이미지를 건너뛰었습니다.`);
}
onProgress?.(`${imageFiles.length}장의 이미지를 가져왔습니다.`);
// 설명 생성
let description = '';
if (placeDetails.generativeSummary?.overview?.text) {
description = placeDetails.generativeSummary.overview.text;
} else if (placeDetails.reviews && placeDetails.reviews.length > 0) {
description = placeDetails.reviews[0].text.text;
}
return {
name: placeDetails.displayName.text,
description: description || `${placeDetails.displayName.text} - ${placeDetails.primaryTypeDisplayName?.text || ''} (${placeDetails.formattedAddress})`,
images: imageFiles,
address: placeDetails.formattedAddress,
category: placeDetails.primaryTypeDisplayName?.text,
sourceUrl: urlOrQuery
};
} catch (error: any) {
console.error("Google Places 크롤링 실패:", error);
throw new Error(error.message || "Google Places 정보를 가져오는데 실패했습니다.");
}
};
interface PlaceDetails {
displayName: { text: string };
formattedAddress: string;
rating?: number;
userRatingCount?: number;
reviews?: {
name: string;
relativePublishTimeDescription: string;
text: { text: string };
rating: number;
}[];
photos?: {
name: string;
widthPx: number;
heightPx: number;
}[];
generativeSummary?: { overview: { text: string } };
primaryTypeDisplayName?: { text: string };
}
/**
* Google Places API를 사용하여 장소를 검색하고 상세 정보를 가져옵니다.
*/
export const searchPlaceDetails = async (query: string): Promise<PlaceDetails | null> => {
try {
// 1. 텍스트 검색 (Text Search) - 백엔드 프록시 사용
const searchRes = await fetch(`/api/google/places/search`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify({
textQuery: query,
languageCode: "ko"
})
});
if (!searchRes.ok) {
const errorData = await searchRes.json();
throw new Error(errorData.error || `Server error: ${searchRes.statusText}`);
}
const searchData = await searchRes.json();
if (!searchData.places || searchData.places.length === 0) return null;
const placeId = searchData.places[0].name.split('/')[1];
// 2. 상세 정보 요청 (Details) - 백엔드 프록시 사용
const fieldMask = [
'displayName',
'formattedAddress',
'rating',
'userRatingCount',
'reviews',
'photos',
'primaryTypeDisplayName'
].join(',');
const detailRes = await fetch(`/api/google/places/details`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify({
placeId,
fieldMask
})
});
if (!detailRes.ok) {
const errorData = await detailRes.json();
throw new Error(errorData.error || `Server error: ${detailRes.statusText}`);
}
return await detailRes.json();
} catch (error: any) {
console.error("Google Places API Error (Frontend):", error);
throw new Error(error.message || "Google Places 정보를 가져오는데 실패했습니다.");
}
};
/**
* 사진 리소스 이름(media key)을 사용하여 실제 이미지 Blob을 다운로드합니다.
* 백엔드 프록시 이용.
*/
export const fetchPlacePhoto = async (photoName: string, maxWidth = 800): Promise<File | null> => {
try {
if (!photoName) return null;
const response = await fetch('/api/google/places/photo', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify({ photoName, maxWidthPx: maxWidth })
});
if (!response.ok) return null;
const blob = await response.blob();
return new File([blob], "place_photo.jpg", { type: "image/jpeg" });
} catch (error: any) {
console.error("Photo Fetch Error (Frontend):", error);
return null;
}
};
+153
View File
@@ -0,0 +1,153 @@
import { BusinessInfo } from '../types';
/**
* 헬퍼 함수: URL에서 파일을 가져와 File 객체로 변환합니다.
* CORS 문제나 Blob URL 등을 처리하기 위해 백업 프록시 로직을 포함합니다.
* @param {string} url - 가져올 파일의 URL
* @param {string} filename - 생성할 File 객체의 이름
* @returns {Promise<File>} - File 객체
*/
const urlToFile = async (url: string, filename: string): Promise<File> => {
try {
// 백엔드 프록시를 통해 이미지 다운로드 (CORS 우회)
const proxyUrl = `/api/proxy/image?url=${encodeURIComponent(url)}`;
const response = await fetch(proxyUrl);
if (!response.ok) {
throw new Error(`Proxy failed with status: ${response.status}`);
}
const blob = await response.blob();
return new File([blob], filename, { type: blob.type || 'image/jpeg' });
} catch (e) {
console.error(`이미지 다운로드 실패 ${url}:`, e);
throw new Error(`이미지 다운로드 실패: ${url}`);
}
};
/**
* 이미지 파일의 간단한 해시를 생성합니다 (파일 크기 + 첫 바이트).
* 완벽한 중복 검사는 아니지만 빠르고 대부분의 경우를 처리합니다.
*/
const getImageFingerprint = async (file: File): Promise<string> => {
const size = file.size;
const slice = file.slice(0, 1024); // 첫 1KB만 읽기
const buffer = await slice.arrayBuffer();
const bytes = new Uint8Array(buffer);
let sum = 0;
for (let i = 0; i < bytes.length; i++) {
sum = (sum + bytes[i]) % 65536;
}
return `${size}-${sum}`;
};
/**
* 기존 이미지들의 fingerprint 목록을 생성합니다.
*/
export const getExistingFingerprints = async (existingImages: File[]): Promise<Set<string>> => {
const fingerprints = new Set<string>();
for (const img of existingImages) {
try {
const fp = await getImageFingerprint(img);
fingerprints.add(fp);
} catch (e) {
console.warn('Fingerprint 생성 실패:', e);
}
}
return fingerprints;
};
export interface CrawlOptions {
maxImages?: number; // 가져올 최대 이미지 수 (기본값: 15)
existingFingerprints?: Set<string>; // 중복 검사용 기존 이미지 fingerprints
}
/**
* 네이버 플레이스 정보를 크롤링하는 함수입니다.
* 클라이언트에서 백엔드 API를 호출하여 네이버 장소 정보를 가져옵니다.
* @param {string} url - 네이버 플레이스 URL 또는 장소 ID
* @param {(msg: string) => void} [onProgress] - 진행 상황을 알리는 콜백 함수 (선택 사항)
* @param {CrawlOptions} [options] - 추가 옵션 (maxImages, existingFingerprints)
* @returns {Promise<Partial<BusinessInfo>>} - 비즈니스 정보의 부분 객체
*/
export const crawlNaverPlace = async (
url: string,
onProgress?: (msg: string) => void,
options?: CrawlOptions
): Promise<Partial<BusinessInfo>> => {
const maxImages = options?.maxImages ?? 15;
const existingFingerprints = options?.existingFingerprints ?? new Set<string>();
onProgress?.("네이버 플레이스 정보 가져오는 중 (서버 요청)...");
try {
// 백엔드 Express 서버의 /api/naver/crawl 엔드포인트 호출
const response = await fetch('/api/naver/crawl', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url }) // 크롤링할 URL을 백엔드로 전송
});
if (!response.ok) {
// 서버 응답이 성공적이지 않을 경우 에러 처리
const errData = await response.json().catch(() => ({})); // 에러 JSON 파싱 시도
throw new Error(errData.error || "서버 크롤링 요청 실패");
}
const data = await response.json(); // 성공 시 응답 데이터 파싱
console.log(`백엔드 크롤링 결과: ${data.name}, 총 ${data.totalImages || data.images?.length}장 이미지 (셔플됨)`);
onProgress?.(`'${data.name}' 정보 수신 완료. 이미지 다운로드 중... (총 ${data.totalImages || '?'}장 중 최대 ${maxImages}장)`);
// 크롤링된 이미지 URL들을 File 객체로 변환 (중복 검사 포함)
const imageFiles: File[] = [];
const imageUrls = data.images || [];
let skippedDuplicates = 0;
for (let i = 0; i < imageUrls.length && imageFiles.length < maxImages; i++) {
const imgUrl = imageUrls[i];
try {
onProgress?.(`이미지 다운로드 중 (${imageFiles.length + 1}/${maxImages})...`);
// 각 이미지 URL을 File 객체로 변환
const file = await urlToFile(imgUrl, `naver_${data.place_id}_${i}.jpg`);
// 중복 검사
const fingerprint = await getImageFingerprint(file);
if (existingFingerprints.has(fingerprint)) {
console.log(`중복 이미지 발견, 건너뜁니다: ${imgUrl.slice(-30)}`);
skippedDuplicates++;
continue;
}
imageFiles.push(file);
} catch (e) {
console.warn("이미지 다운로드 실패, 건너뜁니다:", imgUrl, e);
}
}
if (skippedDuplicates > 0) {
console.log(`총 ${skippedDuplicates}장의 중복 이미지를 건너뛰었습니다.`);
}
// 다운로드된 이미지가 없을 경우 에러 발생
if (imageFiles.length === 0) {
throw new Error("유효한 이미지를 하나도 다운로드하지 못했습니다. 다른 URL을 시도해보세요.");
}
onProgress?.(`${imageFiles.length}장의 이미지를 가져왔습니다.`);
// 비즈니스 정보 객체 반환
return {
name: data.name,
description: data.description || `${data.name} - ${data.category} (${data.address})`,
images: imageFiles,
address: data.address,
category: data.category,
sourceUrl: url
};
} catch (error: any) {
console.error("크롤링 실패:", error);
throw new Error(error.message || "네이버 플레이스 정보를 가져오는데 실패했습니다.");
}
};
+117
View File
@@ -0,0 +1,117 @@
// Suno API 응답 인터페이스 (백엔드 응답용)
interface SunoBackendResponse {
audioUrl: string;
}
/**
* 가사 정제 로직 (Python의 _sanitize_lyrics 함수를 JavaScript로 포팅).
* Suno AI가 가사를 올바르게 해석하도록 특정 패턴을 [Verse 1]과 같은 태그로 변환합니다.
* @param {string} lyrics - 원본 가사 텍스트
* @returns {string} - Suno AI에 최적화된 정제된 가사 텍스트
*/
const sanitizeLyrics = (lyrics: string): string => {
// 섹션 헤더를 감지하는 정규식 (예: Verse, Chorus, Bridge, Hook, Intro, Outro)
const sectionPattern = /^(verse|chorus|bridge|hook|intro|outro)\s*(\d+)?\s*:?/i;
const sanitizedLines: string[] = []; // 정제된 가사 라인들을 저장할 배열
const lines = lyrics.split('\n'); // 가사를 줄 단위로 분리
for (const rawLine of lines) {
const line = rawLine.trim(); // 각 줄의 앞뒤 공백 제거
if (!line) {
sanitizedLines.push(""); // 빈 줄은 그대로 추가
continue;
}
const match = line.match(sectionPattern); // 섹션 패턴 매칭 시도
if (match) {
// 섹션 이름 첫 글자 대문자화
const name = match[1].charAt(0).toUpperCase() + match[1].slice(1).toLowerCase();
const number = match[2] || ""; // 섹션 번호 (있으면 사용, 없으면 빈 문자열)
// [Verse 1] 형태의 태그로 변환하여 추가
const label = `[${name}${number ? ' ' + number : ''}]`;
sanitizedLines.push(label);
} else {
sanitizedLines.push(line); // 패턴에 해당하지 않으면 원본 줄 추가
}
}
const result = sanitizedLines.join('\n').trim(); // 정제된 줄들을 다시 합치고 최종 공백 제거
if (!result) throw new Error("정제된 가사가 비어있습니다. Suno AI에 전달할 유효한 가사가 필요합니다.");
return result;
};
/**
* Suno AI를 사용하여 음악을 생성하는 함수입니다.
* 백엔드 프록시 서버(/api/suno/generate)를 통해 요청을 전송하여 CORS 문제 및 안정성을 개선했습니다.
*
* @param {string} rawLyrics - 사용자가 입력한 원본 가사
* @param {string} style - 음악 스타일 (예: Pop, Rock, Acoustic 등)
* @param {string} title - 노래 제목
* @param {boolean} isFullSong - 전체 길이 곡 생성 여부 (현재는 사용되지 않지만, API에 따라 달라질 수 있음)
* @returns {Promise<string>} - 생성된 음악 파일의 URL
*/
export const generateSunoMusic = async (
rawLyrics: string,
style: string,
title: string,
isFullSong: boolean, // 현재는 사용되지 않음
isInstrumental: boolean = false // 연주곡 여부
): Promise<string> => {
// 1. 가사 정제 (연주곡이 아닐 때만 수행)
let sanitizedLyrics = "";
if (!isInstrumental) {
sanitizedLyrics = sanitizeLyrics(rawLyrics);
} else {
// console.log("연주곡 모드: 가사 생성 생략"); // 제거
}
// 2. 요청 페이로드 구성 (Suno OpenAPI v1 Spec 준수)
const payload = {
// Custom Mode에서 instrumental이 false이면 prompt는 가사로 사용됨.
// instrumental이 true이면 prompt는 사용되지 않음 (하지만 예제에는 포함되어 있으므로 안전하게 유지).
prompt: isInstrumental ? "" : sanitizedLyrics,
style: style, // tags -> style 로 복구
title: title.substring(0, 80), // V4/V4_5ALL 기준 80자 제한 안전하게 적용
customMode: true,
instrumental: isInstrumental, // make_instrumental -> instrumental 로 복구
model: "V5", // 필수 필드: V5 사용
callBackUrl: "https://api.example.com/callback" // 필수 필드: 더미 URL이라도 보내야 함
};
try {
// console.log("백엔드를 통해 Suno 음악 생성 요청 시작..."); // 제거
// 백엔드 엔드포인트 호출 (프록시 사용 X, 로컬 서버 사용)
const response = await fetch('/api/suno/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}` // 인증 토큰 포함
},
body: JSON.stringify(payload) // JSON 페이로드 전송
});
if (!response.ok) {
const errorJson = await response.json().catch(() => ({ error: "Unknown Error" }));
console.error("Suno Backend Error:", errorJson);
throw new Error(`음악 생성 실패 (서버): ${errorJson.error || response.statusText}`);
}
const resData: SunoBackendResponse = await response.json();
if (!resData.audioUrl) {
throw new Error("서버에서 오디오 URL을 반환하지 않았습니다.");
}
console.log(`생성 완료! Audio URL: ${resData.audioUrl}`);
return resData.audioUrl;
} catch (e: any) {
console.error("Suno 서비스 오류 발생", e);
throw new Error(e.message || "음악 생성 중 알 수 없는 오류가 발생했습니다.");
}
};