from PIL import Image import traceback def generate_caption(filepaths, choice_index): try: idx = int(choice_index) img_path = filepaths[idx] print(f"[DEBUG] Selected image path: {img_path}") # 1) 이미지 로드 img = Image.open(img_path).convert("RGB") print("[DEBUG] Image loaded") # 2) 캡션 생성 out = captioner(img) print(f"[DEBUG] captioner output: {out!r}") first = out[0] if isinstance(out, list) else out raw = first.get("generated_text") or first.get("text") or str(first) raw = raw.strip() print(f"[DEBUG] raw caption: {raw!r}") # 3) 장면 분류 cls = scene_classifier(img, candidate_labels=SCENE_LABELS) print(f"[DEBUG] scene_classifier output: {cls!r}") scene = cls["labels"][0] # 4) 템플릿 매핑 template = TEMPLATES.get(scene, "In this picture, {caption}.") result = template.format(caption=raw) print(f"[DEBUG] Final result: {result}") return result except Exception as e: # 에러 메시지와 스택 트레이스 리턴 error_msg = f"🔴 Error:\n{e}\n\n{traceback.format_exc()}" print(error_msg) return error_msg