Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,7 +2,6 @@ import gradio as gr
|
|
2 |
from sentence_transformers import SentenceTransformer, util
|
3 |
import openai
|
4 |
import os
|
5 |
-
import random
|
6 |
|
7 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
8 |
|
@@ -11,6 +10,28 @@ filename = "output_topic_details.txt" # Path to the file storing song-specific
|
|
11 |
retrieval_model_name = 'output/sentence-transformer-finetuned/'
|
12 |
|
13 |
openai.api_key = os.environ["OPENAI_API_KEY"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
print(f"Failed to load or preprocess text: {e}")
|
15 |
return []
|
16 |
|
@@ -19,45 +40,62 @@ segments = load_and_preprocess_text(filename)
|
|
19 |
def find_relevant_segment(user_query, segments):
|
20 |
"""
|
21 |
Find the most relevant text segment for a user's query using cosine similarity among sentence embeddings.
|
|
|
|
|
22 |
try:
|
23 |
# Lowercase the query for better matching
|
24 |
lower_query = user_query.lower()
|
25 |
-
|
26 |
# Encode the query and the segments
|
27 |
query_embedding = retrieval_model.encode(lower_query)
|
28 |
segment_embeddings = retrieval_model.encode(segments)
|
29 |
-
|
30 |
# Compute cosine similarities between the query and the segments
|
31 |
similarities = util.pytorch_cos_sim(query_embedding, segment_embeddings)[0]
|
32 |
-
|
33 |
# Find the index of the most similar segment
|
34 |
best_idx = similarities.argmax()
|
35 |
-
|
36 |
# Return the most relevant segment
|
37 |
return segments[best_idx]
|
38 |
except Exception as e:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
# Append user's message to messages list
|
41 |
messages.append({"role": "user", "content": user_message})
|
42 |
-
|
43 |
# Use OpenAI's API to generate a response based on the user's query and system messages
|
44 |
response = openai.ChatCompletion.create(
|
45 |
model="gpt-3.5-turbo",
|
|
|
|
|
|
|
|
|
46 |
frequency_penalty=0,
|
47 |
presence_penalty=0
|
48 |
)
|
49 |
-
|
50 |
# Extract the response text
|
51 |
output_text = response['choices'][0]['message']['content'].strip()
|
52 |
-
|
53 |
# Append assistant's message to messages list for context
|
54 |
messages.append({"role": "assistant", "content": output_text})
|
55 |
-
|
56 |
return output_text
|
57 |
-
|
58 |
except Exception as e:
|
59 |
print(f"Error in generating response: {e}")
|
60 |
return f"Error in generating response: {e}"
|
|
|
|
|
61 |
"""
|
62 |
Recommend songs based on the user's mood query.
|
63 |
"""
|
@@ -69,84 +107,59 @@ def find_relevant_segment(user_query, segments):
|
|
69 |
"Song D",
|
70 |
"Song E"
|
71 |
]
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
|
|
|
|
|
79 |
|
|
|
80 |
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
if mood in songs_by_mood:
|
104 |
-
song = random.choice(songs_by_mood[mood]["description"])
|
105 |
-
topic = songs_by_mood[mood]["topic"]
|
106 |
-
return {"song": song, "description": description}
|
107 |
-
else:
|
108 |
-
return {"error": "Mood not recognized"}
|
109 |
-
|
110 |
def query_model(user_query):
|
111 |
"""
|
112 |
Process a user's query, find relevant information, and generate a response.
|
113 |
"""
|
114 |
if user_query == "":
|
115 |
return "Welcome to SongBot! Ask me for song recommendations based on mood."
|
116 |
-
|
117 |
# Example logic to identify if the user query is related to song recommendations based on mood
|
118 |
if "recommend" in user_query.lower() and ("song" in user_query.lower() or "music" in user_query.lower()):
|
119 |
mood = user_query.lower().split("recommend", 1)[1].strip() # Extract mood from query
|
120 |
-
|
121 |
-
if "error" in recommendation:
|
122 |
-
response = recommendation["error"]
|
123 |
-
|
124 |
-
|
125 |
else:
|
126 |
relevant_segment = find_relevant_segment(user_query, segments)
|
127 |
if not relevant_segment:
|
128 |
response = "Could not find specific information. Please refine your question."
|
129 |
else:
|
130 |
response = generate_response(user_query, relevant_segment)
|
131 |
-
|
132 |
return response
|
133 |
|
134 |
# Define the welcome message and specific topics the chatbot can provide information about
|
135 |
welcome_message = """
|
136 |
-
#
|
137 |
## Your AI-driven assistant for music curation. Created by Fenet, Lia, and Zamira of the 2024 Kode With Klossy DC Camp.
|
138 |
"""
|
139 |
|
140 |
topics = """
|
141 |
### Feel free to ask me for song recommendations based on mood!
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
"""
|
148 |
|
149 |
# Setup the Gradio Blocks interface with custom layout components
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
150 |
|
151 |
# Launch the Gradio app to allow user interaction
|
152 |
-
demo.launch(share=True)
|
|
|
2 |
from sentence_transformers import SentenceTransformer, util
|
3 |
import openai
|
4 |
import os
|
|
|
5 |
|
6 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
7 |
|
|
|
10 |
retrieval_model_name = 'output/sentence-transformer-finetuned/'
|
11 |
|
12 |
openai.api_key = os.environ["OPENAI_API_KEY"]
|
13 |
+
|
14 |
+
system_message = "You are a song chatbot specialized in providing song recommendations based on mood catering to Gen Z taste in music."
|
15 |
+
# Initial system message to set the behavior of the assistant
|
16 |
+
messages = [{"role": "system", "content": system_message}]
|
17 |
+
|
18 |
+
# Attempt to load the necessary models and provide feedback on success or failure
|
19 |
+
try:
|
20 |
+
retrieval_model = SentenceTransformer(retrieval_model_name)
|
21 |
+
print("Models loaded successfully.")
|
22 |
+
except Exception as e:
|
23 |
+
print(f"Failed to load models: {e}")
|
24 |
+
|
25 |
+
def load_and_preprocess_text(filename):
|
26 |
+
"""
|
27 |
+
Load and preprocess text from a file, removing empty lines and stripping whitespace.
|
28 |
+
"""
|
29 |
+
try:
|
30 |
+
with open(filename, 'r', encoding='utf-8') as file:
|
31 |
+
segments = [line.strip() for line in file if line.strip()]
|
32 |
+
print("Text loaded and preprocessed successfully.")
|
33 |
+
return segments
|
34 |
+
except Exception as e:
|
35 |
print(f"Failed to load or preprocess text: {e}")
|
36 |
return []
|
37 |
|
|
|
40 |
def find_relevant_segment(user_query, segments):
|
41 |
"""
|
42 |
Find the most relevant text segment for a user's query using cosine similarity among sentence embeddings.
|
43 |
+
This version finds the best match based on the content of the query.
|
44 |
+
"""
|
45 |
try:
|
46 |
# Lowercase the query for better matching
|
47 |
lower_query = user_query.lower()
|
48 |
+
|
49 |
# Encode the query and the segments
|
50 |
query_embedding = retrieval_model.encode(lower_query)
|
51 |
segment_embeddings = retrieval_model.encode(segments)
|
52 |
+
|
53 |
# Compute cosine similarities between the query and the segments
|
54 |
similarities = util.pytorch_cos_sim(query_embedding, segment_embeddings)[0]
|
55 |
+
|
56 |
# Find the index of the most similar segment
|
57 |
best_idx = similarities.argmax()
|
58 |
+
|
59 |
# Return the most relevant segment
|
60 |
return segments[best_idx]
|
61 |
except Exception as e:
|
62 |
+
print(f"Error in finding relevant segment: {e}")
|
63 |
+
return ""
|
64 |
+
|
65 |
+
def generate_response(user_query, relevant_segment):
|
66 |
+
"""
|
67 |
+
Generate a response emphasizing the bot's capability in providing song recommendations.
|
68 |
+
"""
|
69 |
+
try:
|
70 |
+
user_message = f"Here's the information on songs: {relevant_segment}"
|
71 |
|
72 |
# Append user's message to messages list
|
73 |
messages.append({"role": "user", "content": user_message})
|
74 |
+
|
75 |
# Use OpenAI's API to generate a response based on the user's query and system messages
|
76 |
response = openai.ChatCompletion.create(
|
77 |
model="gpt-3.5-turbo",
|
78 |
+
messages=messages,
|
79 |
+
max_tokens=150,
|
80 |
+
temperature=0.2,
|
81 |
+
top_p=1,
|
82 |
frequency_penalty=0,
|
83 |
presence_penalty=0
|
84 |
)
|
85 |
+
|
86 |
# Extract the response text
|
87 |
output_text = response['choices'][0]['message']['content'].strip()
|
88 |
+
|
89 |
# Append assistant's message to messages list for context
|
90 |
messages.append({"role": "assistant", "content": output_text})
|
91 |
+
|
92 |
return output_text
|
93 |
+
|
94 |
except Exception as e:
|
95 |
print(f"Error in generating response: {e}")
|
96 |
return f"Error in generating response: {e}"
|
97 |
+
|
98 |
+
def recommend_songs_based_on_mood(mood):
|
99 |
"""
|
100 |
Recommend songs based on the user's mood query.
|
101 |
"""
|
|
|
107 |
"Song D",
|
108 |
"Song E"
|
109 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
110 |
|
111 |
+
# Format the recommendation list as a string
|
112 |
+
recommended_songs_str = "\n- " + "\n- ".join(recommended_songs)
|
113 |
|
114 |
+
return f"Here are some songs you might like based on '{mood}' mood:{recommended_songs_str}"
|
115 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
def query_model(user_query):
|
117 |
"""
|
118 |
Process a user's query, find relevant information, and generate a response.
|
119 |
"""
|
120 |
if user_query == "":
|
121 |
return "Welcome to SongBot! Ask me for song recommendations based on mood."
|
122 |
+
|
123 |
# Example logic to identify if the user query is related to song recommendations based on mood
|
124 |
if "recommend" in user_query.lower() and ("song" in user_query.lower() or "music" in user_query.lower()):
|
125 |
mood = user_query.lower().split("recommend", 1)[1].strip() # Extract mood from query
|
126 |
+
response = recommend_songs_based_on_mood(mood)
|
|
|
|
|
|
|
|
|
127 |
else:
|
128 |
relevant_segment = find_relevant_segment(user_query, segments)
|
129 |
if not relevant_segment:
|
130 |
response = "Could not find specific information. Please refine your question."
|
131 |
else:
|
132 |
response = generate_response(user_query, relevant_segment)
|
133 |
+
|
134 |
return response
|
135 |
|
136 |
# Define the welcome message and specific topics the chatbot can provide information about
|
137 |
welcome_message = """
|
138 |
+
# :musical_note: Welcome to Song Seeker!
|
139 |
## Your AI-driven assistant for music curation. Created by Fenet, Lia, and Zamira of the 2024 Kode With Klossy DC Camp.
|
140 |
"""
|
141 |
|
142 |
topics = """
|
143 |
### Feel free to ask me for song recommendations based on mood!
|
144 |
+
Happy songs
|
145 |
+
Sad songs
|
146 |
+
Chill songs
|
147 |
+
Angry songs
|
148 |
+
Workout songs
|
149 |
"""
|
150 |
|
151 |
# Setup the Gradio Blocks interface with custom layout components
|
152 |
+
with gr.Blocks(theme='dabble') as demo:
|
153 |
+
gr.Markdown(welcome_message) # Display the formatted welcome message
|
154 |
+
with gr.Row():
|
155 |
+
with gr.Column():
|
156 |
+
gr.Markdown(topics) # Show the topics on the left side
|
157 |
+
with gr.Row():
|
158 |
+
with gr.Column():
|
159 |
+
question = gr.Textbox(label="Your mood (e.g., happy, sad)", placeholder="What mood are you in?")
|
160 |
+
answer = gr.Textbox(label="SongBot Response", placeholder="SongBot will respond here...", interactive=False, lines=10)
|
161 |
+
submit_button = gr.Button("Submit")
|
162 |
+
submit_button.click(fn=query_model, inputs=question, outputs=answer)
|
163 |
|
164 |
# Launch the Gradio app to allow user interaction
|
165 |
+
demo.launch(share=True)
|