Spaces:
Sleeping
Sleeping
from smolagents import CodeAgent, HfApiModel, load_tool, tool | |
from langchain.memory import SimpleMemory | |
from tools.final_answer import FinalAnswerTool | |
from gradio import Interface | |
import os | |
import base64 | |
import datetime | |
import pytz | |
from skyfield.api import load, Topos, load_file | |
from skyfield import almanac | |
# Load astronomical data (ephemeris) for moon calculations | |
planets = load('de421.bsp') | |
ts = load.timescale() | |
# Define Zodiac signs and their boundaries (0° to 360° ecliptic longitude) | |
ZODIAC_SIGNS = [ | |
("Aries", 0, 30), | |
("Taurus", 30, 60), | |
("Gemini", 60, 90), | |
("Cancer", 90, 120), | |
("Leo", 120, 150), | |
("Virgo", 150, 180), | |
("Libra", 180, 210), | |
("Scorpio", 210, 240), | |
("Sagittarius", 240, 270), | |
("Capricorn", 270, 300), | |
("Aquarius", 300, 330), | |
("Pisces", 330, 360), | |
] | |
# Moon phase boundaries (0° to 360° phase angle) for display purposes | |
MOON_PHASES = [ | |
("New Moon", 0, 45), | |
("Waxing Crescent", 45, 90), | |
("First Quarter", 90, 135), | |
("Waxing Gibbous", 135, 180), | |
("Full Moon", 180, 225), | |
("Waning Gibbous", 225, 270), | |
("Last Quarter", 270, 315), | |
("Waning Crescent", 315, 360), | |
] | |
# Fertility sign coefficients (applicable to all plants) | |
FERTILITY_SIGN_COEFFS = { | |
"Aries": 1, | |
"Taurus": 2, | |
"Gemini": 0, | |
"Cancer": 2, | |
"Leo": 1, | |
"Virgo": 0, | |
"Libra": 0.5, | |
"Scorpio": 1.5, | |
"Sagittarius": 1, | |
"Capricorn": 1, | |
"Aquarius": 0, | |
"Pisces": 2, | |
} | |
# Pruning sign coefficients (applicable to all plants) | |
PRUNING_SIGN_COEFFS = { | |
"Aries": 1, | |
"Taurus": 0, | |
"Gemini": 2, | |
"Cancer": 0, | |
"Leo": 1, | |
"Virgo": 2, | |
"Libra": 1.5, | |
"Scorpio": 0.5, | |
"Sagittarius": 1, | |
"Capricorn": 1, | |
"Aquarius": 2, | |
"Pisces": 0, | |
} | |
# Fertility phase coefficients for above-ground plants | |
FERTILITY_PHASE_COEFFS_ABOVE = { | |
"New Moon": 0, | |
"Waxing Moon": 1, | |
"Full Moon": 0, | |
"Waning Moon": 0.5, | |
} | |
# Fertility phase coefficients for root crops | |
FERTILITY_PHASE_COEFFS_ROOT = { | |
"New Moon": 0, | |
"Waxing Moon": 0.5, | |
"Full Moon": 0, | |
"Waning Moon": 1, | |
} | |
# Pruning phase coefficients | |
PRUNING_PHASE_COEFFS = { | |
"New Moon": 0, | |
"Waxing Moon": 1, | |
"Full Moon": 0, | |
"Waning Moon": 0.5, | |
} | |
# Tool definitions | |
def get_moon_info(date_time: str) -> dict: | |
""" | |
Returns Moon's Zodiac position, phase, and fertility and pruning indices for the given date/time. | |
Args: | |
date_time (str): ISO 8601 formatted datetime (YYYY-MM-DDTHH:MM:SS) | |
Returns: | |
dict: { | |
"zodiac_position": "Leo 15°30'", | |
"moon_phase": "Waxing Gibbous", | |
"fertility_above_ground": 2.0, | |
"fertility_root_crop": 1.5, | |
"pruning": 2.0 | |
} | |
""" | |
try: | |
# Parse input datetime and localize to UTC | |
user_time = datetime.datetime.strptime(date_time, "%Y-%m-%dT%H:%M:%S") | |
user_time = pytz.utc.localize(user_time) | |
# Use loaded ephemeris and timescale | |
t = ts.from_datetime(user_time) | |
# Define celestial bodies | |
earth = planets['earth'] | |
moon = planets['moon'] | |
sun = planets['sun'] | |
# Calculate Moon's ecliptic longitude | |
astrometric = earth.at(t).observe(moon) | |
ecliptic_lat, ecliptic_lon, distance = astrometric.ecliptic_latlon() | |
lon_deg = ecliptic_lon.degrees % 360 | |
# Calculate the phase angle using almanac.moon_phase | |
phase = almanac.moon_phase(planets, t) | |
phase_angle = phase.degrees | |
# Determine Zodiac sign and position | |
zodiac_sign = "Unknown" | |
position_degrees = 0 | |
for sign, start, end in ZODIAC_SIGNS: | |
if start <= lon_deg < end: | |
zodiac_sign = sign | |
position_degrees = lon_deg - start | |
break | |
# Format position to degrees and minutes | |
degrees = int(position_degrees) | |
minutes = int((position_degrees % 1) * 60) | |
position_str = f"{zodiac_sign} {degrees}°{minutes:02}'" | |
# Determine moon phase for display | |
moon_phase = "Unknown" | |
for phase, start, end in MOON_PHASES: | |
if start <= phase_angle < end: | |
moon_phase = phase | |
break | |
# Determine phase category for indices with 15° orbis for New and Full Moon | |
if (phase_angle >= 345 or phase_angle < 15): | |
phase_category = "New Moon" # 345° to 15° (30° total orbis) | |
elif 15 <= phase_angle < 165: | |
phase_category = "Waxing Moon" | |
elif 165 <= phase_angle < 195: | |
phase_category = "Full Moon" # 165° to 195° (30° total orbis) | |
elif 195 <= phase_angle < 345: | |
phase_category = "Waning Moon" | |
else: | |
phase_category = "Unknown" | |
# Calculate fertility and pruning indices | |
if zodiac_sign in FERTILITY_SIGN_COEFFS and phase_category in FERTILITY_PHASE_COEFFS_ABOVE: | |
fertility_above_ground = FERTILITY_SIGN_COEFFS[zodiac_sign] + FERTILITY_PHASE_COEFFS_ABOVE[phase_category] | |
fertility_root_crop = FERTILITY_SIGN_COEFFS[zodiac_sign] + FERTILITY_PHASE_COEFFS_ROOT[phase_category] | |
pruning = PRUNING_SIGN_COEFFS[zodiac_sign] + PRUNING_PHASE_COEFFS[phase_category] | |
else: | |
fertility_above_ground = None | |
fertility_root_crop = None | |
pruning = None | |
return { | |
"zodiac_position": position_str, | |
"moon_phase": moon_phase, | |
"fertility_above_ground": fertility_above_ground, | |
"fertility_root_crop": fertility_root_crop, | |
"pruning": pruning | |
} | |
except Exception as e: | |
raise ValueError(f"Error in get_moon_info: {str(e)}") | |
def get_current_time_in_timezone(timezone: str) -> str: | |
""" | |
Returns the current local time in the specified timezone with description. | |
Args: | |
timezone (str): A string representing a valid timezone (e.g., 'UTC') | |
Returns: | |
str: Formatted local time with timezone description | |
""" | |
try: | |
tz = pytz.timezone(timezone) | |
now = datetime.datetime.now(tz) | |
return f"Local time in {timezone}: {now.strftime('%Y-%m-%d %H:%M:%S')}" | |
except Exception as e: | |
return f"Error: {str(e)}" | |
def get_current_time_raw(timezone: str) -> str: | |
""" | |
Returns current local time in specified timezone as ISO 8601 string. | |
Args: | |
timezone (str): A string representing a valid timezone (e.g., 'UTC') | |
Returns: | |
str: Datetime in ISO 8601 format (YYYY-MM-DDTHH:MM:SS) | |
""" | |
try: | |
tz = pytz.timezone(timezone) | |
now = datetime.datetime.now(tz) | |
return now.strftime("%Y-%m-%dT%H:%M:%S") | |
except Exception as e: | |
return f"Error: {str(e)}" | |
# Memory initialization for state management | |
memory = SimpleMemory( | |
memory={ | |
"location_provided": False, | |
"plant": None, | |
"root_crop": None, | |
"location_cautions": "", | |
"answer": "", | |
"last_question": None | |
} | |
) | |
# Prompt template for the agent | |
prompt_templates = { | |
"main_prompt": """ | |
Current state: | |
- location_provided: {memory[location_provided]} | |
- plant: {memory[plant]} | |
- root_crop: {memory[root_crop]} | |
- location_cautions: {memory[location_cautions]} | |
- answer: {memory[answer]} | |
- last_question: {memory[last_question]} | |
User's input: {input} | |
Instructions: | |
1. If responding to a clarification question (last_question is not None), interpret the input as the answer to that question and update the state accordingly. | |
2. Otherwise, process the user's request as follows: | |
- Check if a plant name is provided and recognized. If not, ask "Please specify the plant you are interested in." If recognized, determine if it’s a root crop or above-ground plant (e.g., known plants: potato=root, tomato=above-ground). If unrecognized, ask "Is this plant a root crop? (yes/no)". | |
- Check if a location is provided. If yes, set location_provided to true. If the location is not on Earth (e.g., "Moon", "Mars"), set location_cautions to "Salute you explorer! Moon indices are Earth-specific due to gravitational and tidal influences. For other planets, develop indices based on local celestial cycles." and use it as the final answer. If on Earth, ask "Is this location suitable for outdoor planting? (yes/no)" to determine suitability. | |
- Determine if the request is about planting or pruning. For planting, ensure plant is defined (ask if not), then calculate the fertility index using get_moon_info. For pruning, calculate the pruning index. | |
- If location_cautions is not empty, append it to the answer. | |
3. When asking a question, format your response as: | |
"Action: Ask user\nQuestion: [your question]" | |
4. When all information is gathered, calculate the answer and call FinalAnswerTool. | |
""" | |
} | |
# Initialize model and tools | |
final_answer = FinalAnswerTool() | |
model = HfApiModel( | |
max_tokens=2096, | |
temperature=0.5, | |
model_id="https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud/", | |
custom_role_conversions=None, | |
) | |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) | |
# Initialize the agent without the 'memory' parameter | |
agent = CodeAgent( | |
model=model, | |
tools=[final_answer, get_moon_info, get_current_time_in_timezone, get_current_time_raw], | |
max_steps=10, | |
verbosity_level=1, | |
prompt_templates=prompt_templates, | |
) | |
# Conversation handler for multi-turn interactions | |
def conversation_handler(user_input, history): | |
global memory, agent | |
if memory["last_question"] is not None: | |
if memory["last_question"] == "plant": | |
memory["plant"] = user_input | |
known_plants = {"potato": True, "tomato": False} | |
if user_input in known_plants: | |
memory["root_crop"] = known_plants[user_input] | |
else: | |
memory["last_question"] = "root_crop" | |
return "Action: Ask user\nQuestion: Is this plant a root crop? (yes/no)" | |
elif memory["last_question"] == "root_crop": | |
memory["root_crop"] = user_input.lower() in ["yes", "y"] | |
memory["last_question"] = None | |
elif memory["last_question"] == "location_suitability": | |
if user_input.lower() in ["no", "n"]: | |
memory["location_cautions"] = "Ensure required conditions for the plant (e.g., indoor) before relying on the fertility indices." | |
else: | |
memory["location_cautions"] = "" | |
memory["last_question"] = None | |
# Update the prompt with current memory state | |
current_prompt = prompt_templates["main_prompt"].format( | |
memory=memory.memory, # Pass the memory dictionary directly | |
input=user_input | |
) | |
# Run the agent with the updated prompt | |
output = agent.run(current_prompt) | |
if "Action: Ask user" in output: | |
question = output.split("Question: ")[1].strip() | |
if "plant" in question.lower(): | |
memory["last_question"] = "plant" | |
elif "root crop" in question.lower(): | |
memory["last_question"] = "root_crop" | |
elif "suitable for outdoor" in question.lower(): | |
memory["last_question"] = "location_suitability" | |
memory["location_provided"] = True | |
return question | |
else: | |
if "Salute you explorer!" in output: | |
memory["location_cautions"] = output | |
memory["answer"] = output | |
elif memory["location_cautions"]: | |
memory["answer"] = output + " " + memory["location_cautions"] | |
else: | |
memory["answer"] = output | |
return output | |
# Set up Gradio interface | |
interface = Interface( | |
fn=conversation_handler, | |
inputs="text", | |
outputs="text", | |
title="Garden Magus", | |
description="Ask about planting or pruning based on moon indices." | |
) | |
# Launch the application | |
if __name__ == "__main__": | |
interface.launch() |