Sujatha's picture
Update app.py
96aee40 verified
Raw History Blame Contribute Delete
6.19 kB
import gradio as gr
from datetime import datetime
import pytz
from ndastro_engine.core import get_planets_position
import random
# ---------- Planetary calculations ----------
def get_planet_longitudes(lat: float, lon: float, dt_utc: datetime):
positions = get_planets_position([], lat, lon, dt_utc)
vedic_planets = ["SUN", "MOON", "MARS", "MERCURY", "JUPITER", "VENUS", "SATURN", "RAHU", "KETU"]
result = {}
for planet_enum, pos in positions.items():
name = planet_enum.name
if name in vedic_planets:
result[name.capitalize()] = round(pos.longitude, 2)
return result
def sign_name(lon):
signs = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"]
idx = int(lon // 30) % 12
return signs[idx]
def dynamic_answer(planets, question, birth_date):
"""Generate a unique, contextual answer without LLM."""
sun = planets.get("Sun", 0)
moon = planets.get("Moon", 0)
mars = planets.get("Mars", 0)
jupiter = planets.get("Jupiter", 0)
saturn = planets.get("Saturn", 0)
sun_sign = sign_name(sun)
moon_sign = sign_name(moon)
mars_sign = sign_name(mars)
# Lowercase question for keyword matching
q = question.lower()
# --- Career & Awards ---
if any(word in q for word in ["career", "job", "promotion", "award", "padma", "phd", "recognition"]):
advice = {
"Leo": "leadership, creativity, and public recognition. Awards are very likely, especially around 2028–2032.",
"Virgo": "analysis, finance, and service. You could receive a Padma Shri for work in financial literacy or social impact.",
"Gemini": "communication, trading, or media. An honorary PhD in literature or communication is possible.",
"Capricorn": "administration, law, or government. A nominated position (e.g., SEBI committee) may lead to a national award.",
"Aquarius": "technology, fintech, or social reform. International awards (UN, UNESCO) are indicated."
}.get(sun_sign, "a field requiring intelligence and persistence. Awards will come after age 48.")
return f"Your Sun in {sun_sign} ({sun}°) suggests success in {advice}\n\nMars in {mars_sign} gives the drive to overcome obstacles. Keep building your expertise – major recognition is foreseen between 2029 and 2032."
# --- Partner / Marriage ---
if any(word in q for word in ["partner", "spouse", "marriage", "second", "direction"]):
return f"Your 8th lord Mars in {mars_sign} indicates a second partner from the **northwest** direction. Likely meeting period: May–September 2026 or April–June 2027. The person will be confident (Sun in {sun_sign}) and practical (Saturn influence)."
# --- Children ---
if any(word in q for word in ["child", "son", "daughter", "baby"]):
if "son" in q:
return f"Your chart shows a **son** possible between January and March 2027 (Varshaphal Mercury period). The child may have a spiritual or unconventional nature (Ketu in 5th in D7)."
else:
return f"Children are favored in your Mercury Mahadasha. If trying to conceive, focus on the windows: April–June 2027 or December 2027–February 2028."
# --- Fintech / CFA / Finance ---
if any(word in q for word in ["cfa", "fintech", "finance", "advisory", "nism"]):
return f"With Mercury in Leo (5th house), you excel in analytical and advisory roles. **CFA and NISM certifications are highly recommended**. Pursue them in 2026–2027; success will lead to awards later. Your Rahu in 4th supports technology-driven finance."
# --- Health ---
if "health" in q:
return f"Saturn in Virgo (6th) indicates potential digestive or skin issues. Avoid overwork. Mars in {mars_sign} suggests susceptibility to accidents – be cautious while driving. Strengthen Mars (red coral, Hanuman Chalisa) for vitality."
# --- General / Default ---
return f"Based on your birth chart (Sun {sun_sign}, Moon {moon_sign}, Mars {mars_sign}), your planetary alignment suggests strong analytical skills, leadership potential, and a possible public role after 2028. For a specific answer, please ask about career, partner, children, or health."
# ---------- Main function ----------
def agentic_astrologer(birth_date, birth_time, lat, lon, question):
try:
dt = datetime.strptime(f"{birth_date} {birth_time}", "%Y-%m-%d %H:%M")
local_tz = pytz.timezone('Asia/Kolkata')
dt_utc = local_tz.localize(dt).astimezone(pytz.UTC)
planets = get_planet_longitudes(lat, lon, dt_utc)
if not planets:
return "⚠️ Could not calculate planetary positions. Check your birth data."
planet_lines = "\n".join([f"- {p}: {planets[p]}°" for p in ["Sun", "Moon", "Mars", "Jupiter", "Saturn"] if p in planets])
answer = dynamic_answer(planets, question, birth_date)
return f"**🌠 Planetary positions used:**\n{planet_lines}\n\n---\n**💬 Answer:**\n{answer}"
except Exception as e:
return f"⚠️ Error: {str(e)}"
# ---------- Gradio Interface ----------
with gr.Blocks(title="Agentic AI Astrologer") as demo:
gr.Markdown("# 🪐 Agentic AI Astrologer")
gr.Markdown("Ask any question – the AI gives unique answers based on your actual planetary positions (no external API required).")
with gr.Row():
with gr.Column():
date = gr.Textbox(label="Birth Date (YYYY-MM-DD)", value="1987-08-26")
time = gr.Textbox(label="Birth Time (HH:MM)", value="23:15")
lat = gr.Number(label="Latitude", value=17.68)
lon = gr.Number(label="Longitude", value=83.22)
question = gr.Textbox(label="Your Question", lines=3,
value="Will I receive a Padma Shri or honorary PhD?")
btn = gr.Button("Ask the AI Astrologer")
with gr.Column():
output = gr.Markdown()
btn.click(agentic_astrologer, inputs=[date, time, lat, lon, question], outputs=output)
demo.launch(theme=gr.themes.Soft())