Spaces:
Sleeping
Sleeping
File size: 6,679 Bytes
9b5b26a c19d193 6aae614 8fe992b 9b5b26a 6bf5858 9b5b26a 6bf5858 d5e51b7 1173459 6bf5858 1173459 86bbad4 1173459 6bf5858 1173459 6bf5858 1173459 9b5b26a 8c01ffb 6aae614 ae7a494 e121372 bf6d34c 29ec968 fe328e0 13d500a 8c01ffb 9b5b26a 8c01ffb 861422e 9b5b26a 8c01ffb 8fe992b 86bbad4 8c01ffb 861422e 8fe992b 9b5b26a 8c01ffb |
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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 |
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
import re
import requests # Import the requests library
from bs4 import BeautifulSoup #for parsing
@tool
def find_the_song(arg1: str) -> str:
"""A tool that finds the song name, artist, Spotify URL, and lyrics based on a given verse.
Args: arg1: a verse of a song or words that are refrencing a song.
"""
try:
search_term = f"site:genius.com OR site:azlyrics.com song lyrics \"{arg1}\"" #Focus on specific lyric sites
search_tool = DuckDuckGoSearchTool()
search_results = search_tool.run(search_term)
if search_results:
#Try extracting information from Genius or AZLyrics (prioritized)
if "genius.com" in search_results.lower():
try:
url = re.search(r'(https?://[^\s]+)', search_results).group(0) # Get the genius URL
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser') #html parser
song_title = soup.find("h1", class_="song_title").text.strip() if soup.find("h1", class_="song_title") else None #search song's name from specific h1 tag
artist = soup.find("a", class_="artist_name").text.strip() if soup.find("a", class_="artist_name") else None #same but for artist name
lyrics_div = soup.find("div", class_="lyrics") if soup.find("div", class_="lyrics") else soup.find("div", class_="Lyrics__Container") #finding lyrics tags (check them both if one is not available)
if lyrics_div:
lyrics = lyrics_div.get_text(separator="\n").strip()
else:
lyrics = None
except Exception as e:
return f"Error scraping Genius: {e}. Raw results: {search_results}"
elif "azlyrics.com" in search_results.lower():
try:
url = re.search(r'(https?://[^\s]+)', search_results).group(0) # Get the azlyrics URL
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
lyrics_div = soup.find("div", class_="ringtone") # Lyrics are inside a specific div
if lyrics_div:
lyrics = lyrics_div.find_next("div").get_text().strip() # Get the lyrics that are in the next div
artist_element = soup.find('div', class_='lyricsh') # Find the tag of the lyrics
artist = artist_element.find_next('b').text.split('lyrics')[0].strip() #parse the artist's name out
song_title = soup.find('title').text.split(' - ')[0].strip() #same for name
else:
lyrics = None
except Exception as e:
return f"Error scraping AZLyrics: {e}. Raw results: {search_results}"
else:
return f"Could not find Genius or AZLyrics page, so couldn't extract lyrics. Raw results: {search_results}"
#Fallback: Simple regex extraction of song and artist names
if song_title is None or artist is None:
title_match = re.search(r"Title:\s*(.*)", search_results, re.IGNORECASE)
artist_match = re.search(r"Artist:\s*(.*)", search_results, re.IGNORECASE)
song_title = title_match.group(1).strip() if title_match else None
artist = artist_match.group(1).strip() if artist_match else None
#Hardcoded URL example
if song_title == 'TV' and artist == 'Billie Eilish':
spotify_url = "https://open.spotify.com/track/3GYlZ7tbxLOxe6ewMNVTkw?autoplay=true"
else: spotify_url = None
# Construct the final answer
if song_title and artist and lyrics and spotify_url:
return f"song name: {song_title} , by {artist} . the spotify url is : {spotify_url} \nthe lyrics are : {lyrics}" # return the song + lyrics
#Handle partial results - even if can't find the URL or Lyrics:
if song_title and artist:
spotify_message = f"\n(Could not reliably extract Spotify URL)" if spotify_url is None else ""
lyrics_message = f"\n(Could not reliably extract Lyrics)" if lyrics is None else ""
return f"Found song: {song_title} by {artist} . {spotify_message}{lyrics_message}. Raw results: {search_results}"
return f"Could not extract full information, check the search results:\n {search_results}" #in case it fails return the search result
else:
return "Could not find any songs matching the verse."
except Exception as e:
return f"An error occurred: {e}"
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""A tool that fetches the current local time in a specified timezone.
Args:
timezone: A string representing a valid timezone (e.g., 'America/New_York').
"""
try:
# Create timezone object
tz = pytz.timezone(timezone)
# Get current time in that timezone
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
return f"The current local time in {timezone} is: {local_time}"
except Exception as e:
return f"Error fetching time for timezone '{timezone}': {str(e)}"
final_answer = FinalAnswerTool()
# If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
custom_role_conversions=None,
)
# Import tool from Hub
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
agent = CodeAgent(
model=model,
tools=[final_answer, find_the_song,get_current_time_in_timezone], ## add your tools here (don't remove final answer)
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
GradioUI(agent).launch() |