{''.join(cards)}
"""
@gpu(duration=30)
def generate_playlist(situation, mood):
global _generation_count
situation = (situation or "").strip()
if not situation:
return "
먼저 상황을 한 줄로 입력해 주세요.
"
if len(situation) > MAX_SITUATION_LENGTH:
return f"
상황은 {MAX_SITUATION_LENGTH}자 이내로 입력해 주세요.
"
with _generation_lock:
if _generation_count >= MAX_GENERATIONS:
return "
이번 Space 실행의 생성 한도에 도달했습니다. 잠시 뒤 다시 이용해 주세요.
"
_generation_count += 1
try:
brief = _json_from_response(
_chat(
[
{
"role": "system",
"content": (
"너는 한국어 상황 플레이리스트 DJ다. 사용자가 입력한 상황을 가볍고 재치 있게 해석하되 "
"사실이나 혐의를 만들어내지 않는다. 기존 곡 제목을 찾기 위한 짧은 검색어 3개를 만든다. "
"JSON만 반환한다: {\"playlist_title\": string, \"search_terms\": [string, string, string]}. "
"검색어는 실제 노래 제목에 있을 법한 짧은 한국어 또는 영어 표현으로 쓴다."
),
},
{
"role": "user",
"content": f"상황: {situation}\n분위기: {mood}",
},
],
max_tokens=512,
)
)
title = str(brief.get("playlist_title") or "오늘의 상황 플리").strip()[:80]
terms = brief.get("search_terms")
if not isinstance(terms, list):
raise RuntimeError("AI가 곡 검색어를 만들지 못했습니다. 다시 시도해 주세요.")
terms = [str(term).strip()[:80] for term in terms if str(term).strip()][:3]
if not terms:
raise RuntimeError("AI가 곡 검색어를 만들지 못했습니다. 다시 시도해 주세요.")
candidates = _search_tracks(terms)
if not candidates:
return "
실제 곡 후보를 찾지 못했어요. 상황을 조금 더 짧게 쓰거나 분위기를 바꿔 보세요.
"
candidate_text = json.dumps(
[{key: item[key] for key in ("index", "title", "artist")} for item in candidates],
ensure_ascii=False,
)
selection = _json_from_response(
_chat(
[
{
"role": "system",
"content": (
"주어진 곡 후보만 사용해 상황과 분위기에 맞는 곡을 최대 5개 고른다. "
"곡명이나 아티스트를 새로 만들지 않는다. 설명은 짧고 가볍게 쓴다. "
"JSON만 반환한다: {\"tracks\": [{\"index\": integer, \"reason\": string}]}. "
"index는 후보의 번호이며 중복 없이 고른다."
),
},
{
"role": "user",
"content": (
f"상황: {situation}\n분위기: {mood}\n"
f"후보 곡(JSON): {candidate_text}"
),
},
],
max_tokens=512,
)
)
by_index = {item["index"]: item for item in candidates}
selected = []
for item in selection.get("tracks", []):
try:
index = int(item.get("index"))
except (AttributeError, TypeError, ValueError):
continue
if index in by_index and index not in {track["index"] for track in selected}:
selected.append(
{
**by_index[index],
"reason": str(item.get("reason") or "이 상황에 어울리는 곡 제목이에요.")[:120],
}
)
if len(selected) == 5:
break
if not selected:
selected = [
{**item, "reason": "AI가 만든 검색어와 제목이 맞는 실제 곡 후보예요."}
for item in candidates[:5]
]
return _render(title, situation, selected)
except requests.RequestException:
return "
곡 검색 서비스가 잠시 응답하지 않습니다. 잠시 후 다시 시도해 주세요.
"
except Exception as error:
message = str(error)
if "401" in message or "403" in message:
message = "HF_TOKEN의 Inference Providers 권한을 확인해 주세요."
elif "402" in message or "credit" in message.lower():
message = "추론 크레딧이 부족하거나 모델 제공자를 사용할 수 없습니다."
else:
message = html.escape(message)
return f"