gsinghjay/zodiac-engine(新しいタブで開きます)
主要言語: Python
A modern astrological calculation API powered by Kerykeion. Interpretations by an LLM.
- star 数
- 12
- watcher 数
- 1
- fork 数
- 7
- issue 数
- 1
- 最終更新
- 2026/06/15
主要言語: Python
A modern astrological calculation API powered by Kerykeion. Interpretations by an LLM.
Zodiac Engine is a comprehensive FastAPI web application designed for astrological chart generation, detailed visualization, insightful reporting, and AI-powered interpretations. It leverages the powerful Kerykeion library for its core astrological calculations and offers a responsive, user-friendly web interface.
The Zodiac Engine follows a layered architecture with clear separation of concerns:
flowchart TD
Client[Client Browser] --> WebRoutes[Web Routes]
Client --> ApiRoutes[API Routes]
subgraph "API Layer"
WebRoutes --> DI[Dependency Injection]
ApiRoutes --> DI
end
subgraph "Service Layer"
DI --> AstroService[Astrology Service]
DI --> VisService[Chart Visualization Service]
DI --> FileService[File Conversion Service]
DI --> ReportService[Report Service]
DI --> InterpService[Interpretation Service]
DI --> GeoService[Geo Service]
end
subgraph "Integrations"
AstroService --> Kerykeion[Kerykeion Library]
VisService --> Kerykeion
ReportService --> Kerykeion
GeoService --> GeoNames[GeoNames API]
InterpService --> LLM[LLM Provider API]
end
subgraph "Data Storage"
VisService --> SVGFiles[SVG Chart Files]
Client --> Cache[In-Memory Cache]
end
What You're Seeing:
This architecture diagram shows the four main layers of our application:
Client Interaction Layer: The user interacts with our application through their browser, accessing either web routes (for the UI) or API routes (for direct data access).
API Layer: All requests flow through our FastAPI routers and use dependency injection to access services. This creates a clean separation between routing logic and business logic.
Service Layer: The core of our application contains six specialized services:
Integrations & Storage: Our services connect to:
This architecture ensures each component has a single responsibility and allows for easy extension or replacement of individual services.
sequenceDiagram
participant User
participant Web as Web UI
participant API as API Layer
participant Service as Service Layer
participant Kerykeion
participant Storage as File Storage
User->>Web: Enter birth details
Web->>API: POST /generate-chart
API->>Service: AstrologyService.calculate_natal_chart()
Service->>Kerykeion: Create AstrologicalSubject
Kerykeion-->>Service: Return chart data
Service->>Kerykeion: Generate chart SVG
Kerykeion-->>Service: Return SVG content
Service->>Storage: Save SVG file
Storage-->>Service: Return file path
Service-->>API: Return chart metadata & SVG URL
API-->>Web: Redirect to chart details page
Web-->>User: Display chart & options
What You're Seeing:
This sequence diagram illustrates the complete flow of generating an astrological chart:
User Input: The process begins when a user enters birth details (name, date, time, location) and chart preferences in the web interface.
Request Processing:
Chart Visualization:
Response & Display:
This flow demonstrates how we handle the entire process from user input to displaying results, with clean separation between the UI, API, services, and external libraries.
flowchart LR
Chart[Chart Data] --> Report[Report Service]
Report --> |Structured Data| InterpService[Interpretation Service]
subgraph "Interpretation Service"
InterpService --> PromptTemplate[Prompt Template]
PromptTemplate --> |Formatted Prompt| Provider[Provider Selector]
Provider --> |API Request| GeminiAPI[Gemini API]
Provider -.-> |Alternative| OpenAIAPI[OpenAI API]
Provider -.-> |Alternative| AnthropicAPI[Anthropic API]
end
GeminiAPI --> |Markdown Response| Processor[Response Processor]
OpenAIAPI -.-> |Markdown Response| Processor
AnthropicAPI -.-> |Markdown Response| Processor
Processor --> |Convert MD to HTML| Formatter[Markdown Formatter]
Formatter --> |Extract Highlights| Extractor[Section Extractor]
Extractor --> InterpResult[Interpretation Result]
InterpResult --> UI[User Interface]
What You're Seeing:
This flowchart details our AI integration process, which is the standout feature of this application:
Data Preparation:
Interpretation Service Pipeline:
Response Processing:
User Presentation:
This architecture demonstrates our sophisticated AI integration, going beyond simple API calls to create a robust processing pipeline that enhances the user experience with high-quality, formatted interpretations.
The Zodiac Engine aims to provide a modern, accessible platform for exploring astrological charts. Users can generate detailed natal charts (both Western Tropical and Vedic Sidereal systems) by providing birth information. The application then renders a high-quality SVG visualization of the chart, offers downloadable reports, and integrates with Large Language Models (LLMs) like Google Gemini or OpenAI's GPT to provide natural language interpretations of the astrological data.
The project emphasizes a responsive web experience, making it accessible on both desktop and mobile devices, and is built with a robust FastAPI backend ensuring scalability and maintainability.
google-generativeai SDK)InterpretationService)chart_cache in app/api/web.py) for temporary storage of generated chart metadata for the web UI.TestClientvenvZodiac Engine integrates AI to provide users with natural language interpretations of their astrological charts. This feature enhances the user experience by translating complex astrological data into understandable insights.
gemini-pro model). The system is designed to be adaptable to other providers like OpenAI (GPT models) or Anthropic (Claude models) by modifying the InterpretationService.ReportService) generates a detailed, structured textual report of the chart using Kerykeion. This report includes tables for birth data, planet positions (sign, degrees, house), and house cusp positions.InterpretationService sends this prompt to the configured LLM API (e.g., Google Gemini).app/services/interpretation.py: Contains the logic for interacting with the LLM and crafting prompts.app/services/report.py: Generates the structured data fed to the LLM.app/core/config.py and .env file: Manage API keys and LLM provider settings.This AI integration transforms raw astrological data into personalized narratives, making astrology more accessible and engaging.
The Zodiac Engine features a clean, responsive web interface designed with a mobile-first approach using Bootstrap 5. Key aspects include:
Landing Page (/): An engaging cosmic-themed entry point with animated SVG background, feature cards highlighting key capabilities, and a dedicated section showcasing the AI interpretation feature. Clear call-to-action buttons guide users to the chart generation page.
Chart Generation Page (/chart-generator or /home): A straightforward form allows users to input birth details for either Western (Tropical) or Vedic (Sidereal) charts. It includes a city lookup feature powered by HTMX and the GeoNames API.
Chart Details Page (/chart/{chart_id}):
Progressive Enhancement with HTMX: HTMX is used to load reports and AI interpretations dynamically without full page reloads, creating a smoother and faster user experience.
Consistent Visual Theme: A purple-to-blue gradient theme is applied throughout the application, creating a cohesive cosmic visual identity.
Session Data: Generated chart metadata (name, birth details, chart ID) is temporarily stored in an in-memory cache (chart_cache) for the current user session, allowing them to navigate to the chart details page and interact with it.
Zodiac Engine is designed with a strong focus on mobile usability:
Mobile UI Screenshots:
Some components require system-level libraries:
sudo apt-get install libcairo2-dev libpango1.0-dev libgdk-pixbuf2.0-dev libffi-dev shared-mime-infobrew install cairo pango gdk-pixbuf libffi shared-mime-infoClone the repository:
git clone https://github.com/yourusername/zodiac-engine.git # Replace with your actual repo URL cd zodiac-engine
Create and activate a Python virtual environment:
python -m venv venv
source venv/bin/activatevenv\Scripts\activateInstall dependencies:
pip install -r requirements.txt
Create a .env file in the project's root directory. You can copy the example below.
# .env PROJECT_NAME="Zodiac Engine" VERSION="1.0.0" # This can be dynamic if using semantic-release effectively API_V1_STR="/api/v1" ALLOWED_ORIGINS="http://localhost:8000,http://127.0.0.1:8000" # Kerykeion settings - Required for full city/timezone lookup GEONAMES_USERNAME="your_geonames_username" # Replace with your GeoNames username # LLM API settings for chart interpretations LLM_PROVIDER="gemini" # Default is gemini. Options: "openai", "anthropic", "gemini" LLM_API_KEY="your_llm_api_key" # Replace with your API key for the chosen provider LLM_MODEL_NAME="gemini-pro" # e.g., "gemini-pro", "gpt-4", "claude-3-opus-20240229" LLM_MAX_TOKENS=2000 LLM_TEMPERATURE=0.7 LLM_CACHE_ENABLED=true LLM_CACHE_TTL_HOURS=24
Important:
"your_geonames_username" with your actual GeoNames username.LLM_PROVIDER to your chosen service (gemini, openai, or anthropic)."your_llm_api_key" with the corresponding API key.LLM_MODEL_NAME to a model compatible with your chosen provider.Ensure your virtual environment is activated.
uvicorn app.main:app --reload
The application will be accessible at:
.env file. Note there are usage limits for free accounts.Zodiac Engine implements persistence in several ways:
chart_cache) during the user's session. This allows users to navigate between pages while maintaining access to their chart data.app/static/images/svg/ with unique IDs, allowing for later retrieval.LLM_CACHE_ENABLED=true) LLM-generated interpretations can be cached to reduce API costs and improve performance.Future implementations will include SQLite database integration for more robust persistence across server restarts.
Zodiac Engine provides a RESTful API for astrological functionalities. Key endpoints include:
POST /api/v1/charts/natal/POST /api/v1/charts/visualization/natalPOST /api/v1/charts/visualization/synastryPOST /api/v1/charts/reports/natal/POST /api/v1/charts/reports/synastry/POST /api/v1/charts/interpretations/natal/GET /api/v1/geo/searchPlaceholders exist for composite and transit chart functionalities. The API is self-documenting via OpenAPI (Swagger UI at /docs and ReDoc at /redoc).
The project uses pytest for automated testing. Tests cover API endpoints, service logic, and utility functions.
To run the tests:
# Ensure virtual environment is active and dependencies installed
pytestTest files are located in the tests/ directory.
The scripts/ directory contains shell scripts for manually testing API endpoints using curl:
scripts/test_western_chart.sh: Tests Western (Tropical) chart generation.scripts/test_vedic_chart.sh: Tests Vedic (Sidereal) chart generation.To run them (after starting the application):
bash scripts/test_western_chart.sh
The codebase is organized into the following main directories:
app/: Main application package.
api/: API endpoint definitions, structured by version and resource.
v1/: Version 1 of the API.
routers/: Routers for different API resources (charts, geo).core/: Core application components (config, dependencies, error handling, custom exceptions).schemas/: Pydantic models for data validation and serialization.services/: Business logic for different functionalities (astrology, visualization, interpretation, etc.).static/: Static files (CSS, generated SVG images).templates/: Jinja2 HTML templates for the web interface.main.py: FastAPI application entry point.scripts/: Utility and test scripts.tests/: Automated tests using Pytest..github/workflows/: GitHub Actions workflows (e.g., semantic-release)..cursor/rules/: (If using Cursor IDE) Project-specific documentation and coding rules.Throughout the development of Zodiac Engine, several challenges were encountered and valuable lessons learned:
SVG Processing: Handling CSS variables in SVG files required custom preprocessing before conversion to other formats. We developed a regex-based solution to resolve CSS variables, ensuring compatibility with CairoSVG.
Asynchronous Pattern Consistency: Balancing async and sync code when integrating with blocking libraries like Kerykeion required careful threading management using run_in_threadpool for performance optimization.
LLM Integration Complexity: Crafting effective prompts for LLMs to interpret astrological data required multiple iterations to achieve useful outputs. The structured Report format proved essential for providing LLMs with sufficient context.
Progressive Enhancement with HTMX: Implementing HTMX for a smoother user experience while maintaining functionality without JavaScript required careful planning of partial templates and response handling.
House System Mapping: Reconciling differences between human-readable house system names and Kerykeion's internal codes required additional mapping logic and comprehensive error handling.
These challenges led to a more robust application architecture with better error handling, thoughtful abstraction layers, and improved user experience.
This project fulfills the academic requirements as follows:
Technology:
AI Integration:
Application Requirements:
Deliverables:
chart_cache with a lightweight database (e.g., SQLite or TinyDB) to allow users to save and revisit their charts.InterpretationService).MIT License (Assuming you'll add an MIT License file. If not, adjust accordingly, e.g., "This project is for educational purposes and is not licensed for redistribution without permission.")