import html import json import os import re import threading import time from urllib.parse import quote import gradio as gr import requests from huggingface_hub import InferenceClient from dotenv import load_dotenv load_dotenv() try: import spaces gpu = spaces.GPU except ImportError: def gpu(**_kwargs): return lambda function: function MODEL_ID = os.getenv("HF_MODEL_ID", "LiquidAI/LFM3-1.7B:cheapest") MAX_GENERATIONS = 12 MAX_SITUATION_LENGTH = 300 MAX_CANDIDATES = 12 MUSICBRAINZ_URL = "https://musicbrainz.org/ws/2/recording" MUSICBRAINZ_HEADERS = { "User-Agent": "SituationDJ/0.1 (https://huggingface.co/skylei)" } _generation_count = 0 _generation_lock = threading.Lock() def _chat(messages, max_tokens): token = os.getenv("HF_TOKEN") if not token: raise RuntimeError( "Space Settings의 Secrets에 Inference Providers 권한이 있는 HF_TOKEN을 추가해 주세요." ) client = InferenceClient(api_key=token) response = client.chat.completions.create( model=MODEL_ID, messages=messages, max_tokens=max_tokens, temperature=0.35, ) choice = response.choices[0] message = choice.message content = message.content if not content: usage = getattr(response, "usage", None) completion_tokens = getattr(usage, "completion_tokens", None) has_reasoning = bool( getattr(message, "reasoning", None) or getattr(message, "reasoning_content", None) ) print( "SituationDJ empty model response: " f"finish_reason={choice.finish_reason}, " f"completion_tokens={completion_tokens}, " f"has_reasoning={has_reasoning}" ) raise RuntimeError( "AI 응답이 비었습니다. Logs > Container에서 종료 사유를 확인해 주세요." ) return content def _json_from_response(text): match = re.search(r"\{.*\}", text, re.DOTALL) if not match: raise RuntimeError("AI 응답 형식이 올바르지 않습니다. 다시 생성해 주세요.") try: return json.loads(match.group(0)) except json.JSONDecodeError as error: raise RuntimeError("AI 응답을 읽지 못했습니다. 다시 생성해 주세요.") from error def _artists(recording): phrase = recording.get("artist-credit-phrase") if phrase: return phrase credits = recording.get("artist-credit", []) return "".join( str(item.get("name") or item.get("artist", {}).get("name") or "") + str(item.get("joinphrase") or "") for item in credits if isinstance(item, dict) ).strip() def _search_tracks(terms): session = requests.Session() session.headers.update(MUSICBRAINZ_HEADERS) found = [] seen = set() last_request = 0.0 for term in terms[:3]: delay = 1.05 - (time.monotonic() - last_request) if last_request and delay > 0: time.sleep(delay) response = session.get( MUSICBRAINZ_URL, params={"query": f'recording:"{term}"', "fmt": "json", "limit": 5}, timeout=15, ) last_request = time.monotonic() response.raise_for_status() for recording in response.json().get("recordings", []): title = str(recording.get("title") or "").strip() artist = _artists(recording).strip() musicbrainz_id = recording.get("id") key = (title.casefold(), artist.casefold()) if title and artist and key not in seen: seen.add(key) found.append( { "index": len(found) + 1, "title": title, "artist": artist, "id": musicbrainz_id, } ) if len(found) >= MAX_CANDIDATES: return found return found def _render(title, situation, tracks): cards = [] for track in tracks: song = html.escape(track["title"]) artist = html.escape(track["artist"]) reason = html.escape(track["reason"]) search_url = "https://open.spotify.com/search/" + quote( f'{track["title"]} {track["artist"]}', safe="" ) cards.append( f"""
{track['index']:02}
{song}{artist}

{reason}

Spotify에서 검색 ↗
""" ) return f"""
SITUATION DJ · 오늘의 상황 선곡

{html.escape(title)}

“{html.escape(situation)}”

{''.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"
{message}
" CSS = """ :root { color-scheme: light; } body, .gradio-container { background: #f7f4f0 !important; color: #2b2430 !important; } .gradio-container { max-width: 900px !important; margin: auto !important; } .gradio-container label, .gradio-container .prose, .gradio-container .prose p, .gradio-container h1, .gradio-container h2, .gradio-container h3 { color: #30283a !important; } .hero { padding: 34px 28px 18px; background: radial-gradient(ellipse at 80% 0%, #6844aa 0, transparent 42%), #211b2b; border: 1px solid #d9d0e2; border-radius: 24px; color: #fff !important; } .hero .kicker { font: 12px Consolas, monospace; letter-spacing: .18em; color: #d6c2ff !important; } .hero h1 { font: 800 clamp(34px, 7vw, 58px) system-ui, sans-serif; letter-spacing: -.06em; margin: 12px 0 4px; color: #fff !important; } .hero p { color: #e4ddeb !important; margin: 0; } .playlist { margin-top: 18px; padding: 24px; border-radius: 22px; background: #fff; border: 1px solid #e4ddea; } .eyebrow { font: 11px Consolas, monospace; letter-spacing: .14em; color: #6844aa; } .playlist h2 { font: 800 28px system-ui, sans-serif; margin: 8px 0; color: #30283a !important; } .situation { color: #62596b !important; margin: 0 0 18px; } .track { display: flex; align-items: center; gap: 14px; padding: 14px 0; border-top: 1px solid #eee8f1; } .track-number { color: #6844aa; font: 13px Consolas, monospace; width: 28px; } .track-copy { flex: 1; min-width: 0; display: grid; gap: 2px; } .track-copy strong { color: #30283a; font-size: 16px; } .track-copy span, .track-copy p { color: #62596b; font-size: 13px; margin: 0; } .track a { color: #fff !important; text-decoration: none !important; background: #6844aa; padding: 9px 12px; border-radius: 999px; font-weight: 700; font-size: 12px; white-space: nowrap; } .playlist footer { margin-top: 16px; color: #62596b; font-size: 11px; } .message { padding: 18px; border: 1px solid #d8cbea; border-radius: 14px; background: #f0eafb; color: #30283a !important; } @media (max-width: 600px) { .track { align-items: flex-start; flex-wrap: wrap; } .track-copy { min-width: 65%; } .track a { margin-left: 42px; } } """ with gr.Blocks(title="상황 DJ", css=CSS) as demo: gr.HTML( """
SITUATION DJ / PLAYLIST MAKER

상황을 틀어봐.

오늘의 기분과 순간에 어울리는 실제 곡 제목으로 플리를 만들어요.

""" ) situation = gr.Textbox( label="어떤 상황인가요?", placeholder="예: 신입사원이 첫 출근하는 날, 긴장되지만 괜히 자신감은 넘침", lines=2, max_length=MAX_SITUATION_LENGTH, ) mood = gr.Dropdown( ["설렘 + 자신감", "민망 + 웃픔", "위로 + 회복", "나락 + 후회", "출근 + 각성", "직접 입력"], value="설렘 + 자신감", label="원하는 분위기", ) create = gr.Button("상황 플리 만들기", variant="primary") result = gr.HTML() gr.Markdown( "곡 제목·아티스트는 MusicBrainz 검색 결과를 사용합니다. AI가 상황을 해석한 패러디이며 사실 확인이나 인물 평가가 아닙니다." ) create.click(generate_playlist, inputs=[situation, mood], outputs=result, trigger_mode="once") gr.Examples( [ ["신입사원이 첫 출근하는 날", "설렘 + 자신감"], ["시험을 망쳤는데 친구한테는 괜찮다고 한 날", "민망 + 웃픔"], ["오랜만에 다시 시작하기로 한 순간", "위로 + 회복"], ], inputs=[situation, mood], ) demo.queue(max_size=8, default_concurrency_limit=1) if __name__ == "__main__": demo.launch()