# Astrology & Synastry Compatibility Project - Complete Overview

A professional-grade astrology platform designed to calculate birth charts, analyze moon phases, and determine synastry compatibility between two individuals using Swiss Ephemeris and Kerykeion chart generation.

---

## 📋 Project Structure

```
astrology-project-birthdate-chart/
├── frontend/                 # React + Vite frontend
├── backend/                  # FastAPI backend
├── ephe/                     # Ephemeris data files
├── cache/                    # Cached data
├── charts/                   # Generated chart output (SVG files)
├── README.md
├── frontend-backend.md
└── Astrology.md              # This file
```

---

## 🚀 Key Features

### 1. **Synastry Chart Report**
- Comprehensive analysis of love compatibility between two people
- Generates SVG visualizations using Kerykeion
- Color-coded planets (User: Blue, Partner: Pink)
- Major and minor aspect detection

### 2. **Birth Chart Generation**
- Complete natal chart with planetary positions
- House system: Placidus
- All major planets, nodes, and asteroids
- Moon phase analysis (8-phase cycle)

### 3. **Advanced Calculations**
- **Moon Phase Logic**: 8-phase natal moon cycle using elongation (Sun-Moon angle)
- **Aspect Analysis**: Major (Conjunction, Opposition, Sextile, Square, Trine) and Minor aspects
- **Synastry Comparison**: Compares every planet pair between two charts
- **House Placements**: 12-house system with precise calculations

### 4. **Additional Chart Types**
- Progressed Charts (Secondary Progression: 1 year life = 1 day after birth)
- Solar Return Charts
- Lunar Return Charts
- Saturn Return Charts
- Transit Charts
- Composite Charts

---

## 🛠️ Technology Stack

### **Frontend**
| Package | Version |
|---------|---------|
| React | 19.2.5 |
| Vite | 8.0.10 |
| React Router DOM | 7.14.2 |
| Axios | 1.15.2 |
| Framer Motion | 12.38.0 |
| React Icons | 5.6.0 |
| React Markdown | 10.1.0 |

### **Backend - Core Dependencies**
| Package | Version |
|---------|---------|
| Python | 3.10.12 |
| FastAPI | 0.135.3 |
| Uvicorn | 0.44.0 |
| Pydantic | 2.12.5 |
| SQLAlchemy | 2.0.49 |

### **Backend - Astrology & Calculations**
| Package | Version | Purpose |
|---------|---------|---------|
| kerykeion | 5.12.7 | SVG chart generation, AstrologicalSubject handling |
| pyswisseph | 2.10.3.2 | Swiss Ephemeris wrapper for planetary calculations |

### **Backend - Utilities**
| Package | Version |
|---------|---------|
| python-dotenv | 1.2.2 |
| bcrypt | 5.0.0 |
| PyMySQL | 1.1.3 |
| mysql-connector-python | 9.7.0 |
| requests | 2.33.1 |
| pytz | 2026.1.post1 |

---

## 🏗️ Architecture & How It Works

### **Frontend Flow**

1. **User Input** → Birth details form (Date, Time, Location)
2. **API Request** → Sends data to backend
3. **Chart Display** → Renders SVG charts + planet data + aspects
4. **Interactive UI** → Moon phase details, aspect interpretations

### **Backend Flow**

#### **Step 1: Receive Request**
```
User Form Data (year, month, day, hour, minute, second, latitude, longitude, timezone)
         ↓
API Endpoint (/chart-data, /calculators/birth-chart, etc.)
```

#### **Step 2: Calculate Planets**
```
Backend uses pyswisseph to calculate:
  • Planet positions (longitude, latitude, speed)
  • House cusps (Placidus system)
  • Moon phases (Sun-Moon elongation)
  • Aspects between planets
```

#### **Step 3: Generate SVG Charts**
```
Create AstrologicalSubject using Kerykeion
         ↓
Generate SVG wheel using KerykeionChartSVG
         ↓
Extract wheel from full chart
         ↓
Save SVG to /charts directory
```

#### **Step 4: Calculate Aspects**
```
For each planet pair:
  • Calculate angular difference
  • Match against aspect definitions
  • Check if within orb tolerance
  • Label as Major or Minor
```

#### **Step 5: Return Complete Response**
```
{
  "birth_date": "YYYY-MM-DD",
  "planets": [...],
  "major_aspects": [...],
  "minor_aspects": [...],
  "moon_phase": "Waxing Crescent",
  "chart_svg": "/charts/birthchart/chart_XXX.svg"
}
```

### **Data Flow: Synastry Example**

```
User's Birth Data          Partner's Birth Data
        ↓                           ↓
  Calculate Planets 1       Calculate Planets 2
        ↓                           ↓
    Planets 1 Array         Planets 2 Array
        ↓________________________________↓
                    ↓
        Compare Every Planet Pair
                    ↓
        Generate Aspects List
        (e.g., User's Venus ✦ Partner's Mars)
                    ↓
        Generate Dual Wheel SVG
                    ↓
        Return complete synastry data
```

---

## 📡 API Reference

### **Core Endpoints**

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/` | GET | Health check |
| `/chart-data` | POST | Get planet positions for a birth time |
| `/synastry-aspects` | POST | Calculate aspects between two charts |
| `/synastry-patterns` | POST | Analyze synastry patterns |
| `/calculator/moon-phase` | POST | Calculate moon phase details |

### **Chart Generation Endpoints**

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/calculators/birth-chart` | POST | Generate full birth chart with SVG |
| `/calculators/progressed-chart` | POST | Generate progressed chart |
| `/calculators/solar-return-chart` | POST | Generate solar return chart |
| `/calculators/lunar-return-chart` | POST | Generate lunar return chart |
| `/calculators/saturn-return-chart` | POST | Generate Saturn return chart |
| `/synastry-chart` | POST | Generate dual synastry wheel |

### **Result Retrieval**

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/calculators/birth-chart/{result_id}` | GET | Retrieve saved birth chart |
| `/calculators/progressed-chart/{result_id}` | GET | Retrieve saved progressed chart |
| `/calculators/solar-return-chart/{result_id}` | GET | Retrieve saved solar return chart |
| `/calculators/lunar-return-chart/{result_id}` | GET | Retrieve saved lunar return chart |

**Total: 14+ API Endpoints**

---

## 🧮 Core Calculation Logic

### **1. Moon Phase Calculation**

The 8-phase moon cycle is calculated using the Sun-Moon elongation (angular distance):

```
Elongation = (Moon Longitude - Sun Longitude) % 360

Phases:
  0°   - 45°    → New Moon
  45°  - 90°    → Waxing Crescent
  90°  - 135°   → First Quarter
  135° - 180°   → Waxing Gibbous
  180° - 225°   → Full Moon
  225° - 270°   → Waning Gibbous
  270° - 315°   → Last Quarter
  315° - 360°   → Waning Crescent
```

### **2. Aspect Calculation**

For each planet pair:

```
Angular Difference = |Planet1 Longitude - Planet2 Longitude|

Major Aspects (with orb ±8° for personal planets):
  • Conjunction   (0°)
  • Sextile       (60°)
  • Square        (90°)
  • Trine         (120°)
  • Opposition    (180°)

Minor Aspects (with orb ±3°):
  • Semi-sextile  (30°)
  • Quincunx      (150°)
  • Semi-square   (45°)
  • And others...
```

### **3. Synastry Aspect Analysis**

```
For each planet in User's chart:
  For each planet in Partner's chart:
    Calculate angular difference
    Check against all aspect definitions
    If orb matches → add to aspects list
```

### **4. House System**

Backend uses **Placidus house system** for:
- 12 houses starting from Ascendant
- Cusp positions calculated via pyswisseph
- Planet house placement based on longitude

---

## 🗂️ Backend File Structure

### **Core Calculation Files**
- `astrology.py` - Planet position calculations (pyswisseph wrapper)
- `Natal_Planet_Aspects.py` - Aspect detection logic
- `chart_patterns.py` - Pattern detection helpers

### **Chart Generation Files**
- `birthday_chart.py` - Birth chart generation
- `synastry-chart.py` - Synastry chart generation (loaded dynamically)
- `progressed_chart.py` - Progressed chart generation
- `solar_return_calculation.py` - Solar return chart logic
- `lunar_return_calculation.py` - Lunar return chart logic
- `saturn_return_chart.py` - Saturn return chart logic
- `transit_chart_generate.py` - Transit chart generation

### **Utility Files**
- `chart_utils.py` - SVG manipulation and Kerykeion helpers
- `chart_storage.py` - Database router for storing results
- `astrology_chart.py` - Chart rendering utilities
- `upcoming_aspects.py` - Upcoming transits calculator
- `synastry_patterns.py` - Synastry pattern analysis

### **Infrastructure Files**
- `main.py` - FastAPI app setup, routers, CORS, static file mounting
- `database.py` - SQLAlchemy engine and session setup
- `models.py` - Database models (ChartResult, etc.)
- `schemas.py` - Pydantic request/response models
- `admin_auth.py` - Admin authentication router
- `horoscope.py` - Horoscope endpoint router

---

## ⚙️ Installation & Setup

### **Prerequisites**
- Python 3.10+
- Node.js 16+ (for frontend)
- Virtual environment (venv or similar)

### **Backend Setup**

1. **Navigate to project root:**
```bash
cd /var/www/html/astrology-project-birthdate-chart
```

2. **Activate virtual environment:**
```bash
source venv/bin/activate
```

3. **Install dependencies:**
```bash
pip install \
  fastapi==0.135.3 \
  uvicorn==0.44.0 \
  pydantic==2.12.5 \
  python-dotenv==1.2.2 \
  pyswisseph==2.10.3.2 \
  kerykeion==5.12.7 \
  sqlalchemy==2.0.49 \
  bcrypt==5.0.0 \
  pymysql==1.1.3 \
  requests==2.33.1
```

4. **Configure environment:**
```bash
# Create backend/.env
FRONTEND_URL=http://172.16.16.148:5173
```

5. **Run backend:**
```bash
cd backend
python main.py
```

Backend will start at: `http://172.16.16.148:8000`

### **Frontend Setup**

1. **Navigate to frontend:**
```bash
cd frontend
```

2. **Install dependencies:**
```bash
npm install
```

3. **Run development server:**
```bash
npm run dev
```

Frontend will start at: `http://localhost:5173` or `http://172.16.16.148:5173`

---

## 🔗 API URLs in Production

- **Frontend URL:** `http://172.16.16.148:5173`
- **Backend URL:** `http://172.16.16.148:8000` (or localhost:8000 for local dev)
- **Charts Endpoint:** `http://backend:8000/charts/`

---

## 📁 Database & Storage

- **Chart Output:** `/backend/charts/` (served via `/charts` route)
  - Birth charts: `charts/birthchart/`
  - Synastry charts: `charts/synastry-chart/`
  - Progressed charts: `charts/progressedchart/`
  - Solar returns: `charts/solar-return/`
  - Lunar returns: `charts/lunar-return/`
  - Saturn returns: `charts/saturn_return/`
  - Transit charts: `charts/transit/`

- **Ephemeris Data:** `/backend/ephe/` (Swiss Ephemeris files)
  - `sepl_18.se1` - Planet positions
  - `semo_18.se1` - Moon data
  - `seas_18.se1` - Asteroids
  - `sefstars.txt` - Fixed stars

---

## 🎨 Frontend Routes

| Route | Purpose |
|-------|---------|
| `/` | Home page |
| `/birth-chart` | Birth chart calculator form |
| `/birth-chart/:id` | Birth chart result display |
| `/synastry-chart` | Synastry form (two people) |
| `/calculators/synastry-chart/:id` | Synastry result display |
| `/calculators/solar-return-chart` | Solar return form |
| `/calculators/lunar-return-chart` | Lunar return form |
| `/calculators/saturn-return-chart` | Saturn return form |
| `/calculators/progressed-chart` | Progressed chart form |
| `/calculators` | All tools/calculators |
| `/calculator/moon-phase` | Moon phase calculator |
| `/calculator/{planet}` | Dynamic planet calculator |
| `/love-compatibility` | Love compatibility analyzer |

---

## 🌍 Environment Variables

### **Backend (.env in backend/ folder)**
```env
FRONTEND_URL=http://172.16.16.148:5173
DATABASE_URL=sqlite:///./charts.db  # or MySQL connection string
```

### **CORS Configuration**
The backend allows requests from:
- `FRONTEND_URL` (from .env)
- `http://localhost:5173` (local development)
- `http://127.0.0.1:5173` (local development)

---

## 📊 Data Models

### **Birth Details Request**
```python
{
  "name": "John Doe",
  "year": 1990,
  "month": 3,
  "day": 15,
  "hour": 14,
  "minute": 30,
  "second": 0,
  "latitude": 28.7041,
  "longitude": 77.1025,
  "timezone": 5.5
}
```

### **Chart Response**
```python
{
  "birth_date": "1990-03-15",
  "birth_time": "14:30:00",
  "planets": [...],  # List of planet objects
  "houses": [...],   # House cusps
  "major_aspects": [...],
  "minor_aspects": [...],
  "moon_phase": "Waxing Crescent",
  "chart_svg": "/charts/birthchart/chart_abc123.svg"
}
```

---

## 🔐 Security Notes

- CORS is configured to allow only specified origins
- Admin authentication uses bcrypt for password hashing
- Chart results are stored and can be retrieved via result_id
- Sensitive data (coordinates, times) should be handled securely

---

## 📝 Notes

- **Kerykeion** generates SVG charts; the backend extracts just the wheel portion for cleaner UI display
- **PySwissEph** performs all astronomical calculations; results are accurate as of modern ephemeris data
- **Timezone** defaults to 5.5 (India Standard Time) but accepts any valid UTC offset
- **House System** uses Placidus (most common in Western astrology)
- **Aspects** use standard orbs; customizable via code modifications

---

## 🚀 Performance & Optimization

- Chart SVGs are cached in `/backend/charts/` directory
- Database queries use indexes for fast result retrieval
- Frontend uses Vite for fast HMR (Hot Module Replacement)
- Static files (charts) are served via FastAPI StaticFiles

---

## 🐛 Common Issues & Troubleshooting

### Backend won't start
- Ensure `FRONTEND_URL` is set in `.env`
- Check if port 8000 is already in use
- Verify Python 3.10+ is installed

### Charts not generating
- Ensure ephemeris files exist in `backend/ephe/`
- Check file permissions in `backend/charts/` directory
- Verify Kerykeion is correctly installed

### CORS errors
- Add frontend URL to `FRONTEND_URL` in `.env`
- Restart backend after changing `.env`

### Frontend can't reach backend
- Check backend URL in frontend API calls (should be `http://172.16.16.148:8000`)
- Verify network connectivity between frontend and backend servers

---

## 📚 References

- **Kerykeion Docs:** https://github.com/g-battaglia/Kerykeion
- **PySwissEph Docs:** https://pyswisseph.readthedocs.io/
- **FastAPI Docs:** https://fastapi.tiangolo.com/
- **React Docs:** https://react.dev/
- **Vite Docs:** https://vitejs.dev/

---

**Last Updated:** May 25, 2026
**Project Status:** Active Development
**Version:** 1.0.0
