Spaces:
Sleeping
Sleeping
File size: 7,850 Bytes
9b5b26a c19d193 6aae614 8fe992b 9b5b26a 5df72d6 9b5b26a 8c01ffb 7199aa9 8c01ffb 6aae614 ae7a494 e121372 bf6d34c 29ec968 fe328e0 13d500a 8c01ffb 9b5b26a 8c01ffb 861422e 9b5b26a 8c01ffb 8fe992b d2f6a24 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 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
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 !
@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)}"
@tool
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() |