Spaces:
Sleeping
Sleeping
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 | |
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}" | |
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() |