Spaces:
Runtime error
Runtime error
new version with weighted probs when selecting song
Browse files- app.py +118 -31
- embeddings.npy +0 -0
- names.py +0 -1
- playground.py +0 -60
- prompts/bot.prompt +8 -5
- requirements.txt +0 -2
- temp.ipynb +0 -381
app.py
CHANGED
|
@@ -6,14 +6,27 @@ from langchain.chains import LLMChain
|
|
| 6 |
from langchain.prompts import PromptTemplate
|
| 7 |
|
| 8 |
load_dotenv()
|
| 9 |
-
import os
|
| 10 |
import json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
from langchain.chat_models import ChatOpenAI
|
| 12 |
from langchain.embeddings.openai import OpenAIEmbeddings
|
|
|
|
| 13 |
|
| 14 |
from data import load_db
|
| 15 |
from names import DATASET_ID, MODEL_ID
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
|
| 19 |
@st.cache_resource
|
|
@@ -30,51 +43,125 @@ def init():
|
|
| 30 |
)
|
| 31 |
|
| 32 |
prompt = PromptTemplate(
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
)
|
| 36 |
|
| 37 |
-
llm = ChatOpenAI(temperature=0.
|
| 38 |
|
| 39 |
chain = LLMChain(llm=llm, prompt=prompt)
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
movies_and_names_to_songs = {}
|
| 45 |
|
| 46 |
-
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
|
| 49 |
-
for song in songs:
|
| 50 |
-
movie_and_name = f"{movie};{song['name']}".lower()
|
| 51 |
-
songs_str += f"{movie_and_name}:{song['text']}\n"
|
| 52 |
-
movies_and_names_to_songs[movie_and_name] = song
|
| 53 |
|
| 54 |
-
return db, chain, movies_and_names_to_songs, songs_str
|
| 55 |
|
| 56 |
-
db, chain
|
| 57 |
|
| 58 |
-
st.title("Disney
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
text_input = st.text_input(
|
| 61 |
label="How are you feeling today?",
|
| 62 |
placeholder="I am ready to rock and rool!",
|
| 63 |
)
|
| 64 |
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
placeholder_emotions = st.empty()
|
| 67 |
placeholder = st.empty()
|
| 68 |
|
| 69 |
-
def get_emotions(songs_str, user_input):
|
| 70 |
-
res = chain.run(songs=songs_str, user_input=user_input)
|
| 71 |
-
song_key = random.choice(eval(res))
|
| 72 |
-
doc = movies_and_names_to_songs[song_key.lower()]
|
| 73 |
-
print(f"Reply: {res}, chosen: {song_key}")
|
| 74 |
-
with placeholder:
|
| 75 |
-
embed_url = doc["embed_url"]
|
| 76 |
-
iframe_html = f'<iframe src="{embed_url}" style="border:0"> </iframe>'
|
| 77 |
-
st.components.v1.html(f"<div style='display:flex;flex-direction:column'>{iframe_html}</div>")
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
from langchain.prompts import PromptTemplate
|
| 7 |
|
| 8 |
load_dotenv()
|
|
|
|
| 9 |
import json
|
| 10 |
+
import os
|
| 11 |
+
import random
|
| 12 |
+
from enum import Enum
|
| 13 |
+
from typing import List, Tuple
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
from langchain.chat_models import ChatOpenAI
|
| 17 |
from langchain.embeddings.openai import OpenAIEmbeddings
|
| 18 |
+
from langchain.schema import Document
|
| 19 |
|
| 20 |
from data import load_db
|
| 21 |
from names import DATASET_ID, MODEL_ID
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class RetrievalType:
|
| 25 |
+
FIRST_MATCH = "first-match"
|
| 26 |
+
POOL_MATCHES = "pool-matches"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
Matches = List[Tuple[Document, float]]
|
| 30 |
|
| 31 |
|
| 32 |
@st.cache_resource
|
|
|
|
| 43 |
)
|
| 44 |
|
| 45 |
prompt = PromptTemplate(
|
| 46 |
+
input_variables=["user_input"],
|
| 47 |
+
template=Path("prompts/bot.prompt").read_text(),
|
| 48 |
+
)
|
| 49 |
|
| 50 |
+
llm = ChatOpenAI(temperature=0.3)
|
| 51 |
|
| 52 |
chain = LLMChain(llm=llm, prompt=prompt)
|
| 53 |
|
| 54 |
+
return db, chain
|
| 55 |
+
|
|
|
|
|
|
|
| 56 |
|
| 57 |
+
# Don't show the setting sidebar
|
| 58 |
+
if "sidebar_state" not in st.session_state:
|
| 59 |
+
st.session_state.sidebar_state = "collapsed"
|
| 60 |
|
| 61 |
+
st.set_page_config(initial_sidebar_state=st.session_state.sidebar_state)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
|
|
|
| 63 |
|
| 64 |
+
db, chain = init()
|
| 65 |
|
| 66 |
+
st.title("Disney songs for you 🎵🏰")
|
| 67 |
+
st.markdown(
|
| 68 |
+
"""
|
| 69 |
+
*<small>Made with [DeepLake](https://www.deeplake.ai/) 🚀 and [LangChain](https://python.langchain.com/en/latest/index.html) 🦜⛓️</small>*
|
| 70 |
+
|
| 71 |
+
💫 Unleash the magic within you with our enchanting app, turning your sentiments into a Disney soundtrack! 🌈 Just express your emotions, and embark on a whimsical journey as we tailor a Disney melody to match your mood. 👑💖""",
|
| 72 |
+
unsafe_allow_html=True,
|
| 73 |
+
)
|
| 74 |
+
how_it_works = st.expander(label="How it works")
|
| 75 |
|
| 76 |
text_input = st.text_input(
|
| 77 |
label="How are you feeling today?",
|
| 78 |
placeholder="I am ready to rock and rool!",
|
| 79 |
)
|
| 80 |
|
| 81 |
+
run_btn = st.button("Make me sing! 🎶")
|
| 82 |
+
with how_it_works:
|
| 83 |
+
st.markdown(
|
| 84 |
+
"""
|
| 85 |
+
The application follows a sequence of steps to deliver Disney songs matching the user's emotions:
|
| 86 |
+
- **User Input**: The application starts by collecting user's emotional state through a text input.
|
| 87 |
+
- **Emotion Encoding**: The user-provided emotions are then fed to a Language Model (LLM). The LLM interprets and encodes these emotions.
|
| 88 |
+
- **Similarity Search**: These encoded emotions are utilized to perform a similarity search within our [vector database](https://www.deeplake.ai/). This database houses Disney songs, each represented as emotional embeddings.
|
| 89 |
+
- **Song Selection**: From the pool of top matching songs, the application randomly selects one. The selection is weighted, giving preference to songs with higher similarity scores.
|
| 90 |
+
- **Song Retrieval**: The selected song's embedded player is displayed on the webpage for the user. Additionally, the LLM interpreted emotional state associated with the chosen song is displayed.
|
| 91 |
+
"""
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
placeholder_emotions = st.empty()
|
| 96 |
placeholder = st.empty()
|
| 97 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
+
with st.sidebar:
|
| 100 |
+
st.text("App settings")
|
| 101 |
+
filter_threshold = st.slider(
|
| 102 |
+
"Threadhol used to filter out low scoring songs",
|
| 103 |
+
min_value=0.0,
|
| 104 |
+
max_value=1.0,
|
| 105 |
+
value=0.8,
|
| 106 |
+
)
|
| 107 |
+
max_number_of_songs = st.slider(
|
| 108 |
+
"Max number of songs we will retrieve from the db",
|
| 109 |
+
min_value=5,
|
| 110 |
+
max_value=50,
|
| 111 |
+
value=20,
|
| 112 |
+
step=1,
|
| 113 |
+
)
|
| 114 |
+
number_of_displayed_songs = st.slider(
|
| 115 |
+
"Number of displayed songs", min_value=1, max_value=4, value=1, step=1
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def filter_scores(matches: Matches, th: float = 0.8) -> Matches:
|
| 120 |
+
return [(doc, score) for (doc, score) in matches if score > th]
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def normalize_scores_by_sum(matches: Matches) -> Matches:
|
| 124 |
+
scores = [score for _, score in matches]
|
| 125 |
+
tot = sum(scores)
|
| 126 |
+
return [(doc, (score / tot)) for doc, score in matches]
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def get_song(user_input: str, k: int = 20):
|
| 130 |
+
emotions = chain.run(user_input=user_input)
|
| 131 |
+
matches = db.similarity_search_with_score(emotions, distance_metric="cos", k=k)
|
| 132 |
+
# [print(doc.metadata['name'], score) for doc, score in matches]
|
| 133 |
+
docs, scores = zip(
|
| 134 |
+
*normalize_scores_by_sum(filter_scores(matches, filter_threshold))
|
| 135 |
+
)
|
| 136 |
+
choosen_docs = np.random.choice(docs, size=number_of_displayed_songs, p=scores)
|
| 137 |
+
return choosen_docs, emotions
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def set_song(user_input):
|
| 141 |
+
if user_input == "":
|
| 142 |
+
return
|
| 143 |
+
# take first 120 chars
|
| 144 |
+
user_input = user_input[:120]
|
| 145 |
+
docs, emotions = get_song(user_input, k=max_number_of_songs)
|
| 146 |
+
with placeholder_emotions:
|
| 147 |
+
st.markdown("Your emotions: `" + emotions + "`")
|
| 148 |
+
with placeholder:
|
| 149 |
+
iframes_html = ""
|
| 150 |
+
for doc in docs:
|
| 151 |
+
print(doc.metadata["name"])
|
| 152 |
+
embed_url = doc.metadata["embed_url"]
|
| 153 |
+
iframes_html += (
|
| 154 |
+
f'<iframe src="{embed_url}" style="border:0;height:100px"> </iframe>'
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
st.markdown(
|
| 158 |
+
f"<div style='display:flex;flex-direction:column'>{iframes_html}</div>",
|
| 159 |
+
unsafe_allow_html=True,
|
| 160 |
+
)
|
| 161 |
+
# st.components.v1.html(
|
| 162 |
+
# f"<div>{iframes_html}</div>"
|
| 163 |
+
# )
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
if run_btn:
|
| 167 |
+
set_song(text_input)
|
embeddings.npy
DELETED
|
Binary file (24.7 kB)
|
|
|
names.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
MODEL_ID = "text-embedding-ada-002"
|
| 2 |
# DATASET_ID = "disney-lyrics"
|
| 3 |
DATASET_ID = "disney-lyrics-emotions"
|
| 4 |
-
|
|
|
|
| 1 |
MODEL_ID = "text-embedding-ada-002"
|
| 2 |
# DATASET_ID = "disney-lyrics"
|
| 3 |
DATASET_ID = "disney-lyrics-emotions"
|
|
|
playground.py
DELETED
|
@@ -1,60 +0,0 @@
|
|
| 1 |
-
from dotenv import load_dotenv
|
| 2 |
-
|
| 3 |
-
load_dotenv()
|
| 4 |
-
import json
|
| 5 |
-
import os
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
|
| 8 |
-
import deeplake
|
| 9 |
-
import numpy as np
|
| 10 |
-
import openai
|
| 11 |
-
|
| 12 |
-
# https://www.disneyclips.com/lyrics/
|
| 13 |
-
DATASET_NAME = "disney-lyrics"
|
| 14 |
-
model_id = "text-embedding-ada-002"
|
| 15 |
-
dataset_path = f"hub://{os.environ['ACTIVELOOP_ORG_ID']}/{DATASET_NAME}"
|
| 16 |
-
print(dataset_path)
|
| 17 |
-
runtime = {"db_engine": True}
|
| 18 |
-
|
| 19 |
-
with open("lyrics.json", "rb") as f:
|
| 20 |
-
lyrics = json.load(f)["lyrics"]
|
| 21 |
-
|
| 22 |
-
# embeddings = [el["embedding"] for el in openai.Embedding.create(input=lyrics, model=model_id)['data']]
|
| 23 |
-
|
| 24 |
-
# embeddings_np = np.array(embeddings)
|
| 25 |
-
# np.save("embeddings.npy", embeddings_np)
|
| 26 |
-
|
| 27 |
-
embeddings_np = np.load("embeddings.npy")
|
| 28 |
-
|
| 29 |
-
print(embeddings_np.shape)
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
# ds = deeplake.empty(dataset_path, runtime=runtime, overwrite=True)
|
| 33 |
-
|
| 34 |
-
# # https://docs.deeplake.ai/en/latest/Htypes.html
|
| 35 |
-
# with ds:
|
| 36 |
-
# ds.create_tensor("embedding", htype="embedding", dtype=np.float32, exist_ok=True)
|
| 37 |
-
# ds.extend({ "embedding": embeddings_np.astype(np.float32)})
|
| 38 |
-
# ds.summary()
|
| 39 |
-
|
| 40 |
-
search_term = "Let's get down to business"
|
| 41 |
-
|
| 42 |
-
embedding = openai.Embedding.create(input=search_term, model="text-embedding-ada-002")[
|
| 43 |
-
"data"
|
| 44 |
-
][0]["embedding"]
|
| 45 |
-
|
| 46 |
-
# Format the embedding as a string, so it can be passed in the REST API request.
|
| 47 |
-
embedding_search = ",".join([str(item) for item in embedding])
|
| 48 |
-
|
| 49 |
-
# embedding_search = ",".join([str(item) for item in embeddings_np[0].tolist()])
|
| 50 |
-
# print(embedding_search)
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
ds = deeplake.load(dataset_path)
|
| 54 |
-
|
| 55 |
-
# print(embedding_search)
|
| 56 |
-
query = f'select * from (select l2_norm(embedding - ARRAY[{embedding_search}]) as score from "{dataset_path}") order by score desc limit 5'
|
| 57 |
-
with open("foo.txt", "w") as f:
|
| 58 |
-
f.write(query)
|
| 59 |
-
query_res = ds.query(query)
|
| 60 |
-
print(query_res)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
prompts/bot.prompt
CHANGED
|
@@ -1,9 +1,12 @@
|
|
| 1 |
-
We have a simple song retrieval system. It accepts
|
|
|
|
|
|
|
| 2 |
|
| 3 |
Input: "I had a great day!"
|
| 4 |
-
|
| 5 |
Input: "I am very tired today and I am not feeling weel"
|
| 6 |
-
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
Please, suggest emotions for input = "{content}", reply ONLY with a max of 4 emotions.
|
|
|
|
| 1 |
+
We have a simple song retrieval system. It accepts 8 emotions. You are tasked to suggest between 1 and 4 emotions to match the users feelings. Suggest more emotions for longer sentences and just one or two for small ones, trying to condense the main theme of the input
|
| 2 |
+
|
| 3 |
+
Examples:
|
| 4 |
|
| 5 |
Input: "I had a great day!"
|
| 6 |
+
"Joy"
|
| 7 |
Input: "I am very tired today and I am not feeling weel"
|
| 8 |
+
"Exhaustion, Discomfort, and Fatigue"
|
| 9 |
+
Input: "I am in Love"
|
| 10 |
+
"Love"
|
| 11 |
|
| 12 |
+
Please, uggest emotions for input = "{user_input}", reply ONLY with a list of emotions/feelings/vibes
|
|
|
requirements.txt
CHANGED
|
@@ -1,6 +1,4 @@
|
|
| 1 |
openai
|
| 2 |
-
torch==2.0.1
|
| 3 |
-
torchvision
|
| 4 |
python-dotenv
|
| 5 |
deeplake
|
| 6 |
langchain
|
|
|
|
| 1 |
openai
|
|
|
|
|
|
|
| 2 |
python-dotenv
|
| 3 |
deeplake
|
| 4 |
langchain
|
temp.ipynb
DELETED
|
@@ -1,381 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"cells": [
|
| 3 |
-
{
|
| 4 |
-
"cell_type": "code",
|
| 5 |
-
"execution_count": 1,
|
| 6 |
-
"id": "26b62e0c",
|
| 7 |
-
"metadata": {},
|
| 8 |
-
"outputs": [],
|
| 9 |
-
"source": [
|
| 10 |
-
"%load_ext autoreload\n",
|
| 11 |
-
"%autoreload "
|
| 12 |
-
]
|
| 13 |
-
},
|
| 14 |
-
{
|
| 15 |
-
"cell_type": "code",
|
| 16 |
-
"execution_count": 2,
|
| 17 |
-
"id": "b1a6a020",
|
| 18 |
-
"metadata": {
|
| 19 |
-
"scrolled": true
|
| 20 |
-
},
|
| 21 |
-
"outputs": [
|
| 22 |
-
{
|
| 23 |
-
"name": "stderr",
|
| 24 |
-
"output_type": "stream",
|
| 25 |
-
"text": [
|
| 26 |
-
"/home/zuppif/miniconda3/envs/activeloop/lib/python3.9/site-packages/deeplake/util/check_latest_version.py:32: UserWarning: A newer version of deeplake (3.4.3) is available. It's recommended that you update to the latest version using `pip install -U deeplake`.\n",
|
| 27 |
-
" warnings.warn(\n",
|
| 28 |
-
"-"
|
| 29 |
-
]
|
| 30 |
-
},
|
| 31 |
-
{
|
| 32 |
-
"name": "stdout",
|
| 33 |
-
"output_type": "stream",
|
| 34 |
-
"text": [
|
| 35 |
-
"This dataset can be visualized in Jupyter Notebook by ds.visualize() or at https://app.activeloop.ai/zuppif/disney-lyrics-emotions\n",
|
| 36 |
-
"\n"
|
| 37 |
-
]
|
| 38 |
-
},
|
| 39 |
-
{
|
| 40 |
-
"name": "stderr",
|
| 41 |
-
"output_type": "stream",
|
| 42 |
-
"text": [
|
| 43 |
-
"\\"
|
| 44 |
-
]
|
| 45 |
-
},
|
| 46 |
-
{
|
| 47 |
-
"name": "stdout",
|
| 48 |
-
"output_type": "stream",
|
| 49 |
-
"text": [
|
| 50 |
-
"hub://zuppif/disney-lyrics-emotions loaded successfully.\n",
|
| 51 |
-
"\n",
|
| 52 |
-
"Deep Lake Dataset in hub://zuppif/disney-lyrics-emotions already exists, loading from the storage\n",
|
| 53 |
-
"Dataset(path='hub://zuppif/disney-lyrics-emotions', read_only=True, tensors=['embedding', 'ids', 'metadata', 'text'])\n",
|
| 54 |
-
"\n",
|
| 55 |
-
" tensor htype shape dtype compression\n",
|
| 56 |
-
" ------- ------- ------- ------- ------- \n",
|
| 57 |
-
" embedding generic (85, 1536) float32 None \n",
|
| 58 |
-
" ids text (85, 1) str None \n",
|
| 59 |
-
" metadata json (85, 1) str None \n",
|
| 60 |
-
" text text (85, 1) str None \n"
|
| 61 |
-
]
|
| 62 |
-
},
|
| 63 |
-
{
|
| 64 |
-
"name": "stderr",
|
| 65 |
-
"output_type": "stream",
|
| 66 |
-
"text": [
|
| 67 |
-
"\r",
|
| 68 |
-
" \r",
|
| 69 |
-
"\r",
|
| 70 |
-
" \r"
|
| 71 |
-
]
|
| 72 |
-
}
|
| 73 |
-
],
|
| 74 |
-
"source": [
|
| 75 |
-
"from dotenv import load_dotenv\n",
|
| 76 |
-
"load_dotenv() \n",
|
| 77 |
-
"from names import DATASET_ID, MODEL_ID\n",
|
| 78 |
-
"from data import load_db\n",
|
| 79 |
-
"import os\n",
|
| 80 |
-
"from langchain.chains import RetrievalQA, ConversationalRetrievalChain\n",
|
| 81 |
-
"from langchain.vectorstores import DeepLake\n",
|
| 82 |
-
"from langchain.llms import OpenAI\n",
|
| 83 |
-
"from langchain.embeddings.openai import OpenAIEmbeddings\n",
|
| 84 |
-
"from langchain.chat_models import ChatOpenAI\n",
|
| 85 |
-
"\n",
|
| 86 |
-
"embeddings = OpenAIEmbeddings(model=MODEL_ID)\n",
|
| 87 |
-
"dataset_path = f\"hub://{os.environ['ACTIVELOOP_ORG_ID']}/{DATASET_ID}\"\n",
|
| 88 |
-
"\n",
|
| 89 |
-
"db = load_db(dataset_path, embedding_function=embeddings, token=os.environ['ACTIVELOOP_TOKEN'], org_id=os.environ[\"ACTIVELOOP_ORG_ID\"], read_only=True)"
|
| 90 |
-
]
|
| 91 |
-
},
|
| 92 |
-
{
|
| 93 |
-
"cell_type": "markdown",
|
| 94 |
-
"id": "97c3370c",
|
| 95 |
-
"metadata": {},
|
| 96 |
-
"source": [
|
| 97 |
-
"## Using similarity search"
|
| 98 |
-
]
|
| 99 |
-
},
|
| 100 |
-
{
|
| 101 |
-
"cell_type": "code",
|
| 102 |
-
"execution_count": 75,
|
| 103 |
-
"id": "07d8a381",
|
| 104 |
-
"metadata": {},
|
| 105 |
-
"outputs": [],
|
| 106 |
-
"source": [
|
| 107 |
-
"from langchain.chains import LLMChain\n",
|
| 108 |
-
"from langchain.prompts import PromptTemplate\n",
|
| 109 |
-
"from pathlib import Path\n",
|
| 110 |
-
"\n",
|
| 111 |
-
"prompt = PromptTemplate(\n",
|
| 112 |
-
" input_variables=[\"content\"],\n",
|
| 113 |
-
" template=Path(\"prompts/bot.prompt\").read_text(),\n",
|
| 114 |
-
")\n",
|
| 115 |
-
"\n",
|
| 116 |
-
"llm = ChatOpenAI(temperature=0.7)\n",
|
| 117 |
-
"\n",
|
| 118 |
-
"chain = LLMChain(llm=llm, prompt=prompt)"
|
| 119 |
-
]
|
| 120 |
-
},
|
| 121 |
-
{
|
| 122 |
-
"cell_type": "code",
|
| 123 |
-
"execution_count": 76,
|
| 124 |
-
"id": "ebca722d",
|
| 125 |
-
"metadata": {},
|
| 126 |
-
"outputs": [
|
| 127 |
-
{
|
| 128 |
-
"data": {
|
| 129 |
-
"text/plain": [
|
| 130 |
-
"'Exhaustion, Fatigue, Sleepiness, Drained.'"
|
| 131 |
-
]
|
| 132 |
-
},
|
| 133 |
-
"execution_count": 76,
|
| 134 |
-
"metadata": {},
|
| 135 |
-
"output_type": "execute_result"
|
| 136 |
-
}
|
| 137 |
-
],
|
| 138 |
-
"source": [
|
| 139 |
-
"emotions = chain.run(content=\"Damn I am feeling so tired\")\n",
|
| 140 |
-
"emotions"
|
| 141 |
-
]
|
| 142 |
-
},
|
| 143 |
-
{
|
| 144 |
-
"cell_type": "code",
|
| 145 |
-
"execution_count": 77,
|
| 146 |
-
"id": "9598a36c",
|
| 147 |
-
"metadata": {
|
| 148 |
-
"scrolled": false
|
| 149 |
-
},
|
| 150 |
-
"outputs": [
|
| 151 |
-
{
|
| 152 |
-
"name": "stdout",
|
| 153 |
-
"output_type": "stream",
|
| 154 |
-
"text": [
|
| 155 |
-
"[(Document(page_content='Hopeful, determined, inspired, optimistic, longing, driven, passionate, adventurous.', metadata={'movie': 'Hercules', 'name': 'Go the Distance', 'embed_url': 'https://open.spotify.com/embed/track/0D1OY0M5A0qD5HGBvFmFid?utm_source=generator'}), 0.8135085701942444), (Document(page_content='upset, mad, regret, sad, fine, longing, hopeful, impatient', metadata={'movie': 'Encanto', 'name': 'Waiting on a Miracle', 'embed_url': 'https://open.spotify.com/embed/track/3oRW9ZGPRbLRMneQ5lwflt?utm_source=generator'}), 0.8108540177345276), (Document(page_content='nasty, repentant, magic, sad, lonely, bored, withdrawn, busy', metadata={'movie': 'The Little Mermaid', 'name': 'Poor Unfortunate Souls', 'embed_url': 'https://open.spotify.com/embed/track/7zsw78LtXUD7JfEwH64HK2?utm_source=generator'}), 0.8080281615257263), (Document(page_content='hopeful, optimistic, dreamy, inspired, happy, content, fulfilled, grateful', metadata={'movie': 'Pinocchio', 'name': 'When You Wish Upon a Star', 'embed_url': 'https://open.spotify.com/embed/track/1WrPa4lrIddctGWAIYYfP9?utm_source=generator'}), 0.8055723309516907)]\n",
|
| 156 |
-
"https://open.spotify.com/embed/track/0D1OY0M5A0qD5HGBvFmFid?utm_source=generator\n",
|
| 157 |
-
"page_content='Hopeful, determined, inspired, optimistic, longing, driven, passionate, adventurous.' metadata={'movie': 'Hercules', 'name': 'Go the Distance', 'embed_url': 'https://open.spotify.com/embed/track/0D1OY0M5A0qD5HGBvFmFid?utm_source=generator'}\n"
|
| 158 |
-
]
|
| 159 |
-
},
|
| 160 |
-
{
|
| 161 |
-
"data": {
|
| 162 |
-
"text/html": [
|
| 163 |
-
"\n",
|
| 164 |
-
" <iframe\n",
|
| 165 |
-
" width=\"700\"\n",
|
| 166 |
-
" height=\"350\"\n",
|
| 167 |
-
" src=\"https://open.spotify.com/embed/track/0D1OY0M5A0qD5HGBvFmFid?utm_source=generator\"\n",
|
| 168 |
-
" frameborder=\"0\"\n",
|
| 169 |
-
" allowfullscreen\n",
|
| 170 |
-
" \n",
|
| 171 |
-
" ></iframe>\n",
|
| 172 |
-
" "
|
| 173 |
-
],
|
| 174 |
-
"text/plain": [
|
| 175 |
-
"<IPython.lib.display.IFrame at 0x7f1890ed7430>"
|
| 176 |
-
]
|
| 177 |
-
},
|
| 178 |
-
"execution_count": 77,
|
| 179 |
-
"metadata": {},
|
| 180 |
-
"output_type": "execute_result"
|
| 181 |
-
}
|
| 182 |
-
],
|
| 183 |
-
"source": [
|
| 184 |
-
"matches = db.similarity_search_with_score(emotions, distance_metric=\"cos\")\n",
|
| 185 |
-
"print(matches)\n",
|
| 186 |
-
"doc, score = matches[0]\n",
|
| 187 |
-
"print(doc.metadata[\"embed_url\"])\n",
|
| 188 |
-
"print(doc)\n",
|
| 189 |
-
"\n",
|
| 190 |
-
"from IPython.display import IFrame\n",
|
| 191 |
-
"IFrame(doc.metadata[\"embed_url\"], width=700, height=350)"
|
| 192 |
-
]
|
| 193 |
-
},
|
| 194 |
-
{
|
| 195 |
-
"cell_type": "markdown",
|
| 196 |
-
"id": "8a474a1c",
|
| 197 |
-
"metadata": {},
|
| 198 |
-
"source": [
|
| 199 |
-
"## Using all the songs emotions in the prommpt"
|
| 200 |
-
]
|
| 201 |
-
},
|
| 202 |
-
{
|
| 203 |
-
"cell_type": "code",
|
| 204 |
-
"execution_count": 23,
|
| 205 |
-
"id": "c3cb2f3d",
|
| 206 |
-
"metadata": {},
|
| 207 |
-
"outputs": [],
|
| 208 |
-
"source": [
|
| 209 |
-
"import json\n",
|
| 210 |
-
"from langchain.chains import LLMChain\n",
|
| 211 |
-
"from langchain.prompts import PromptTemplate\n",
|
| 212 |
-
"from pathlib import Path\n",
|
| 213 |
-
"\n",
|
| 214 |
-
"prompt = PromptTemplate(\n",
|
| 215 |
-
" input_variables=[\"songs\", \"user_input\"],\n",
|
| 216 |
-
" template=Path(\"prompts/bot_with_summary.prompt\").read_text(),\n",
|
| 217 |
-
")\n",
|
| 218 |
-
"\n",
|
| 219 |
-
"llm = ChatOpenAI(temperature=0.7)\n",
|
| 220 |
-
"\n",
|
| 221 |
-
"chain = LLMChain(llm=llm, prompt=prompt)"
|
| 222 |
-
]
|
| 223 |
-
},
|
| 224 |
-
{
|
| 225 |
-
"cell_type": "markdown",
|
| 226 |
-
"id": "b1ca9c9c",
|
| 227 |
-
"metadata": {},
|
| 228 |
-
"source": [
|
| 229 |
-
"Let's create the songs string"
|
| 230 |
-
]
|
| 231 |
-
},
|
| 232 |
-
{
|
| 233 |
-
"cell_type": "code",
|
| 234 |
-
"execution_count": 24,
|
| 235 |
-
"id": "00416443",
|
| 236 |
-
"metadata": {},
|
| 237 |
-
"outputs": [],
|
| 238 |
-
"source": [
|
| 239 |
-
"with open(\"data/emotions_with_spotify_url.json\", \"r\") as f:\n",
|
| 240 |
-
" data = json.load(f)\n",
|
| 241 |
-
" \n",
|
| 242 |
-
"movies_and_names_to_songs = {}"
|
| 243 |
-
]
|
| 244 |
-
},
|
| 245 |
-
{
|
| 246 |
-
"cell_type": "code",
|
| 247 |
-
"execution_count": 25,
|
| 248 |
-
"id": "e4bf60d4",
|
| 249 |
-
"metadata": {
|
| 250 |
-
"scrolled": true
|
| 251 |
-
},
|
| 252 |
-
"outputs": [],
|
| 253 |
-
"source": [
|
| 254 |
-
"songs_str = \"\"\n",
|
| 255 |
-
"\n",
|
| 256 |
-
"for movie, songs in data.items():\n",
|
| 257 |
-
" for song in songs:\n",
|
| 258 |
-
" movie_and_name = f\"{movie};{song['name']}\".lower()\n",
|
| 259 |
-
" songs_str += f\"{movie_and_name}:{song['text']}\\n\"\n",
|
| 260 |
-
" movies_and_names_to_songs[movie_and_name] = song"
|
| 261 |
-
]
|
| 262 |
-
},
|
| 263 |
-
{
|
| 264 |
-
"cell_type": "code",
|
| 265 |
-
"execution_count": 26,
|
| 266 |
-
"id": "32cd1a47",
|
| 267 |
-
"metadata": {},
|
| 268 |
-
"outputs": [],
|
| 269 |
-
"source": [
|
| 270 |
-
"# prompt.format(songs=songs_str, user_input=\"I am feeling great today\")"
|
| 271 |
-
]
|
| 272 |
-
},
|
| 273 |
-
{
|
| 274 |
-
"cell_type": "code",
|
| 275 |
-
"execution_count": 30,
|
| 276 |
-
"id": "a056e5e9",
|
| 277 |
-
"metadata": {},
|
| 278 |
-
"outputs": [
|
| 279 |
-
{
|
| 280 |
-
"data": {
|
| 281 |
-
"text/plain": [
|
| 282 |
-
"'[\"coco;remember me (dúo)\", \"mulan;reflection\", \"frozen;do you want to build a snowman?\"]'"
|
| 283 |
-
]
|
| 284 |
-
},
|
| 285 |
-
"execution_count": 30,
|
| 286 |
-
"metadata": {},
|
| 287 |
-
"output_type": "execute_result"
|
| 288 |
-
}
|
| 289 |
-
],
|
| 290 |
-
"source": [
|
| 291 |
-
"res = chain.run(songs=songs_str, user_input=\"I am sad\")\n",
|
| 292 |
-
"res"
|
| 293 |
-
]
|
| 294 |
-
},
|
| 295 |
-
{
|
| 296 |
-
"cell_type": "code",
|
| 297 |
-
"execution_count": 31,
|
| 298 |
-
"id": "e84eeeaa",
|
| 299 |
-
"metadata": {},
|
| 300 |
-
"outputs": [],
|
| 301 |
-
"source": [
|
| 302 |
-
"import random\n",
|
| 303 |
-
"\n",
|
| 304 |
-
"res = random.choice(eval(res))"
|
| 305 |
-
]
|
| 306 |
-
},
|
| 307 |
-
{
|
| 308 |
-
"cell_type": "code",
|
| 309 |
-
"execution_count": 32,
|
| 310 |
-
"id": "e24ed65f",
|
| 311 |
-
"metadata": {},
|
| 312 |
-
"outputs": [
|
| 313 |
-
{
|
| 314 |
-
"name": "stdout",
|
| 315 |
-
"output_type": "stream",
|
| 316 |
-
"text": [
|
| 317 |
-
"frozen;do you want to build a snowman?\n"
|
| 318 |
-
]
|
| 319 |
-
},
|
| 320 |
-
{
|
| 321 |
-
"data": {
|
| 322 |
-
"text/html": [
|
| 323 |
-
"\n",
|
| 324 |
-
" <iframe\n",
|
| 325 |
-
" width=\"700\"\n",
|
| 326 |
-
" height=\"350\"\n",
|
| 327 |
-
" src=\"https://open.spotify.com/embed/track/2yi7HZrBOC4bMUSTcs4VK6?utm_source=generator\"\n",
|
| 328 |
-
" frameborder=\"0\"\n",
|
| 329 |
-
" allowfullscreen\n",
|
| 330 |
-
" \n",
|
| 331 |
-
" ></iframe>\n",
|
| 332 |
-
" "
|
| 333 |
-
],
|
| 334 |
-
"text/plain": [
|
| 335 |
-
"<IPython.lib.display.IFrame at 0x7f54178b9d00>"
|
| 336 |
-
]
|
| 337 |
-
},
|
| 338 |
-
"execution_count": 32,
|
| 339 |
-
"metadata": {},
|
| 340 |
-
"output_type": "execute_result"
|
| 341 |
-
}
|
| 342 |
-
],
|
| 343 |
-
"source": [
|
| 344 |
-
"print(res)\n",
|
| 345 |
-
"doc = movies_and_names_to_songs[res]\n",
|
| 346 |
-
"\n",
|
| 347 |
-
"from IPython.display import IFrame\n",
|
| 348 |
-
"IFrame(doc[\"embed_url\"], width=700, height=350)"
|
| 349 |
-
]
|
| 350 |
-
},
|
| 351 |
-
{
|
| 352 |
-
"cell_type": "code",
|
| 353 |
-
"execution_count": null,
|
| 354 |
-
"id": "03de1b93",
|
| 355 |
-
"metadata": {},
|
| 356 |
-
"outputs": [],
|
| 357 |
-
"source": []
|
| 358 |
-
}
|
| 359 |
-
],
|
| 360 |
-
"metadata": {
|
| 361 |
-
"kernelspec": {
|
| 362 |
-
"display_name": "Python 3 (ipykernel)",
|
| 363 |
-
"language": "python",
|
| 364 |
-
"name": "python3"
|
| 365 |
-
},
|
| 366 |
-
"language_info": {
|
| 367 |
-
"codemirror_mode": {
|
| 368 |
-
"name": "ipython",
|
| 369 |
-
"version": 3
|
| 370 |
-
},
|
| 371 |
-
"file_extension": ".py",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