Spaces:
Runtime error
Runtime error
File size: 2,274 Bytes
bb58e01 8429645 40d0295 a77b6fa 1ae841c 40d0295 8429645 40d0295 8429645 bb58e01 40d0295 bb58e01 a77b6fa 40d0295 ee7a0fe 8429645 40d0295 8429645 ee7a0fe bb58e01 40d0295 bb58e01 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | import gradio as gr
from openai import OpenAI
import os
import chromadb
from datasets import load_dataset
ds = load_dataset("RTVS/SpotifyLyrics001")
apikey=os.getenv('apikey')
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=f"{apikey}",
)
# Hàm chuẩn bị chạy trước Gradio
def setup_chromadb():
global collection # để dùng lại trong các hàm Gradio nếu cần
client = chromadb.Client()
collection_name = "my_collection"
existing_collections = [col.name for col in client.list_collections()]
if collection_name not in existing_collections:
print(f"Creating collection: {collection_name}")
collection = client.create_collection(name=collection_name)
ids = []
i = 0
for song,artist in zip(ds['train']['song'], ds['train']['artist']):
ids.append(f"Index: {i} - Name song:{song} - Artis:{artist}")
i+=1
collection.add(
documents=ds['train']['text'],
ids=ids
)
else:
print(f"Collection {collection_name} already exists.")
collection = client.get_collection(name=collection_name)
return
setup_chromadb()
def respond(
message,
history: list[tuple[str, str]],
):
response = ""
musics = collection.query(
query_texts=[message],
n_results=10
)['ids'][0]
response = client.chat.completions.create(
extra_body={},
model="openrouter/optimus-alpha",
messages=[
{
"role": "system",
"content": [
{
"type": "text",
"text": f"Generate a recommendation for the song based on user and this list: {musics}"
},
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": f"{message}"
},
]
}
]
).choices[0].message.content
return response
"""
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
"""
demo = gr.ChatInterface(
fn=respond,
)
if __name__ == "__main__":
demo.launch()
|