Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,41 +1,16 @@
|
|
1 |
-
from smolagents import CodeAgent,
|
2 |
-
import smolagents # Added for aliasing
|
3 |
-
# from smolagents.security import E2BSandbox
|
4 |
-
import datetime
|
5 |
-
import pytz
|
6 |
-
import yaml
|
7 |
-
from skyfield.api import load, Topos, load_file
|
8 |
-
from skyfield import almanac
|
9 |
-
from tools.final_answer import FinalAnswerTool
|
10 |
-
from Gradio_UI import GradioUI
|
11 |
from langchain.memory import SimpleMemory
|
|
|
12 |
from gradio import Interface
|
13 |
import os
|
14 |
import base64
|
|
|
|
|
|
|
|
|
15 |
|
16 |
-
#
|
17 |
-
|
18 |
-
|
19 |
-
LANGFUSE_PUBLIC_KEY="pk-lf-133099c7-8644-49e8-8f6e-ec8bd6d543fd"
|
20 |
-
LF_SECRET_KEY = os.environ["LANGFUSE_SECRET_KEY"]
|
21 |
-
LANGFUSE_AUTH=base64.b64encode(f"{LANGFUSE_PUBLIC_KEY}:{LF_SECRET_KEY}".encode()).decode()
|
22 |
-
|
23 |
-
os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = "https://cloud.langfuse.com/api/public/otel" # EU data region
|
24 |
-
# os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = "https://us.cloud.langfuse.com/api/public/otel" # US data region
|
25 |
-
os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"Authorization=Basic {LANGFUSE_AUTH}"
|
26 |
-
|
27 |
-
from opentelemetry.sdk.trace import TracerProvider
|
28 |
-
from openinference.instrumentation.smolagents import SmolagentsInstrumentor
|
29 |
-
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
30 |
-
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
31 |
-
|
32 |
-
trace_provider = TracerProvider()
|
33 |
-
trace_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter()))
|
34 |
-
|
35 |
-
SmolagentsInstrumentor().instrument(tracer_provider=trace_provider)
|
36 |
-
|
37 |
-
# Load ephemeris and timescale
|
38 |
-
planets = load('https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/de440.bsp')
|
39 |
ts = load.timescale()
|
40 |
|
41 |
# Define Zodiac signs and their boundaries (0° to 360° ecliptic longitude)
|
@@ -122,46 +97,14 @@ PRUNING_PHASE_COEFFS = {
|
|
122 |
"Waning Moon": 0.5,
|
123 |
}
|
124 |
|
125 |
-
|
|
|
126 |
def get_moon_info(date_time: str) -> dict:
|
127 |
"""
|
128 |
Returns Moon's Zodiac position, phase, and fertility and pruning indices for the given date/time.
|
129 |
|
130 |
-
The fertility and pruning indices are calculated as sum of sign and phase fertility values of the Moon position. Moon sign fertility
|
131 |
-
amounts up to 2.0 value and phase fertility value could be 1.0 max.
|
132 |
-
It is observed that when Moon is in different Zodiac signs, the fertility of new plants and impact of pruning differs.
|
133 |
-
When Moon is in fertile sign the plant is in the active phase, when all processes are particularly intense, and any intervention
|
134 |
-
such as pruning can be very traumatic for the plant. Here:
|
135 |
-
Most fertile signs: Taurus, Pisces, Cancer - Plants are in the active growth phase, juices and nutrients actively circulate
|
136 |
-
in the plant, and it is best time for fertilizers, harvasting cutting, vaccination, rooting.
|
137 |
-
Conditionally fertile: Scorpio
|
138 |
-
Neutral: Aries, Leo, Sagittarius, Capricorn
|
139 |
-
Conditionally sterile: Libra
|
140 |
-
Sterile: Gemini, Virgo, Aquarius
|
141 |
-
|
142 |
-
Fertility indices ranges from 0.0 to 3.0 where proportionaly
|
143 |
-
0 - minimal expected fertility
|
144 |
-
3.0 - most favorable fertility for platining,
|
145 |
-
and depends on type of plant (root crop or produce above ground).
|
146 |
-
|
147 |
-
Pruning indices ranges from 0 to 3 where proportionaly:
|
148 |
-
0 - pruning is not recommended as it causes most damage to tree and can lead to:
|
149 |
-
Increased sap production from the cut points
|
150 |
-
Increased vulnerability to infections
|
151 |
-
Delayed wound healing
|
152 |
-
Possible weakening of the plant.
|
153 |
-
Instead of pruning into fertile signs, you can do:
|
154 |
-
Crown formation
|
155 |
-
Pinching the shoots
|
156 |
-
Removing dead branches
|
157 |
-
Sanitary treatment
|
158 |
-
1.0 - pruning is not recommended,
|
159 |
-
2.0 - allowed only minimum or sanitary pruning,
|
160 |
-
3.0 - most favorable time for pruning.
|
161 |
-
|
162 |
Args:
|
163 |
date_time (str): ISO 8601 formatted datetime (YYYY-MM-DDTHH:MM:SS)
|
164 |
-
|
165 |
Returns:
|
166 |
dict: {
|
167 |
"zodiac_position": "Leo 15°30'",
|
@@ -184,10 +127,10 @@ def get_moon_info(date_time: str) -> dict:
|
|
184 |
moon = planets['moon']
|
185 |
sun = planets['sun']
|
186 |
|
187 |
-
# Calculate Moon's ecliptic longitude
|
188 |
astrometric = earth.at(t).observe(moon)
|
189 |
ecliptic_lat, ecliptic_lon, distance = astrometric.ecliptic_latlon()
|
190 |
-
|
191 |
|
192 |
# Calculate the phase angle using almanac.moon_phase
|
193 |
phase = almanac.moon_phase(planets, t)
|
@@ -247,15 +190,12 @@ def get_moon_info(date_time: str) -> dict:
|
|
247 |
except Exception as e:
|
248 |
raise ValueError(f"Error in get_moon_info: {str(e)}")
|
249 |
|
250 |
-
@tool
|
251 |
def get_current_time_in_timezone(timezone: str) -> str:
|
252 |
"""
|
253 |
Returns the current local time in the specified timezone with description.
|
254 |
-
|
255 |
Args:
|
256 |
timezone (str): A string representing a valid timezone (e.g., 'UTC')
|
257 |
-
|
258 |
-
|
259 |
Returns:
|
260 |
str: Formatted local time with timezone description
|
261 |
"""
|
@@ -266,14 +206,12 @@ def get_current_time_in_timezone(timezone: str) -> str:
|
|
266 |
except Exception as e:
|
267 |
return f"Error: {str(e)}"
|
268 |
|
269 |
-
@tool
|
270 |
def get_current_time_raw(timezone: str) -> str:
|
271 |
"""
|
272 |
Returns current local time in specified timezone as ISO 8601 string.
|
273 |
-
|
274 |
Args:
|
275 |
timezone (str): A string representing a valid timezone (e.g., 'UTC')
|
276 |
-
|
277 |
Returns:
|
278 |
str: Datetime in ISO 8601 format (YYYY-MM-DDTHH:MM:SS)
|
279 |
"""
|
@@ -284,7 +222,7 @@ def get_current_time_raw(timezone: str) -> str:
|
|
284 |
except Exception as e:
|
285 |
return f"Error: {str(e)}"
|
286 |
|
287 |
-
# Memory initialization
|
288 |
memory = SimpleMemory(
|
289 |
memory={
|
290 |
"location_provided": False,
|
@@ -296,23 +234,7 @@ memory = SimpleMemory(
|
|
296 |
}
|
297 |
)
|
298 |
|
299 |
-
#
|
300 |
-
final_answer = FinalAnswerTool()
|
301 |
-
model = HfApiModel(
|
302 |
-
max_tokens=2096,
|
303 |
-
temperature=0.5,
|
304 |
-
model_id="https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud/",
|
305 |
-
custom_role_conversions=None,
|
306 |
-
)
|
307 |
-
|
308 |
-
# Load image tool from Hub
|
309 |
-
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
310 |
-
|
311 |
-
# Load prompt templates
|
312 |
-
with open("prompts.yaml", 'r') as stream:
|
313 |
-
prompt_templates = yaml.safe_load(stream)
|
314 |
-
|
315 |
-
# Prompt template
|
316 |
prompt_templates = {
|
317 |
"main_prompt": """
|
318 |
Current state:
|
@@ -338,27 +260,27 @@ prompt_templates = {
|
|
338 |
"""
|
339 |
}
|
340 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
341 |
|
342 |
-
# Initialize agent
|
343 |
agent = CodeAgent(
|
344 |
model=model,
|
345 |
-
tools=[final_answer, get_moon_info, get_current_time_in_timezone, get_current_time_raw],
|
346 |
max_steps=10,
|
347 |
verbosity_level=1,
|
348 |
-
prompt_templates=prompt_templates
|
349 |
-
|
350 |
-
# allowed_imports=["numpy", "pandas"], # Explicitly permitted packages
|
351 |
-
# blocked_imports=["subprocess"], # Prevent system access
|
352 |
-
# ),
|
353 |
-
# safe_mode=True, # Enable safe code execution
|
354 |
-
# timeout=10, # Seconds before execution timeout
|
355 |
-
# max_memory=512, # MB memory limit
|
356 |
-
# file_system_access=False, # Disable disk write access
|
357 |
-
# network_access=False, # Block network operations
|
358 |
-
# max_code_iterations=100, # Prevent infinite loops
|
359 |
)
|
360 |
|
361 |
-
# Conversation handler
|
362 |
def conversation_handler(user_input, history):
|
363 |
global memory, agent
|
364 |
if memory["last_question"] is not None:
|
@@ -401,7 +323,7 @@ def conversation_handler(user_input, history):
|
|
401 |
memory["answer"] = output
|
402 |
return output
|
403 |
|
404 |
-
# Gradio interface
|
405 |
interface = Interface(
|
406 |
fn=conversation_handler,
|
407 |
inputs="text",
|
@@ -410,8 +332,6 @@ interface = Interface(
|
|
410 |
description="Ask about planting or pruning based on moon indices."
|
411 |
)
|
412 |
|
|
|
413 |
if __name__ == "__main__":
|
414 |
-
interface.launch()
|
415 |
-
|
416 |
-
# Change to your username and repo name
|
417 |
-
# agent.push_to_hub('sergeyo7/Garden_Magus')
|
|
|
1 |
+
from smolagents import CodeAgent, HfApiModel, load_tool
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
from langchain.memory import SimpleMemory
|
3 |
+
from tools.final_answer import FinalAnswerTool
|
4 |
from gradio import Interface
|
5 |
import os
|
6 |
import base64
|
7 |
+
import datetime
|
8 |
+
import pytz
|
9 |
+
from skyfield.api import load, Topos, load_file
|
10 |
+
from skyfield import almanac
|
11 |
|
12 |
+
# Load astronomical data (ephemeris) for moon calculations
|
13 |
+
planets = load('de421.bsp')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
ts = load.timescale()
|
15 |
|
16 |
# Define Zodiac signs and their boundaries (0° to 360° ecliptic longitude)
|
|
|
97 |
"Waning Moon": 0.5,
|
98 |
}
|
99 |
|
100 |
+
# Tool definitions
|
101 |
+
|
102 |
def get_moon_info(date_time: str) -> dict:
|
103 |
"""
|
104 |
Returns Moon's Zodiac position, phase, and fertility and pruning indices for the given date/time.
|
105 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
Args:
|
107 |
date_time (str): ISO 8601 formatted datetime (YYYY-MM-DDTHH:MM:SS)
|
|
|
108 |
Returns:
|
109 |
dict: {
|
110 |
"zodiac_position": "Leo 15°30'",
|
|
|
127 |
moon = planets['moon']
|
128 |
sun = planets['sun']
|
129 |
|
130 |
+
# Calculate Moon's ecliptic longitude
|
131 |
astrometric = earth.at(t).observe(moon)
|
132 |
ecliptic_lat, ecliptic_lon, distance = astrometric.ecliptic_latlon()
|
133 |
+
lon_thr = ecliptic_lon.degrees % 360
|
134 |
|
135 |
# Calculate the phase angle using almanac.moon_phase
|
136 |
phase = almanac.moon_phase(planets, t)
|
|
|
190 |
except Exception as e:
|
191 |
raise ValueError(f"Error in get_moon_info: {str(e)}")
|
192 |
|
|
|
193 |
def get_current_time_in_timezone(timezone: str) -> str:
|
194 |
"""
|
195 |
Returns the current local time in the specified timezone with description.
|
196 |
+
|
197 |
Args:
|
198 |
timezone (str): A string representing a valid timezone (e.g., 'UTC')
|
|
|
|
|
199 |
Returns:
|
200 |
str: Formatted local time with timezone description
|
201 |
"""
|
|
|
206 |
except Exception as e:
|
207 |
return f"Error: {str(e)}"
|
208 |
|
|
|
209 |
def get_current_time_raw(timezone: str) -> str:
|
210 |
"""
|
211 |
Returns current local time in specified timezone as ISO 8601 string.
|
212 |
+
|
213 |
Args:
|
214 |
timezone (str): A string representing a valid timezone (e.g., 'UTC')
|
|
|
215 |
Returns:
|
216 |
str: Datetime in ISO 8601 format (YYYY-MM-DDTHH:MM:SS)
|
217 |
"""
|
|
|
222 |
except Exception as e:
|
223 |
return f"Error: {str(e)}"
|
224 |
|
225 |
+
# Memory initialization for state management
|
226 |
memory = SimpleMemory(
|
227 |
memory={
|
228 |
"location_provided": False,
|
|
|
234 |
}
|
235 |
)
|
236 |
|
237 |
+
# Prompt template for the agent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
238 |
prompt_templates = {
|
239 |
"main_prompt": """
|
240 |
Current state:
|
|
|
260 |
"""
|
261 |
}
|
262 |
|
263 |
+
# Initialize model and tools
|
264 |
+
final_answer = FinalAnswerTool()
|
265 |
+
model = HfApiModel(
|
266 |
+
max_tokens=2096,
|
267 |
+
temperature=0.5,
|
268 |
+
model_id="https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud/",
|
269 |
+
custom_role_conversions=None,
|
270 |
+
)
|
271 |
+
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
272 |
|
273 |
+
# Initialize the agent
|
274 |
agent = CodeAgent(
|
275 |
model=model,
|
276 |
+
tools=[final_answer, get_moon_info, get_current_time_in_timezone, get_current_time_raw, image_generation_tool],
|
277 |
max_steps=10,
|
278 |
verbosity_level=1,
|
279 |
+
prompt_templates=prompt_templates,
|
280 |
+
memory=memory
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
281 |
)
|
282 |
|
283 |
+
# Conversation handler for multi-turn interactions
|
284 |
def conversation_handler(user_input, history):
|
285 |
global memory, agent
|
286 |
if memory["last_question"] is not None:
|
|
|
323 |
memory["answer"] = output
|
324 |
return output
|
325 |
|
326 |
+
# Set up Gradio interface
|
327 |
interface = Interface(
|
328 |
fn=conversation_handler,
|
329 |
inputs="text",
|
|
|
332 |
description="Ask about planting or pruning based on moon indices."
|
333 |
)
|
334 |
|
335 |
+
# Launch the application
|
336 |
if __name__ == "__main__":
|
337 |
+
interface.launch()
|
|
|
|
|
|