Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,26 +2,17 @@ import gradio as gr
|
|
2 |
from sentence_transformers import SentenceTransformer, util
|
3 |
import openai
|
4 |
import os
|
5 |
-
|
6 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
7 |
-
|
8 |
# Initialize paths and model identifiers for easy configuration and maintenance
|
9 |
-
filename = "output_topic_details.txt" # Path to the file storing song
|
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.
|
@@ -34,9 +25,7 @@ def load_and_preprocess_text(filename):
|
|
34 |
except Exception as e:
|
35 |
print(f"Failed to load or preprocess text: {e}")
|
36 |
return []
|
37 |
-
|
38 |
segments = load_and_preprocess_text(filename)
|
39 |
-
|
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.
|
@@ -45,121 +34,81 @@ def find_relevant_segment(user_query, segments):
|
|
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
|
68 |
"""
|
69 |
try:
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
response = openai.ChatCompletion.create(
|
77 |
model="gpt-3.5-turbo",
|
78 |
messages=messages,
|
79 |
max_tokens=150,
|
80 |
-
temperature=0.
|
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 |
-
|
101 |
"""
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
"
|
107 |
-
|
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 |
-
#
|
139 |
-
##
|
140 |
"""
|
141 |
-
|
142 |
topics = """
|
143 |
-
### Feel free to ask me for song recommendations
|
144 |
-
-
|
145 |
-
-
|
146 |
-
-
|
147 |
-
-
|
148 |
-
-
|
|
|
|
|
|
|
|
|
149 |
"""
|
150 |
-
|
151 |
# Setup the Gradio Blocks interface with custom layout components
|
152 |
-
with gr.Blocks(
|
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
|
160 |
-
answer = gr.Textbox(label="
|
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)
|
|
|
2 |
from sentence_transformers import SentenceTransformer, util
|
3 |
import openai
|
4 |
import os
|
|
|
5 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
|
|
6 |
# Initialize paths and model identifiers for easy configuration and maintenance
|
7 |
+
filename = "output_topic_details.txt" # Path to the file storing song recommendation details
|
8 |
retrieval_model_name = 'output/sentence-transformer-finetuned/'
|
|
|
9 |
openai.api_key = os.environ["OPENAI_API_KEY"]
|
|
|
|
|
|
|
|
|
|
|
10 |
# Attempt to load the necessary models and provide feedback on success or failure
|
11 |
try:
|
12 |
retrieval_model = SentenceTransformer(retrieval_model_name)
|
13 |
print("Models loaded successfully.")
|
14 |
except Exception as e:
|
15 |
print(f"Failed to load models: {e}")
|
|
|
16 |
def load_and_preprocess_text(filename):
|
17 |
"""
|
18 |
Load and preprocess text from a file, removing empty lines and stripping whitespace.
|
|
|
25 |
except Exception as e:
|
26 |
print(f"Failed to load or preprocess text: {e}")
|
27 |
return []
|
|
|
28 |
segments = load_and_preprocess_text(filename)
|
|
|
29 |
def find_relevant_segment(user_query, segments):
|
30 |
"""
|
31 |
Find the most relevant text segment for a user's query using cosine similarity among sentence embeddings.
|
|
|
34 |
try:
|
35 |
# Lowercase the query for better matching
|
36 |
lower_query = user_query.lower()
|
|
|
37 |
# Encode the query and the segments
|
38 |
query_embedding = retrieval_model.encode(lower_query)
|
39 |
segment_embeddings = retrieval_model.encode(segments)
|
|
|
40 |
# Compute cosine similarities between the query and the segments
|
41 |
similarities = util.pytorch_cos_sim(query_embedding, segment_embeddings)[0]
|
|
|
42 |
# Find the index of the most similar segment
|
43 |
best_idx = similarities.argmax()
|
|
|
44 |
# Return the most relevant segment
|
45 |
return segments[best_idx]
|
46 |
except Exception as e:
|
47 |
print(f"Error in finding relevant segment: {e}")
|
48 |
return ""
|
|
|
49 |
def generate_response(user_query, relevant_segment):
|
50 |
"""
|
51 |
+
Generate a response providing song recommendations based on mood.
|
52 |
"""
|
53 |
try:
|
54 |
+
system_message = "You are a music recommendation chatbot designed to suggest songs based on mood, catering to Gen Z's taste in music."
|
55 |
+
user_message = f"User query: {user_query}. Recommended songs: {relevant_segment}"
|
56 |
+
messages = [
|
57 |
+
{"role": "system", "content": system_message},
|
58 |
+
{"role": "user", "content": user_message}
|
59 |
+
]
|
60 |
response = openai.ChatCompletion.create(
|
61 |
model="gpt-3.5-turbo",
|
62 |
messages=messages,
|
63 |
max_tokens=150,
|
64 |
+
temperature=0.7,
|
65 |
top_p=1,
|
66 |
frequency_penalty=0,
|
67 |
presence_penalty=0
|
68 |
)
|
69 |
+
return response['choices'][0]['message']['content'].strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
except Exception as e:
|
71 |
print(f"Error in generating response: {e}")
|
72 |
return f"Error in generating response: {e}"
|
73 |
+
def query_model(question):
|
|
|
74 |
"""
|
75 |
+
Process a question, find relevant information, and generate a response.
|
76 |
"""
|
77 |
+
if question == "":
|
78 |
+
return "Welcome to the Song Recommendation Bot! Ask me for song recommendations based on your mood."
|
79 |
+
relevant_segment = find_relevant_segment(question, segments)
|
80 |
+
if not relevant_segment:
|
81 |
+
return "Could not find specific song recommendations. Please refine your question."
|
82 |
+
response = generate_response(question, relevant_segment)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
return response
|
|
|
84 |
# Define the welcome message and specific topics the chatbot can provide information about
|
85 |
welcome_message = """
|
86 |
+
# :musical_note: Welcome to the Song Recommendation Bot!
|
87 |
+
## I am here to help you find the perfect songs based on your mood, specially curated for Gen Z tastes.
|
88 |
"""
|
|
|
89 |
topics = """
|
90 |
+
### Feel free to ask me for song recommendations for:
|
91 |
+
- Sad mood
|
92 |
+
- Happy mood
|
93 |
+
- Angry mood
|
94 |
+
- Workout
|
95 |
+
- Chilling
|
96 |
+
- Study
|
97 |
+
- Eating a meal
|
98 |
+
- Nostalgic
|
99 |
+
- Self care
|
100 |
"""
|
|
|
101 |
# Setup the Gradio Blocks interface with custom layout components
|
102 |
+
with gr.Blocks() as demo:
|
103 |
gr.Markdown(welcome_message) # Display the formatted welcome message
|
104 |
with gr.Row():
|
105 |
with gr.Column():
|
106 |
gr.Markdown(topics) # Show the topics on the left side
|
107 |
with gr.Row():
|
108 |
with gr.Column():
|
109 |
+
question = gr.Textbox(label="Your question", placeholder="What's your mood or activity?")
|
110 |
+
answer = gr.Textbox(label="Song Recommendations", placeholder="Your recommendations will appear here...", interactive=False, lines=10)
|
111 |
submit_button = gr.Button("Submit")
|
112 |
submit_button.click(fn=query_model, inputs=question, outputs=answer)
|
|
|
113 |
# Launch the Gradio app to allow user interaction
|
114 |
demo.launch(share=True)
|