An intelligent FastAPI backend that provides I Ching divination services using modern NLP techniques. The system analyzes queries using GloVe embeddings and returns relevant hexagrams with their traditional meanings.
- Natural Language Processing: Uses pre-trained GloVe embeddings to understand query semantics
- 64 Hexagram Database: Complete I Ching hexagram set with Unicode characters (ไท-ไทฟ)
- Semantic Similarity: Calculates relevance scores between queries and hexagrams
- RESTful API: Clean, documented endpoints for all operations
- Query History: Stores and retrieves past consultations
- Similar Query Search: Find related questions from history
- Interactive CLI: Command-line interface for easy interaction
- Image Generation Support: Generate mystical images for hexagrams (optional)
- Python 3.8+
- pip3
- 2-3GB free space for GloVe embeddings
- Clone the repository:
git clone <repository-url>
cd Portfolio-ICHING/fastapi-backend- Install dependencies:
pip3 install -r requirements.txt- Set up GloVe embeddings:
chmod +x setup.sh
./setup.sh- (Optional) Configure environment:
cp .env.example .env
# Edit .env if you want to use image generation featuresStart the FastAPI server:
python3 main.pyThe API will be available at http://localhost:8000
View API documentation at http://localhost:8000/docs
Ask a single question:
python3 quick_query.py "What path should I take in my career?"Launch the full interactive experience:
python3 interactive_client.pyAvailable commands:
ask <question>- Consult the I Chingfind <query>- Search similar past querieshistory [n]- View last n querieshexagrams- List all 64 hexagramshelp- Show available commandsquit- Exit
import requests
# Ask a question
response = requests.post(
"http://localhost:8000/queries/",
json={"query": "How can I find balance in my life?"}
)
result = response.json()
# Display hexagrams
for hexagram in result['hexagram_set']:
print(f"{hexagram['hexagram_unicode']} {hexagram['hexagram_name']}")| Method | Endpoint | Description |
|---|---|---|
| GET | / |
Health check |
| POST | /queries/ |
Submit a new query |
| GET | /queries/ |
List all queries |
| GET | /queries/{id} |
Get specific query |
| GET | /queries/search/similar |
Find similar queries |
| GET | /hexagrams/ |
List all 64 hexagrams |
- Query Processing: User questions are tokenized and converted to word embeddings
- Vector Calculation: Query vectors are computed as the average of word embeddings
- Hexagram Matching: Cosine similarity determines the most relevant hexagrams
- Result Ranking: Top 6 hexagrams are returned with normalized relevance scores
fastapi-backend/
โโโ main.py # FastAPI application
โโโ models.py # SQLAlchemy models
โโโ schemas.py # Pydantic schemas
โโโ database.py # Database configuration
โโโ services/
โ โโโ iching_embeddings.py # Core NLP service
โ โโโ image_generation.py # Optional image gen
โโโ interactive_client.py # CLI interface
โโโ quick_query.py # Quick query tool
โโโ test_api.py # API testing script
โโโ glove/ # GloVe embeddings (after setup)
Your question: How can I find inner peace?
The I Ching responds with these hexagrams:
1. ไท Peace (95% relevance)
2. ไทค The Family (82% relevance)
3. ไทพ After Completion (76% relevance)
4. ไท Innocence (71% relevance)
5. ไท Duration (68% relevance)
6. ไท Standstill (65% relevance)
If you have API keys for image generation services, you can generate mystical representations of hexagrams:
- Add API keys to
.env:
OPENAI_API_KEY=your_key_here
STABILITY_API_KEY=your_key_here
REPLICATE_API_TOKEN=your_key_here- Generate images:
python3 generate_hexagram_images.py- First Load: ~10-30 seconds to load GloVe embeddings
- Query Response: <100ms after initialization
- Memory Usage: ~600MB-3GB depending on embedding size
- Database: SQLite by default, can be configured for PostgreSQL/MySQL
python3 test_api.pyUsing Alembic for database migrations:
alembic init alembic
alembic revision --autogenerate -m "Your migration message"
alembic upgrade head- Extend the models in
models.py - Update schemas in
schemas.py - Add new endpoints in
main.py - Update the embedding service if needed
Cannot connect to API
- Ensure the server is running:
python3 main.py - Check if port 8000 is available
GloVe download fails
- Check internet connection
- Manually download from Stanford NLP
- Place in
./glove/directory
High memory usage
- Use smaller embeddings (50d or 100d instead of 300d)
- Implement selective vocabulary loading
- Consider using a database for embeddings
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
- Stanford NLP Group for GloVe embeddings
- I Ching wisdom tradition
- FastAPI framework
- Open source community
"The I Ching does not offer itself with proofs and results; it does not vaunt itself, nor is it easy to approach. Like a part of nature, it waits until it is discovered." - Carl Jung
