Spaces:
Sleeping
Sleeping
Download app.py from skylei/SituationDJ: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/spaces/skylei/SituationDJ/resolve/main/app.py
- Command line
-
hf download hf://spaces/skylei/SituationDJ/app.py
-
curl -L -o app.py https://huggingface.co/spaces/skylei/SituationDJ/resolve/main/app.py
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>""" | |
| 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() | |