KWK25 commited on
Commit
6959cdc
·
verified ·
1 Parent(s): 25d0a1d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -66
app.py CHANGED
@@ -1,30 +1,94 @@
 
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
 
4
- # Connect to the model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  client = InferenceClient("microsoft/phi-4")
6
 
7
- # Chat function
8
  def respond(message, history):
9
- messages = [
10
- {"role": "system", "content": "You are a friendly, hyper-energetic K-pop expert chatbot. Always give clear answers and, when possible, recommend K-pop songs with clickable Spotify links."}
11
- ]
12
-
13
- # Keep chat history
14
  if history:
15
- for h in history:
16
- if isinstance(h, tuple):
17
- messages.append({"role": "user", "content": h[0]})
18
- messages.append({"role": "assistant", "content": h[1]})
19
- else:
20
- messages.append(h)
21
-
22
  messages.append({"role": "user", "content": message})
23
-
 
 
 
 
 
 
24
  response = client.chat_completion(messages, max_tokens=500)
25
  return response['choices'][0]['message']['content'].strip()
26
 
27
- # Soft theme
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  chat_theme = gr.themes.Soft(
29
  primary_hue="pink",
30
  secondary_hue="rose",
@@ -38,54 +102,30 @@ chat_theme = gr.themes.Soft(
38
  button_primary_background_fill_hover="*primary_400"
39
  )
40
 
41
- # Interface
 
 
 
 
 
 
 
 
 
 
 
 
42
  with gr.Blocks(theme=chat_theme) as demo:
43
- with gr.Tab("Information"):
44
- gr.Markdown("# 🎤 Welcome to the Ultimate K-pop Chatbot 🎶💜")
45
- gr.Markdown("""
46
- Annyeong, K-pop fan! 🌟 Whether you’ve just discovered your first idol or you’ve been stanning since the 2nd gen days, this chatbot is your ultimate companion.
47
-
48
- I can spill the tea ☕, give you trivia 🧠, recommend music 🎧, and even link you directly to Spotify so you can stream instantly!
49
- Together, we’ll explore the dazzling world of Korean pop culture — from catchy hooks to unforgettable choreographies. 🕺💃
50
-
51
- ---
52
- ## 🌟 Top 10 Popular K-pop Groups
53
- 1. **BTS** [🎧 Listen on Spotify](https://open.spotify.com/artist/3Nrfpe0tUJi4K4DXYWgMUX)
54
- 2. **BLACKPINK** – [🎧 Listen on Spotify](https://open.spotify.com/artist/41MozSoPIsD1dJM0CLPjZF)
55
- 3. **TWICE** – [🎧 Listen on Spotify](https://open.spotify.com/artist/7n2Ycct7Beij7Dj7meI4X0)
56
- 4. **Stray Kids** – [🎧 Listen on Spotify](https://open.spotify.com/artist/2dIgFjalVxs4ThymZ67YCE)
57
- 5. **SEVENTEEN** – [🎧 Listen on Spotify](https://open.spotify.com/artist/7nqOGRxlXj7N2JYbgNEjYH)
58
- 6. **NewJeans** – [🎧 Listen on Spotify](https://open.spotify.com/artist/6HvZYsbFfjnjFrWF950C9d)
59
- 7. **ITZY** – [🎧 Listen on Spotify](https://open.spotify.com/artist/2KC9Qb60EaY0kW4eH68vr3)
60
- 8. **ENHYPEN** – [🎧 Listen on Spotify](https://open.spotify.com/artist/5t5FqBwTcgKTaWmfEbwQY9)
61
- 9. **(G)I-DLE** – [🎧 Listen on Spotify](https://open.spotify.com/artist/2AfmfGFbe0A0WsTYm0SDTx)
62
- 10. **IVE** – [🎧 Listen on Spotify](https://open.spotify.com/artist/6RHTUrRF63xao58xh9FXYJ)
63
-
64
- ---
65
- ## 💡 How to Use the Chatbot
66
- 1. Switch to the **Chat** tab.
67
- 2. Ask any question about K-pop — songs, groups, history, concepts, comebacks.
68
- 3. Use **pre-written questions** to start fast.
69
- 4. If you ask for song recs, I’ll give you a **Spotify link** so you can click & play instantly.
70
- 5. Try broad prompts like:
71
- - "Recommend me upbeat K-pop songs"
72
- - "Tell me about rookie groups in 2025"
73
- - "What's the difference between 2nd gen and 4th gen?"
74
- 6. Don’t be shy — I’m here to help you stan smarter and harder 💜
75
- """)
76
-
77
- with gr.Tab("Chat"):
78
- gr.ChatInterface(
79
- fn=respond,
80
- type="messages",
81
- examples=[
82
- "What is K-pop?",
83
- "How to find your bias?",
84
- "Tell me about BTS",
85
- "Recommend a K-pop song",
86
- "Who are the most popular idols right now?",
87
- "What's the history of K-pop?"
88
- ]
89
- )
90
-
91
- demo.launch()
 
1
+ import os
2
+ import requests
3
  import gradio as gr
4
  from huggingface_hub import InferenceClient
5
 
6
+ # -----------------------
7
+ # SPOTIFY AUTH
8
+ # -----------------------
9
+ def get_spotify_token():
10
+ client_id = os.getenv("SPOTIFY_CLIENT_ID")
11
+ client_secret = os.getenv("SPOTIFY_CLIENT_SECRET")
12
+ auth_url = "https://accounts.spotify.com/api/token"
13
+ auth_response = requests.post(
14
+ auth_url,
15
+ data={"grant_type": "client_credentials"},
16
+ auth=(client_id, client_secret),
17
+ )
18
+ if auth_response.status_code == 200:
19
+ return auth_response.json()["access_token"]
20
+ else:
21
+ return None
22
+
23
+ def search_spotify(query, limit=3):
24
+ token = get_spotify_token()
25
+ if not token:
26
+ return []
27
+ url = f"https://api.spotify.com/v1/search?q={query}&type=track&limit={limit}"
28
+ headers = {"Authorization": f"Bearer {token}"}
29
+ r = requests.get(url, headers=headers)
30
+ if r.status_code == 200:
31
+ items = r.json()["tracks"]["items"]
32
+ links = [f"{item['name']} by {item['artists'][0]['name']}: {item['external_urls']['spotify']}" for item in items]
33
+ return links
34
+ else:
35
+ return []
36
+
37
+ # -----------------------
38
+ # CHATBOT LOGIC
39
+ # -----------------------
40
  client = InferenceClient("microsoft/phi-4")
41
 
 
42
  def respond(message, history):
43
+ # Only add short responses unless user asks for more
44
+ style_prompt = "Answer briefly unless the user asks for more details. If recommending songs, provide working Spotify links."
45
+
46
+ messages = [{"role": "system", "content": f"You are a friendly Kpop expert chatbot. {style_prompt}"}]
47
+
48
  if history:
49
+ messages.extend([{"role": "user", h[0]} if isinstance(h, tuple) else h for h in history])
50
+
 
 
 
 
 
51
  messages.append({"role": "user", "content": message})
52
+
53
+ # Song recommendation check
54
+ if "recommend" in message.lower() and "song" in message.lower():
55
+ songs = search_spotify("kpop")
56
+ if songs:
57
+ return "Here are some Kpop songs I recommend:\n" + "\n".join(songs)
58
+
59
  response = client.chat_completion(messages, max_tokens=500)
60
  return response['choices'][0]['message']['content'].strip()
61
 
62
+ # -----------------------
63
+ # INFO CONTENT
64
+ # -----------------------
65
+ intro_text = """
66
+ # 🎤 Welcome to the Ultimate Kpop Chatbot! 💜
67
+
68
+ Whether you’re brand new or a long-time stan, I’m your friendly Kpop buddy ready to help you explore this amazing music genre.
69
+
70
+ ## 🌟 Top 10 Popular Kpop Groups (2025)
71
+ 1. BTS
72
+ 2. BLACKPINK
73
+ 3. Stray Kids
74
+ 4. SEVENTEEN
75
+ 5. NewJeans
76
+ 6. ATEEZ
77
+ 7. TWICE
78
+ 8. TXT (Tomorrow X Together)
79
+ 9. IVE
80
+ 10. ENHYPEN
81
+
82
+ ## 💡 How to use this chatbot:
83
+ - Click a preset question above the chat box for instant answers.
84
+ - Ask me anything about Kpop history, groups, songs, or trends.
85
+ - Request song recommendations and I’ll give you working Spotify links.
86
+ - Keep chatting to learn more — and if you want details, just say *Tell me more!*
87
+ """
88
+
89
+ # -----------------------
90
+ # THEME
91
+ # -----------------------
92
  chat_theme = gr.themes.Soft(
93
  primary_hue="pink",
94
  secondary_hue="rose",
 
102
  button_primary_background_fill_hover="*primary_400"
103
  )
104
 
105
+ # -----------------------
106
+ # UI
107
+ # -----------------------
108
+ preset_questions = [
109
+ "What is Kpop?",
110
+ "How to find your bias?",
111
+ "Who are the most popular Kpop groups?",
112
+ "How can I start listening to Kpop?",
113
+ "What are Kpop fan chants?",
114
+ "Can you recommend me some Kpop songs?",
115
+ "What is a Kpop comeback?"
116
+ ]
117
+
118
  with gr.Blocks(theme=chat_theme) as demo:
119
+ with gr.Tab("ℹ️ Information"):
120
+ gr.Markdown(intro_text)
121
+
122
+ with gr.Tab("💬 Chat"):
123
+ with gr.Column():
124
+ gr.Markdown("### Click a question below to ask instantly:")
125
+ with gr.Row():
126
+ for q in preset_questions:
127
+ gr.Button(q).click(fn=respond, inputs=gr.Textbox(value=q, visible=False), outputs=gr.Textbox())
128
+
129
+ chatbot = gr.ChatInterface(fn=respond, type="messages")
130
+
131
+ demo.launch()