cryogenic22 commited on
Commit
3615e00
·
verified ·
1 Parent(s): 3944ead

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -113
app.py CHANGED
@@ -1,53 +1,24 @@
1
- """
2
- Streamlined Streamlit application for AI Astrology app with automatic timezone detection.
3
- """
4
-
5
  import streamlit as st
6
  from datetime import datetime
7
  from geopy.geocoders import Nominatim
8
  from geopy.exc import GeocoderTimedOut, GeocoderServiceError
9
  from timezonefinder import TimezoneFinder
10
  from dotenv import load_dotenv
11
- from astro_core import ChartCalculator # Assuming you have the astro_core.py file
12
- from ai_interpreter import AstroAI # Assuming you have the ai_interpreter.py file
13
 
14
- # Load environment variables (if you are using .env for API keys, etc.)
15
  load_dotenv()
16
 
17
- def init_session_state():
18
- """Initialize session state variables"""
19
- if 'birth_chart' not in st.session_state:
20
- st.session_state.birth_chart = None
21
- if 'chat_history' not in st.session_state:
22
- st.session_state.chat_history = []
23
- if 'user_info' not in st.session_state:
24
- st.session_state.user_info = None
25
- if 'calculation_error' not in st.session_state:
26
- st.session_state.calculation_error = None
27
-
28
  def get_location_details(location_name: str) -> dict:
29
- """Get coordinates and timezone from location name"""
30
  try:
31
- # Initialize geocoder and timezone finder
32
  geolocator = Nominatim(user_agent="ai_astrology_app")
33
  tf = TimezoneFinder()
34
-
35
- # Get location
36
  location = geolocator.geocode(location_name)
37
  if location:
38
  latitude, longitude = location.latitude, location.longitude
39
-
40
- # Get timezone string for the coordinates
41
  timezone_str = tf.timezone_at(lng=longitude, lat=latitude)
42
  if not timezone_str:
43
- timezone_str = 'UTC' # Fallback to UTC if timezone not found
44
-
45
- return {
46
- 'latitude': latitude,
47
- 'longitude': longitude,
48
- 'timezone': timezone_str,
49
- 'error': None
50
- }
51
  return {'error': 'Location not found'}
52
  except (GeocoderTimedOut, GeocoderServiceError) as e:
53
  return {'error': f'Geocoding error: {str(e)}'}
@@ -55,113 +26,57 @@ def get_location_details(location_name: str) -> dict:
55
  return {'error': f'Unexpected error: {str(e)}'}
56
 
57
  def calculate_chart(user_data: dict):
58
- """Calculate birth chart based on user data"""
59
- try:
60
- calculator = ChartCalculator()
61
- birth_datetime = datetime.combine(user_data['birth_date'], user_data['birth_time'])
62
-
63
- chart_data = calculator.calculate_birth_chart(
64
- birth_datetime,
65
- user_data['latitude'],
66
- user_data['longitude'],
67
- user_data['timezone']
68
- )
69
-
70
- # Check for calculation errors
71
- if 'error' in chart_data:
72
- st.session_state.calculation_error = chart_data['error']
73
- return None
74
-
75
- return chart_data
76
- except Exception as e:
77
- st.session_state.calculation_error = str(e)
78
- return None
79
 
80
  def main():
81
  st.title("AI Astrology Assistant")
82
 
83
- # Initialize session state
84
- init_session_state()
85
-
86
- # User Information Form
87
  with st.form("user_info_form"):
88
- st.subheader("Personal Information")
89
-
90
- col1, col2 = st.columns(2)
91
- with col1:
92
- name = st.text_input("Full Name")
93
- gender = st.selectbox("Gender", ["Male", "Female", "Non-binary", "Prefer not to say"])
94
- birth_date = st.date_input("Birth Date", min_value=datetime(1900, 1, 1))
95
-
96
- with col2:
97
- birth_time = st.time_input("Birth Time")
98
- birth_place = st.text_input("Birth Place (City, Country)")
99
-
100
  submit_button = st.form_submit_button("Generate Birth Chart")
101
 
102
  if submit_button:
103
  if not birth_place:
104
  st.error("Please enter your birth place.")
105
  else:
106
- with st.spinner("Looking up location details..."):
107
  location_details = get_location_details(birth_place)
108
 
109
  if location_details.get('error'):
110
  st.error(location_details['error'])
111
  else:
112
- # Reset error state
113
- st.session_state.calculation_error = None
114
-
115
- # Store user information
116
- st.session_state.user_info = {
117
  'name': name,
118
- 'gender': gender,
119
  'birth_date': birth_date,
120
  'birth_time': birth_time,
121
- 'birth_place': birth_place,
122
  'latitude': location_details['latitude'],
123
  'longitude': location_details['longitude'],
124
  'timezone': location_details['timezone']
125
  }
126
 
127
- # Display detected timezone
128
- st.info(f"Detected timezone for {birth_place}: {location_details['timezone']}")
129
-
130
- # Calculate birth chart
131
- with st.spinner("Calculating your birth chart..."):
132
- st.session_state.birth_chart = calculate_chart(st.session_state.user_info)
133
 
134
- if st.session_state.birth_chart:
 
 
135
  st.success("Birth chart calculated successfully!")
136
- elif st.session_state.calculation_error:
137
- st.error(f"Error calculating birth chart: {st.session_state.calculation_error}")
138
-
139
- # Display areas (only show if birth chart is calculated)
140
- if st.session_state.birth_chart and st.session_state.user_info:
141
- col1, col2 = st.columns([2, 3])
142
-
143
- with col1:
144
- st.subheader(f"Birth Chart for {st.session_state.user_info['name']}")
145
-
146
- # Display birth details
147
- st.write("**Birth Details:**")
148
- st.write(f"Date: {st.session_state.user_info['birth_date'].strftime('%B %d, %Y')}")
149
- st.write(f"Time: {st.session_state.user_info['birth_time'].strftime('%H:%M')}")
150
- st.write(f"Location: {st.session_state.user_info['birth_place']}")
151
- st.write(f"Timezone: {st.session_state.user_info['timezone']}")
152
-
153
- # Display planetary positions
154
- st.write("**Planetary Positions:**")
155
- for planet, data in st.session_state.birth_chart['planets'].items():
156
- st.write(f"{planet}: {data['degrees']:.2f}° {data['sign']}")
157
-
158
- with col2:
159
- st.subheader("Graphical Astrology Chart")
160
- if st.button("Show Astrology Chart"):
161
- # Generate and display graphical chart
162
- calculator = ChartCalculator()
163
- with st.spinner("Generating graphical chart..."):
164
- calculator.draw_chart(st.session_state.birth_chart)
165
 
166
  if __name__ == "__main__":
167
  main()
 
 
 
 
 
1
  import streamlit as st
2
  from datetime import datetime
3
  from geopy.geocoders import Nominatim
4
  from geopy.exc import GeocoderTimedOut, GeocoderServiceError
5
  from timezonefinder import TimezoneFinder
6
  from dotenv import load_dotenv
7
+ from astro_core import ChartCalculator
 
8
 
 
9
  load_dotenv()
10
 
 
 
 
 
 
 
 
 
 
 
 
11
  def get_location_details(location_name: str) -> dict:
 
12
  try:
 
13
  geolocator = Nominatim(user_agent="ai_astrology_app")
14
  tf = TimezoneFinder()
 
 
15
  location = geolocator.geocode(location_name)
16
  if location:
17
  latitude, longitude = location.latitude, location.longitude
 
 
18
  timezone_str = tf.timezone_at(lng=longitude, lat=latitude)
19
  if not timezone_str:
20
+ timezone_str = 'UTC'
21
+ return {'latitude': latitude, 'longitude': longitude, 'timezone': timezone_str, 'error': None}
 
 
 
 
 
 
22
  return {'error': 'Location not found'}
23
  except (GeocoderTimedOut, GeocoderServiceError) as e:
24
  return {'error': f'Geocoding error: {str(e)}'}
 
26
  return {'error': f'Unexpected error: {str(e)}'}
27
 
28
  def calculate_chart(user_data: dict):
29
+ calculator = ChartCalculator()
30
+ birth_datetime = datetime.combine(user_data['birth_date'], user_data['birth_time'])
31
+ return calculator.calculate_birth_chart(
32
+ birth_datetime,
33
+ user_data['latitude'],
34
+ user_data['longitude'],
35
+ user_data['timezone']
36
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  def main():
39
  st.title("AI Astrology Assistant")
40
 
 
 
 
 
41
  with st.form("user_info_form"):
42
+ name = st.text_input("Full Name")
43
+ birth_date = st.date_input("Birth Date", min_value=datetime(1900, 1, 1))
44
+ birth_time = st.time_input("Birth Time")
45
+ birth_place = st.text_input("Birth Place (City, Country)")
 
 
 
 
 
 
 
 
46
  submit_button = st.form_submit_button("Generate Birth Chart")
47
 
48
  if submit_button:
49
  if not birth_place:
50
  st.error("Please enter your birth place.")
51
  else:
52
+ with st.spinner("Fetching location details..."):
53
  location_details = get_location_details(birth_place)
54
 
55
  if location_details.get('error'):
56
  st.error(location_details['error'])
57
  else:
58
+ user_data = {
 
 
 
 
59
  'name': name,
 
60
  'birth_date': birth_date,
61
  'birth_time': birth_time,
 
62
  'latitude': location_details['latitude'],
63
  'longitude': location_details['longitude'],
64
  'timezone': location_details['timezone']
65
  }
66
 
67
+ with st.spinner("Calculating birth chart..."):
68
+ birth_chart = calculate_chart(user_data)
 
 
 
 
69
 
70
+ if 'error' in birth_chart:
71
+ st.error(f"Error: {birth_chart['error']}")
72
+ else:
73
  st.success("Birth chart calculated successfully!")
74
+ st.write("**Planetary Positions:**")
75
+ for planet, data in birth_chart['planets'].items():
76
+ if 'error' in data:
77
+ st.write(f"{planet}: {data['error']}")
78
+ else:
79
+ st.write(f"{planet}: {data['degrees']:.2f}° {data['sign']}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  if __name__ == "__main__":
82
  main()