YenLai commited on
Commit
7199aa9
·
verified ·
1 Parent(s): ae7a494

modify the default tool to get_sunrise_time

Browse files
Files changed (1) hide show
  1. app.py +118 -10
app.py CHANGED
@@ -8,16 +8,6 @@ from tools.final_answer import FinalAnswerTool
8
  from Gradio_UI import GradioUI
9
 
10
  # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
- @tool
12
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that does nothing yet
15
- Args:
16
- arg1: the first argument
17
- arg2: the second argument
18
- """
19
- return "What magic will you build ?"
20
-
21
  @tool
22
  def get_current_time_in_timezone(timezone: str) -> str:
23
  """A tool that fetches the current local time in a specified timezone.
@@ -33,6 +23,124 @@ def get_current_time_in_timezone(timezone: str) -> str:
33
  except Exception as e:
34
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  final_answer = FinalAnswerTool()
38
 
 
8
  from Gradio_UI import GradioUI
9
 
10
  # Below is an example of a tool that does nothing. Amaze us with your creativity !
 
 
 
 
 
 
 
 
 
 
11
  @tool
12
  def get_current_time_in_timezone(timezone: str) -> str:
13
  """A tool that fetches the current local time in a specified timezone.
 
23
  except Exception as e:
24
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
25
 
26
+ @tool
27
+ def get_sunrise_time(location: str, date: str = "today") -> str:
28
+ """Get sunrise time and photography tips for a specified location.
29
+ Args:
30
+ location: Location name or coordinates (e.g., "London" or "51.5074,-0.1278")
31
+ date: Date string (e.g., "2023-12-25" or "today" for current date)
32
+ """
33
+ try:
34
+ # Use Sunrise-Sunset API to get sunrise data
35
+ if date == "today":
36
+ date_param = "" # API defaults to today
37
+ else:
38
+ date_param = f"&date={date}"
39
+
40
+ # Check if location is in coordinate format
41
+ if "," in location and all(part.replace('.', '', 1).replace('-', '', 1).isdigit() for part in location.split(',')):
42
+ lat, lng = location.split(',')
43
+ else:
44
+ # Use Nominatim API for geocoding (convert location name to coordinates)
45
+ geo_response = requests.get(f"https://nominatim.openstreetmap.org/search?q={location}&format=json&limit=1")
46
+ geo_data = geo_response.json()
47
+
48
+ if not geo_data:
49
+ return f"Could not find location: {location}"
50
+
51
+ lat = geo_data[0]['lat']
52
+ lng = geo_data[0]['lon']
53
+
54
+ # Use coordinates to get sunrise data
55
+ response = requests.get(f"https://api.sunrise-sunset.org/json?lat={lat}&lng={lng}{date_param}&formatted=0")
56
+ data = response.json()
57
+
58
+ if data['status'] != 'OK':
59
+ return f"Error getting sunrise data: {data['status']}"
60
+
61
+ # Process sunrise times (convert from UTC to local time)
62
+ sunrise_utc = datetime.datetime.fromisoformat(data['results']['sunrise'].replace('Z', '+00:00'))
63
+ civil_twilight_utc = datetime.datetime.fromisoformat(data['results']['civil_twilight_begin'].replace('Z', '+00:00'))
64
+
65
+ # Get timezone for the location (using timezonefinder library)
66
+ from timezonefinder import TimezoneFinder
67
+ tf = TimezoneFinder()
68
+ timezone_str = tf.certain_timezone_at(lat=float(lat), lng=float(lng))
69
+
70
+ if not timezone_str:
71
+ timezone = pytz.UTC
72
+ timezone_name = "UTC"
73
+ else:
74
+ timezone = pytz.timezone(timezone_str)
75
+ timezone_name = timezone_str
76
+
77
+ # Convert to local time
78
+ sunrise_local = sunrise_utc.astimezone(timezone)
79
+ civil_twilight_local = civil_twilight_utc.astimezone(timezone)
80
+
81
+ # Calculate best shooting time (typically from civil twilight to sunrise)
82
+ best_start = civil_twilight_local
83
+ best_end = sunrise_local
84
+
85
+ # Calculate golden hour (about 30 minutes after sunrise)
86
+ golden_hour_end = sunrise_local + datetime.timedelta(minutes=30)
87
+
88
+ # Format times
89
+ sunrise_time = sunrise_local.strftime("%H:%M:%S")
90
+ civil_twilight_time = civil_twilight_local.strftime("%H:%M:%S")
91
+ golden_hour_end_time = golden_hour_end.strftime("%H:%M:%S")
92
+
93
+ # Provide season-specific advice
94
+ month = sunrise_local.month
95
+ season = ""
96
+ season_tip = ""
97
+
98
+ if 3 <= month <= 5: # Spring
99
+ season = "Spring"
100
+ season_tip = "Spring sunrises often feature mist and soft light. Try to capture flowers in the foreground."
101
+ elif 6 <= month <= 8: # Summer
102
+ season = "Summer"
103
+ season_tip = "Summer sunrise comes early and temperatures rise quickly. Bring insect repellent and watch for lens fog due to humidity."
104
+ elif 9 <= month <= 11: # Fall/Autumn
105
+ season = "Fall/Autumn"
106
+ season_tip = "Fall sunrises often have fog and interesting cloud formations. Try using fallen leaves as foreground elements."
107
+ else: # Winter
108
+ season = "Winter"
109
+ season_tip = "Winter sunrises come later with cooler light. Stay warm and bring extra batteries as cold temperatures drain them faster."
110
+
111
+ # Generate photography tips
112
+ photography_tips = [
113
+ f"Best arrival time: {civil_twilight_time} (civil twilight begins)",
114
+ f"Sunrise time: {sunrise_time}",
115
+ f"Golden light ends: {golden_hour_end_time}",
116
+ f"{season} photography tip: {season_tip}",
117
+ "Recommended gear: Tripod (essential), Variable ND filter, Remote shutter, Extra batteries",
118
+ "Composition tip: Look for interesting foreground elements, don't just focus on the sky",
119
+ "For best exposure, use bracketing (HDR) or graduated filters"
120
+ ]
121
+
122
+ # Add a humorous tip
123
+ humor_tips = [
124
+ "Remember to bring coffee, because your eyes might still be dreaming at dawn!",
125
+ "If you see other photographers, don't stand in front of them... unless you want to be the 'silhouette art' in their photos.",
126
+ "If your memory card fills up before the sunrise begins, that's why you should always bring two!",
127
+ "First rule of sunrise photography: Don't oversleep. Second rule: Seriously, don't oversleep!",
128
+ "Remember, the best tripod is the one you forgot at home...",
129
+ "The ultimate test for your sunrise photo: If your mom says 'Wow!' instead of just politely nodding, you've succeeded.",
130
+ "While waiting for sunrise in the frigid morning, remember that your bed misses you too.",
131
+ "If your photos come out blurry, just tell everyone it's an 'artistic style'.",
132
+ "The secret formula for the perfect sunrise shot: Weather forecast accuracy + Luck × Preparation ÷ Snooze button index"
133
+ ]
134
+ photography_tips.append(random.choice(humor_tips))
135
+
136
+ # Return formatted results
137
+ result = f"== Sunrise Photography Guide for {location} ==\n\n"
138
+ result += "\n".join(photography_tips)
139
+
140
+ return result
141
+
142
+ except Exception as e:
143
+ return f"Error getting sunrise information: {str(e)}"
144
 
145
  final_answer = FinalAnswerTool()
146