-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
351 lines (288 loc) · 10.3 KB
/
main.py
File metadata and controls
351 lines (288 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
"""
K-Vibe Localizer - 메인 에이전트 실행 로직
한국 시장 맞춤형 UI/UX 현지화 에이전트
"""
import base64
from contextlib import asynccontextmanager
from functools import lru_cache
from dotenv import load_dotenv
from fastapi import FastAPI, UploadFile, File, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, JSONResponse
from pydantic import BaseModel
from pydantic_settings import BaseSettings
from services.parser import DocumentParser
from services.extractor import InfoExtractor
from services.solar_llm import SolarLLM
# .env 파일 로드
load_dotenv()
# 최대 파일 크기 (10MB)
MAX_FILE_SIZE = 10 * 1024 * 1024
class Settings(BaseSettings):
"""애플리케이션 설정"""
upstage_api_key: str = ""
solar_api_key: str = ""
app_name: str = "K-Vibe Localizer"
debug: bool = False
class Config:
env_file = ".env"
extra = "ignore"
class AnalyzeRequest(BaseModel):
"""단일 텍스트 분석 요청"""
text: str
element_type: str = "general"
class CTARequest(BaseModel):
"""CTA 변형 생성 요청"""
cta_text: str
context: str = ""
@lru_cache
def get_settings() -> Settings:
"""설정 싱글톤 인스턴스 반환"""
return Settings()
@asynccontextmanager
async def lifespan(app: FastAPI):
"""애플리케이션 시작/종료 시 실행되는 로직"""
settings = get_settings()
# API 키 검증
if not settings.upstage_api_key or settings.upstage_api_key == "your_upstage_api_key_here":
print("⚠️ 경고: UPSTAGE_API_KEY가 설정되지 않았습니다.")
else:
print("✅ Upstage API 키 로드 완료")
if not settings.solar_api_key or settings.solar_api_key == "your_solar_api_key_here":
print("⚠️ 경고: SOLAR_API_KEY가 설정되지 않았습니다.")
else:
print("✅ Solar API 키 로드 완료")
print(f"🚀 {settings.app_name} 서버 시작")
print("📍 http://localhost:8000 에서 접속 가능")
yield
print(f"👋 {settings.app_name} 서버 종료")
app = FastAPI(
title="K-Vibe Localizer",
description="한국 시장 맞춤형 UI/UX 현지화 에이전트",
version="1.0.0",
lifespan=lifespan
)
# CORS 설정
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# React 빌드 산출물: /assets (JS, CSS)
app.mount("/assets", StaticFiles(directory="web/assets"), name="assets")
# 기타 정적 파일 (web 폴더)
app.mount("/static", StaticFiles(directory="web"), name="static")
def validate_api_keys(settings: Settings) -> None:
"""API 키 유효성 검사"""
if not settings.upstage_api_key or settings.upstage_api_key == "your_upstage_api_key_here":
raise HTTPException(
status_code=503,
detail={
"error": "API_KEY_NOT_CONFIGURED",
"message": "Upstage API 키가 설정되지 않았습니다. .env 파일을 확인해주세요."
}
)
def validate_file_size(content: bytes) -> None:
"""파일 크기 검사"""
if len(content) > MAX_FILE_SIZE:
size_mb = len(content) / (1024 * 1024)
raise HTTPException(
status_code=413,
detail={
"error": "FILE_TOO_LARGE",
"message": f"파일 크기({size_mb:.1f}MB)가 너무 큽니다. 최대 10MB까지 업로드 가능합니다."
}
)
def validate_file_type(content_type: str) -> None:
"""파일 타입 검사"""
allowed_types = ["image/png", "image/jpeg", "image/jpg", "image/webp", "image/gif"]
if content_type not in allowed_types:
raise HTTPException(
status_code=415,
detail={
"error": "UNSUPPORTED_FILE_TYPE",
"message": f"지원하지 않는 파일 형식입니다. PNG, JPG, WEBP, GIF만 업로드 가능합니다."
}
)
@app.get("/")
async def root():
"""메인 페이지 반환"""
return FileResponse("web/index.html")
@app.get("/health")
async def health_check(settings: Settings = Depends(get_settings)):
"""서버 상태 및 API 키 설정 여부 확인"""
return {
"status": "healthy",
"app_name": settings.app_name,
"upstage_api_configured": bool(settings.upstage_api_key and settings.upstage_api_key != "your_upstage_api_key_here"),
"solar_api_configured": bool(settings.solar_api_key and settings.solar_api_key != "your_solar_api_key_here"),
"max_file_size_mb": MAX_FILE_SIZE / (1024 * 1024)
}
@app.post("/analyze")
async def analyze_screenshot(
file: UploadFile = File(...),
settings: Settings = Depends(get_settings)
):
"""
스크린샷을 분석하여 한국화 제안을 반환합니다.
전체 파이프라인:
1. 이미지 유효성 검사
2. Upstage Document Parse API로 OCR + 레이아웃 분석
3. Solar LLM으로 한국화 카피 생성
4. 결과 반환
"""
try:
# 1. API 키 검증
validate_api_keys(settings)
# 2. 파일 읽기 및 검증
contents = await file.read()
validate_file_size(contents)
validate_file_type(file.content_type)
# 3. Document Parse API 호출 (OCR + Layout 분석)
parser = DocumentParser()
parse_result = await parser.parse_image(contents, file.filename)
# 파싱된 텍스트 추출
markdown_text = parser.get_full_text(parse_result)
layout_elements = parser.extract_text_elements(parse_result)
if not markdown_text.strip():
return JSONResponse(
status_code=200,
content={
"status": "warning",
"message": "이미지에서 텍스트를 찾을 수 없습니다. 다른 이미지를 시도해주세요.",
"original_image": base64.b64encode(contents).decode("utf-8"),
"localized_copies": []
}
)
# 4. Solar LLM으로 한국화 분석
solar = SolarLLM()
localized_copies = await solar.localize_copy(
markdown_text=markdown_text,
layout_info={"elements": layout_elements}
)
# 5. 가격/날짜/단위 추출 (추가 정보)
extractor = InfoExtractor()
extracted_info = extractor.extract_all(markdown_text)
# 6. 결과 반환
return {
"status": "success",
"filename": file.filename,
"file_size": len(contents),
"original_image": base64.b64encode(contents).decode("utf-8"),
"parsed_text": markdown_text,
"layout_elements": layout_elements,
"localized_copies": localized_copies,
"extracted_info": extracted_info,
"element_count": len(localized_copies)
}
except HTTPException:
raise
except Exception as e:
return JSONResponse(
status_code=500,
content={
"status": "error",
"error": "ANALYSIS_FAILED",
"message": f"분석 중 오류가 발생했습니다: {str(e)}"
}
)
@app.post("/analyze/text")
async def analyze_single_text(
request: AnalyzeRequest,
settings: Settings = Depends(get_settings)
):
"""단일 텍스트를 한국화 스타일로 변환합니다."""
try:
validate_api_keys(settings)
solar = SolarLLM()
result = await solar.convert_single_copy(
original_text=request.text,
element_type=request.element_type
)
return {
"status": "success",
"result": result
}
except HTTPException:
raise
except Exception as e:
return JSONResponse(
status_code=500,
content={
"status": "error",
"message": f"변환 중 오류가 발생했습니다: {str(e)}"
}
)
@app.post("/analyze/cta")
async def generate_cta_variants(
request: CTARequest,
settings: Settings = Depends(get_settings)
):
"""CTA 버튼의 여러 한국어 변형을 생성합니다."""
try:
validate_api_keys(settings)
solar = SolarLLM()
variants = await solar.generate_cta_variants(
original_cta=request.cta_text,
context=request.context
)
return {
"status": "success",
"original": request.cta_text,
"variants": variants
}
except HTTPException:
raise
except Exception as e:
return JSONResponse(
status_code=500,
content={
"status": "error",
"message": f"CTA 생성 중 오류가 발생했습니다: {str(e)}"
}
)
@app.post("/analyze/full-report")
async def generate_full_report(
file: UploadFile = File(...),
settings: Settings = Depends(get_settings)
):
"""전체 페이지 종합 현지화 리포트를 생성합니다."""
try:
validate_api_keys(settings)
contents = await file.read()
validate_file_size(contents)
validate_file_type(file.content_type)
# Document Parse
parser = DocumentParser()
parse_result = await parser.parse_image(contents, file.filename)
markdown_text = parser.get_full_text(parse_result)
layout_elements = parser.extract_text_elements(parse_result)
# 종합 리포트 생성
solar = SolarLLM()
report = await solar.analyze_full_page(
markdown_text=markdown_text,
layout_info={"elements": layout_elements}
)
return {
"status": "success",
"filename": file.filename,
"original_image": base64.b64encode(contents).decode("utf-8"),
"parsed_text": markdown_text,
"report": report
}
except HTTPException:
raise
except Exception as e:
return JSONResponse(
status_code=500,
content={
"status": "error",
"message": f"리포트 생성 중 오류가 발생했습니다: {str(e)}"
}
)
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)