File size: 24,456 Bytes
86a8165 | 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 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 | """
λ
Έμ½λ© Python+ β μ¬νκ³Όν μ°κ΅¬μμ© λ°μ΄ν° λΆμ μΉμ±
FastAPI backend
"""
import io
import json
import os
import re
import threading
import traceback
import uuid
from datetime import datetime
from pathlib import Path
from typing import Optional
import numpy as np
import pandas as pd
from dotenv import load_dotenv
from fastapi import BackgroundTasks, FastAPI, File, HTTPException, UploadFile
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
import anthropic
from sandbox import execute_code
load_dotenv()
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Matplotlib νκΈ ν°νΈ κ°μ§ (μλ² μμ μ 1ν μ€ν)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _detect_korean_font() -> str:
"""μ¬μ© κ°λ₯ν νκΈ ν°νΈ μ΄λ¦μ λ°ν. μμΌλ©΄ DejaVu Sans."""
try:
import matplotlib.font_manager as fm
keywords = ["nanum", "malgun", "gothic", "gulim", "dotum", "batang"]
for f in fm.fontManager.ttflist:
if any(k in f.name.lower() for k in keywords):
return f.name
except Exception:
pass
return "DejaVu Sans"
MATPLOTLIB_FONT = _detect_korean_font()
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# App & directory setup
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
app = FastAPI(title="λ
Έμ½λ© Python+", version="1.0.0")
BASE_DIR = Path(__file__).parent
UPLOAD_DIR = BASE_DIR / "uploads"
RESULTS_DIR = BASE_DIR / "results"
STATIC_DIR = BASE_DIR / "static"
for d in [UPLOAD_DIR, RESULTS_DIR]:
d.mkdir(exist_ok=True)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# In-memory stores (protected by a lock)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
sessions: dict = {}
jobs: dict = {}
_lock = threading.Lock()
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Claude client (lazy β fails gracefully if key missing)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def get_claude_client() -> anthropic.Anthropic:
api_key = os.getenv("ANTHROPIC_API_KEY")
if not api_key:
raise HTTPException(
503,
"ANTHROPIC_API_KEYκ° μ€μ λμ§ μμμ΅λλ€. .env νμΌμ νμΈν΄μ£ΌμΈμ.",
)
return anthropic.Anthropic(api_key=api_key)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Request / Response models
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class AnalyzeRequest(BaseModel):
session_id: str
query: str
job_id: Optional[str] = None # optional follow-up context
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Data helpers
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _classify_column(series: pd.Series) -> str:
if pd.api.types.is_datetime64_any_dtype(series):
return "λ μ§ν"
if pd.api.types.is_numeric_dtype(series):
return "μμΉν"
n_unique = series.nunique(dropna=True)
if n_unique <= 20 or (len(series) > 0 and n_unique / len(series) < 0.05):
return "λ²μ£Όν"
return "λ¬Έμν"
def build_df_info(df: pd.DataFrame) -> dict:
columns = []
for col in df.columns:
col_type = _classify_column(df[col])
sample_vals = df[col].dropna().head(3).tolist()
# Make sample JSON-serialisable
sample_vals = [
str(v) if not isinstance(v, (int, float, bool)) else v
for v in sample_vals
]
columns.append(
{
"name": col,
"type": col_type,
"dtype": str(df[col].dtype),
"missing": int(df[col].isna().sum()),
"missing_pct": round(df[col].isna().sum() / max(len(df), 1) * 100, 1),
"unique": int(df[col].nunique(dropna=True)),
"sample": sample_vals,
}
)
return {
"shape": list(df.shape),
"columns": columns,
"missing_cols": sum(1 for c in columns if c["missing"] > 0),
}
def df_to_preview(df: pd.DataFrame) -> list:
preview = df.head(50).copy()
for col in preview.columns:
preview[col] = preview[col].astype(str).replace("nan", "")
return preview.to_dict("records")
def safe_read_file(file_path: Path, ext: str) -> pd.DataFrame:
if ext == ".csv":
for enc in ["utf-8-sig", "utf-8", "cp949", "euc-kr"]:
try:
return pd.read_csv(file_path, encoding=enc)
except UnicodeDecodeError:
continue
raise ValueError("CSV μΈμ½λ©μ μΈμν μ μμ΅λλ€.")
return pd.read_excel(file_path)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Sample data generator
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def make_sample_df() -> pd.DataFrame:
rng = np.random.default_rng(42)
n = 200
genders = rng.choice(["λ¨", "μ¬"], n)
pre = rng.normal(60, 15, n).clip(0, 100).round(1)
# post slightly higher on average to show a real effect
post = (pre + rng.normal(8, 10, n)).clip(0, 100).round(1)
return pd.DataFrame(
{
"ID": range(1, n + 1),
"gender": genders,
"age": rng.integers(22, 60, n),
"education": rng.choice(["κ³ μ‘Έ", "λμ‘Έ", "μμ¬", "λ°μ¬"], n, p=[0.15, 0.50, 0.25, 0.10]),
"department": rng.choice(["μΈλ¬Έμ¬ν", "μ΄κ³΅κ³", "μμ 체μ‘", "μμ½"], n),
"experience_years": rng.integers(0, 25, n),
"satisfaction_job": rng.integers(1, 6, n),
"satisfaction_wage": rng.integers(1, 6, n),
"satisfaction_balance": rng.integers(1, 6, n),
"satisfaction_overall": rng.integers(1, 6, n),
"pre_score": pre,
"post_score": post,
"stress_level": rng.integers(1, 6, n),
}
)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Claude prompts
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CODE_SYSTEM_PROMPT = """λΉμ μ μ¬νκ³Όν μ°κ΅¬μλ₯Ό μν Python λ°μ΄ν° λΆμ μ λ¬Έκ°μ
λλ€.
μ¬μ©μμ μμ°μ΄ μμ²μ λ°μ μμ ν μ€ν κ°λ₯ν Python λΆμ μ½λλ₯Ό μμ±ν©λλ€.
## μ½λ κ·μΉ
1. μ¬μ© κ°λ₯ν λΌμ΄λΈλ¬λ¦¬λ§ μ¬μ©νμΈμ:
pandas, numpy, scipy, matplotlib, seaborn, sklearn, statsmodels,
openpyxl, json, os, warnings, math, re, io, base64
2. μ½λ μ΅μλ¨ (λ°λμ ν¬ν¨):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
# νκΈ ν°νΈ μ€μ (Windows/Linux/Mac μλ κ°μ§)
_kor_keywords = ['nanum', 'malgun', 'gothic', 'gulim', 'dotum', 'batang']
_kor_fonts = [f.name for f in fm.fontManager.ttflist
if any(k in f.name.lower() for k in _kor_keywords)]
plt.rcParams['font.family'] = _kor_fonts[0] if _kor_fonts else 'DejaVu Sans'
plt.rcParams['axes.unicode_minus'] = False
3. μ¬μ μ μλ λ³μ (μμ κΈμ§, κ·Έλλ‘ μ¬μ©):
DATA_PATH β CSV λ°μ΄ν° νμΌ κ²½λ‘
OUTPUT_DIR β κ²°κ³Ό νμΌ μ μ₯ λλ ν 리
RESULT_FILE β κ²°κ³Ό JSON μ μ₯ κ²½λ‘
4. λ°μ΄ν° λ‘λ©: pd.read_csv(DATA_PATH, encoding='utf-8-sig')
5. λΆμ μλ£ ν λ°λμ RESULT_FILEμ JSON μ μ₯:
result = {
"summary": "μνν λΆμ νκ΅μ΄ μμ½ (2-3λ¬Έμ₯)",
"preprocessing": ["μ μ²λ¦¬1", "μ μ²λ¦¬2"],
"method": "μ¬μ© ν΅κ³ κΈ°λ² μ΄λ¦",
"tables": [{"title": "ν μ λͺ©", "html": "HTML λ¬Έμμ΄"}],
"charts": ["μ μ₯ν μ°¨νΈ νμΌλͺ
λͺ©λ‘"],
"interpretation": "λΉμ 곡μλ μ΄ν΄ν μ μλ νκ΅μ΄ κ²°κ³Ό ν΄μ (3-5λ¬Έμ₯, μμΉ ν¬ν¨)",
"packages": ["μ¬μ© ν¨ν€μ§ λͺ©λ‘"],
"log": "κ²½κ³ /νΉμ΄μ¬ν (μμΌλ©΄ λΉ λ¬Έμμ΄)"
}
with open(RESULT_FILE, 'w', encoding='utf-8') as f:
json.dump(result, f, ensure_ascii=False, indent=2)
6. μ°¨νΈ μ μ₯:
plt.savefig(os.path.join(OUTPUT_DIR, 'chart_01.png'), dpi=150, bbox_inches='tight')
plt.close()
7. HTML ν
μ΄λΈ μμ±:
df.to_html(classes='result-table', index=False, border=0)
8. μ 체λ₯Ό try-exceptλ‘ κ°μΈκ³ , μ€λ₯ λ°μ μμλ λΆλΆ κ²°κ³Όλ₯Ό RESULT_FILEμ μ μ₯νμΈμ.
9. λΆμ κ²°κ³Ό Excel μ μ₯ (μ νμ¬ν):
result_df.to_excel(os.path.join(OUTPUT_DIR, 'analysis_result.xlsx'), index=False)
μ½λλ§ λ°ννμΈμ. ```python λΈλ‘μΌλ‘ κ°μΈμ λ°ννμΈμ. μ€λͺ
μ νμ μμ΅λλ€."""
def _extract_code_from_response(text: str) -> str:
if "```python" in text:
return text.split("```python")[1].split("```")[0].strip()
if "```" in text:
return text.split("```")[1].split("```")[0].strip()
return text.strip()
def _build_col_info(df_info: dict) -> str:
lines = []
for c in df_info["columns"]:
sample_str = ", ".join(str(s) for s in c["sample"])
missing_str = f"κ²°μΈ‘ {c['missing']}κ°" if c["missing"] else "κ²°μΈ‘ μμ"
lines.append(f" - {c['name']} ({c['type']}, {missing_str}, κ³ μ κ° {c['unique']}κ°): μν=[{sample_str}]")
return "\n".join(lines)
def generate_analysis_code(session_info: dict, query: str, prev_results: Optional[dict] = None) -> str:
client = get_claude_client()
df_info = session_info["df_info"]
col_info = _build_col_info(df_info)
prev_ctx = ""
if prev_results:
prev_ctx = f"\n\nμ΄μ λΆμ κ²°κ³Ό (μ°Έκ³ μ©):\nλ°©λ²: {prev_results.get('method', '')}\nμμ½: {prev_results.get('summary', '')}"
user_message = f"""λ°μ΄ν° μ 보:
- νμΌ: {session_info['file_name']}
- ν¬κΈ°: {df_info['shape'][0]}ν Γ {df_info['shape'][1]}μ΄
- κ²°μΈ‘μΉ ν¬ν¨ 컬λΌ: {df_info['missing_cols']}κ°
μ»¬λΌ λͺ©λ‘:
{col_info}
{prev_ctx}
μ¬μ©μ μμ²: {query}
μ μμ²μ μ²λ¦¬νλ Python μ½λλ₯Ό μμ±ν΄μ£ΌμΈμ."""
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=4096,
system=CODE_SYSTEM_PROMPT,
messages=[{"role": "user", "content": user_message}],
)
return _extract_code_from_response(response.content[0].text)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Error message translator
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def friendly_error(stderr: str) -> str:
if "TimeoutExpired" in stderr or "timeout" in stderr.lower():
return "λΆμ μκ°μ΄ μ΄κ³Όλμμ΅λλ€ (μ΅λ 120μ΄). λ κ°λ¨ν λΆμμ μμ²ν΄λ³΄μΈμ."
if "MemoryError" in stderr:
return "λ©λͺ¨λ¦¬κ° λΆμ‘±ν©λλ€. λ°μ΄ν° ν¬κΈ°λ₯Ό μ€μ΄κ±°λ λΆμ λ²μλ₯Ό μ’νμ£ΌμΈμ."
m = re.search(r"KeyError: ['\"](.+?)['\"]", stderr)
if m:
return f"'{m.group(1)}' 컬λΌμ μ°Ύμ μ μμ΅λλ€. λ°μ΄ν° 미리보기μμ 컬λΌλͺ
μ νμΈν΄μ£ΌμΈμ."
if "ModuleNotFoundError" in stderr:
m2 = re.search(r"No module named '(.+?)'", stderr)
if m2:
return f"'{m2.group(1)}' λΌμ΄λΈλ¬λ¦¬λ₯Ό μ¬μ©ν μ μμ΅λλ€."
if "ValueError" in stderr and "convert" in stderr.lower():
return "μ«μν λ³νμ μ€ν¨νμ΅λλ€. ν΄λΉ 컬λΌμ΄ μ€μ λ‘ μ«μνμΈμ§ νμΈν΄μ£ΌμΈμ."
if "not enough values" in stderr or "shape" in stderr.lower():
return "λ°μ΄ν° κ΅¬μ‘°κ° λΆμμ μ ν©νμ§ μμ΅λλ€. λ€λ₯Έ λΆμ λ°©λ²μ μλν΄λ³΄μΈμ."
return "λΆμ μ€ μ€λ₯κ° λ°μνμ΅λλ€. μμ²μ λ€λ₯΄κ² νννκ±°λ λ€λ₯Έ λΆμμ μλν΄λ³΄μΈμ."
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Background analysis job
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _update_job(job_id: str, **kwargs):
with _lock:
for k, v in kwargs.items():
if k == "log_append":
jobs[job_id].setdefault("log", []).append(v)
else:
jobs[job_id][k] = v
def run_analysis_job(job_id: str, session_id: str, query: str, prev_results: Optional[dict]):
_update_job(job_id, status="generating_code", log_append="λΆμ κ³ν μ립 μ€β¦")
session_info = sessions.get(session_id)
if not session_info:
_update_job(job_id, status="error", error="μΈμ
μ μ°Ύμ μ μμ΅λλ€.")
return
job_dir = RESULTS_DIR / job_id
job_dir.mkdir(exist_ok=True)
result_file = job_dir / "result.json"
try:
# ββ Step 1: code generation ββββββββββββββββββββββββββββ
_update_job(job_id, log_append="Claudeκ° Python μ½λλ₯Ό μμ± μ€β¦")
code = generate_analysis_code(session_info, query, prev_results)
_update_job(job_id, code=code, status="executing", log_append="μ½λ μμ± μλ£. μ€ν μ€β¦")
# ββ Step 2: sandbox execution ββββββββββββββββββββββββββ
exec_result = execute_code(
code=code,
data_path=session_info["csv_path"],
output_dir=str(job_dir),
result_file=str(result_file),
)
if exec_result["success"] and result_file.exists():
with open(result_file, "r", encoding="utf-8") as f:
analysis_results = json.load(f)
# Collect downloadable files
files = []
for p in sorted(job_dir.iterdir()):
if p.name != "result.json":
files.append(p.name)
_update_job(
job_id,
status="completed",
results=analysis_results,
files=files,
completed_at=datetime.now().isoformat(),
log_append="λΆμ μλ£!",
)
with _lock:
sessions[session_id]["analyses"].append(
{"job_id": job_id, "query": query, "completed_at": datetime.now().isoformat()}
)
elif not result_file.exists():
stderr = exec_result.get("stderr", "")
_update_job(
job_id,
status="error",
error=friendly_error(stderr) if stderr else "κ²°κ³Ό νμΌμ΄ μμ±λμ§ μμμ΅λλ€.",
stderr=exec_result.get("stderr", ""),
log_append="μ€λ₯: κ²°κ³Ό νμΌ μμ",
)
else:
stderr = exec_result.get("stderr", "")
_update_job(
job_id,
status="error",
error=friendly_error(stderr),
stderr=stderr,
log_append=f"μ€ν μ€λ₯: {stderr[:200]}",
)
except anthropic.APIError as exc:
_update_job(job_id, status="error", error=f"Claude API μ€λ₯: {exc}")
except Exception:
_update_job(
job_id,
status="error",
error="λ΄λΆ μ€λ₯κ° λ°μνμ΅λλ€. μ μ ν λ€μ μλν΄μ£ΌμΈμ.",
log_append=traceback.format_exc(),
)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Routes
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/")
async def root():
return FileResponse(str(STATIC_DIR / "index.html"))
@app.get("/api/health")
async def health():
api_key_set = bool(os.getenv("ANTHROPIC_API_KEY"))
return {"status": "ok", "api_key_configured": api_key_set}
@app.post("/api/upload")
async def upload_file(file: UploadFile = File(...)):
filename = file.filename or "upload"
ext = Path(filename).suffix.lower()
if ext not in {".xlsx", ".xls", ".csv"}:
raise HTTPException(400, "μ§μνμ§ μλ νμΌ νμμ
λλ€. .xlsx, .xls, .csv νμΌλ§ μ§μν©λλ€.")
content = await file.read()
size_mb = len(content) / (1024 * 1024)
if size_mb > 50:
raise HTTPException(400, f"νμΌ ν¬κΈ°κ° λ무 ν½λλ€ ({size_mb:.1f} MB). μ΅λ 50 MBκΉμ§ μ§μν©λλ€.")
session_id = str(uuid.uuid4())
file_path = UPLOAD_DIR / f"{session_id}{ext}"
file_path.write_bytes(content)
try:
df = safe_read_file(file_path, ext)
except Exception as exc:
file_path.unlink(missing_ok=True)
raise HTTPException(400, f"νμΌμ μ½μ μ μμ΅λλ€: {exc}")
if df.empty:
file_path.unlink(missing_ok=True)
raise HTTPException(400, "νμΌμ΄ λΉμ΄ μμ΅λλ€.")
csv_path = UPLOAD_DIR / f"{session_id}.csv"
df.to_csv(csv_path, index=False, encoding="utf-8-sig")
df_info = build_df_info(df)
preview = df_to_preview(df)
with _lock:
sessions[session_id] = {
"session_id": session_id,
"file_name": filename,
"file_path": str(file_path),
"csv_path": str(csv_path),
"size_mb": round(size_mb, 2),
"created_at": datetime.now().isoformat(),
"df_info": df_info,
"preview": preview,
"analyses": [],
}
return {
"session_id": session_id,
"file_name": filename,
"rows": df_info["shape"][0],
"cols": df_info["shape"][1],
"size_mb": round(size_mb, 2),
}
@app.get("/api/sample/load")
async def load_sample():
"""Create a session from built-in sample data."""
df = make_sample_df()
session_id = str(uuid.uuid4())
csv_path = UPLOAD_DIR / f"{session_id}.csv"
df.to_csv(csv_path, index=False, encoding="utf-8-sig")
df_info = build_df_info(df)
preview = df_to_preview(df)
with _lock:
sessions[session_id] = {
"session_id": session_id,
"file_name": "sample_survey_data.csv",
"file_path": str(csv_path),
"csv_path": str(csv_path),
"size_mb": round(csv_path.stat().st_size / 1024 / 1024, 3),
"created_at": datetime.now().isoformat(),
"df_info": df_info,
"preview": preview,
"analyses": [],
}
return {
"session_id": session_id,
"file_name": "sample_survey_data.csv",
"rows": df_info["shape"][0],
"cols": df_info["shape"][1],
"size_mb": round(csv_path.stat().st_size / 1024 / 1024, 3),
}
@app.get("/api/preview/{session_id}")
async def get_preview(session_id: str):
session = sessions.get(session_id)
if not session:
raise HTTPException(404, "μΈμ
μ μ°Ύμ μ μμ΅λλ€.")
return {
"file_name": session["file_name"],
"df_info": session["df_info"],
"preview": session["preview"],
}
@app.post("/api/analyze")
async def analyze(req: AnalyzeRequest, background_tasks: BackgroundTasks):
session = sessions.get(req.session_id)
if not session:
raise HTTPException(404, "μΈμ
μ μ°Ύμ μ μμ΅λλ€.")
if not req.query.strip():
raise HTTPException(400, "λΆμ μμ²μ μ
λ ₯ν΄μ£ΌμΈμ.")
# Resolve previous results if follow-up
prev_results = None
if req.job_id:
prev_job = jobs.get(req.job_id, {})
prev_results = prev_job.get("results")
job_id = str(uuid.uuid4())
with _lock:
jobs[job_id] = {
"job_id": job_id,
"session_id": req.session_id,
"query": req.query,
"status": "pending",
"created_at": datetime.now().isoformat(),
"completed_at": None,
"code": None,
"results": None,
"files": [],
"error": None,
"stderr": None,
"log": ["λΆμ μμ² μ μλ¨"],
}
background_tasks.add_task(
run_analysis_job, job_id, req.session_id, req.query, prev_results
)
return {"job_id": job_id, "status": "pending"}
@app.get("/api/job/{job_id}")
async def get_job(job_id: str):
job = jobs.get(job_id)
if not job:
raise HTTPException(404, "μμ
μ μ°Ύμ μ μμ΅λλ€.")
return job
@app.get("/api/download/{job_id}/{filename}")
async def download_file(job_id: str, filename: str):
# Prevent path traversal
safe_name = Path(filename).name
path = RESULTS_DIR / job_id / safe_name
if not path.exists():
raise HTTPException(404, "νμΌμ μ°Ύμ μ μμ΅λλ€.")
return FileResponse(str(path), filename=safe_name)
@app.get("/api/session/{session_id}")
async def get_session(session_id: str):
session = sessions.get(session_id)
if not session:
raise HTTPException(404, "μΈμ
μ μ°Ύμ μ μμ΅λλ€.")
return {
"session_id": session_id,
"file_name": session["file_name"],
"rows": session["df_info"]["shape"][0],
"cols": session["df_info"]["shape"][1],
"analyses": session["analyses"],
}
# ββ static + results file serving βββββββββββββββββββββββββββββ
app.mount("/results", StaticFiles(directory=str(RESULTS_DIR)), name="results")
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"main:app",
host=os.getenv("HOST", "0.0.0.0"),
port=int(os.getenv("PORT", 8000)),
reload=True, # λ‘컬 κ°λ°μ© β Renderλ startCommandλ₯Ό μ¬μ©νλ―λ‘ λ¬΄μλ¨
)
|