Spaces:
Sleeping
Sleeping
File size: 19,807 Bytes
57d22d1 4fbe1ee 57d22d1 e1af63d 3378916 e1af63d 3378916 e1af63d 3378916 e1af63d 3378916 4fbe1ee | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 | ---
title: Braindump Sanctuary
emoji: π
colorFrom: purple
colorTo: indigo
sdk: docker
app_port: 8501
tags:
- streamlit
pinned: false
short_description: β¨ Transform scattered thoughts into insights.
license: mit
---
# π§ Brain Dump Sanctuary
> **Capture, cluster, and reflect on your thoughts in real-time.**
A full-stack NLP application that transforms scattered thoughts into organized, semantically meaningful clusters with AI-powered insights. Built with Streamlit, LangGraph agents, and Neo4j.
---
## β¨ Features
### Core Capabilities
- **π Brain Dump Capture**: Write down thoughts, ideas, and questions instantly
- **π Semantic Clustering**: Automatically group related thoughts using embeddings (sentence-transformers) and HDBSCAN
- **π Interactive Knowledge Graph**: Visualize all thoughts as an interactive Plotly graph with color-coded clusters
- **π·οΈ AI-Generated Labels**: Auto-label clusters using Google Gemini LLM (e.g., "Personal Growth", "Technical Concepts")
- **π€ Multi-Agent Intelligence**:
- **SearchAgent**: Generate contextualized summaries with optional web search (Tavily)
- **QuestionAgent**: Generate Socratic questions for deeper reflection
- **GenerationAgent**: Synthesize insights across related thoughts
- **FeedAgent**: Curate a blog-style feed of your 5 most recent thoughts with agent insights
- **π Persistent Storage**: All thoughts stored in Neo4j graph database with full history
- **π Real-time Updates**: Refresh embeddings and recalculate clusters on demand
### Two-View Interface
1. **Home Tab** π : Semantic cluster map + comprehensive table of all thoughts
2. **Feed Tab** π°: Blog-style cards with summaries and reflection questions
---
## ποΈ Architecture
### Tech Stack
```
Frontend: Streamlit (single-page Python web app)
Backend: Python 3.10+ with LangChain/LangGraph
Database: Neo4j Aura (graph database)
NLP Pipeline:
- Embeddings: sentence-transformers (all-MiniLM-L6-v2)
- Clustering: HDBSCAN + UMAP dimensionality reduction
- LLM: Google Gemini 2.5 Flash (via LangChain)
Search: Tavily API (optional, with mock fallback)
```
### System Architecture
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STREAMLIT UI β
β (app.py - Home Tab | Feed Tab | Sidebar Controls) β
βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββ΄ββββββββββ
β β
βββββΌβββββ ββββββΌβββββββ
β AGENTS β β EMBEDDINGS β
β (Day2) β β & CLUSTERS β
βββββ¬βββββ β (Day 1) β
β ββββββ¬ββββββββ
β β
βββββ΄ββββββββββββββββββββΌβββββ
β BRAINDUMP_CORE.PY β
β - BrainDumpDB (Neo4j) β
β - EmbeddingEngine β
β - ClusterEngine β
β - ClusterLabelEngine β
βββββ¬βββββββββββββββββββββββββ
β
βββββΌβββββββββββββββββββ
β NEO4J GRAPH DB β
β (Aura Cloud) β
β - Dump Nodes β
β - Cluster Nodes β
β - Relationships β
ββββββββββββββββββββββββ
```
### Data Flow
**Input β Processing β Storage β Visualization**
1. **User enters brain dump** β `app.py` sidebar
2. **Generate embedding** β `EmbeddingEngine` (sentence-transformer)
3. **Store in Neo4j** β `BrainDumpDB.add_dump()`
4. **Re-cluster on demand** β `ClusterEngine.cluster()` + `ClusterLabelEngine.label_clusters()`
5. **Visualize clusters** β Plotly interactive graph (Home tab)
6. **Enrich with AI** β Agents analyze for Feed tab
### Neo4j Graph Schema
```cypher
Node: Dump
βββ id: UUID
βββ text: String (the brain dump)
βββ embedding: Vector[384] (from sentence-transformer)
βββ created_at: DateTime
βββ cluster_id: Reference to Cluster
Node: Cluster
βββ id: UUID
βββ label: String (e.g., "Personal Growth")
βββ description: String (optional)
βββ created_at: DateTime
Relationships:
βββ Dump -[:IN_CLUSTER]-> Cluster
βββ Dump -[:SIMILAR_TO {weight: 0.0-1.0}]-> Dump
```
### Component Breakdown
| File | Purpose | Key Classes |
|------|---------|------------|
| `app.py` | Streamlit UI & session management | Main app logic, page layout |
| `braindump_core.py` | NLP pipeline & database | `BrainDumpDB`, `EmbeddingEngine`, `ClusterEngine`, `ClusterLabelEngine` |
| `agents.py` | AI agents for insights | `QuestionAgent`, `SearchAgent`, `GenerationAgent`, `FeedAgent` |
| `neo4j_maintenance.py` | Database utilities | Neo4j query helpers, debugging |
| `cleanup_db.py` | Reset database | Wipe all data (for testing) |
---
## π Quick Start
### Prerequisites
- Python 3.10+
- Neo4j Aura account (free tier available)
- API keys for Google Gemini (free) and optionally Tavily
### 1. Setup Neo4j (Required)
Create a free Neo4j Aura instance:
1. Go to https://console.neo4j.io/
2. Sign up for a free account
3. Create a new "Free" Aura instance
4. Copy your connection details:
- **URI**: `neo4j+ssc://xxxxx.databases.neo4j.io`
- **Username**: `neo4j`
- **Password**: (set during creation)
### 2. Installation
```bash
# Clone repository
git clone <repo-url>
cd braindump-sanctuary
# Install dependencies
pip install -r requirements.txt
# Create environment file
cp .env.example .env # or create manually
# Edit .env with your credentials
```
**.env Template:**
```env
# Neo4j (Required)
NEO4J_URI=neo4j+ssc://your-instance-id.databases.neo4j.io
NEO4J_USER=neo4j
NEO4J_PASSWORD=your-password-here
# Google Gemini (Required for AI features)
GOOGLE_API_KEY=your_google_api_key_here
# Web Search (Optional - uses mock data if not provided)
TAVILY_API_KEY=your_tavily_api_key_here
# Alternative: Perplexity (Optional)
PERPLEXITY_API_KEY=your_perplexity_key_here
```
**Get API Keys:**
- π **Google Gemini** (free): https://aistudio.google.com/app/apikey
- π **Tavily Search** (optional): https://app.tavily.com
- π§ **Perplexity** (optional): https://www.perplexity.ai/
### 3. Run the App
```bash
streamlit run app.py
```
App opens at `http://localhost:8501`
---
## π± User Interface Guide
### Sidebar Controls
**Left Sidebar** - Main interaction hub:
- πΊοΈ **Navigation**: Radio buttons to toggle between **Home** and **Feed** tabs
- π **Text Area**: Input field for new brain dumps
- β
**Add to Sanctuary**: Save the thought to Neo4j
- ποΈ **Clear**: Empty the input field
- π **Refresh Clusters**: Recalculate all embeddings and clusters (computationally intensive, 10-30 seconds)
- β οΈ **Clear All Dumps**: Permanently delete all thoughts from the database
- π **Total Brain Dumps**: Counter showing total stored thoughts
### Home Tab π - Knowledge Graph View
**Top Section: Interactive Cluster Map**
- **Visualization**: 2D interactive Plotly graph
- **Nodes**: Each point = one brain dump
- **Colors**: Each color = a semantic cluster (similar ideas grouped together)
- **Layout**: UMAP dimensionality reduction for spatial meaning
- **Interactions**: Hover to see full text, zoom/pan to explore
- **Relationships**: Edges show semantic similarity between thoughts
**Bottom Section: Comprehensive Table**
- **Columns**: Brain Dump | Cluster Label | Created At
- **Sorting**: Most recent first (newest at top)
- **Format**: Plain text, easy to copy
**Actions**:
- Click "π **Refresh Clusters**" to recalculate (when you add many new thoughts)
- Spinner animations show progress of embedding generation and labeling
### Feed Tab π° - Blog-Style Feed
**What You See**:
1. **Up to 5 Recent Cards** in reverse chronological order
2. **Each Card Contains**:
- π **Title**: Your full brain dump text
- π·οΈ **Cluster Badge**: Category label (generated by LLM)
- π **Summary**: AI-generated context
- If Tavily API set: Real web search + synthesis
- If not: Mock contextual data (demo mode)
- β **Reflection Questions**: 5 Socratic questions (from QuestionAgent)
**Why Use Feed?**
- Quick morning review without table scrolling
- AI-generated insights help you think deeper
- Guided reflection via questions
- Patterns become visible across multiple cards
- Perfect for journaling workflow
---
## π Typical Workflows
### Workflow 1: Daily Brain Dumping + Review
```
Morning:
1. Open app at http://localhost:8501
2. Sidebar: Type 3-5 quick thoughts
3. Click "Add to Sanctuary" each time
4. Switch to Feed tab
5. Read summaries and reflect on questions
6. (Takes 5-10 minutes)
Evening:
1. Go to Home tab
2. Click "Refresh Clusters"
3. Observe how new thoughts clustered with existing ones
4. Spot emerging themes and connections
```
### Workflow 2: Deep Dive Analysis
```
1. Accumulate 20+ thoughts over several days
2. Go to Home tab
3. Click "Refresh Clusters"
4. Examine the visualization:
- Which clusters are densest?
- What themes emerge?
- Any surprising connections?
5. Switch to Feed tab
6. Read the agent-generated insights
7. Use for next creative session
```
### Workflow 3: Topic-Specific Exploration
```
1. Add 10+ thoughts about a specific topic
2. They should cluster together automatically
3. Hover over the cluster in Home tab
4. Read the AI-generated cluster label
5. Check Feed tab for synthesis across related thoughts
6. Use the questions to drill deeper
```
---
## π€ Agent Capabilities
### QuestionAgent
**Role**: Socratic questioning for deeper reflection
**Input**: Brain dump text
**Output**: 5 open-ended questions
**Example**:
```
Brain Dump: "Why do I procrastinate on important tasks?"
Generated Questions:
1. What task are you procrastinating on right now?
2. What emotion arises when you think about starting it?
3. What would you do instead if you didn't procrastinate?
4. What is the smallest first step you could take?
5. What would happen if you started today?
```
### SearchAgent
**Role**: Web search + synthesis or mock data generation
**Input**: Brain dump text
**Output**: Relevant context or summary
**With Tavily API**:
- Searches the web for related information
- Synthesizes findings with LLM
- Provides citations and context
**Without Tavily API** (Demo Mode):
- Generates plausible contextual information
- Maintains consistency with the thought
- Allows testing without API key
### GenerationAgent
**Role**: Cross-thought synthesis
**Input**: Multiple related brain dumps (from same cluster)
**Output**: Synthesized insight combining themes
**Example**:
```
Related Dumps:
- "Neural networks learn patterns"
- "Our brains also learn from patterns"
- "What if consciousness is pattern recognition?"
Synthesis: These thoughts suggest that consciousness might emerge
from the brain's pattern recognition capabilities...
```
### FeedAgent
**Role**: Orchestrates other agents for feed generation
**Process**:
1. Selects 5 most recent thoughts
2. For each thought:
- Gets cluster assignment
- Calls SearchAgent for summary
- Calls QuestionAgent for reflection questions
3. Formats as blog-style cards
---
## βοΈ Configuration & Customization
### Environment Variables (.env)
Create `.env` file in project root:
```bash
# ============ REQUIRED ============
# Neo4j Aura Connection
NEO4J_URI=neo4j+ssc://your-instance-id.databases.neo4j.io
NEO4J_USER=neo4j
NEO4J_PASSWORD=your-super-secure-password
# Google Gemini LLM API
GOOGLE_API_KEY=AIzaSyDxxxxxxxxxxxxxxxxxxxxx
# ============ OPTIONAL ============
# Tavily Web Search (for better summaries)
TAVILY_API_KEY=tvly-xxxxxxxxxxxxxxxxx
# Perplexity API (alternative search)
PERPLEXITY_API_KEY=pplx-xxxxxxxxxxxxxxxxx
```
### Optional: Streamlit Configuration
Create `.streamlit/config.toml`:
```toml
[theme]
primaryColor = "#4ECDC4"
backgroundColor = "#0d1117"
secondaryBackgroundColor = "#161b22"
textColor = "#c9d1d9"
[client]
showErrorDetails = true
[logger]
level = "info"
[server]
port = 8501
```
---
## π§ Development & Debugging
### Running Locally
```bash
streamlit run app.py
```
### Clearing Database
```bash
python cleanup_db.py
```
### Neo4j Maintenance
```bash
python neo4j_maintenance.py
```
### Viewing Logs
```bash
# Terminal shows Streamlit logs
# Check sidebar for spinner status during refresh
```
### Common Issues
**Issue**: "Failed to connect to Neo4j"
- Verify `.env` has correct URI, username, password
- Check Neo4j Aura instance is running (console.neo4j.io)
- Firewall: Neo4j needs outbound HTTPS (port 7687)
**Issue**: "GOOGLE_API_KEY not found"
- Ensure key is in `.env` file
- Restart streamlit: `streamlit run app.py`
**Issue**: Clusters not showing
- Click "Refresh Clusters" in sidebar
- Wait for spinner to finish (10-30 seconds)
- Needs at least 2-3 thoughts for clustering
**Issue**: Tavily search not working
- Mock data is used if API key missing (expected)
- Optional feature; not required for core functionality
---
## π Performance Notes
### Computational Complexity
- **Adding 1 thought**: ~1 second
- **Clustering N thoughts**: ~O(N) to O(N log N) depending on N
- 10 thoughts: ~2 seconds
- 100 thoughts: ~5-10 seconds
- 1000 thoughts: ~30-60 seconds
- **LLM labeling**: ~2-5 seconds per cluster (depends on Gemini API latency)
### Storage
- Neo4j Free Tier: ~5 GB storage
- Typical thought: ~500 bytes
- Can store ~10 million thoughts theoretically
### Scaling Recommendations
- **Local testing**: β
Recommended
- **Shared team use**: Consider dedicated Neo4j instance
- **Large scale (10k+ thoughts)**: May need performance tuning (indexing, batching)
---
## π Learning Resources
### Concepts Explained
**Semantic Embeddings**
- sentence-transformers model converts text to 384-dimensional vectors
- Similar texts β similar vectors β can cluster together
- Distance in vector space β semantic similarity
**HDBSCAN Clustering**
- Density-based clustering (unlike K-means which needs K)
- Automatically finds clusters of any shape
- Robust to outliers (marks them as "noise")
**Neo4j Graph Database**
- Stores relationships as first-class citizens
- Fast for relationship queries (unlike SQL)
- Perfect for knowledge graphs and recommendations
**LLMs for Labeling**
- Google Gemini generates cluster labels from examples
- LangChain chains handle prompt + LLM + parsing
- Enables semantic understanding of cluster themes
---
## π License
See `LICENSE` file for details.
---
## π€ Contributing
Found a bug or have a feature idea?
1. Check existing issues
2. Create new issue with clear description
3. (Optional) Submit PR with fix
---
## β FAQ
**Q**: Can I use this with a local Neo4j instance?
**A**: Yes! Update `NEO4J_URI` to `neo4j://localhost:7687` in `.env`
**Q**: What if I don't have a Tavily API key?
**A**: That's fine! SearchAgent will generate mock data (demo mode)
**Q**: Can I export all my thoughts?
**A**: Use the table in Home tab or query Neo4j directly. Export feature coming soon.
**Q**: How often should I click "Refresh Clusters"?
**A**: After adding multiple new thoughts (5+), or when you want to see updated organization.
**Q**: Is my data secure?
**A**: Only you have your Neo4j password. Data is encrypted in transit and at rest on Neo4j Aura.
---
## π Roadmap
- [ ] Export functionality (CSV, JSON, markdown)
- [ ] Thought search & filtering
- [ ] Collaborative mode (multiple users)
- [ ] Email digest of weekly summaries
- [ ] Browser extension for quick capture
- [ ] Mobile app
- [ ] Advanced analytics dashboard
[client]
showErrorDetails = true
```
---
## π§ Database Management
### Re-calculate Clusters
1. Go to Home tab
2. Click π **Refresh** button
3. Wait for spinner to complete
### Clear Everything and Start Fresh
1. Click ποΈ **Clear All Dumps** in sidebar
2. Confirm action
3. Add new thoughts
### Neo4j Maintenance
Use the `neo4j_maintenance.py` script:
```bash
# Show database statistics
python neo4j_maintenance.py stats
# Remove duplicate brain dumps
python neo4j_maintenance.py dedup
# Clear all data (WARNING: Irreversible)
python neo4j_maintenance.py clear
```
---
## π Performance Tips
### Clustering
- **Fast**: 3-20 dumps (< 5 seconds)
- **Moderate**: 20-100 dumps (5-30 seconds)
- **Slow**: 100+ dumps (> 30 seconds)
- Use caching to avoid recomputing
### API Usage
- **Google Gemini**: Free tier allows ~60 requests/min
- **Tavily Search**: Free tier allows ~100 searches/month
- Set environment variables to enable features
### Neo4j Query Performance
- Dump and cluster lookups are indexed for fast retrieval
- Embedding vectors cached in graph nodes
- Knowledge graph relationships enable fast similarity searches
---
## π Troubleshooting
### Neo4j Connection Error
β Verify your Aura instance is running: https://console.neo4j.io/
β Check `NEO4J_URI`, `NEO4J_USER`, `NEO4J_PASSWORD` in `.env`
β Ensure your IP is allowlisted in Aura instance settings
### "API Key not found" error
β Make sure `.env` file exists with `GOOGLE_API_KEY`
β Restart streamlit: `streamlit run app.py`
### Clustering takes forever
β You might have 100+ dumps
β Only happens on first run or "Refresh"
β Consider batching cluster operations for large datasets
### Feed cards showing mock data
β Your `TAVILY_API_KEY` isn't set
β Add it to `.env` and restart
### "ModuleNotFoundError" for imports
β Missing dependencies: `pip install -r requirements.txt`
β Wrong Python version? Try `python3 -m pip install ...`
---
## π Architecture Overview
```
braindump_core.py
βββ BrainDumpDB (Neo4j Graph Database)
βββ EmbeddingEngine (sentence-transformers)
βββ ClusterEngine (HDBSCAN + UMAP)
βββ Visualization (Plotly)
agents.py
βββ QuestionAgent (Socratic questions)
βββ SearchAgent (Web search + synthesis)
app.py
βββ Sidebar (Input + Navigation)
βββ Home Tab (Knowledge Graph + Table)
βββ Feed Tab (Blog-style cards)
βββ Helper Functions (Rendering)
neo4j_maintenance.py
βββ Database statistics
βββ Deduplication
βββ Data cleanup
```
---
## π― Next Steps
1. **Set up Neo4j Aura** instance at https://console.neo4j.io/
2. **Add your first thought** via sidebar
3. **Switch between Home and Feed** to see different views
4. **Check back daily** to build your idea garden
5. **Monitor performance** using `neo4j_maintenance.py stats`
---
## π‘ Tips
- **Best for**: Capturing fleeting thoughts, finding patterns, exploring ideas
- **Start small**: 5-10 thoughts to see clustering in action
- **Use specificity**: "Why do dreams fade?" works better than "dreams"
- **Review regularly**: Feed tab is great for morning/evening review
- **Share clusters**: Screenshot Home tab to share your thinking
---
## π Notes
- All data stored locally in `braindump.db` (no cloud sync)
- Embeddings cached in database (fast retrieval)
- Cluster labels generated once and reused
- Each brain dump timestamped automatically
---
**Ready to catch your thoughts before they slip away!** π§ β¨
For issues or questions, check REFACTOR_SUMMARY.md or ARCHITECTURE.md |