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 | |
# Below is an example of a tool that does nothing. Amaze us with your creativity ! | |
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)}" | |
def get_sunrise_time(location: str, date: str = "today") -> str: | |
"""Get sunrise time and photography tips for a specified location. | |
Args: | |
location: Location name or coordinates (e.g., "London" or "51.5074,-0.1278") | |
date: Date string (e.g., "2023-12-25" or "today" for current date) | |
""" | |
try: | |
# Use Sunrise-Sunset API to get sunrise data | |
if date == "today": | |
date_param = "" # API defaults to today | |
else: | |
date_param = f"&date={date}" | |
# Check if location is in coordinate format | |
if "," in location and all(part.replace('.', '', 1).replace('-', '', 1).isdigit() for part in location.split(',')): | |
lat, lng = location.split(',') | |
else: | |
# Use Nominatim API for geocoding (convert location name to coordinates) | |
geo_response = requests.get(f"https://nominatim.openstreetmap.org/search?q={location}&format=json&limit=1") | |
geo_data = geo_response.json() | |
if not geo_data: | |
return f"Could not find location: {location}" | |
lat = geo_data[0]['lat'] | |
lng = geo_data[0]['lon'] | |
# Use coordinates to get sunrise data | |
response = requests.get(f"https://api.sunrise-sunset.org/json?lat={lat}&lng={lng}{date_param}&formatted=0") | |
data = response.json() | |
if data['status'] != 'OK': | |
return f"Error getting sunrise data: {data['status']}" | |
# Process sunrise times (convert from UTC to local time) | |
sunrise_utc = datetime.datetime.fromisoformat(data['results']['sunrise'].replace('Z', '+00:00')) | |
civil_twilight_utc = datetime.datetime.fromisoformat(data['results']['civil_twilight_begin'].replace('Z', '+00:00')) | |
# Get timezone for the location (using timezonefinder library) | |
from timezonefinder import TimezoneFinder | |
tf = TimezoneFinder() | |
timezone_str = tf.certain_timezone_at(lat=float(lat), lng=float(lng)) | |
if not timezone_str: | |
timezone = pytz.UTC | |
timezone_name = "UTC" | |
else: | |
timezone = pytz.timezone(timezone_str) | |
timezone_name = timezone_str | |
# Convert to local time | |
sunrise_local = sunrise_utc.astimezone(timezone) | |
civil_twilight_local = civil_twilight_utc.astimezone(timezone) | |
# Calculate best shooting time (typically from civil twilight to sunrise) | |
best_start = civil_twilight_local | |
best_end = sunrise_local | |
# Calculate golden hour (about 30 minutes after sunrise) | |
golden_hour_end = sunrise_local + datetime.timedelta(minutes=30) | |
# Format times | |
sunrise_time = sunrise_local.strftime("%H:%M:%S") | |
civil_twilight_time = civil_twilight_local.strftime("%H:%M:%S") | |
golden_hour_end_time = golden_hour_end.strftime("%H:%M:%S") | |
# Provide season-specific advice | |
month = sunrise_local.month | |
season = "" | |
season_tip = "" | |
if 3 <= month <= 5: # Spring | |
season = "Spring" | |
season_tip = "Spring sunrises often feature mist and soft light. Try to capture flowers in the foreground." | |
elif 6 <= month <= 8: # Summer | |
season = "Summer" | |
season_tip = "Summer sunrise comes early and temperatures rise quickly. Bring insect repellent and watch for lens fog due to humidity." | |
elif 9 <= month <= 11: # Fall/Autumn | |
season = "Fall/Autumn" | |
season_tip = "Fall sunrises often have fog and interesting cloud formations. Try using fallen leaves as foreground elements." | |
else: # Winter | |
season = "Winter" | |
season_tip = "Winter sunrises come later with cooler light. Stay warm and bring extra batteries as cold temperatures drain them faster." | |
# Generate photography tips | |
photography_tips = [ | |
f"Best arrival time: {civil_twilight_time} (civil twilight begins)", | |
f"Sunrise time: {sunrise_time}", | |
f"Golden light ends: {golden_hour_end_time}", | |
f"{season} photography tip: {season_tip}", | |
"Recommended gear: Tripod (essential), Variable ND filter, Remote shutter, Extra batteries", | |
"Composition tip: Look for interesting foreground elements, don't just focus on the sky", | |
"For best exposure, use bracketing (HDR) or graduated filters" | |
] | |
# Add a humorous tip | |
humor_tips = [ | |
"Remember to bring coffee, because your eyes might still be dreaming at dawn!", | |
"If you see other photographers, don't stand in front of them... unless you want to be the 'silhouette art' in their photos.", | |
"If your memory card fills up before the sunrise begins, that's why you should always bring two!", | |
"First rule of sunrise photography: Don't oversleep. Second rule: Seriously, don't oversleep!", | |
"Remember, the best tripod is the one you forgot at home...", | |
"The ultimate test for your sunrise photo: If your mom says 'Wow!' instead of just politely nodding, you've succeeded.", | |
"While waiting for sunrise in the frigid morning, remember that your bed misses you too.", | |
"If your photos come out blurry, just tell everyone it's an 'artistic style'.", | |
"The secret formula for the perfect sunrise shot: Weather forecast accuracy + Luck × Preparation ÷ Snooze button index" | |
] | |
photography_tips.append(random.choice(humor_tips)) | |
# Return formatted results | |
result = f"== Sunrise Photography Guide for {location} ==\n\n" | |
result += "\n".join(photography_tips) | |
return result | |
except Exception as e: | |
return f"Error getting sunrise information: {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], ## 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() |