Spaces:
Sleeping

SituationDJ / app.py
Haneul Lee
Allow required model reasoning with larger output budget
cf97caa
Raw History Blame Contribute Delete
14.1 kB
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"""<article class="track">
<span class="track-number">{track['index']:02}</span>
<div class="track-copy"><strong>{song}</strong><span>{artist}</span>
<p>{reason}</p></div>
<a href="{search_url}" target="_blank" rel="noopener noreferrer">Spotify์—์„œ ๊ฒ€์ƒ‰ โ†—</a>
</article>"""
)
return f"""<section class="playlist">
<div class="eyebrow">SITUATION DJ ยท ์˜ค๋Š˜์˜ ์ƒํ™ฉ ์„ ๊ณก</div>
<h2>{html.escape(title)}</h2>
<p class="situation">โ€œ{html.escape(situation)}โ€</p>
{''.join(cards)}
<footer>๊ณก ์ •๋ณด: MusicBrainz ยท Spotify ๊ฒ€์ƒ‰ ๋งํฌ๋กœ ์—ด๊ธฐ ยท ์Œ์›/๊ฐ€์‚ฌ/์•จ๋ฒ” ์ด๋ฏธ์ง€๋Š” ์ œ๊ณตํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.</footer>
</section>"""
@gpu(duration=30)
def generate_playlist(situation, mood):
global _generation_count
situation = (situation or "").strip()
if not situation:
return "<div class='message'>๋จผ์ € ์ƒํ™ฉ์„ ํ•œ ์ค„๋กœ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.</div>"
if len(situation) > MAX_SITUATION_LENGTH:
return f"<div class='message'>์ƒํ™ฉ์€ {MAX_SITUATION_LENGTH}์ž ์ด๋‚ด๋กœ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.</div>"
with _generation_lock:
if _generation_count >= MAX_GENERATIONS:
return "<div class='message'>์ด๋ฒˆ Space ์‹คํ–‰์˜ ์ƒ์„ฑ ํ•œ๋„์— ๋„๋‹ฌํ–ˆ์Šต๋‹ˆ๋‹ค. ์ž ์‹œ ๋’ค ๋‹ค์‹œ ์ด์šฉํ•ด ์ฃผ์„ธ์š”.</div>"
_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 "<div class='message'>์‹ค์ œ ๊ณก ํ›„๋ณด๋ฅผ ์ฐพ์ง€ ๋ชปํ–ˆ์–ด์š”. ์ƒํ™ฉ์„ ์กฐ๊ธˆ ๋” ์งง๊ฒŒ ์“ฐ๊ฑฐ๋‚˜ ๋ถ„์œ„๊ธฐ๋ฅผ ๋ฐ”๊ฟ” ๋ณด์„ธ์š”.</div>"
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 "<div class='message'>๊ณก ๊ฒ€์ƒ‰ ์„œ๋น„์Šค๊ฐ€ ์ž ์‹œ ์‘๋‹ตํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์ž ์‹œ ํ›„ ๋‹ค์‹œ ์‹œ๋„ํ•ด ์ฃผ์„ธ์š”.</div>"
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"<div class='message'>{message}</div>"
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(
"""<header class="hero"><div class="kicker">SITUATION DJ / PLAYLIST MAKER</div>
<h1>์ƒํ™ฉ์„ ํ‹€์–ด๋ด.</h1><p>์˜ค๋Š˜์˜ ๊ธฐ๋ถ„๊ณผ ์ˆœ๊ฐ„์— ์–ด์šธ๋ฆฌ๋Š” ์‹ค์ œ ๊ณก ์ œ๋ชฉ์œผ๋กœ ํ”Œ๋ฆฌ๋ฅผ ๋งŒ๋“ค์–ด์š”.</p></header>"""
)
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()