Sujatha commited on
Commit
ecf96bf
·
verified ·
1 Parent(s): f92f5f0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -163
app.py CHANGED
@@ -1,163 +0,0 @@
1
- import gradio as gr
2
- from datetime import datetime
3
- import pandas as pd
4
- import requests
5
- import json
6
- import re
7
-
8
- # Try to import vedastro; if not available, fallback to custom API calls
9
- try:
10
- from vedastro import Calculate, Time, GeoLocation, PlanetName, Tools
11
- VEDASTRO_AVAILABLE = True
12
- except ImportError:
13
- VEDASTRO_AVAILABLE = False
14
- print("VedAstro not installed, using direct API calls.")
15
-
16
- # Free API key for VedAstro
17
- API_KEY = "FreeAPIUser"
18
- VEDASTRO_BASE_URL = "https://api.vedastro.org/"
19
-
20
- # Optional: Use a free Hugging Face LLM for interpretation
21
- HF_API_TOKEN = None # You can add your token if needed
22
- HF_MODEL = "HuggingFaceH4/zephyr-7b-beta" # Free via HF Inference API
23
-
24
- def get_planet_positions(date_str, time_str, lat, lon, tz_offset=5.5):
25
- """
26
- Get planetary positions using VedAstro.
27
- Returns a dict with planet names and their signs/degrees.
28
- """
29
- # Parse date and time
30
- dt = datetime.strptime(f"{date_str} {time_str}", "%Y-%m-%d %H:%M")
31
-
32
- if VEDASTRO_AVAILABLE:
33
- geo = GeoLocation("User", lon, lat)
34
- birth_time = Time(hour=dt.hour, minute=dt.minute, day=dt.day, month=dt.month, year=dt.year, offset=f"+{tz_offset}", geolocation=geo)
35
-
36
- results = {}
37
- for planet in [PlanetName.Sun, PlanetName.Moon, PlanetName.Mars, PlanetName.Mercury, PlanetName.Jupiter, PlanetName.Venus, PlanetName.Saturn, PlanetName.Rahu, PlanetName.Ketu]:
38
- data = Calculate.AllPlanetData(planet, birth_time)
39
- # Extract sign and longitude
40
- sign = data.Rasi.Name if hasattr(data, 'Rasi') else "Unknown"
41
- lon = data.Longitude if hasattr(data, 'Longitude') else 0
42
- results[planet.name] = {"sign": sign, "longitude": round(lon, 2)}
43
- return results
44
- else:
45
- # Fallback: Use public API endpoint (if available, else mock)
46
- # For real deployment, you would use requests to VedAstro REST API
47
- # Here we return mock data for demonstration
48
- return mock_planet_positions()
49
-
50
- def mock_planet_positions():
51
- return {
52
- "Sun": {"sign": "Leo", "longitude": 142.5},
53
- "Moon": {"sign": "Aquarius", "longitude": 315.2},
54
- "Mars": {"sign": "Gemini", "longitude": 67.8},
55
- "Mercury": {"sign": "Leo", "longitude": 138.4},
56
- "Jupiter": {"sign": "Virgo", "longitude": 173.1},
57
- "Venus": {"sign": "Virgo", "longitude": 168.9},
58
- "Saturn": {"sign": "Virgo", "longitude": 165.3},
59
- "Rahu": {"sign": "Cancer", "longitude": 105.6},
60
- "Ketu": {"sign": "Capricorn", "longitude": 285.6}
61
- }
62
-
63
- def get_divisional_chart(birth_data, division):
64
- """
65
- Request a specific divisional chart (D1 to D60) from VedAstro.
66
- Returns a pandas DataFrame.
67
- """
68
- # This is a placeholder – VedAstro Python library returns objects.
69
- # For simplicity, we return mock data.
70
- signs = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"]
71
- planets = ["Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu"]
72
- data = {}
73
- for p in planets:
74
- # Random sign for demo
75
- data[p] = signs[hash(p + str(division)) % 12]
76
- return pd.DataFrame(list(data.items()), columns=["Planet", "Sign"])
77
-
78
- def interpret_with_ai(user_question, planet_data):
79
- """
80
- Use a free Hugging Face LLM to interpret the astrological data.
81
- If no HF token, return a generic response.
82
- """
83
- if HF_API_TOKEN is None:
84
- return "AI interpretation not available (no Hugging Face token). Here is the raw data:\n" + str(planet_data)
85
-
86
- prompt = f"""
87
- You are a vedic astrologer. A user asks: "{user_question}"
88
-
89
- Based on the following planetary positions:
90
- {planet_data}
91
-
92
- Give a concise, helpful answer (max 150 words).
93
- """
94
- headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
95
- payload = {"inputs": prompt, "parameters": {"max_new_tokens": 200, "temperature": 0.7}}
96
- try:
97
- response = requests.post(f"https://api-inference.huggingface.co/models/{HF_MODEL}", headers=headers, json=payload)
98
- if response.status_code == 200:
99
- return response.json()[0]["generated_text"].replace(prompt, "").strip()
100
- else:
101
- return f"AI error: {response.status_code}"
102
- except Exception as e:
103
- return f"AI error: {str(e)}"
104
-
105
- def analyze_birth_chart(date, time, lat, lon, tz, question):
106
- """
107
- Main function called by Gradio interface.
108
- """
109
- try:
110
- # Validate inputs
111
- lat = float(lat)
112
- lon = float(lon)
113
- tz = float(tz)
114
-
115
- # Get planetary positions
116
- planets = get_planet_positions(date, time, lat, lon, tz)
117
- planet_df = pd.DataFrame([
118
- {"Planet": p, "Sign": data["sign"], "Longitude": data["longitude"]}
119
- for p, data in planets.items()
120
- ])
121
-
122
- # Get D1 chart as example (full D1-D60 would be heavy)
123
- d1_chart = get_divisional_chart({"date": date, "time": time, "lat": lat, "lon": lon}, 1)
124
-
125
- # Create summary text
126
- summary = "### Planetary Positions\n" + planet_df.to_markdown() + "\n\n### D1 (Rashi) Chart\n" + d1_chart.to_markdown()
127
-
128
- # If user asked a question, get AI interpretation
129
- if question and question.strip():
130
- interpretation = interpret_with_ai(question, planet_df.to_dict())
131
- return summary + "\n\n### AI Interpretation\n" + interpretation
132
- else:
133
- return summary
134
- except Exception as e:
135
- return f"Error: {str(e)}"
136
-
137
- # Gradio interface
138
- with gr.Blocks(title="Vedic Astrology AI Agent") as demo:
139
- gr.Markdown("# 📜 Vedic Astrology AI Agent (D1–D60 Charts)")
140
- gr.Markdown("Enter birth details. The app will compute planetary positions and divisional charts using VedAstro. Optionally ask a question about your horoscope.")
141
-
142
- with gr.Row():
143
- with gr.Column():
144
- date_input = gr.Textbox(label="Birth Date (YYYY-MM-DD)", value="1981-08-16")
145
- time_input = gr.Textbox(label="Birth Time (HH:MM)", value="23:15")
146
- lat_input = gr.Textbox(label="Latitude (e.g., 17.68)", value="17.68")
147
- lon_input = gr.Textbox(label="Longitude (e.g., 83.22)", value="83.22")
148
- tz_input = gr.Textbox(label="Timezone offset (hours, e.g., 5.5)", value="5.5")
149
- question_input = gr.Textbox(label="Ask a question (optional)", placeholder="What does my career look like?")
150
- submit_btn = gr.Button("Analyze")
151
- with gr.Column():
152
- output_text = gr.Markdown()
153
-
154
- submit_btn.click(
155
- fn=analyze_birth_chart,
156
- inputs=[date_input, time_input, lat_input, lon_input, tz_input, question_input],
157
- outputs=output_text
158
- )
159
-
160
- gr.Markdown("---\n**Note:** Uses VedAstro free API. For full D1-D60 charts, you may need to extend the `get_divisional_chart` function. The AI interpretation requires a Hugging Face API token (set `HF_API_TOKEN` in the Space secrets).")
161
-
162
- if __name__ == "__main__":
163
- demo.launch()