full upgrade to dev
This commit is contained in:
460
docs/ACTIVITY_FEATURES.md
Normal file
460
docs/ACTIVITY_FEATURES.md
Normal file
@@ -0,0 +1,460 @@
|
||||
# 🎨 Activity Feed Features & Animations
|
||||
|
||||
## ✨ Implementierte Features
|
||||
|
||||
### 1. **Dynamische Activity Bubbles**
|
||||
Jede Aktivität hat ihre eigene:
|
||||
- 🎨 Einzigartige Pastellfarben
|
||||
- 🎭 Spezifische Animationen
|
||||
- 🔗 Interaktive Links
|
||||
- 💫 Hintergrundeffekte
|
||||
|
||||
---
|
||||
|
||||
## 🎬 Animations-Typen
|
||||
|
||||
### 🔨 Coding Activity
|
||||
**Visueller Effekt:**
|
||||
- **Matrix Rain** im Hintergrund (grüne 0/1 Zahlen fallen)
|
||||
- Rotierendes Terminal-Icon
|
||||
- Grüner Pulsing-Dot
|
||||
|
||||
**Daten:**
|
||||
```json
|
||||
{
|
||||
"type": "coding",
|
||||
"details": "Building Portfolio Website",
|
||||
"project": "portfolio",
|
||||
"language": "TypeScript",
|
||||
"repo": "https://github.com/user/repo",
|
||||
"link": "https://github.com/user/repo/commit/abc123"
|
||||
}
|
||||
```
|
||||
|
||||
**Animation:**
|
||||
- 15 vertikal fallende Spalten mit 0/1 Zeichen
|
||||
- Unterschiedliche Geschwindigkeiten (2-5s)
|
||||
- Opacity fade in/out
|
||||
- Mint-grüne Farbe (liquid-mint)
|
||||
|
||||
---
|
||||
|
||||
### 🎵 Music Activity (Now Playing)
|
||||
**Visueller Effekt:**
|
||||
- **Sound Waves** (5 animierte Balken)
|
||||
- Rotierendes Album Cover (10s pro Rotation)
|
||||
- Pulsierendes Headphone-Icon
|
||||
- Progress Bar
|
||||
|
||||
**Daten:**
|
||||
```json
|
||||
{
|
||||
"isPlaying": true,
|
||||
"track": "Song Title",
|
||||
"artist": "Artist Name",
|
||||
"album": "Album Name",
|
||||
"progress": 45,
|
||||
"albumArt": "https://url-to-image.jpg",
|
||||
"spotifyUrl": "https://open.spotify.com/track/..."
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- ✅ Link "Listen with me" → Spotify Track
|
||||
- ✅ Live Progress Bar (0-100%)
|
||||
- ✅ Verschwindet automatisch wenn Musik stoppt
|
||||
- ✅ Album Cover rotiert kontinuierlich
|
||||
|
||||
**Animation:**
|
||||
- 5 vertikale Balken bewegen sich wellenförmig (20-80% Höhe)
|
||||
- Jeder Balken 0.1s delay
|
||||
- 0.8s Animationsdauer
|
||||
- Rose/Coral Gradient
|
||||
|
||||
---
|
||||
|
||||
### 🏃 Running Activity
|
||||
**Visueller Effekt:**
|
||||
- **Animierter Läufer-Emoji** (🏃) bewegt sich von links nach rechts
|
||||
- Horizontale "Laufbahn" als Linie
|
||||
- Lime-grüne Farbpalette
|
||||
|
||||
**Daten:**
|
||||
```json
|
||||
{
|
||||
"type": "running",
|
||||
"details": "Morning run - 5km",
|
||||
"link": "https://strava.com/activities/..."
|
||||
}
|
||||
```
|
||||
|
||||
**Animation:**
|
||||
- Läufer bewegt sich linear von -10% bis 110% (3s)
|
||||
- Kontinuierliche Wiederholung
|
||||
- Unendlich Loop
|
||||
|
||||
---
|
||||
|
||||
### 🎮 Gaming Activity
|
||||
**Visueller Effekt:**
|
||||
- **Particle System** (10 schwebende Partikel)
|
||||
- Peach/Orange Farbschema
|
||||
- Gamepad-Icon
|
||||
|
||||
**Daten:**
|
||||
```json
|
||||
{
|
||||
"game": "Elden Ring",
|
||||
"platform": "steam",
|
||||
"status": "playing"
|
||||
}
|
||||
```
|
||||
|
||||
**Animation:**
|
||||
- 10 Partikel an zufälligen Positionen
|
||||
- Scale animation (0 → 1 → 0)
|
||||
- Opacity fade
|
||||
- Unterschiedliche Delays (0-2s)
|
||||
- 2s Gesamtdauer, unendlich
|
||||
|
||||
---
|
||||
|
||||
### 📺 Watching Activity
|
||||
**Visueller Effekt:**
|
||||
- **TV Scan Lines** (retro CRT-Effekt)
|
||||
- Lavender/Pink Gradient
|
||||
- TV-Icon
|
||||
|
||||
**Daten:**
|
||||
```json
|
||||
{
|
||||
"title": "Breaking Bad S05E14",
|
||||
"platform": "netflix",
|
||||
"type": "series"
|
||||
}
|
||||
```
|
||||
|
||||
**Animation:**
|
||||
- Horizontaler Gradient-Balken (8px hoch)
|
||||
- Bewegt sich von -100% bis 200% vertikal
|
||||
- 3s linear
|
||||
- Weiß/transparent gradient
|
||||
- Simuliert alte TV-Bildschirme
|
||||
|
||||
---
|
||||
|
||||
### 😊 Status & Mood
|
||||
**Visueller Effekt:**
|
||||
- **Wackelndes Emoji** (rotate: 0° → 10° → -10° → 0°)
|
||||
- Lavender/Pink Gradient
|
||||
- Custom Message
|
||||
|
||||
**Daten:**
|
||||
```json
|
||||
{
|
||||
"mood": "💻",
|
||||
"customMessage": "Deep work mode - Building features"
|
||||
}
|
||||
```
|
||||
|
||||
**Animation:**
|
||||
- Emoji schwingt hin und her
|
||||
- 2s Dauer, easeInOut
|
||||
- Unendliche Wiederholung
|
||||
- Subtile Bewegung (-10° bis +10°)
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Interaktive Elemente
|
||||
|
||||
### 1. **Spotify "Listen with me"**
|
||||
```tsx
|
||||
<a href={spotifyUrl} target="_blank">
|
||||
<Waves size={10} />
|
||||
Listen with me
|
||||
</a>
|
||||
```
|
||||
- Öffnet Spotify Web Player
|
||||
- Direkt zum aktuellen Song
|
||||
- Kleine Wellen-Icon
|
||||
|
||||
### 2. **GitHub "View Repo"**
|
||||
```tsx
|
||||
<a href={repoUrl} target="_blank">
|
||||
View <ExternalLink size={10} />
|
||||
</a>
|
||||
```
|
||||
- Link zum Repository
|
||||
- External Link Icon
|
||||
- Hover Underline
|
||||
|
||||
### 3. **Live Progress Bar**
|
||||
- Dynamisch basiert auf Spotify API
|
||||
- Smooth animation (0.5s transition)
|
||||
- Rose → Coral Gradient
|
||||
|
||||
---
|
||||
|
||||
## 🎨 Farbschema pro Activity
|
||||
|
||||
| Activity | Background Gradient | Border | Pulse Dot |
|
||||
|----------|-------------------|--------|-----------|
|
||||
| Coding | `from-liquid-mint/20 to-liquid-sky/20` | `border-liquid-mint/40` | Green |
|
||||
| Music | `from-liquid-rose/20 to-liquid-coral/20` | `border-liquid-rose/40` | Red |
|
||||
| Gaming | `from-liquid-peach/20 to-liquid-yellow/20` | `border-liquid-peach/40` | Orange |
|
||||
| Watching | `from-liquid-lavender/20 to-liquid-pink/20` | `border-liquid-lavender/40` | Purple |
|
||||
| Running | `from-liquid-lime/20 to-liquid-mint/20` | `border-liquid-lime/40` | Lime |
|
||||
| Reading | `from-liquid-teal/20 to-liquid-lime/20` | `border-liquid-teal/40` | Teal |
|
||||
|
||||
---
|
||||
|
||||
## 💬 AI Chatbot Features
|
||||
|
||||
### Design
|
||||
- **Gradient Header**: Mint → Sky
|
||||
- **Message Bubbles**:
|
||||
- User: Stone-900 gradient, rounded-tr-none
|
||||
- AI: White → Stone-50 gradient, rounded-tl-none
|
||||
- **Sparkles Icon**: Animated AI indicator
|
||||
- **Thinking State**: Rotating Loader2 mit liquid-mint Farbe
|
||||
|
||||
### Features
|
||||
- ✅ Real-time responses via n8n
|
||||
- ✅ Fallback responses bei Offline
|
||||
- ✅ Context über Dennis
|
||||
- ✅ Smooth animations
|
||||
- ✅ Loading states
|
||||
- ✅ Error handling
|
||||
|
||||
### Example Responses
|
||||
```
|
||||
"Great question! Dennis specializes in..."
|
||||
"Dennis loves self-hosting! He manages..."
|
||||
"Check out his projects to see what he's building!"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎭 Zusätzliche Animation-Ideen
|
||||
|
||||
### Noch nicht implementiert (Ideen):
|
||||
|
||||
#### 1. **Coffee Counter ☕**
|
||||
```tsx
|
||||
{coffeeCount > 0 && (
|
||||
<motion.div
|
||||
animate={{
|
||||
y: [0, -5, 0],
|
||||
rotate: [0, -5, 5, 0]
|
||||
}}
|
||||
>
|
||||
☕ × {coffeeCount}
|
||||
</motion.div>
|
||||
)}
|
||||
```
|
||||
|
||||
#### 2. **Code Streak 🔥**
|
||||
```tsx
|
||||
<motion.div>
|
||||
🔥 {consecutiveDays} day streak!
|
||||
</motion.div>
|
||||
```
|
||||
|
||||
#### 3. **Live Visitor Count 👥**
|
||||
```tsx
|
||||
<motion.div
|
||||
animate={{ scale: [1, 1.05, 1] }}
|
||||
>
|
||||
👥 {liveVisitors} online
|
||||
</motion.div>
|
||||
```
|
||||
|
||||
#### 4. **Deployment Status 🚀**
|
||||
```tsx
|
||||
{isDeploying && (
|
||||
<motion.div>
|
||||
<Rocket className="animate-bounce" />
|
||||
Deploying...
|
||||
</motion.div>
|
||||
)}
|
||||
```
|
||||
|
||||
#### 5. **Weather Integration 🌤️**
|
||||
```tsx
|
||||
<motion.div>
|
||||
{weatherEmoji} {temperature}°C in Osnabrück
|
||||
</motion.div>
|
||||
```
|
||||
|
||||
#### 6. **Pomodoro Timer 🍅**
|
||||
```tsx
|
||||
{pomodoroActive && (
|
||||
<CircularProgress value={timeLeft} />
|
||||
)}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Auto-Clear Logic
|
||||
|
||||
### Musik
|
||||
- ✅ Verschwindet automatisch wenn `is_playing = false`
|
||||
- ✅ n8n checkt alle 30s via Spotify API
|
||||
- ✅ Database Update wenn gestoppt
|
||||
|
||||
### Aktivitäten
|
||||
- ✅ Verfallen nach 2 Stunden
|
||||
- ✅ Check in API Route: `hoursSinceUpdate < 2`
|
||||
- ✅ Optionaler n8n Cleanup-Workflow
|
||||
|
||||
### Gaming
|
||||
- ✅ Basiert auf Discord Presence
|
||||
- ✅ Auto-clear wenn Spiel beendet
|
||||
|
||||
---
|
||||
|
||||
## 📱 Responsive Design
|
||||
|
||||
### Mobile (< 768px)
|
||||
- Bubbles: `max-w-[calc(100vw-6rem)]`
|
||||
- Stacked vertikal
|
||||
- Chat: Full-width minus padding
|
||||
|
||||
### Desktop (> 768px)
|
||||
- Fixed `bottom-6 right-6`
|
||||
- Bubbles: `max-w-xs` (320px)
|
||||
- Chat: 384px breit
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Performance
|
||||
|
||||
### Optimierungen
|
||||
- ✅ `will-change: transform` für Animationen
|
||||
- ✅ `AnimatePresence` für smooth exit
|
||||
- ✅ `overflow: hidden` auf animated containers
|
||||
- ✅ `pointer-events-none` auf Hintergrund-Effekte
|
||||
- ✅ CSS `backdrop-filter` statt JS blur
|
||||
- ✅ Relative Z-Index (10, 20, 9999)
|
||||
|
||||
### Polling
|
||||
- Frontend: Alle 30s (konfigurierbar)
|
||||
- Spotify: Alle 30s (n8n)
|
||||
- GitHub: Echtzeit via Webhooks
|
||||
- Discord: Alle 60s
|
||||
|
||||
---
|
||||
|
||||
## 🎨 Neue Activity hinzufügen
|
||||
|
||||
### 1. **Backend (Database)**
|
||||
```sql
|
||||
ALTER TABLE activity_status
|
||||
ADD COLUMN new_activity_field VARCHAR(255);
|
||||
```
|
||||
|
||||
### 2. **n8n Workflow**
|
||||
```javascript
|
||||
// Update database
|
||||
UPDATE activity_status SET
|
||||
new_activity_field = 'value'
|
||||
WHERE id = 1;
|
||||
```
|
||||
|
||||
### 3. **Frontend (ActivityFeed.tsx)**
|
||||
```tsx
|
||||
// Add to interface
|
||||
interface ActivityData {
|
||||
newActivity: {
|
||||
field: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
// Add color scheme
|
||||
const activityColors = {
|
||||
newActivity: {
|
||||
bg: "from-liquid-purple/20 to-liquid-pink/20",
|
||||
border: "border-liquid-purple/40",
|
||||
text: "text-liquid-purple",
|
||||
pulse: "bg-purple-500",
|
||||
}
|
||||
};
|
||||
|
||||
// Add animation component
|
||||
const NewActivityAnimation = () => {
|
||||
return (
|
||||
<div className="absolute inset-0">
|
||||
{/* Your custom animation */}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Render function
|
||||
const renderNewActivity = () => {
|
||||
if (!data?.newActivity) return null;
|
||||
|
||||
return (
|
||||
<motion.div className="...">
|
||||
<NewActivityAnimation />
|
||||
{/* Content */}
|
||||
</motion.div>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 Analytics Integration
|
||||
|
||||
### Track Activity Views
|
||||
```typescript
|
||||
// In ActivityFeed
|
||||
useEffect(() => {
|
||||
if (data?.activity) {
|
||||
fetch('/api/analytics/activity-view', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
type: data.activity.type
|
||||
})
|
||||
});
|
||||
}
|
||||
}, [data?.activity]);
|
||||
```
|
||||
|
||||
### Popular Activities Dashboard
|
||||
```sql
|
||||
SELECT
|
||||
activity_type,
|
||||
COUNT(*) as views,
|
||||
AVG(duration) as avg_duration
|
||||
FROM activity_history
|
||||
WHERE created_at > NOW() - INTERVAL '7 days'
|
||||
GROUP BY activity_type
|
||||
ORDER BY views DESC;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Nächste Steps
|
||||
|
||||
1. ✅ Datenbank Setup (`setup_activity_status.sql`)
|
||||
2. ✅ n8n Workflows importieren
|
||||
3. ⏳ Spotify OAuth konfigurieren
|
||||
4. ⏳ GitHub Webhooks setup
|
||||
5. ⏳ Activity Dashboard testen
|
||||
6. ⏳ AI Chatbot mit OpenAI verbinden
|
||||
7. ⏳ Auto-Clear Workflows aktivieren
|
||||
|
||||
---
|
||||
|
||||
## 🎨 Design Philosophy
|
||||
|
||||
- **Smooth**: Alle Animationen 0.5-1s, nie schneller
|
||||
- **Subtle**: Opacity 20-40%, nie zu grell
|
||||
- **Consistent**: Gleiche Easing-Function überall
|
||||
- **Performant**: GPU-beschleunigt (transform, opacity)
|
||||
- **Delightful**: Kleine Details machen den Unterschied
|
||||
|
||||
---
|
||||
|
||||
**Happy Coding! 🚀**
|
||||
470
docs/DYNAMIC_ACTIVITY_MANAGEMENT.md
Normal file
470
docs/DYNAMIC_ACTIVITY_MANAGEMENT.md
Normal file
@@ -0,0 +1,470 @@
|
||||
# 🎛️ Dynamic Activity Management - No Rebuild Required!
|
||||
|
||||
## Übersicht
|
||||
|
||||
Dieses System erlaubt dir, alle Aktivitäten dynamisch zu steuern **ohne die Website neu zu bauen**. Alle Änderungen werden in Echtzeit über die Datenbank und n8n gesteuert.
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Konzept: Zentrales Management
|
||||
|
||||
```
|
||||
┌─────────────────┐
|
||||
│ n8n Dashboard │ ← Du steuerst hier alles
|
||||
└────────┬────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ PostgreSQL │ ← Daten werden hier gespeichert
|
||||
└────────┬────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ API Route │ ← Website liest alle 30s
|
||||
└────────┬────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ ActivityFeed UI │ ← Besucher sehen live updates
|
||||
└─────────────────┘
|
||||
```
|
||||
|
||||
**Vorteile:**
|
||||
- ✅ Keine Website-Rebuild notwendig
|
||||
- ✅ Echtzeit-Updates (30 Sekunden)
|
||||
- ✅ Volle Kontrolle via n8n
|
||||
- ✅ Historische Daten verfügbar
|
||||
- ✅ Multiple Steuerungsmöglichkeiten
|
||||
|
||||
---
|
||||
|
||||
## 🎮 Management Optionen
|
||||
|
||||
### Option 1: n8n Dashboard UI ⭐ EMPFOHLEN
|
||||
|
||||
Erstelle ein simples n8n Workflow-Dashboard mit Webhook-Buttons:
|
||||
|
||||
**Workflow: "Activity Manager Dashboard"**
|
||||
```json
|
||||
{
|
||||
"nodes": [
|
||||
{
|
||||
"name": "HTTP Server",
|
||||
"type": "n8n-nodes-base.webhook",
|
||||
"parameters": {
|
||||
"path": "activity-dashboard",
|
||||
"method": "GET",
|
||||
"responseMode": "responseNode",
|
||||
"options": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "HTML Dashboard",
|
||||
"type": "n8n-nodes-base.respondToWebhook",
|
||||
"parameters": {
|
||||
"responseBody": "=<html>\n<head>\n <title>Activity Manager</title>\n <style>\n body { font-family: system-ui; max-width: 800px; margin: 50px auto; padding: 20px; }\n .activity-section { background: #f5f5f5; padding: 20px; margin: 20px 0; border-radius: 8px; }\n button { background: #333; color: white; padding: 10px 20px; margin: 5px; border: none; border-radius: 5px; cursor: pointer; }\n button:hover { background: #555; }\n input, select, textarea { padding: 8px; margin: 5px 0; border: 1px solid #ddd; border-radius: 4px; width: 100%; }\n .status { display: inline-block; width: 12px; height: 12px; border-radius: 50%; }\n .active { background: #4ade80; }\n .inactive { background: #ef4444; }\n </style>\n</head>\n<body>\n <h1>🎛️ Activity Manager</h1>\n \n <div class=\"activity-section\">\n <h2>🎵 Music Control</h2>\n <p>Status: <span class=\"status active\"></span> Auto-syncing from Spotify</p>\n <button onclick=\"fetch('/webhook/stop-music', {method:'POST'})\">Stop Music Display</button>\n </div>\n\n <div class=\"activity-section\">\n <h2>💻 Coding Activity</h2>\n <input type=\"text\" id=\"project\" placeholder=\"Project name\">\n <input type=\"text\" id=\"language\" placeholder=\"Language (e.g., TypeScript)\">\n <input type=\"text\" id=\"repo\" placeholder=\"GitHub Repo URL\">\n <button onclick=\"updateCoding()\">Update Coding Status</button>\n <button onclick=\"clearCoding()\">Clear</button>\n </div>\n\n <div class=\"activity-section\">\n <h2>🎮 Gaming</h2>\n <input type=\"text\" id=\"game\" placeholder=\"Game name\">\n <select id=\"platform\">\n <option>steam</option>\n <option>playstation</option>\n <option>xbox</option>\n </select>\n <button onclick=\"updateGaming()\">Start Gaming</button>\n <button onclick=\"stopGaming()\">Stop Gaming</button>\n </div>\n\n <div class=\"activity-section\">\n <h2>😊 Mood & Status</h2>\n <input type=\"text\" id=\"mood\" placeholder=\"Emoji (e.g., 😊, 💻, 🎮)\" maxlength=\"2\">\n <textarea id=\"message\" placeholder=\"Custom message\" rows=\"2\"></textarea>\n <button onclick=\"updateStatus()\">Update Status</button>\n </div>\n\n <div class=\"activity-section\">\n <h2>🏃 Manual Activities</h2>\n <select id=\"activity-type\">\n <option value=\"running\">Running</option>\n <option value=\"reading\">Reading</option>\n <option value=\"watching\">Watching</option>\n </select>\n <input type=\"text\" id=\"activity-details\" placeholder=\"Details\">\n <button onclick=\"updateActivity()\">Start Activity</button>\n <button onclick=\"clearActivity()\">Clear</button>\n </div>\n\n <div class=\"activity-section\">\n <h2>🧹 Quick Actions</h2>\n <button onclick=\"clearAll()\">Clear All Activities</button>\n <button onclick=\"setAFK()\">Set AFK</button>\n <button onclick=\"setFocusMode()\">Focus Mode (DND)</button>\n </div>\n\n <script>\n function updateCoding() {\n fetch('/webhook/update-activity', {\n method: 'POST',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({\n type: 'coding',\n project: document.getElementById('project').value,\n language: document.getElementById('language').value,\n repo: document.getElementById('repo').value\n })\n }).then(() => alert('✅ Updated!'));\n }\n\n function updateGaming() {\n fetch('/webhook/update-activity', {\n method: 'POST',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({\n type: 'gaming',\n game: document.getElementById('game').value,\n platform: document.getElementById('platform').value\n })\n }).then(() => alert('✅ Gaming status updated!'));\n }\n\n function updateStatus() {\n fetch('/webhook/update-status', {\n method: 'POST',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({\n mood: document.getElementById('mood').value,\n message: document.getElementById('message').value\n })\n }).then(() => alert('✅ Status updated!'));\n }\n\n function clearAll() {\n if(confirm('Clear all activities?')) {\n fetch('/webhook/clear-all', {method: 'POST'})\n .then(() => alert('✅ All cleared!'));\n }\n }\n\n function setAFK() {\n fetch('/webhook/update-status', {\n method: 'POST',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({mood: '💤', message: 'AFK - Be right back'})\n }).then(() => alert('✅ AFK mode activated!'));\n }\n </script>\n</body>\n</html>"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Zugriff:**
|
||||
```
|
||||
https://your-n8n-instance.com/webhook/activity-dashboard
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Option 2: Discord Bot Commands
|
||||
|
||||
Erstelle einen Discord Bot für schnelle Updates:
|
||||
|
||||
**Commands:**
|
||||
```
|
||||
!status 💻 Working on new features
|
||||
!coding Portfolio Next.js
|
||||
!music <automatic from spotify>
|
||||
!gaming Elden Ring
|
||||
!clear
|
||||
!afk
|
||||
```
|
||||
|
||||
**n8n Workflow:**
|
||||
```json
|
||||
{
|
||||
"nodes": [
|
||||
{
|
||||
"name": "Discord Webhook",
|
||||
"type": "n8n-nodes-base.webhook",
|
||||
"parameters": {
|
||||
"path": "discord-bot"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Parse Command",
|
||||
"type": "n8n-nodes-base.function",
|
||||
"parameters": {
|
||||
"functionCode": "const message = items[0].json.content;\nconst [command, ...args] = message.split(' ');\n\nswitch(command) {\n case '!status':\n return [{\n json: {\n action: 'update_status',\n mood: args[0],\n message: args.slice(1).join(' ')\n }\n }];\n \n case '!coding':\n return [{\n json: {\n action: 'update_activity',\n type: 'coding',\n details: args.join(' ')\n }\n }];\n \n case '!clear':\n return [{\n json: { action: 'clear_all' }\n }];\n}\n\nreturn [{ json: {} }];"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Update Database",
|
||||
"type": "n8n-nodes-base.postgres"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Option 3: Mobile App / Shortcut
|
||||
|
||||
**iOS Shortcuts:**
|
||||
```
|
||||
1. "Start Coding" → POST to n8n webhook
|
||||
2. "Finished Work" → Clear activity
|
||||
3. "Set Mood" → Update status
|
||||
```
|
||||
|
||||
**Android Tasker:**
|
||||
- Similar webhooks
|
||||
- Location-based triggers
|
||||
- Time-based automation
|
||||
|
||||
---
|
||||
|
||||
### Option 4: CLI Tool
|
||||
|
||||
Erstelle ein simples CLI Tool:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# activity.sh
|
||||
|
||||
N8N_URL="https://your-n8n-instance.com"
|
||||
|
||||
case "$1" in
|
||||
status)
|
||||
curl -X POST "$N8N_URL/webhook/update-status" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"mood\":\"$2\",\"message\":\"$3\"}"
|
||||
;;
|
||||
coding)
|
||||
curl -X POST "$N8N_URL/webhook/update-activity" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"type\":\"coding\",\"project\":\"$2\",\"language\":\"$3\"}"
|
||||
;;
|
||||
clear)
|
||||
curl -X POST "$N8N_URL/webhook/clear-all"
|
||||
;;
|
||||
*)
|
||||
echo "Usage: activity.sh [status|coding|clear] [args]"
|
||||
;;
|
||||
esac
|
||||
```
|
||||
|
||||
**Usage:**
|
||||
```bash
|
||||
./activity.sh status 💻 "Deep work mode"
|
||||
./activity.sh coding "Portfolio" "TypeScript"
|
||||
./activity.sh clear
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Automatische Sync-Workflows
|
||||
|
||||
### Musik geht weg wenn nicht mehr läuft
|
||||
|
||||
**n8n Workflow: "Spotify Auto-Clear"**
|
||||
```json
|
||||
{
|
||||
"nodes": [
|
||||
{
|
||||
"name": "Check Every 30s",
|
||||
"type": "n8n-nodes-base.cron",
|
||||
"parameters": {
|
||||
"cronExpression": "*/30 * * * * *"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Get Spotify Status",
|
||||
"type": "n8n-nodes-base.httpRequest",
|
||||
"parameters": {
|
||||
"url": "https://api.spotify.com/v1/me/player/currently-playing"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Check If Playing",
|
||||
"type": "n8n-nodes-base.if",
|
||||
"parameters": {
|
||||
"conditions": {
|
||||
"boolean": [
|
||||
{
|
||||
"value1": "={{$json.is_playing}}",
|
||||
"value2": false
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Clear Music from Database",
|
||||
"type": "n8n-nodes-base.postgres",
|
||||
"parameters": {
|
||||
"operation": "executeQuery",
|
||||
"query": "UPDATE activity_status SET music_playing = FALSE, music_track = NULL, music_artist = NULL, music_album = NULL, music_album_art = NULL, music_progress = NULL WHERE id = 1"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Auto-Clear nach Zeit
|
||||
|
||||
**n8n Workflow: "Activity Timeout"**
|
||||
```javascript
|
||||
// Function Node: Check Activity Age
|
||||
const lastUpdate = new Date(items[0].json.updated_at);
|
||||
const now = new Date();
|
||||
const hoursSinceUpdate = (now - lastUpdate) / (1000 * 60 * 60);
|
||||
|
||||
// Clear activity if older than 2 hours
|
||||
if (hoursSinceUpdate > 2) {
|
||||
return [{
|
||||
json: {
|
||||
should_clear: true,
|
||||
reason: `Activity too old (${hoursSinceUpdate.toFixed(1)} hours)`
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
||||
return [{ json: { should_clear: false } }];
|
||||
```
|
||||
|
||||
### Smart Activity Detection
|
||||
|
||||
**Workflow: "Detect Coding from Git Commits"**
|
||||
```javascript
|
||||
// When you push to GitHub
|
||||
const commit = items[0].json;
|
||||
const repo = commit.repository.name;
|
||||
const message = commit.head_commit.message;
|
||||
|
||||
// Detect language from files
|
||||
const files = commit.head_commit.modified;
|
||||
const language = files[0]?.split('.').pop(); // Get extension
|
||||
|
||||
return [{
|
||||
json: {
|
||||
activity_type: 'coding',
|
||||
activity_details: message,
|
||||
activity_project: repo,
|
||||
activity_language: language,
|
||||
activity_repo: commit.repository.html_url,
|
||||
link: commit.head_commit.url
|
||||
}
|
||||
}];
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 Activity Analytics Dashboard
|
||||
|
||||
**Workflow: "Activity History & Stats"**
|
||||
|
||||
Speichere Historie in separater Tabelle:
|
||||
|
||||
```sql
|
||||
CREATE TABLE activity_history (
|
||||
id SERIAL PRIMARY KEY,
|
||||
activity_type VARCHAR(50),
|
||||
details TEXT,
|
||||
duration INTEGER, -- in minutes
|
||||
started_at TIMESTAMP,
|
||||
ended_at TIMESTAMP,
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- View für Statistiken
|
||||
CREATE VIEW activity_stats AS
|
||||
SELECT
|
||||
activity_type,
|
||||
COUNT(*) as count,
|
||||
SUM(duration) as total_minutes,
|
||||
AVG(duration) as avg_duration,
|
||||
DATE(created_at) as date
|
||||
FROM activity_history
|
||||
GROUP BY activity_type, DATE(created_at)
|
||||
ORDER BY date DESC;
|
||||
```
|
||||
|
||||
**Dashboard Queries:**
|
||||
```sql
|
||||
-- Heute
|
||||
SELECT * FROM activity_stats WHERE date = CURRENT_DATE;
|
||||
|
||||
-- Diese Woche
|
||||
SELECT activity_type, SUM(total_minutes) as minutes
|
||||
FROM activity_stats
|
||||
WHERE date >= CURRENT_DATE - INTERVAL '7 days'
|
||||
GROUP BY activity_type;
|
||||
|
||||
-- Most Coded Languages
|
||||
SELECT activity_language, COUNT(*)
|
||||
FROM activity_history
|
||||
WHERE activity_type = 'coding'
|
||||
GROUP BY activity_language
|
||||
ORDER BY COUNT(*) DESC;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎨 Custom Activity Types
|
||||
|
||||
Erweitere das System mit eigenen Activity-Types:
|
||||
|
||||
```sql
|
||||
-- Add custom columns
|
||||
ALTER TABLE activity_status
|
||||
ADD COLUMN custom_activity_type VARCHAR(100),
|
||||
ADD COLUMN custom_activity_data JSONB;
|
||||
|
||||
-- Example: Workout tracking
|
||||
UPDATE activity_status SET
|
||||
custom_activity_type = 'workout',
|
||||
custom_activity_data = '{
|
||||
"exercise": "Push-ups",
|
||||
"reps": 50,
|
||||
"icon": "💪",
|
||||
"color": "orange"
|
||||
}'::jsonb
|
||||
WHERE id = 1;
|
||||
```
|
||||
|
||||
**Frontend Support:**
|
||||
```typescript
|
||||
// In ActivityFeed.tsx
|
||||
interface CustomActivity {
|
||||
type: string;
|
||||
data: {
|
||||
icon: string;
|
||||
color: string;
|
||||
[key: string]: any;
|
||||
};
|
||||
}
|
||||
|
||||
// Render custom activities dynamically
|
||||
if (data.customActivity) {
|
||||
return (
|
||||
<motion.div
|
||||
className={`bg-${data.customActivity.data.color}/20`}
|
||||
>
|
||||
<span>{data.customActivity.data.icon}</span>
|
||||
<span>{data.customActivity.type}</span>
|
||||
{/* Render data fields dynamically */}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔐 Security & Best Practices
|
||||
|
||||
### 1. Webhook Authentication
|
||||
|
||||
```javascript
|
||||
// In n8n webhook
|
||||
const secret = $credentials.webhookSecret;
|
||||
const providedSecret = $node["Webhook"].json.headers["x-webhook-secret"];
|
||||
|
||||
if (secret !== providedSecret) {
|
||||
return [{
|
||||
json: { error: "Unauthorized" },
|
||||
statusCode: 401
|
||||
}];
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Rate Limiting
|
||||
|
||||
```sql
|
||||
-- Track requests
|
||||
CREATE TABLE webhook_requests (
|
||||
ip_address VARCHAR(45),
|
||||
endpoint VARCHAR(100),
|
||||
requested_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Check rate limit (max 10 requests per minute)
|
||||
SELECT COUNT(*) FROM webhook_requests
|
||||
WHERE ip_address = $1
|
||||
AND requested_at > NOW() - INTERVAL '1 minute';
|
||||
```
|
||||
|
||||
### 3. Input Validation
|
||||
|
||||
```javascript
|
||||
// In n8n Function node
|
||||
const validateInput = (data) => {
|
||||
if (!data.type || typeof data.type !== 'string') {
|
||||
throw new Error('Invalid activity type');
|
||||
}
|
||||
|
||||
if (data.type === 'coding' && !data.project) {
|
||||
throw new Error('Project name required for coding activity');
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Quick Deploy Checklist
|
||||
|
||||
- [ ] Datenbank Table erstellt (`setup_activity_status.sql`)
|
||||
- [ ] n8n Workflows importiert
|
||||
- [ ] Spotify OAuth konfiguriert
|
||||
- [ ] GitHub Webhooks eingerichtet
|
||||
- [ ] Dashboard-URL getestet
|
||||
- [ ] API Routes deployed
|
||||
- [ ] Environment Variables gesetzt
|
||||
- [ ] Frontend ActivityFeed getestet
|
||||
- [ ] Auto-Clear Workflows aktiviert
|
||||
|
||||
---
|
||||
|
||||
## 💡 Pro-Tipps
|
||||
|
||||
1. **Backup System**: Exportiere n8n Workflows regelmäßig
|
||||
2. **Monitoring**: Setup alerts wenn Workflows fehlschlagen
|
||||
3. **Testing**: Nutze n8n's Test-Modus vor Produktion
|
||||
4. **Logging**: Speichere alle Aktivitäten für Analyse
|
||||
5. **Fallbacks**: Zeige Placeholder wenn keine Daten vorhanden
|
||||
|
||||
---
|
||||
|
||||
## 📞 Quick Support Commands
|
||||
|
||||
```bash
|
||||
# Check database status
|
||||
psql -d portfolio_dev -c "SELECT * FROM activity_status WHERE id = 1;"
|
||||
|
||||
# Clear all activities
|
||||
psql -d portfolio_dev -c "UPDATE activity_status SET activity_type = NULL, music_playing = FALSE WHERE id = 1;"
|
||||
|
||||
# View recent history
|
||||
psql -d portfolio_dev -c "SELECT * FROM activity_history ORDER BY created_at DESC LIMIT 10;"
|
||||
|
||||
# Test n8n webhook
|
||||
curl -X POST https://your-n8n.com/webhook/update-activity \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"type":"coding","details":"Testing","project":"Portfolio"}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
Happy automating! 🎉
|
||||
590
docs/N8N_INTEGRATION.md
Normal file
590
docs/N8N_INTEGRATION.md
Normal file
@@ -0,0 +1,590 @@
|
||||
# 🚀 n8n Integration Guide - Complete Setup
|
||||
|
||||
## Übersicht
|
||||
|
||||
Dieses Portfolio nutzt n8n für:
|
||||
- ⚡ **Echtzeit-Aktivitätsanzeige** (Coding, Musik, Gaming, etc.)
|
||||
- 💬 **AI-Chatbot** (mit OpenAI/Anthropic)
|
||||
- 📊 **Aktivitäts-Tracking** (GitHub, Spotify, Netflix, etc.)
|
||||
- 🎮 **Gaming-Status** (Steam, Discord)
|
||||
- 📧 **Automatische Benachrichtigungen**
|
||||
|
||||
---
|
||||
|
||||
## 🎨 Coole Ideen für Integrationen
|
||||
|
||||
### 1. **GitHub Activity Feed** 🔨
|
||||
**Was es zeigt:**
|
||||
- "Currently coding: Portfolio Website"
|
||||
- "Last commit: 5 minutes ago"
|
||||
- "Working on: feature/n8n-integration"
|
||||
- Programming language (TypeScript, Python, etc.)
|
||||
|
||||
**n8n Workflow:**
|
||||
```
|
||||
GitHub Webhook → Extract Data → Update Database → Display on Site
|
||||
```
|
||||
|
||||
### 2. **Spotify Now Playing** 🎵
|
||||
**Was es zeigt:**
|
||||
- Aktueller Song + Artist
|
||||
- Album Cover (rotierend animiert!)
|
||||
- Fortschrittsbalken
|
||||
- "Listening to X since Y minutes"
|
||||
|
||||
**n8n Workflow:**
|
||||
```
|
||||
Cron (every 30s) → Spotify API → Parse Track Data → Update Database
|
||||
```
|
||||
|
||||
### 3. **Netflix/YouTube/Twitch Watching** 📺
|
||||
**Was es zeigt:**
|
||||
- "Watching: Breaking Bad S05E14"
|
||||
- "Streaming: Coding Tutorial"
|
||||
- Platform badges (Netflix/YouTube/Twitch)
|
||||
|
||||
**n8n Workflow:**
|
||||
```
|
||||
Trakt.tv API → Get Current Watching → Update Database
|
||||
Discord Rich Presence → Extract Activity → Update Database
|
||||
```
|
||||
|
||||
### 4. **Gaming Activity** 🎮
|
||||
**Was es zeigt:**
|
||||
- "Playing: Elden Ring"
|
||||
- Platform: Steam/PlayStation/Xbox
|
||||
- Play time
|
||||
- Achievement notifications
|
||||
|
||||
**n8n Workflow:**
|
||||
```
|
||||
Steam API → Get Current Game → Update Database
|
||||
Discord Presence → Parse Game → Update Database
|
||||
```
|
||||
|
||||
### 5. **Mood & Custom Status** 😊
|
||||
**Was es zeigt:**
|
||||
- Emoji mood (😊, 💻, 🏃, 🎮, 😴)
|
||||
- Custom message: "Focused on DevOps"
|
||||
- Auto-status based on time/activity
|
||||
|
||||
**n8n Workflow:**
|
||||
```
|
||||
Schedule → Determine Status (work hours/break/sleep) → Update Database
|
||||
Manual Webhook → Set Custom Status → Update Database
|
||||
```
|
||||
|
||||
### 6. **Smart Notifications** 📬
|
||||
**Was es zeigt:**
|
||||
- "New email from X"
|
||||
- "GitHub PR needs review"
|
||||
- "Calendar event in 15 min"
|
||||
|
||||
**n8n Workflow:**
|
||||
```
|
||||
Email/Calendar/GitHub → Filter Important → Create Notification → Display
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📦 Setup: Datenbank Schema
|
||||
|
||||
### PostgreSQL Table: `activity_status`
|
||||
|
||||
```sql
|
||||
CREATE TABLE activity_status (
|
||||
id SERIAL PRIMARY KEY,
|
||||
|
||||
-- Activity
|
||||
activity_type VARCHAR(50), -- 'coding', 'listening', 'watching', 'gaming', 'reading'
|
||||
activity_details TEXT,
|
||||
activity_project VARCHAR(255),
|
||||
activity_language VARCHAR(50),
|
||||
activity_repo VARCHAR(255),
|
||||
|
||||
-- Music
|
||||
music_playing BOOLEAN DEFAULT FALSE,
|
||||
music_track VARCHAR(255),
|
||||
music_artist VARCHAR(255),
|
||||
music_album VARCHAR(255),
|
||||
music_platform VARCHAR(50), -- 'spotify', 'apple'
|
||||
music_progress INTEGER, -- 0-100
|
||||
music_album_art TEXT,
|
||||
|
||||
-- Watching
|
||||
watching_title VARCHAR(255),
|
||||
watching_platform VARCHAR(50), -- 'youtube', 'netflix', 'twitch'
|
||||
watching_type VARCHAR(50), -- 'video', 'stream', 'movie', 'series'
|
||||
|
||||
-- Gaming
|
||||
gaming_game VARCHAR(255),
|
||||
gaming_platform VARCHAR(50), -- 'steam', 'playstation', 'xbox'
|
||||
gaming_status VARCHAR(50), -- 'playing', 'idle'
|
||||
|
||||
-- Status
|
||||
status_mood VARCHAR(10), -- emoji
|
||||
status_message TEXT,
|
||||
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 n8n Workflows
|
||||
|
||||
### Workflow 1: GitHub Activity Tracker
|
||||
|
||||
**Trigger:** Webhook bei Push/Commit
|
||||
**Frequenz:** Echtzeit
|
||||
|
||||
```json
|
||||
{
|
||||
"nodes": [
|
||||
{
|
||||
"name": "GitHub Webhook",
|
||||
"type": "n8n-nodes-base.webhook",
|
||||
"parameters": {
|
||||
"path": "github-activity",
|
||||
"method": "POST"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Extract Commit Data",
|
||||
"type": "n8n-nodes-base.function",
|
||||
"parameters": {
|
||||
"functionCode": "const commit = items[0].json;\nreturn [\n {\n json: {\n activity_type: 'coding',\n activity_details: commit.head_commit.message,\n activity_project: commit.repository.name,\n activity_language: 'TypeScript',\n activity_repo: commit.repository.html_url,\n updated_at: new Date().toISOString()\n }\n }\n];"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Update Database",
|
||||
"type": "n8n-nodes-base.postgres",
|
||||
"parameters": {
|
||||
"operation": "executeQuery",
|
||||
"query": "INSERT INTO activity_status (activity_type, activity_details, activity_project, activity_language, activity_repo, updated_at) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (id) DO UPDATE SET activity_type = $1, activity_details = $2, activity_project = $3, activity_language = $4, activity_repo = $5, updated_at = $6 WHERE activity_status.id = 1"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Setup in GitHub:**
|
||||
1. Gehe zu deinem Repository → Settings → Webhooks
|
||||
2. Add webhook: `https://your-n8n-instance.com/webhook/github-activity`
|
||||
3. Content type: `application/json`
|
||||
4. Events: Push events
|
||||
|
||||
---
|
||||
|
||||
### Workflow 2: Spotify Now Playing
|
||||
|
||||
**Trigger:** Cron (alle 30 Sekunden)
|
||||
|
||||
```json
|
||||
{
|
||||
"nodes": [
|
||||
{
|
||||
"name": "Schedule",
|
||||
"type": "n8n-nodes-base.cron",
|
||||
"parameters": {
|
||||
"cronExpression": "*/30 * * * * *"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Spotify API",
|
||||
"type": "n8n-nodes-base.httpRequest",
|
||||
"parameters": {
|
||||
"url": "https://api.spotify.com/v1/me/player/currently-playing",
|
||||
"method": "GET",
|
||||
"authentication": "oAuth2",
|
||||
"headers": {
|
||||
"Authorization": "Bearer {{$credentials.spotify.accessToken}}"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Parse Track Data",
|
||||
"type": "n8n-nodes-base.function",
|
||||
"parameters": {
|
||||
"functionCode": "const track = items[0].json;\nif (!track || !track.is_playing) {\n return [{ json: { music_playing: false } }];\n}\n\nreturn [\n {\n json: {\n music_playing: true,\n music_track: track.item.name,\n music_artist: track.item.artists[0].name,\n music_album: track.item.album.name,\n music_platform: 'spotify',\n music_progress: Math.round((track.progress_ms / track.item.duration_ms) * 100),\n music_album_art: track.item.album.images[0].url,\n updated_at: new Date().toISOString()\n }\n }\n];"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Update Database",
|
||||
"type": "n8n-nodes-base.postgres",
|
||||
"parameters": {
|
||||
"operation": "executeQuery",
|
||||
"query": "UPDATE activity_status SET music_playing = $1, music_track = $2, music_artist = $3, music_album = $4, music_platform = $5, music_progress = $6, music_album_art = $7, updated_at = $8 WHERE id = 1"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Spotify API Setup:**
|
||||
1. Gehe zu https://developer.spotify.com/dashboard
|
||||
2. Create App
|
||||
3. Add Redirect URI: `https://your-n8n-instance.com/oauth/callback`
|
||||
4. Kopiere Client ID & Secret in n8n Credentials
|
||||
5. Scopes: `user-read-currently-playing`, `user-read-playback-state`
|
||||
|
||||
---
|
||||
|
||||
### Workflow 3: AI Chatbot mit OpenAI
|
||||
|
||||
**Trigger:** Webhook bei Chat-Message
|
||||
|
||||
```json
|
||||
{
|
||||
"nodes": [
|
||||
{
|
||||
"name": "Chat Webhook",
|
||||
"type": "n8n-nodes-base.webhook",
|
||||
"parameters": {
|
||||
"path": "chat",
|
||||
"method": "POST"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Build Context",
|
||||
"type": "n8n-nodes-base.function",
|
||||
"parameters": {
|
||||
"functionCode": "const userMessage = items[0].json.message;\n\nconst context = `You are Dennis Konkol's AI assistant. Here's information about Dennis:\n\n- Student in Osnabrück, Germany\n- Passionate self-hoster and DevOps enthusiast\n- Skills: Next.js, Flutter, Docker Swarm, Traefik, CI/CD, n8n\n- Runs own infrastructure on IONOS and OVHcloud\n- Projects: Clarity (Flutter dyslexia app), Self-hosted portfolio with Docker Swarm\n- Hobbies: Gaming, Jogging, Experimenting with tech\n- Fun fact: Uses pen & paper for calendar despite automating everything\n\nAnswer questions about Dennis professionally and friendly. Keep answers concise (2-3 sentences).\n\nUser question: ${userMessage}`;\n\nreturn [{ json: { context, userMessage } }];"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "OpenAI Chat",
|
||||
"type": "n8n-nodes-base.openAi",
|
||||
"parameters": {
|
||||
"resource": "chat",
|
||||
"operation": "message",
|
||||
"model": "gpt-4",
|
||||
"messages": {
|
||||
"values": [
|
||||
{
|
||||
"role": "system",
|
||||
"content": "={{$node[\"Build Context\"].json[\"context\"]}}"
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "={{$node[\"Build Context\"].json[\"userMessage\"]}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Return Response",
|
||||
"type": "n8n-nodes-base.respondToWebhook",
|
||||
"parameters": {
|
||||
"responseBody": "={{ { reply: $json.message.content } }}"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**OpenAI API Setup:**
|
||||
1. Gehe zu https://platform.openai.com/api-keys
|
||||
2. Create API Key
|
||||
3. Add zu n8n Credentials
|
||||
4. Wähle Model: gpt-4 oder gpt-3.5-turbo
|
||||
|
||||
---
|
||||
|
||||
### Workflow 4: Discord/Steam Gaming Status
|
||||
|
||||
**Trigger:** Cron (alle 60 Sekunden)
|
||||
|
||||
```json
|
||||
{
|
||||
"nodes": [
|
||||
{
|
||||
"name": "Schedule",
|
||||
"type": "n8n-nodes-base.cron",
|
||||
"parameters": {
|
||||
"cronExpression": "0 * * * * *"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Discord API",
|
||||
"type": "n8n-nodes-base.httpRequest",
|
||||
"parameters": {
|
||||
"url": "https://discord.com/api/v10/users/@me",
|
||||
"method": "GET",
|
||||
"authentication": "oAuth2",
|
||||
"headers": {
|
||||
"Authorization": "Bot {{$credentials.discord.token}}"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Parse Gaming Status",
|
||||
"type": "n8n-nodes-base.function",
|
||||
"parameters": {
|
||||
"functionCode": "const user = items[0].json;\nconst activity = user.activities?.find(a => a.type === 0); // 0 = Playing\n\nif (!activity) {\n return [{ json: { gaming_game: null, gaming_status: 'idle' } }];\n}\n\nreturn [\n {\n json: {\n gaming_game: activity.name,\n gaming_platform: 'discord',\n gaming_status: 'playing',\n updated_at: new Date().toISOString()\n }\n }\n];"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Update Database",
|
||||
"type": "n8n-nodes-base.postgres",
|
||||
"parameters": {
|
||||
"operation": "executeQuery",
|
||||
"query": "UPDATE activity_status SET gaming_game = $1, gaming_platform = $2, gaming_status = $3, updated_at = $4 WHERE id = 1"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Workflow 5: Smart Status (Auto-Detect)
|
||||
|
||||
**Trigger:** Cron (alle 5 Minuten)
|
||||
|
||||
```json
|
||||
{
|
||||
"nodes": [
|
||||
{
|
||||
"name": "Schedule",
|
||||
"type": "n8n-nodes-base.cron",
|
||||
"parameters": {
|
||||
"cronExpression": "*/5 * * * *"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Determine Status",
|
||||
"type": "n8n-nodes-base.function",
|
||||
"parameters": {
|
||||
"functionCode": "const hour = new Date().getHours();\nconst day = new Date().getDay(); // 0 = Sunday, 6 = Saturday\n\nlet mood = '💻';\nlet message = 'Working on projects';\n\n// Sleep time (0-7 Uhr)\nif (hour >= 0 && hour < 7) {\n mood = '😴';\n message = 'Sleeping (probably dreaming of code)';\n}\n// Morning (7-9 Uhr)\nelse if (hour >= 7 && hour < 9) {\n mood = '☕';\n message = 'Morning coffee & catching up';\n}\n// Work time (9-17 Uhr, Mo-Fr)\nelse if (hour >= 9 && hour < 17 && day >= 1 && day <= 5) {\n mood = '💻';\n message = 'Deep work mode - coding & learning';\n}\n// Evening (17-22 Uhr)\nelse if (hour >= 17 && hour < 22) {\n mood = '🎮';\n message = 'Relaxing - gaming or watching shows';\n}\n// Late night (22-24 Uhr)\nelse if (hour >= 22) {\n mood = '🌙';\n message = 'Late night coding session';\n}\n// Weekend\nif (day === 0 || day === 6) {\n mood = '🏃';\n message = 'Weekend vibes - exploring & experimenting';\n}\n\nreturn [\n {\n json: {\n status_mood: mood,\n status_message: message,\n updated_at: new Date().toISOString()\n }\n }\n];"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Update Database",
|
||||
"type": "n8n-nodes-base.postgres",
|
||||
"parameters": {
|
||||
"operation": "executeQuery",
|
||||
"query": "UPDATE activity_status SET status_mood = $1, status_message = $2, updated_at = $3 WHERE id = 1"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔌 Frontend API Integration
|
||||
|
||||
### Update `/app/api/n8n/status/route.ts`
|
||||
|
||||
```typescript
|
||||
import { NextResponse } from 'next/server';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
// Fetch from your activity_status table
|
||||
const status = await prisma.$queryRaw`
|
||||
SELECT * FROM activity_status WHERE id = 1 LIMIT 1
|
||||
`;
|
||||
|
||||
if (!status || status.length === 0) {
|
||||
return NextResponse.json({
|
||||
activity: null,
|
||||
music: null,
|
||||
watching: null,
|
||||
gaming: null,
|
||||
status: null,
|
||||
});
|
||||
}
|
||||
|
||||
const data = status[0];
|
||||
|
||||
return NextResponse.json({
|
||||
activity: data.activity_type ? {
|
||||
type: data.activity_type,
|
||||
details: data.activity_details,
|
||||
project: data.activity_project,
|
||||
language: data.activity_language,
|
||||
repo: data.activity_repo,
|
||||
timestamp: data.updated_at,
|
||||
} : null,
|
||||
music: data.music_playing ? {
|
||||
isPlaying: data.music_playing,
|
||||
track: data.music_track,
|
||||
artist: data.music_artist,
|
||||
album: data.music_album,
|
||||
platform: data.music_platform,
|
||||
progress: data.music_progress,
|
||||
albumArt: data.music_album_art,
|
||||
} : null,
|
||||
watching: data.watching_title ? {
|
||||
title: data.watching_title,
|
||||
platform: data.watching_platform,
|
||||
type: data.watching_type,
|
||||
} : null,
|
||||
gaming: data.gaming_game ? {
|
||||
game: data.gaming_game,
|
||||
platform: data.gaming_platform,
|
||||
status: data.gaming_status,
|
||||
} : null,
|
||||
status: data.status_mood ? {
|
||||
mood: data.status_mood,
|
||||
customMessage: data.status_message,
|
||||
} : null,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching activity status:', error);
|
||||
return NextResponse.json({
|
||||
activity: null,
|
||||
music: null,
|
||||
watching: null,
|
||||
gaming: null,
|
||||
status: null,
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Create `/app/api/n8n/chat/route.ts`
|
||||
|
||||
```typescript
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const { message } = await request.json();
|
||||
|
||||
// Call your n8n chat webhook
|
||||
const response = await fetch(`${process.env.N8N_WEBHOOK_URL}/webhook/chat`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ message }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('n8n webhook failed');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return NextResponse.json({ reply: data.reply });
|
||||
} catch (error) {
|
||||
console.error('Chat API error:', error);
|
||||
return NextResponse.json(
|
||||
{ reply: 'Sorry, I encountered an error. Please try again later.' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🌟 Zusätzliche coole Ideen
|
||||
|
||||
### 1. **Live Coding Stats**
|
||||
- Lines of code today
|
||||
- Most used language this week
|
||||
- GitHub contribution graph
|
||||
- Pull requests merged
|
||||
|
||||
### 2. **Coffee Counter** ☕
|
||||
- Button in n8n Dashboard: "I had coffee"
|
||||
- Displays: "3 coffees today"
|
||||
- Funny messages bei > 5 cups
|
||||
|
||||
### 3. **Mood Tracker**
|
||||
- Manual mood updates via Discord Bot
|
||||
- Shows emoji + custom message
|
||||
- Persists über den Tag
|
||||
|
||||
### 4. **Auto-DND Status**
|
||||
- Wenn du in einem Meeting bist (Calendar API)
|
||||
- Wenn du fokussiert arbeitest (Pomodoro Timer)
|
||||
- Custom status: "🔴 In Deep Work - Back at 15:00"
|
||||
|
||||
### 5. **Project Highlights**
|
||||
- "Currently building: X"
|
||||
- "Deployed Y minutes ago"
|
||||
- "Last successful build: Z"
|
||||
|
||||
### 6. **Social Activity**
|
||||
- "New blog post: Title"
|
||||
- "Trending on Twitter: X mentions"
|
||||
- "LinkedIn: Y profile views this week"
|
||||
|
||||
---
|
||||
|
||||
## 📝 Environment Variables
|
||||
|
||||
Add to `.env.local`:
|
||||
|
||||
```bash
|
||||
# n8n
|
||||
N8N_WEBHOOK_URL=https://your-n8n-instance.com
|
||||
N8N_API_KEY=your_n8n_api_key
|
||||
|
||||
# Spotify
|
||||
SPOTIFY_CLIENT_ID=your_spotify_client_id
|
||||
SPOTIFY_CLIENT_SECRET=your_spotify_client_secret
|
||||
|
||||
# OpenAI
|
||||
OPENAI_API_KEY=your_openai_api_key
|
||||
|
||||
# Discord (optional)
|
||||
DISCORD_BOT_TOKEN=your_discord_bot_token
|
||||
|
||||
# GitHub (optional)
|
||||
GITHUB_WEBHOOK_SECRET=your_github_webhook_secret
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
1. **Setup Database:**
|
||||
```bash
|
||||
psql -U postgres -d portfolio_dev -f setup_activity_status.sql
|
||||
```
|
||||
|
||||
2. **Create n8n Workflows:**
|
||||
- Import workflows via n8n UI
|
||||
- Configure credentials
|
||||
- Activate workflows
|
||||
|
||||
3. **Update API Routes:**
|
||||
- Add `status/route.ts` and `chat/route.ts`
|
||||
- Set environment variables
|
||||
|
||||
4. **Test:**
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
- Check bottom-right corner for activity bubbles
|
||||
- Click chat button to test AI
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Best Practices
|
||||
|
||||
1. **Caching:** Cache API responses für 30s (nicht bei jedem Request neu fetchen)
|
||||
2. **Error Handling:** Graceful fallbacks wenn n8n down ist
|
||||
3. **Rate Limiting:** Limitiere Chat-Requests (max 10/minute)
|
||||
4. **Privacy:** Zeige nur das, was du teilen willst
|
||||
5. **Performance:** Nutze Webhooks statt Polling wo möglich
|
||||
|
||||
---
|
||||
|
||||
## 🤝 Community Ideas
|
||||
|
||||
Teile deine coolen n8n-Integrationen!
|
||||
- Discord: Zeig deinen Setup
|
||||
- GitHub: Share deine Workflows
|
||||
- Blog: Write-up über dein System
|
||||
|
||||
Happy automating! 🎉
|
||||
311
docs/ai-image-generation/ENVIRONMENT.md
Normal file
311
docs/ai-image-generation/ENVIRONMENT.md
Normal file
@@ -0,0 +1,311 @@
|
||||
# Environment Variables for AI Image Generation
|
||||
|
||||
This document lists all environment variables needed for the AI image generation system.
|
||||
|
||||
## Required Variables
|
||||
|
||||
Add these to your `.env.local` file:
|
||||
|
||||
```bash
|
||||
# =============================================================================
|
||||
# AI IMAGE GENERATION CONFIGURATION
|
||||
# =============================================================================
|
||||
|
||||
# n8n Webhook Configuration
|
||||
# The base URL where your n8n instance is running
|
||||
N8N_WEBHOOK_URL=http://localhost:5678/webhook
|
||||
|
||||
# Secret token for authenticating webhook requests
|
||||
# Generate a secure random token: openssl rand -hex 32
|
||||
N8N_SECRET_TOKEN=your-secure-random-token-here
|
||||
|
||||
# Stable Diffusion API Configuration
|
||||
# The URL where your Stable Diffusion WebUI is running
|
||||
SD_API_URL=http://localhost:7860
|
||||
|
||||
# Optional: API key if your SD instance requires authentication
|
||||
# SD_API_KEY=your-sd-api-key-here
|
||||
|
||||
# =============================================================================
|
||||
# IMAGE GENERATION SETTINGS
|
||||
# =============================================================================
|
||||
|
||||
# Automatically generate images when new projects are created
|
||||
# Set to 'true' to enable, 'false' to disable
|
||||
AUTO_GENERATE_IMAGES=true
|
||||
|
||||
# Directory where generated images will be saved
|
||||
# Should be inside your public directory for web access
|
||||
GENERATED_IMAGES_DIR=/app/public/generated-images
|
||||
|
||||
# Maximum time to wait for image generation (in milliseconds)
|
||||
# Default: 180000 (3 minutes)
|
||||
IMAGE_GENERATION_TIMEOUT=180000
|
||||
|
||||
# =============================================================================
|
||||
# STABLE DIFFUSION SETTINGS (Optional - Overrides n8n workflow defaults)
|
||||
# =============================================================================
|
||||
|
||||
# Default image dimensions
|
||||
SD_DEFAULT_WIDTH=1024
|
||||
SD_DEFAULT_HEIGHT=768
|
||||
|
||||
# Generation quality settings
|
||||
SD_DEFAULT_STEPS=30
|
||||
SD_DEFAULT_CFG_SCALE=7
|
||||
|
||||
# Sampler algorithm
|
||||
# Options: "Euler a", "DPM++ 2M Karras", "DDIM", etc.
|
||||
SD_DEFAULT_SAMPLER=DPM++ 2M Karras
|
||||
|
||||
# Default model checkpoint
|
||||
# SD_DEFAULT_MODEL=sd_xl_base_1.0.safetensors
|
||||
|
||||
# =============================================================================
|
||||
# FEATURE FLAGS (Optional)
|
||||
# =============================================================================
|
||||
|
||||
# Enable/disable specific features
|
||||
ENABLE_IMAGE_REGENERATION=true
|
||||
ENABLE_BATCH_GENERATION=false
|
||||
ENABLE_IMAGE_OPTIMIZATION=true
|
||||
|
||||
# =============================================================================
|
||||
# LOGGING & MONITORING (Optional)
|
||||
# =============================================================================
|
||||
|
||||
# Log all image generation requests
|
||||
LOG_IMAGE_GENERATION=true
|
||||
|
||||
# Send notifications on generation success/failure
|
||||
# DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...
|
||||
# SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...
|
||||
|
||||
# =============================================================================
|
||||
# ADVANCED SETTINGS (Optional)
|
||||
# =============================================================================
|
||||
|
||||
# Custom prompt prefix for all generations
|
||||
# SD_CUSTOM_PROMPT_PREFIX=professional tech illustration, modern design,
|
||||
|
||||
# Custom negative prompt suffix for all generations
|
||||
# SD_CUSTOM_NEGATIVE_SUFFIX=low quality, blurry, pixelated, text, watermark
|
||||
|
||||
# Image file naming pattern
|
||||
# Available variables: {projectId}, {timestamp}, {title}
|
||||
IMAGE_FILENAME_PATTERN=project-{projectId}-{timestamp}.png
|
||||
|
||||
# Maximum concurrent image generation requests
|
||||
MAX_CONCURRENT_GENERATIONS=2
|
||||
|
||||
# Retry failed generations
|
||||
AUTO_RETRY_ON_FAILURE=true
|
||||
MAX_RETRY_ATTEMPTS=3
|
||||
```
|
||||
|
||||
## Production Environment
|
||||
|
||||
For production deployments, adjust these settings:
|
||||
|
||||
```bash
|
||||
# Production n8n (if using cloud/dedicated instance)
|
||||
N8N_WEBHOOK_URL=https://n8n.yourdomain.com/webhook
|
||||
|
||||
# Production Stable Diffusion (if using dedicated GPU server)
|
||||
SD_API_URL=https://sd-api.yourdomain.com
|
||||
|
||||
# Production image storage (use absolute path)
|
||||
GENERATED_IMAGES_DIR=/var/www/portfolio/public/generated-images
|
||||
|
||||
# Disable auto-generation in production (manual only)
|
||||
AUTO_GENERATE_IMAGES=false
|
||||
|
||||
# Enable logging
|
||||
LOG_IMAGE_GENERATION=true
|
||||
|
||||
# Set timeouts appropriately
|
||||
IMAGE_GENERATION_TIMEOUT=300000
|
||||
|
||||
# Limit concurrent generations
|
||||
MAX_CONCURRENT_GENERATIONS=1
|
||||
```
|
||||
|
||||
## Docker Environment
|
||||
|
||||
If running in Docker, use these paths:
|
||||
|
||||
```bash
|
||||
# Docker-specific paths
|
||||
N8N_WEBHOOK_URL=http://n8n:5678/webhook
|
||||
SD_API_URL=http://stable-diffusion:7860
|
||||
GENERATED_IMAGES_DIR=/app/public/generated-images
|
||||
```
|
||||
|
||||
Add to `docker-compose.yml`:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
portfolio:
|
||||
environment:
|
||||
- N8N_WEBHOOK_URL=http://n8n:5678/webhook
|
||||
- N8N_SECRET_TOKEN=${N8N_SECRET_TOKEN}
|
||||
- SD_API_URL=http://stable-diffusion:7860
|
||||
- AUTO_GENERATE_IMAGES=true
|
||||
- GENERATED_IMAGES_DIR=/app/public/generated-images
|
||||
volumes:
|
||||
- ./public/generated-images:/app/public/generated-images
|
||||
|
||||
n8n:
|
||||
image: n8nio/n8n
|
||||
ports:
|
||||
- "5678:5678"
|
||||
environment:
|
||||
- N8N_BASIC_AUTH_ACTIVE=true
|
||||
- N8N_BASIC_AUTH_USER=admin
|
||||
- N8N_BASIC_AUTH_PASSWORD=${N8N_PASSWORD}
|
||||
|
||||
stable-diffusion:
|
||||
image: your-sd-webui-image
|
||||
ports:
|
||||
- "7860:7860"
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: 1
|
||||
capabilities: [gpu]
|
||||
```
|
||||
|
||||
## Cloud GPU Configuration
|
||||
|
||||
If using cloud GPU services (RunPod, vast.ai, etc.):
|
||||
|
||||
```bash
|
||||
# Remote GPU URL with authentication
|
||||
SD_API_URL=https://your-runpod-instance.com:7860
|
||||
SD_API_KEY=your-api-key-here
|
||||
|
||||
# Longer timeout for network latency
|
||||
IMAGE_GENERATION_TIMEOUT=300000
|
||||
```
|
||||
|
||||
## Security Best Practices
|
||||
|
||||
1. **Never commit `.env.local` to version control**
|
||||
```bash
|
||||
# Add to .gitignore
|
||||
echo ".env.local" >> .gitignore
|
||||
```
|
||||
|
||||
2. **Generate secure tokens**
|
||||
```bash
|
||||
# Generate N8N_SECRET_TOKEN
|
||||
openssl rand -hex 32
|
||||
|
||||
# Or using Node.js
|
||||
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
|
||||
```
|
||||
|
||||
3. **Restrict API access**
|
||||
- Use firewall rules to limit SD API access
|
||||
- Enable authentication on n8n webhooks
|
||||
- Use HTTPS in production
|
||||
|
||||
4. **Environment-specific files**
|
||||
- `.env.local` - local development
|
||||
- `.env.production` - production (server-side only)
|
||||
- `.env.test` - testing environment
|
||||
|
||||
## Verifying Configuration
|
||||
|
||||
Test your environment variables:
|
||||
|
||||
```bash
|
||||
# Check if variables are loaded
|
||||
npm run dev
|
||||
|
||||
# In another terminal
|
||||
node -e "
|
||||
const envFile = require('fs').readFileSync('.env.local', 'utf8');
|
||||
console.log('✓ .env.local exists');
|
||||
console.log('✓ Variables found:', envFile.split('\\n').filter(l => l && !l.startsWith('#')).length);
|
||||
"
|
||||
|
||||
# Test n8n connection
|
||||
curl -f $N8N_WEBHOOK_URL/health || echo "n8n not reachable"
|
||||
|
||||
# Test SD API connection
|
||||
curl -f $SD_API_URL/sdapi/v1/sd-models || echo "SD API not reachable"
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Variables not loading
|
||||
|
||||
```bash
|
||||
# Ensure .env.local is in the project root
|
||||
ls -la .env.local
|
||||
|
||||
# Restart Next.js dev server
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### Wrong paths in Docker
|
||||
|
||||
```bash
|
||||
# Check volume mounts
|
||||
docker-compose exec portfolio ls -la /app/public/generated-images
|
||||
|
||||
# Fix permissions
|
||||
docker-compose exec portfolio chmod 755 /app/public/generated-images
|
||||
```
|
||||
|
||||
### n8n webhook unreachable
|
||||
|
||||
```bash
|
||||
# Check n8n is running
|
||||
docker ps | grep n8n
|
||||
|
||||
# Check network connectivity
|
||||
docker-compose exec portfolio ping n8n
|
||||
|
||||
# Verify webhook URL in n8n UI
|
||||
```
|
||||
|
||||
## Example Complete Configuration
|
||||
|
||||
```bash
|
||||
# .env.local - Complete working example
|
||||
|
||||
# Database (required for project data)
|
||||
DATABASE_URL=postgresql://user:password@localhost:5432/portfolio
|
||||
|
||||
# NextAuth (if using authentication)
|
||||
NEXTAUTH_URL=http://localhost:3000
|
||||
NEXTAUTH_SECRET=your-nextauth-secret
|
||||
|
||||
# AI Image Generation
|
||||
N8N_WEBHOOK_URL=http://localhost:5678/webhook
|
||||
N8N_SECRET_TOKEN=a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6
|
||||
SD_API_URL=http://localhost:7860
|
||||
AUTO_GENERATE_IMAGES=true
|
||||
GENERATED_IMAGES_DIR=/Users/dennis/code/gitea/portfolio/public/generated-images
|
||||
|
||||
# Image settings
|
||||
SD_DEFAULT_WIDTH=1024
|
||||
SD_DEFAULT_HEIGHT=768
|
||||
SD_DEFAULT_STEPS=30
|
||||
SD_DEFAULT_CFG_SCALE=7
|
||||
SD_DEFAULT_SAMPLER=DPM++ 2M Karras
|
||||
|
||||
# Optional features
|
||||
ENABLE_IMAGE_REGENERATION=true
|
||||
LOG_IMAGE_GENERATION=true
|
||||
IMAGE_GENERATION_TIMEOUT=180000
|
||||
MAX_CONCURRENT_GENERATIONS=2
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Note**: Always keep your `.env.local` file secure and never share tokens publicly!
|
||||
612
docs/ai-image-generation/PROMPT_TEMPLATES.md
Normal file
612
docs/ai-image-generation/PROMPT_TEMPLATES.md
Normal file
@@ -0,0 +1,612 @@
|
||||
# AI Image Generation Prompt Templates
|
||||
|
||||
This document contains optimized prompt templates for different project categories to ensure consistent, high-quality AI-generated images.
|
||||
|
||||
## Template Structure
|
||||
|
||||
Each template follows this structure:
|
||||
- **Base Prompt**: Core visual elements and style
|
||||
- **Technical Keywords**: Category-specific terminology
|
||||
- **Color Palette**: Recommended colors for the category
|
||||
- **Negative Prompt**: Elements to avoid
|
||||
- **Recommended Model**: Best SD model for this category
|
||||
|
||||
---
|
||||
|
||||
## Web Application Projects
|
||||
|
||||
### Base Prompt
|
||||
```
|
||||
modern web application interface, clean dashboard UI, sleek web design,
|
||||
gradient backgrounds, glass morphism effect, floating panels,
|
||||
data visualization charts, modern typography,
|
||||
soft shadows, depth layers, isometric perspective,
|
||||
professional tech aesthetic, vibrant interface elements,
|
||||
smooth gradients, minimalist composition,
|
||||
4k resolution, high quality digital art
|
||||
```
|
||||
|
||||
### Technical Keywords
|
||||
- SaaS dashboard, web portal, admin panel
|
||||
- Interactive UI elements, responsive design
|
||||
- Navigation bars, sidebars, cards
|
||||
- Progress indicators, status badges
|
||||
|
||||
### Color Palette
|
||||
- Primary: `#3B82F6` (Blue), `#8B5CF6` (Purple)
|
||||
- Secondary: `#06B6D4` (Cyan), `#EC4899` (Pink)
|
||||
- Accent: `#10B981` (Green), `#F59E0B` (Amber)
|
||||
|
||||
### Negative Prompt
|
||||
```
|
||||
mobile phone, smartphone, app mockup, tablet,
|
||||
realistic photo, stock photo, people, faces,
|
||||
cluttered, messy, dark, gloomy, text, watermark
|
||||
```
|
||||
|
||||
### Recommended Model
|
||||
- SDXL Base 1.0
|
||||
- DreamShaper 8
|
||||
|
||||
---
|
||||
|
||||
## Mobile Application Projects
|
||||
|
||||
### Base Prompt
|
||||
```
|
||||
modern mobile app interface mockup, sleek smartphone design,
|
||||
iOS or Android app screen, mobile UI elements,
|
||||
app icons grid, notification badges, bottom navigation,
|
||||
touch gestures indicators, smooth animations preview,
|
||||
gradient app background, modern mobile design trends,
|
||||
floating action button, card-based layout,
|
||||
professional mobile photography, studio lighting,
|
||||
4k quality, trending on dribbble
|
||||
```
|
||||
|
||||
### Technical Keywords
|
||||
- Native app, cross-platform, Flutter, React Native
|
||||
- Mobile-first design, touch interface
|
||||
- Swipe gestures, pull-to-refresh
|
||||
- Push notifications, app widgets
|
||||
|
||||
### Color Palette
|
||||
- Primary: `#6366F1` (Indigo), `#EC4899` (Pink)
|
||||
- Secondary: `#8B5CF6` (Purple), `#06B6D4` (Cyan)
|
||||
- Accent: `#F59E0B` (Amber), `#EF4444` (Red)
|
||||
|
||||
### Negative Prompt
|
||||
```
|
||||
desktop interface, web browser, laptop, monitor,
|
||||
desktop computer, keyboard, mouse,
|
||||
old phone, cracked screen, low resolution,
|
||||
text, watermark, people holding phones
|
||||
```
|
||||
|
||||
### Recommended Model
|
||||
- Realistic Vision V5.1
|
||||
- Juggernaut XL
|
||||
|
||||
---
|
||||
|
||||
## DevOps & Infrastructure Projects
|
||||
|
||||
### Base Prompt
|
||||
```
|
||||
cloud infrastructure visualization, modern server architecture diagram,
|
||||
Docker containers network, Kubernetes cluster illustration,
|
||||
CI/CD pipeline flowchart, automated deployment system,
|
||||
interconnected server nodes, data flow arrows,
|
||||
cloud services icons, microservices architecture,
|
||||
network topology, distributed systems,
|
||||
glowing connections, tech blueprint style,
|
||||
isometric technical illustration, cyberpunk aesthetic,
|
||||
blue and orange tech colors, professional diagram
|
||||
```
|
||||
|
||||
### Technical Keywords
|
||||
- Docker Swarm, Kubernetes, container orchestration
|
||||
- CI/CD pipeline, Jenkins, GitHub Actions
|
||||
- Cloud architecture, AWS, Azure, GCP
|
||||
- Monitoring dashboard, Grafana, Prometheus
|
||||
|
||||
### Color Palette
|
||||
- Primary: `#0EA5E9` (Sky Blue), `#F97316` (Orange)
|
||||
- Secondary: `#06B6D4` (Cyan), `#8B5CF6` (Purple)
|
||||
- Accent: `#10B981` (Green), `#EF4444` (Red)
|
||||
|
||||
### Negative Prompt
|
||||
```
|
||||
realistic datacenter photo, physical servers,
|
||||
people, technicians, hands, cables mess,
|
||||
dark server room, blurry, low quality,
|
||||
text labels, company logos, watermark
|
||||
```
|
||||
|
||||
### Recommended Model
|
||||
- SDXL Base 1.0
|
||||
- DreamShaper 8
|
||||
|
||||
---
|
||||
|
||||
## Backend & API Projects
|
||||
|
||||
### Base Prompt
|
||||
```
|
||||
API architecture visualization, RESTful endpoints diagram,
|
||||
database schema illustration, data flow architecture,
|
||||
server-side processing, microservices connections,
|
||||
API gateway, request-response flow,
|
||||
JSON data structures, GraphQL schema visualization,
|
||||
modern backend architecture, technical blueprint,
|
||||
glowing data streams, interconnected services,
|
||||
professional tech diagram, isometric view,
|
||||
clean composition, high quality illustration
|
||||
```
|
||||
|
||||
### Technical Keywords
|
||||
- REST API, GraphQL, WebSocket
|
||||
- Microservices, serverless functions
|
||||
- Database architecture, SQL, NoSQL
|
||||
- Authentication, JWT, OAuth
|
||||
|
||||
### Color Palette
|
||||
- Primary: `#8B5CF6` (Purple), `#06B6D4` (Cyan)
|
||||
- Secondary: `#3B82F6` (Blue), `#10B981` (Green)
|
||||
- Accent: `#F59E0B` (Amber), `#EC4899` (Pink)
|
||||
|
||||
### Negative Prompt
|
||||
```
|
||||
frontend UI, user interface, buttons, forms,
|
||||
people, faces, hands, realistic photo,
|
||||
messy cables, physical hardware,
|
||||
text, code snippets, watermark
|
||||
```
|
||||
|
||||
### Recommended Model
|
||||
- SDXL Base 1.0
|
||||
- DreamShaper 8
|
||||
|
||||
---
|
||||
|
||||
## AI & Machine Learning Projects
|
||||
|
||||
### Base Prompt
|
||||
```
|
||||
artificial intelligence concept art, neural network visualization,
|
||||
glowing AI nodes and connections, machine learning algorithm,
|
||||
data science visualization, deep learning architecture,
|
||||
brain-inspired computing, futuristic AI interface,
|
||||
holographic data displays, floating neural pathways,
|
||||
AI chip design, quantum computing aesthetic,
|
||||
particle systems, energy flows, digital consciousness,
|
||||
sci-fi technology, purple and cyan neon lighting,
|
||||
high-tech laboratory, 4k quality, cinematic lighting
|
||||
```
|
||||
|
||||
### Technical Keywords
|
||||
- Neural networks, deep learning, TensorFlow
|
||||
- Computer vision, NLP, transformers
|
||||
- Model training, GPU acceleration
|
||||
- AI agents, reinforcement learning
|
||||
|
||||
### Color Palette
|
||||
- Primary: `#8B5CF6` (Purple), `#EC4899` (Pink)
|
||||
- Secondary: `#06B6D4` (Cyan), `#3B82F6` (Blue)
|
||||
- Accent: `#A855F7` (Fuchsia), `#14B8A6` (Teal)
|
||||
|
||||
### Negative Prompt
|
||||
```
|
||||
realistic lab photo, scientists, people, faces,
|
||||
physical robots, mechanical parts,
|
||||
cluttered, messy, text, formulas, equations,
|
||||
low quality, dark, gloomy, stock photo
|
||||
```
|
||||
|
||||
### Recommended Model
|
||||
- SDXL Base 1.0
|
||||
- Juggernaut XL
|
||||
|
||||
---
|
||||
|
||||
## Game Development Projects
|
||||
|
||||
### Base Prompt
|
||||
```
|
||||
game environment scene, 3D rendered game world,
|
||||
video game interface, game UI overlay, HUD elements,
|
||||
fantasy game landscape, sci-fi game setting,
|
||||
character perspective view, gaming atmosphere,
|
||||
dynamic lighting, particle effects, atmospheric fog,
|
||||
game asset showcase, level design preview,
|
||||
cinematic game screenshot, unreal engine quality,
|
||||
vibrant game colors, epic composition,
|
||||
4k game graphics, trending on artstation
|
||||
```
|
||||
|
||||
### Technical Keywords
|
||||
- Unity, Unreal Engine, game engine
|
||||
- 3D modeling, texture mapping, shaders
|
||||
- Game mechanics, physics engine
|
||||
- Multiplayer, networking, matchmaking
|
||||
|
||||
### Color Palette
|
||||
- Primary: `#EF4444` (Red), `#F59E0B` (Amber)
|
||||
- Secondary: `#8B5CF6` (Purple), `#06B6D4` (Cyan)
|
||||
- Accent: `#10B981` (Green), `#EC4899` (Pink)
|
||||
|
||||
### Negative Prompt
|
||||
```
|
||||
real photo, realistic photography, real people,
|
||||
mobile game screenshot, casual game,
|
||||
low poly, pixelated, retro graphics,
|
||||
text, game title, logos, watermark
|
||||
```
|
||||
|
||||
### Recommended Model
|
||||
- Juggernaut XL
|
||||
- DreamShaper 8
|
||||
|
||||
---
|
||||
|
||||
## Blockchain & Crypto Projects
|
||||
|
||||
### Base Prompt
|
||||
```
|
||||
blockchain network visualization, cryptocurrency concept art,
|
||||
distributed ledger technology, decentralized network nodes,
|
||||
crypto mining visualization, digital currency symbols,
|
||||
smart contracts interface, DeFi platform design,
|
||||
glowing blockchain connections, cryptographic security,
|
||||
web3 technology aesthetic, neon blockchain grid,
|
||||
futuristic finance, holographic crypto data,
|
||||
clean modern composition, professional tech illustration,
|
||||
blue and gold color scheme, high quality render
|
||||
```
|
||||
|
||||
### Technical Keywords
|
||||
- Smart contracts, Solidity, Ethereum
|
||||
- DeFi, NFT, token economics
|
||||
- Consensus mechanisms, proof of stake
|
||||
- Web3, dApp, wallet integration
|
||||
|
||||
### Color Palette
|
||||
- Primary: `#F59E0B` (Gold), `#3B82F6` (Blue)
|
||||
- Secondary: `#8B5CF6` (Purple), `#10B981` (Green)
|
||||
- Accent: `#06B6D4` (Cyan), `#EC4899` (Pink)
|
||||
|
||||
### Negative Prompt
|
||||
```
|
||||
real coins, physical money, paper currency,
|
||||
people, traders, faces, hands,
|
||||
stock market photo, trading floor,
|
||||
text, ticker symbols, logos, watermark
|
||||
```
|
||||
|
||||
### Recommended Model
|
||||
- SDXL Base 1.0
|
||||
- Juggernaut XL
|
||||
|
||||
---
|
||||
|
||||
## IoT & Hardware Projects
|
||||
|
||||
### Base Prompt
|
||||
```
|
||||
Internet of Things network, smart home devices connected,
|
||||
IoT sensor network, embedded systems visualization,
|
||||
smart device ecosystem, wireless communication,
|
||||
connected hardware illustration, automation network,
|
||||
sensor data visualization, edge computing nodes,
|
||||
modern tech devices, clean product design,
|
||||
isometric hardware illustration, minimalist tech aesthetic,
|
||||
glowing connection lines, mesh network topology,
|
||||
professional product photography, studio lighting
|
||||
```
|
||||
|
||||
### Technical Keywords
|
||||
- Raspberry Pi, Arduino, ESP32
|
||||
- Sensor networks, MQTT, edge computing
|
||||
- Smart home, automation, wireless protocols
|
||||
- Embedded systems, firmware, microcontrollers
|
||||
|
||||
### Color Palette
|
||||
- Primary: `#10B981` (Green), `#06B6D4` (Cyan)
|
||||
- Secondary: `#3B82F6` (Blue), `#8B5CF6` (Purple)
|
||||
- Accent: `#F59E0B` (Amber), `#EC4899` (Pink)
|
||||
|
||||
### Negative Prompt
|
||||
```
|
||||
messy wiring, cluttered breadboard, realistic lab photo,
|
||||
people, hands holding devices, technicians,
|
||||
old electronics, broken hardware,
|
||||
text, labels, brand names, watermark
|
||||
```
|
||||
|
||||
### Recommended Model
|
||||
- Realistic Vision V5.1
|
||||
- Juggernaut XL
|
||||
|
||||
---
|
||||
|
||||
## Security & Cybersecurity Projects
|
||||
|
||||
### Base Prompt
|
||||
```
|
||||
cybersecurity concept art, digital security shield,
|
||||
encrypted data streams, firewall visualization,
|
||||
network security diagram, threat detection system,
|
||||
secure connection network, cryptography illustration,
|
||||
cyber defense interface, security monitoring dashboard,
|
||||
glowing security barriers, protected data vault,
|
||||
ethical hacking interface, penetration testing tools,
|
||||
dark mode tech aesthetic, green matrix-style code,
|
||||
professional security illustration, high-tech composition
|
||||
```
|
||||
|
||||
### Technical Keywords
|
||||
- Penetration testing, vulnerability scanning
|
||||
- Firewall, IDS/IPS, SIEM
|
||||
- Encryption, SSL/TLS, zero trust
|
||||
- Security monitoring, threat intelligence
|
||||
|
||||
### Color Palette
|
||||
- Primary: `#10B981` (Green), `#0EA5E9` (Sky Blue)
|
||||
- Secondary: `#8B5CF6` (Purple), `#EF4444` (Red)
|
||||
- Accent: `#F59E0B` (Amber), `#06B6D4` (Cyan)
|
||||
|
||||
### Negative Prompt
|
||||
```
|
||||
realistic office photo, security guards, people,
|
||||
physical locks, keys, cameras,
|
||||
dark, scary, threatening, ominous,
|
||||
text, code snippets, terminal text, watermark
|
||||
```
|
||||
|
||||
### Recommended Model
|
||||
- SDXL Base 1.0
|
||||
- DreamShaper 8
|
||||
|
||||
---
|
||||
|
||||
## Data Science & Analytics Projects
|
||||
|
||||
### Base Prompt
|
||||
```
|
||||
data visualization dashboard, analytics interface,
|
||||
big data processing, statistical charts and graphs,
|
||||
machine learning insights, predictive analytics,
|
||||
data pipeline illustration, ETL process visualization,
|
||||
interactive data dashboard, business intelligence,
|
||||
colorful data charts, infographic elements,
|
||||
modern analytics design, clean data presentation,
|
||||
professional data visualization, gradient backgrounds,
|
||||
isometric data center, flowing information streams
|
||||
```
|
||||
|
||||
### Technical Keywords
|
||||
- Data pipeline, ETL, data warehouse
|
||||
- BI dashboard, Tableau, Power BI
|
||||
- Statistical analysis, data mining
|
||||
- Pandas, NumPy, data processing
|
||||
|
||||
### Color Palette
|
||||
- Primary: `#3B82F6` (Blue), `#8B5CF6` (Purple)
|
||||
- Secondary: `#06B6D4` (Cyan), `#10B981` (Green)
|
||||
- Accent: `#EC4899` (Pink), `#F59E0B` (Amber)
|
||||
|
||||
### Negative Prompt
|
||||
```
|
||||
spreadsheet screenshot, Excel interface,
|
||||
people analyzing data, hands, faces,
|
||||
cluttered charts, messy graphs, confusing layout,
|
||||
text labels, numbers, watermark, low quality
|
||||
```
|
||||
|
||||
### Recommended Model
|
||||
- SDXL Base 1.0
|
||||
- DreamShaper 8
|
||||
|
||||
---
|
||||
|
||||
## E-commerce & Marketplace Projects
|
||||
|
||||
### Base Prompt
|
||||
```
|
||||
modern e-commerce platform interface, online shopping design,
|
||||
product showcase grid, shopping cart visualization,
|
||||
payment system interface, marketplace dashboard,
|
||||
product cards layout, checkout flow design,
|
||||
clean storefront design, modern retail aesthetic,
|
||||
shopping bag icons, product imagery, price tags design,
|
||||
conversion-optimized layout, mobile commerce,
|
||||
professional e-commerce photography, studio product shots,
|
||||
vibrant shopping experience, user-friendly interface
|
||||
```
|
||||
|
||||
### Technical Keywords
|
||||
- Online store, payment gateway, Stripe
|
||||
- Product catalog, inventory management
|
||||
- Shopping cart, checkout flow, conversion
|
||||
- Marketplace platform, vendor management
|
||||
|
||||
### Color Palette
|
||||
- Primary: `#EC4899` (Pink), `#F59E0B` (Amber)
|
||||
- Secondary: `#8B5CF6` (Purple), `#10B981` (Green)
|
||||
- Accent: `#3B82F6` (Blue), `#EF4444` (Red)
|
||||
|
||||
### Negative Prompt
|
||||
```
|
||||
realistic store photo, physical shop, retail store,
|
||||
people shopping, customers, cashiers, hands,
|
||||
cluttered shelves, messy products,
|
||||
text prices, brand logos, watermark
|
||||
```
|
||||
|
||||
### Recommended Model
|
||||
- Realistic Vision V5.1
|
||||
- Juggernaut XL
|
||||
|
||||
---
|
||||
|
||||
## Automation & Workflow Projects
|
||||
|
||||
### Base Prompt
|
||||
```
|
||||
workflow automation visualization, process flow diagram,
|
||||
automated pipeline illustration, task orchestration,
|
||||
business process automation, workflow nodes connected,
|
||||
integration platform design, automation dashboard,
|
||||
robotic process automation, efficiency visualization,
|
||||
streamlined processes, gear mechanisms, conveyor systems,
|
||||
modern workflow interface, productivity tools,
|
||||
clean automation design, professional illustration,
|
||||
isometric process view, smooth gradient backgrounds
|
||||
```
|
||||
|
||||
### Technical Keywords
|
||||
- n8n, Zapier, workflow automation
|
||||
- Integration platform, API orchestration
|
||||
- Task scheduling, cron jobs, triggers
|
||||
- Business process automation, RPA
|
||||
|
||||
### Color Palette
|
||||
- Primary: `#8B5CF6` (Purple), `#06B6D4` (Cyan)
|
||||
- Secondary: `#10B981` (Green), `#3B82F6` (Blue)
|
||||
- Accent: `#F59E0B` (Amber), `#EC4899` (Pink)
|
||||
|
||||
### Negative Prompt
|
||||
```
|
||||
realistic factory photo, physical machinery,
|
||||
people working, hands, faces, workers,
|
||||
cluttered, messy, industrial setting,
|
||||
text, labels, watermark, low quality
|
||||
```
|
||||
|
||||
### Recommended Model
|
||||
- SDXL Base 1.0
|
||||
- DreamShaper 8
|
||||
|
||||
---
|
||||
|
||||
## Universal Negative Prompt
|
||||
|
||||
Use this as a base for all generations:
|
||||
|
||||
```
|
||||
low quality, blurry, pixelated, grainy, jpeg artifacts, compression artifacts,
|
||||
text, letters, words, numbers, watermark, signature, copyright, logo, brand name,
|
||||
people, person, human, face, faces, hands, fingers, arms, body parts,
|
||||
portrait, selfie, crowd, group of people,
|
||||
cluttered, messy, chaotic, disorganized, busy, overwhelming,
|
||||
dark, gloomy, depressing, scary, ominous, threatening,
|
||||
ugly, distorted, deformed, mutation, extra limbs, bad anatomy,
|
||||
realistic photo, stock photo, photograph, camera phone,
|
||||
duplicate, duplication, repetitive, copied elements,
|
||||
old, outdated, vintage, retro (unless specifically wanted),
|
||||
screenshot, UI screenshot, browser window
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Prompt Engineering Best Practices
|
||||
|
||||
### 1. Specificity Matters
|
||||
- Be specific about visual elements you want
|
||||
- Include style keywords: "isometric", "minimalist", "modern"
|
||||
- Specify quality: "4k resolution", "high quality", "professional"
|
||||
|
||||
### 2. Weight Distribution
|
||||
- Most important elements should be early in the prompt
|
||||
- Use emphasis syntax if your tool supports it: `(keyword:1.2)` or `((keyword))`
|
||||
|
||||
### 3. Category Mixing
|
||||
- Combine multiple category templates for hybrid projects
|
||||
- Example: AI + Web App = neural network + modern dashboard UI
|
||||
|
||||
### 4. Color Psychology
|
||||
- **Blue**: Trust, technology, corporate
|
||||
- **Purple**: Innovation, creativity, luxury
|
||||
- **Green**: Growth, success, eco-friendly
|
||||
- **Orange**: Energy, action, excitement
|
||||
- **Pink**: Modern, playful, creative
|
||||
|
||||
### 5. Consistency
|
||||
- Use the same negative prompt across all generations
|
||||
- Maintain consistent aspect ratios (4:3 for project cards)
|
||||
- Stick to similar quality settings
|
||||
|
||||
### 6. A/B Testing
|
||||
- Generate 2-3 variants with slightly different prompts
|
||||
- Test which style resonates better with your audience
|
||||
- Refine prompts based on results
|
||||
|
||||
---
|
||||
|
||||
## Advanced Techniques
|
||||
|
||||
### ControlNet Integration
|
||||
If using ControlNet, you can guide composition:
|
||||
- Use Canny edge detection for layout control
|
||||
- Use Depth maps for 3D perspective
|
||||
- Use OpenPose for element positioning
|
||||
|
||||
### Multi-Stage Generation
|
||||
1. Generate base composition at lower resolution (512x512)
|
||||
2. Upscale using img2img with same prompt
|
||||
3. Apply post-processing (sharpening, color grading)
|
||||
|
||||
### Style Consistency
|
||||
To maintain consistent style across all project images:
|
||||
```
|
||||
Add to every prompt:
|
||||
"in the style of modern tech illustration, consistent design language,
|
||||
professional portfolio aesthetic, cohesive visual identity"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting Common Issues
|
||||
|
||||
### Issue: Too Abstract / Not Related to Project
|
||||
**Solution**: Add more specific technical keywords from project description
|
||||
|
||||
### Issue: Text Appearing in Images
|
||||
**Solution**: Add multiple text-related terms to negative prompt:
|
||||
`text, letters, words, typography, font, writing, characters`
|
||||
|
||||
### Issue: Dark or Poorly Lit
|
||||
**Solution**: Add lighting keywords:
|
||||
`studio lighting, bright, well-lit, soft lighting, professional lighting`
|
||||
|
||||
### Issue: Cluttered Composition
|
||||
**Solution**: Add composition keywords:
|
||||
`clean composition, minimalist, negative space, centered, balanced, organized`
|
||||
|
||||
### Issue: Wrong Aspect Ratio
|
||||
**Solution**: Specify dimensions explicitly in generation settings:
|
||||
- Cards: 1024x768 (4:3)
|
||||
- Hero: 1920x1080 (16:9)
|
||||
- Square: 1024x1024 (1:1)
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference Card
|
||||
|
||||
| Category | Primary Colors | Key Style | Model |
|
||||
|----------|---------------|-----------|-------|
|
||||
| Web | Blue, Purple | Glass UI | SDXL |
|
||||
| Mobile | Indigo, Pink | Mockup | Realistic Vision |
|
||||
| DevOps | Cyan, Orange | Diagram | SDXL |
|
||||
| AI/ML | Purple, Cyan | Futuristic | SDXL |
|
||||
| Game | Red, Amber | Cinematic | Juggernaut |
|
||||
| Blockchain | Gold, Blue | Neon | SDXL |
|
||||
| IoT | Green, Cyan | Product | Realistic Vision |
|
||||
| Security | Green, Blue | Dark Tech | SDXL |
|
||||
| Data | Blue, Purple | Charts | SDXL |
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: 2024
|
||||
**Version**: 1.0
|
||||
**Maintained by**: Portfolio AI Image Generation System
|
||||
366
docs/ai-image-generation/QUICKSTART.md
Normal file
366
docs/ai-image-generation/QUICKSTART.md
Normal file
@@ -0,0 +1,366 @@
|
||||
# Quick Start Guide: AI Image Generation
|
||||
|
||||
Get AI-powered project images up and running in 15 minutes.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Docker installed
|
||||
- 8GB+ RAM
|
||||
- GPU recommended (NVIDIA with CUDA support)
|
||||
- Node.js 18+ for portfolio app
|
||||
|
||||
## Step 1: Install Stable Diffusion WebUI (5 min)
|
||||
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git
|
||||
cd stable-diffusion-webui
|
||||
|
||||
# Run with API enabled
|
||||
./webui.sh --api --listen
|
||||
|
||||
# For low VRAM GPUs (< 8GB)
|
||||
./webui.sh --api --listen --medvram
|
||||
|
||||
# Wait for model download and startup
|
||||
# Access WebUI at: http://localhost:7860
|
||||
```
|
||||
|
||||
## Step 2: Download a Model (3 min)
|
||||
|
||||
Open WebUI at `http://localhost:7860` and download a model:
|
||||
|
||||
**Option A: Via WebUI**
|
||||
1. Go to **Checkpoint Merger** tab
|
||||
2. Click **Model Download**
|
||||
3. Enter: `stabilityai/stable-diffusion-xl-base-1.0`
|
||||
4. Wait for download (6.94 GB)
|
||||
|
||||
**Option B: Manual Download**
|
||||
```bash
|
||||
cd models/Stable-diffusion/
|
||||
wget https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_base_1.0.safetensors
|
||||
```
|
||||
|
||||
## Step 3: Test Stable Diffusion API (1 min)
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:7860/sdapi/v1/txt2img \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"prompt": "modern tech dashboard, blue gradient, minimalist design",
|
||||
"steps": 20,
|
||||
"width": 512,
|
||||
"height": 512
|
||||
}' | jq '.images[0]' | base64 -d > test.png
|
||||
```
|
||||
|
||||
Open `test.png` - if you see an image, API is working! ✅
|
||||
|
||||
## Step 4: Setup n8n (2 min)
|
||||
|
||||
```bash
|
||||
# Docker Compose method
|
||||
docker run -d \
|
||||
--name n8n \
|
||||
-p 5678:5678 \
|
||||
-v ~/.n8n:/home/node/.n8n \
|
||||
n8nio/n8n
|
||||
|
||||
# Wait 30 seconds for startup
|
||||
# Access n8n at: http://localhost:5678
|
||||
```
|
||||
|
||||
## Step 5: Import Workflow (1 min)
|
||||
|
||||
1. Open n8n at `http://localhost:5678`
|
||||
2. Create account (first time only)
|
||||
3. Click **+ New Workflow**
|
||||
4. Click **⋮** (three dots) → **Import from File**
|
||||
5. Select `docs/ai-image-generation/n8n-workflow-ai-image-generator.json`
|
||||
6. Click **Save**
|
||||
|
||||
## Step 6: Configure Workflow (2 min)
|
||||
|
||||
### A. Add PostgreSQL Credentials
|
||||
1. Click **Get Project Data** node
|
||||
2. Click **Credential to connect with**
|
||||
3. Enter your database credentials:
|
||||
- Host: `localhost` (or your DB host)
|
||||
- Database: `portfolio`
|
||||
- User: `your_username`
|
||||
- Password: `your_password`
|
||||
4. Click **Save**
|
||||
|
||||
### B. Configure Stable Diffusion URL
|
||||
1. Click **Generate Image (Stable Diffusion)** node
|
||||
2. Update URL to: `http://localhost:7860/sdapi/v1/txt2img`
|
||||
3. If SD is on different machine: `http://YOUR_SD_IP:7860/sdapi/v1/txt2img`
|
||||
|
||||
### C. Set Webhook Authentication
|
||||
1. Click **Webhook Trigger** node
|
||||
2. Click **Add Credential**
|
||||
3. Set header: `Authorization`
|
||||
4. Set value: `Bearer your-secret-token-here`
|
||||
5. Save this token - you'll need it!
|
||||
|
||||
### D. Update Image Save Path
|
||||
1. Click **Save Image to File** node
|
||||
2. Update `uploadDir` path to your portfolio's public folder:
|
||||
```javascript
|
||||
const uploadDir = '/path/to/portfolio/public/generated-images';
|
||||
```
|
||||
|
||||
## Step 7: Create Directory for Images (1 min)
|
||||
|
||||
```bash
|
||||
cd /path/to/portfolio
|
||||
mkdir -p public/generated-images
|
||||
chmod 755 public/generated-images
|
||||
```
|
||||
|
||||
## Step 8: Add Environment Variables (1 min)
|
||||
|
||||
Add to `portfolio/.env.local`:
|
||||
|
||||
```bash
|
||||
# n8n Webhook Configuration
|
||||
N8N_WEBHOOK_URL=http://localhost:5678/webhook
|
||||
N8N_SECRET_TOKEN=your-secret-token-here
|
||||
|
||||
# Stable Diffusion API
|
||||
SD_API_URL=http://localhost:7860
|
||||
|
||||
# Auto-generate images for new projects
|
||||
AUTO_GENERATE_IMAGES=true
|
||||
|
||||
# Image storage
|
||||
GENERATED_IMAGES_DIR=/path/to/portfolio/public/generated-images
|
||||
```
|
||||
|
||||
## Step 9: Test the Full Pipeline (2 min)
|
||||
|
||||
```bash
|
||||
# Start your portfolio app
|
||||
cd portfolio
|
||||
npm run dev
|
||||
|
||||
# In another terminal, trigger image generation
|
||||
curl -X POST http://localhost:5678/webhook/ai-image-generation \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer your-secret-token-here" \
|
||||
-d '{
|
||||
"projectId": 1
|
||||
}'
|
||||
|
||||
# Check response (should take 15-30 seconds)
|
||||
# Response example:
|
||||
# {
|
||||
# "success": true,
|
||||
# "projectId": 1,
|
||||
# "imageUrl": "/generated-images/project-1-1234567890.png",
|
||||
# "generatedAt": "2024-01-15T10:30:00Z"
|
||||
# }
|
||||
```
|
||||
|
||||
## Step 10: Verify Image (1 min)
|
||||
|
||||
```bash
|
||||
# Check if image was created
|
||||
ls -lh public/generated-images/
|
||||
|
||||
# Open in browser
|
||||
open http://localhost:3000/generated-images/project-1-*.png
|
||||
```
|
||||
|
||||
You should see a generated image! 🎉
|
||||
|
||||
---
|
||||
|
||||
## Using the Admin UI
|
||||
|
||||
If you created the admin component:
|
||||
|
||||
1. Navigate to your admin page (create one if needed)
|
||||
2. Add the AI Image Generator component:
|
||||
|
||||
```tsx
|
||||
import AIImageGenerator from '@/app/components/admin/AIImageGenerator';
|
||||
|
||||
<AIImageGenerator
|
||||
projectId={projectId}
|
||||
projectTitle="My Awesome Project"
|
||||
currentImageUrl={project.imageUrl}
|
||||
onImageGenerated={(url) => console.log('Generated:', url)}
|
||||
/>
|
||||
```
|
||||
|
||||
3. Click **Generate Image** button
|
||||
4. Wait 15-30 seconds
|
||||
5. Image appears automatically!
|
||||
|
||||
---
|
||||
|
||||
## Automatic Generation on New Projects
|
||||
|
||||
Add this to your project creation API:
|
||||
|
||||
```typescript
|
||||
// In portfolio/app/api/projects/route.ts (or similar)
|
||||
|
||||
export async function POST(req: Request) {
|
||||
// ... your project creation code ...
|
||||
|
||||
const newProject = await createProject(data);
|
||||
|
||||
// Trigger AI image generation
|
||||
if (process.env.AUTO_GENERATE_IMAGES === 'true') {
|
||||
fetch(`${process.env.N8N_WEBHOOK_URL}/ai-image-generation`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${process.env.N8N_SECRET_TOKEN}`
|
||||
},
|
||||
body: JSON.stringify({ projectId: newProject.id })
|
||||
}).catch(err => console.error('AI generation failed:', err));
|
||||
}
|
||||
|
||||
return NextResponse.json(newProject);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Connection refused to localhost:7860"
|
||||
```bash
|
||||
# Check if SD WebUI is running
|
||||
ps aux | grep webui
|
||||
|
||||
# Restart with API flag
|
||||
cd stable-diffusion-webui
|
||||
./webui.sh --api --listen
|
||||
```
|
||||
|
||||
### "CUDA out of memory"
|
||||
```bash
|
||||
# Restart with lower VRAM usage
|
||||
./webui.sh --api --listen --medvram
|
||||
|
||||
# Or even lower
|
||||
./webui.sh --api --listen --lowvram
|
||||
```
|
||||
|
||||
### "n8n workflow fails at database step"
|
||||
- Check PostgreSQL is running: `pg_isready`
|
||||
- Verify credentials in n8n node
|
||||
- Check database connection from terminal:
|
||||
```bash
|
||||
psql -h localhost -U your_username -d portfolio
|
||||
```
|
||||
|
||||
### "Image saves but doesn't appear on website"
|
||||
- Check directory permissions: `chmod 755 public/generated-images`
|
||||
- Verify path in n8n workflow matches portfolio structure
|
||||
- Check Next.js static files config in `next.config.js`
|
||||
|
||||
### "Generated images are low quality"
|
||||
Edit n8n workflow's SD node, increase:
|
||||
- `steps`: 20 → 40
|
||||
- `cfg_scale`: 7 → 9
|
||||
- `width/height`: 512 → 1024
|
||||
|
||||
### "Images don't match project theme"
|
||||
Edit **Build AI Prompt** node in n8n:
|
||||
- Add more specific technical keywords
|
||||
- Include project category in style description
|
||||
- Adjust color palette keywords
|
||||
|
||||
---
|
||||
|
||||
## Next Steps
|
||||
|
||||
✅ **You're done!** Images now generate automatically.
|
||||
|
||||
**Optional Enhancements:**
|
||||
|
||||
1. **Batch Generate**: Generate images for all existing projects
|
||||
```bash
|
||||
# Create a script: scripts/batch-generate-images.ts
|
||||
for projectId in $(psql -t -c "SELECT id FROM projects WHERE image_url IS NULL"); do
|
||||
curl -X POST http://localhost:5678/webhook/ai-image-generation \
|
||||
-H "Authorization: Bearer $N8N_SECRET_TOKEN" \
|
||||
-d "{\"projectId\": $projectId}"
|
||||
sleep 30 # Wait for generation
|
||||
done
|
||||
```
|
||||
|
||||
2. **Custom Models**: Download specialized models for better results
|
||||
- `dreamshaper_8.safetensors` for web/UI projects
|
||||
- `realisticVision_v51.safetensors` for product shots
|
||||
- `juggernautXL_v8.safetensors` for modern tech aesthetics
|
||||
|
||||
3. **Prompt Refinement**: Edit prompt templates in n8n workflow
|
||||
- Check `docs/ai-image-generation/PROMPT_TEMPLATES.md`
|
||||
- Test different styles for your brand
|
||||
|
||||
4. **Monitoring**: Set up logging and alerts
|
||||
- Add Discord/Slack notifications to n8n workflow
|
||||
- Log generation stats to analytics
|
||||
|
||||
5. **Optimization**: Compress images after generation
|
||||
```bash
|
||||
npm install sharp
|
||||
# Add post-processing step to n8n workflow
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Performance Benchmarks
|
||||
|
||||
| Hardware | Generation Time | Image Quality |
|
||||
|----------|----------------|---------------|
|
||||
| RTX 4090 | ~8 seconds | Excellent |
|
||||
| RTX 3080 | ~15 seconds | Excellent |
|
||||
| RTX 3060 | ~25 seconds | Good |
|
||||
| GTX 1660 | ~45 seconds | Good |
|
||||
| CPU only | ~5 minutes | Fair |
|
||||
|
||||
**Recommended**: RTX 3060 or better for production use.
|
||||
|
||||
---
|
||||
|
||||
## Cost Analysis
|
||||
|
||||
**Local Setup (One-time):**
|
||||
- GPU (RTX 3060): ~$300-400
|
||||
- OR Cloud GPU (RunPod, vast.ai): $0.20-0.50/hour
|
||||
|
||||
**Per Image Cost:**
|
||||
- Local: $0.00 (electricity ~$0.001)
|
||||
- Cloud GPU: ~$0.01-0.02 per image
|
||||
|
||||
**vs. Commercial APIs:**
|
||||
- DALL-E 3: $0.04 per image
|
||||
- Midjourney: ~$0.06 per image (with subscription)
|
||||
- Stable Diffusion API: $0.02 per image
|
||||
|
||||
💡 **Break-even**: After ~500 images, local setup pays for itself!
|
||||
|
||||
---
|
||||
|
||||
## Support & Resources
|
||||
|
||||
- **Documentation**: `docs/ai-image-generation/SETUP.md`
|
||||
- **Prompt Templates**: `docs/ai-image-generation/PROMPT_TEMPLATES.md`
|
||||
- **SD WebUI Wiki**: https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki
|
||||
- **n8n Documentation**: https://docs.n8n.io
|
||||
- **Community Discord**: [Your Discord link]
|
||||
|
||||
**Need Help?** Open an issue or reach out!
|
||||
|
||||
---
|
||||
|
||||
**Total Setup Time**: ~15 minutes
|
||||
**Result**: Automatic AI-generated project images 🎨✨
|
||||
423
docs/ai-image-generation/README.md
Normal file
423
docs/ai-image-generation/README.md
Normal file
@@ -0,0 +1,423 @@
|
||||
# AI Image Generation System
|
||||
|
||||
Automatically generate stunning project cover images using local AI models.
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
## 🎨 What is this?
|
||||
|
||||
This system automatically creates professional, tech-themed cover images for your portfolio projects using AI. No more stock photos, no design skills needed.
|
||||
|
||||
### Features
|
||||
|
||||
✨ **Fully Automatic** - Generate images when creating new projects
|
||||
🎯 **Context-Aware** - Uses project title, description, category, and tech stack
|
||||
🖼️ **High Quality** - 1024x768 optimized for web display
|
||||
🔒 **Privacy-First** - Runs 100% locally, no data sent to external APIs
|
||||
⚡ **Fast** - 15-30 seconds per image with GPU
|
||||
💰 **Free** - No per-image costs after initial setup
|
||||
🎨 **Customizable** - Full control over style, colors, and aesthetics
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
**Want to get started in 15 minutes?** → Check out [QUICKSTART.md](./QUICKSTART.md)
|
||||
|
||||
**For detailed setup and configuration** → See [SETUP.md](./SETUP.md)
|
||||
|
||||
## 📋 Table of Contents
|
||||
|
||||
- [How It Works](#how-it-works)
|
||||
- [System Architecture](#system-architecture)
|
||||
- [Installation](#installation)
|
||||
- [Usage](#usage)
|
||||
- [Prompt Engineering](#prompt-engineering)
|
||||
- [Examples](#examples)
|
||||
- [Troubleshooting](#troubleshooting)
|
||||
- [FAQ](#faq)
|
||||
|
||||
## 🔧 How It Works
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[Create Project] --> B[Trigger n8n Webhook]
|
||||
B --> C[Fetch Project Data]
|
||||
C --> D[Build AI Prompt]
|
||||
D --> E[Stable Diffusion]
|
||||
E --> F[Save Image]
|
||||
F --> G[Update Database]
|
||||
G --> H[Display on Site]
|
||||
```
|
||||
|
||||
1. **Project Creation**: You create or update a project
|
||||
2. **Data Extraction**: System reads project metadata (title, description, tags, category)
|
||||
3. **Prompt Generation**: AI-optimized prompt is created based on project type
|
||||
4. **Image Generation**: Stable Diffusion generates a unique image
|
||||
5. **Storage**: Image is saved and optimized
|
||||
6. **Database Update**: Project's `imageUrl` is updated
|
||||
7. **Display**: Image appears automatically on your portfolio
|
||||
|
||||
## 🏗️ System Architecture
|
||||
|
||||
```
|
||||
┌─────────────────┐
|
||||
│ Portfolio App │
|
||||
│ (Next.js) │
|
||||
└────────┬────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────┐ ┌─────────────────┐
|
||||
│ n8n Workflow │─────▶│ PostgreSQL DB │
|
||||
│ (Automation) │◀─────│ (Projects) │
|
||||
└────────┬────────┘ └─────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ Stable Diffusion│
|
||||
│ WebUI │
|
||||
│ (Image Gen) │
|
||||
└─────────────────┘
|
||||
```
|
||||
|
||||
### Components
|
||||
|
||||
- **Next.js App**: Frontend and API endpoints
|
||||
- **n8n**: Workflow automation and orchestration
|
||||
- **Stable Diffusion**: Local AI image generation
|
||||
- **PostgreSQL**: Project data storage
|
||||
- **File System**: Generated image storage
|
||||
|
||||
## 📦 Installation
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- **Node.js** 18+
|
||||
- **Docker** (recommended) or Python 3.10+
|
||||
- **PostgreSQL** database
|
||||
- **8GB+ RAM** minimum
|
||||
- **GPU recommended** (NVIDIA with CUDA support)
|
||||
- Minimum: GTX 1060 6GB
|
||||
- Recommended: RTX 3060 12GB or better
|
||||
- Also works on CPU (slower)
|
||||
|
||||
### Step-by-Step Setup
|
||||
|
||||
#### 1. Install Stable Diffusion WebUI
|
||||
|
||||
```bash
|
||||
git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git
|
||||
cd stable-diffusion-webui
|
||||
./webui.sh --api --listen
|
||||
```
|
||||
|
||||
Wait for model download (~7GB). Access at: `http://localhost:7860`
|
||||
|
||||
#### 2. Install n8n
|
||||
|
||||
```bash
|
||||
# Docker (recommended)
|
||||
docker run -d --name n8n -p 5678:5678 -v ~/.n8n:/home/node/.n8n n8nio/n8n
|
||||
|
||||
# Or npm
|
||||
npm install -g n8n
|
||||
n8n start
|
||||
```
|
||||
|
||||
Access at: `http://localhost:5678`
|
||||
|
||||
#### 3. Import Workflow
|
||||
|
||||
1. Open n8n at `http://localhost:5678`
|
||||
2. Import `n8n-workflow-ai-image-generator.json`
|
||||
3. Configure database credentials
|
||||
4. Update Stable Diffusion API URL
|
||||
5. Set webhook authentication token
|
||||
|
||||
#### 4. Configure Portfolio App
|
||||
|
||||
Add to `.env.local`:
|
||||
|
||||
```bash
|
||||
N8N_WEBHOOK_URL=http://localhost:5678/webhook
|
||||
N8N_SECRET_TOKEN=your-secure-token-here
|
||||
SD_API_URL=http://localhost:7860
|
||||
AUTO_GENERATE_IMAGES=true
|
||||
GENERATED_IMAGES_DIR=/path/to/portfolio/public/generated-images
|
||||
```
|
||||
|
||||
#### 5. Create Image Directory
|
||||
|
||||
```bash
|
||||
mkdir -p public/generated-images
|
||||
chmod 755 public/generated-images
|
||||
```
|
||||
|
||||
**That's it!** 🎉 You're ready to generate images.
|
||||
|
||||
## 💻 Usage
|
||||
|
||||
### Automatic Generation
|
||||
|
||||
When you create a new project, an image is automatically generated:
|
||||
|
||||
```typescript
|
||||
// In your project creation API
|
||||
const newProject = await createProject(data);
|
||||
|
||||
if (process.env.AUTO_GENERATE_IMAGES === 'true') {
|
||||
await fetch(`${process.env.N8N_WEBHOOK_URL}/ai-image-generation`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${process.env.N8N_SECRET_TOKEN}`
|
||||
},
|
||||
body: JSON.stringify({ projectId: newProject.id })
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Manual Generation via API
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:3000/api/n8n/generate-image \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer YOUR_TOKEN" \
|
||||
-d '{"projectId": 123}'
|
||||
```
|
||||
|
||||
### Admin UI Component
|
||||
|
||||
```tsx
|
||||
import AIImageGenerator from '@/app/components/admin/AIImageGenerator';
|
||||
|
||||
<AIImageGenerator
|
||||
projectId={project.id}
|
||||
projectTitle={project.title}
|
||||
currentImageUrl={project.imageUrl}
|
||||
onImageGenerated={(url) => {
|
||||
console.log('New image:', url);
|
||||
}}
|
||||
/>
|
||||
```
|
||||
|
||||
### Batch Generation
|
||||
|
||||
Generate images for all existing projects:
|
||||
|
||||
```bash
|
||||
# Get all projects without images
|
||||
psql -d portfolio -t -c "SELECT id FROM projects WHERE image_url IS NULL" | while read id; do
|
||||
curl -X POST http://localhost:3000/api/n8n/generate-image \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"projectId\": $id}"
|
||||
sleep 30 # Wait for generation
|
||||
done
|
||||
```
|
||||
|
||||
## 🎯 Prompt Engineering
|
||||
|
||||
The system automatically generates optimized prompts based on project category:
|
||||
|
||||
### Web Application Example
|
||||
|
||||
**Input Project:**
|
||||
- Title: "Real-Time Analytics Dashboard"
|
||||
- Category: "web"
|
||||
- Tags: ["React", "Next.js", "TypeScript"]
|
||||
|
||||
**Generated Prompt:**
|
||||
```
|
||||
Professional tech project cover image, modern web interface,
|
||||
clean dashboard UI, gradient backgrounds, glass morphism effect,
|
||||
representing "Real-Time Analytics Dashboard", React, Next.js, TypeScript,
|
||||
modern minimalist design, vibrant gradient colors, high quality digital art,
|
||||
isometric perspective, color palette: cyan, purple, pink, blue accents,
|
||||
4k resolution, no text, no watermarks, futuristic, professional
|
||||
```
|
||||
|
||||
**Result:** Clean, modern dashboard visualization in your brand colors
|
||||
|
||||
### Customize Prompts
|
||||
|
||||
Edit the `Build AI Prompt` node in n8n workflow to customize:
|
||||
|
||||
```javascript
|
||||
// Add your brand colors
|
||||
const brandColors = 'navy blue, gold accents, white backgrounds';
|
||||
|
||||
// Add style preferences
|
||||
const stylePreference = 'minimalist, clean, corporate, professional';
|
||||
|
||||
// Modify prompt template
|
||||
const prompt = `
|
||||
${categoryStyle},
|
||||
${projectTitle},
|
||||
${brandColors},
|
||||
${stylePreference},
|
||||
4k quality, trending on artstation
|
||||
`;
|
||||
```
|
||||
|
||||
See [PROMPT_TEMPLATES.md](./PROMPT_TEMPLATES.md) for category-specific templates.
|
||||
|
||||
## 🖼️ Examples
|
||||
|
||||
### Before & After
|
||||
|
||||
| Category | Without AI Image | With AI Image |
|
||||
|----------|------------------|---------------|
|
||||
| Web App | Generic stock photo | Custom dashboard visualization |
|
||||
| Mobile App | App store screenshot | Professional phone mockup |
|
||||
| DevOps | Server rack photo | Cloud architecture diagram |
|
||||
| AI/ML | Brain illustration | Neural network visualization |
|
||||
|
||||
### Quality Comparison
|
||||
|
||||
**Settings:**
|
||||
- Resolution: 1024x768
|
||||
- Steps: 30
|
||||
- CFG Scale: 7
|
||||
- Sampler: DPM++ 2M Karras
|
||||
- Model: SDXL Base 1.0
|
||||
|
||||
**Generation Time:**
|
||||
- RTX 4090: ~8 seconds
|
||||
- RTX 3080: ~15 seconds
|
||||
- RTX 3060: ~25 seconds
|
||||
- CPU: ~5 minutes
|
||||
|
||||
## 🐛 Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### "Connection refused to SD API"
|
||||
```bash
|
||||
# Check if SD WebUI is running
|
||||
ps aux | grep webui
|
||||
|
||||
# Restart with API enabled
|
||||
cd stable-diffusion-webui
|
||||
./webui.sh --api --listen
|
||||
```
|
||||
|
||||
#### "CUDA out of memory"
|
||||
```bash
|
||||
# Use lower VRAM mode
|
||||
./webui.sh --api --listen --medvram
|
||||
```
|
||||
|
||||
#### "Images are low quality"
|
||||
In n8n workflow, increase:
|
||||
- Steps: 30 → 40
|
||||
- CFG Scale: 7 → 9
|
||||
- Resolution: 512 → 1024
|
||||
|
||||
#### "Images don't match project"
|
||||
- Add more specific keywords to prompt
|
||||
- Use category-specific templates
|
||||
- Refine negative prompts
|
||||
|
||||
See [SETUP.md](./SETUP.md#troubleshooting) for more solutions.
|
||||
|
||||
## ❓ FAQ
|
||||
|
||||
### How much does it cost?
|
||||
|
||||
**Initial Setup:** $300-400 for GPU (or $0 with cloud GPU rental)
|
||||
**Per Image:** $0.00 (local electricity ~$0.001)
|
||||
**Break-even:** ~500 images vs. commercial APIs
|
||||
|
||||
### Can I use this without a GPU?
|
||||
|
||||
Yes, but it's slower (~5 minutes per image on CPU). Consider cloud GPU services:
|
||||
- RunPod: ~$0.20/hour
|
||||
- vast.ai: ~$0.15/hour
|
||||
- Google Colab: Free with limitations
|
||||
|
||||
### Is the data sent anywhere?
|
||||
|
||||
No! Everything runs locally. Your project data never leaves your server.
|
||||
|
||||
### Can I customize the style?
|
||||
|
||||
Absolutely! Edit prompts in the n8n workflow or use the template system.
|
||||
|
||||
### What models should I use?
|
||||
|
||||
- **SDXL Base 1.0**: Best all-around quality
|
||||
- **DreamShaper 8**: Artistic, modern tech style
|
||||
- **Realistic Vision V5**: Photorealistic results
|
||||
- **Juggernaut XL**: Clean, professional aesthetics
|
||||
|
||||
### Can I generate images on-demand?
|
||||
|
||||
Yes! Use the admin UI component or API endpoint to regenerate anytime.
|
||||
|
||||
### How do I change image dimensions?
|
||||
|
||||
Edit the n8n workflow's SD node:
|
||||
```json
|
||||
{
|
||||
"width": 1920, // Change this
|
||||
"height": 1080 // And this
|
||||
}
|
||||
```
|
||||
|
||||
### Can I use a different AI model?
|
||||
|
||||
Yes! The system works with:
|
||||
- Stable Diffusion WebUI (default)
|
||||
- ComfyUI (more advanced)
|
||||
- Any API that accepts txt2img requests
|
||||
|
||||
## 📚 Additional Resources
|
||||
|
||||
- **[SETUP.md](./SETUP.md)** - Detailed installation guide
|
||||
- **[QUICKSTART.md](./QUICKSTART.md)** - 15-minute setup guide
|
||||
- **[PROMPT_TEMPLATES.md](./PROMPT_TEMPLATES.md)** - Category-specific prompts
|
||||
- **[n8n-workflow-ai-image-generator.json](./n8n-workflow-ai-image-generator.json)** - Workflow file
|
||||
|
||||
### External Documentation
|
||||
|
||||
- [Stable Diffusion WebUI Wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki)
|
||||
- [n8n Documentation](https://docs.n8n.io)
|
||||
- [Stable Diffusion Prompt Guide](https://prompthero.com/stable-diffusion-prompt-guide)
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
Have improvements or new prompt templates? Contributions welcome!
|
||||
|
||||
1. Fork the repository
|
||||
2. Create a feature branch
|
||||
3. Test your changes
|
||||
4. Submit a pull request
|
||||
|
||||
## 📝 License
|
||||
|
||||
This system is part of your portfolio project. AI-generated images are yours to use freely.
|
||||
|
||||
**Model Licenses:**
|
||||
- SDXL Base 1.0: CreativeML Open RAIL++-M License
|
||||
- Other models: Check individual model licenses
|
||||
|
||||
## 🙏 Credits
|
||||
|
||||
- **Stable Diffusion**: Stability AI & AUTOMATIC1111
|
||||
- **n8n**: n8n GmbH
|
||||
- **Prompt Engineering**: Community templates and best practices
|
||||
|
||||
## 💬 Support
|
||||
|
||||
Need help? Found a bug?
|
||||
|
||||
- Open an issue on GitHub
|
||||
- Check existing documentation
|
||||
- Join the community Discord
|
||||
- Email: contact@dk0.dev
|
||||
|
||||
---
|
||||
|
||||
**Built with ❤️ for automatic, beautiful project images**
|
||||
|
||||
*Last Updated: 2024*
|
||||
486
docs/ai-image-generation/SETUP.md
Normal file
486
docs/ai-image-generation/SETUP.md
Normal file
@@ -0,0 +1,486 @@
|
||||
# AI Image Generation Setup
|
||||
|
||||
This guide explains how to set up automatic AI-powered image generation for your portfolio projects using local AI models.
|
||||
|
||||
## Overview
|
||||
|
||||
The system automatically generates project cover images by:
|
||||
1. Reading project metadata (title, description, tags, tech stack)
|
||||
2. Creating an optimized prompt for image generation
|
||||
3. Sending the prompt to a local AI image generator
|
||||
4. Saving the generated image
|
||||
5. Updating the project's `imageUrl` in the database
|
||||
|
||||
## Supported Local AI Tools
|
||||
|
||||
### Option 1: Stable Diffusion WebUI (AUTOMATIC1111) - Recommended
|
||||
|
||||
**Pros:**
|
||||
- Most mature and widely used
|
||||
- Excellent API support
|
||||
- Large model ecosystem
|
||||
- Easy to use
|
||||
|
||||
**Installation:**
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git
|
||||
cd stable-diffusion-webui
|
||||
|
||||
# Install and run (will download models automatically)
|
||||
./webui.sh --api --listen
|
||||
```
|
||||
|
||||
**API Endpoint:** `http://localhost:7860`
|
||||
|
||||
**Recommended Models:**
|
||||
- **SDXL Base 1.0** - High quality, versatile
|
||||
- **Realistic Vision V5.1** - Photorealistic images
|
||||
- **DreamShaper 8** - Artistic, tech-focused imagery
|
||||
- **Juggernaut XL** - Modern, clean aesthetics
|
||||
|
||||
**Download Models:**
|
||||
```bash
|
||||
cd models/Stable-diffusion/
|
||||
|
||||
# SDXL Base (6.94 GB)
|
||||
wget https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_base_1.0.safetensors
|
||||
|
||||
# Or use the WebUI's model downloader
|
||||
```
|
||||
|
||||
### Option 2: ComfyUI
|
||||
|
||||
**Pros:**
|
||||
- Node-based workflow system
|
||||
- More control over generation pipeline
|
||||
- Better for complex compositions
|
||||
|
||||
**Installation:**
|
||||
```bash
|
||||
git clone https://github.com/comfyanonymous/ComfyUI.git
|
||||
cd ComfyUI
|
||||
pip install -r requirements.txt
|
||||
python main.py --listen 0.0.0.0 --port 8188
|
||||
```
|
||||
|
||||
**API Endpoint:** `http://localhost:8188`
|
||||
|
||||
### Option 3: Ollama + Stable Diffusion
|
||||
|
||||
**Pros:**
|
||||
- Lightweight
|
||||
- Easy model management
|
||||
- Can combine with LLM for better prompts
|
||||
|
||||
**Installation:**
|
||||
```bash
|
||||
# Install Ollama
|
||||
curl -fsSL https://ollama.com/install.sh | sh
|
||||
|
||||
# Install a vision-capable model
|
||||
ollama pull llava
|
||||
|
||||
# For image generation, you'll still need SD WebUI or ComfyUI
|
||||
```
|
||||
|
||||
## n8n Workflow Setup
|
||||
|
||||
### 1. Install n8n (if not already installed)
|
||||
|
||||
```bash
|
||||
# Docker Compose (recommended)
|
||||
docker-compose up -d n8n
|
||||
|
||||
# Or npm
|
||||
npm install -g n8n
|
||||
n8n start
|
||||
```
|
||||
|
||||
### 2. Import Workflow
|
||||
|
||||
1. Open n8n at `http://localhost:5678`
|
||||
2. Go to **Workflows** → **Import from File**
|
||||
3. Import `n8n-workflows/ai-image-generator.json`
|
||||
|
||||
### 3. Configure Workflow Nodes
|
||||
|
||||
#### Node 1: Webhook Trigger
|
||||
- **Method:** POST
|
||||
- **Path:** `ai-image-generation`
|
||||
- **Authentication:** Header Auth (use secret token)
|
||||
|
||||
#### Node 2: Postgres - Get Project Data
|
||||
```sql
|
||||
SELECT id, title, description, tags, category, content
|
||||
FROM projects
|
||||
WHERE id = $json.projectId
|
||||
LIMIT 1;
|
||||
```
|
||||
|
||||
#### Node 3: Code - Build AI Prompt
|
||||
```javascript
|
||||
// Extract project data
|
||||
const project = $input.first().json;
|
||||
|
||||
// Build sophisticated prompt
|
||||
const styleKeywords = {
|
||||
'web': 'modern web interface, clean UI, gradient backgrounds, glass morphism',
|
||||
'mobile': 'mobile app mockup, sleek design, app icons, smartphone screen',
|
||||
'devops': 'server infrastructure, network diagram, cloud architecture, terminal windows',
|
||||
'game': 'game scene, 3D environment, gaming interface, player HUD',
|
||||
'ai': 'neural network visualization, AI chip, data flow, futuristic tech',
|
||||
'automation': 'workflow diagram, automated processes, gears and circuits'
|
||||
};
|
||||
|
||||
const categoryStyle = styleKeywords[project.category?.toLowerCase()] || 'technology concept';
|
||||
|
||||
const prompt = `
|
||||
Professional tech project cover image, ${categoryStyle},
|
||||
representing "${project.title}",
|
||||
modern design, vibrant colors, high quality,
|
||||
isometric view, minimalist, clean composition,
|
||||
4k resolution, trending on artstation,
|
||||
color palette: blue, purple, teal accents,
|
||||
no text, no people, no logos
|
||||
`.trim().replace(/\s+/g, ' ');
|
||||
|
||||
const negativePrompt = `
|
||||
low quality, blurry, pixelated, text, watermark,
|
||||
signature, logo, people, faces, hands,
|
||||
cluttered, messy, dark, gloomy
|
||||
`.trim().replace(/\s+/g, ' ');
|
||||
|
||||
return {
|
||||
json: {
|
||||
projectId: project.id,
|
||||
prompt: prompt,
|
||||
negativePrompt: negativePrompt,
|
||||
title: project.title,
|
||||
category: project.category
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### Node 4: HTTP Request - Generate Image (Stable Diffusion)
|
||||
- **Method:** POST
|
||||
- **URL:** `http://your-sd-server:7860/sdapi/v1/txt2img`
|
||||
- **Body:**
|
||||
```json
|
||||
{
|
||||
"prompt": "={{ $json.prompt }}",
|
||||
"negative_prompt": "={{ $json.negativePrompt }}",
|
||||
"steps": 30,
|
||||
"cfg_scale": 7,
|
||||
"width": 1024,
|
||||
"height": 768,
|
||||
"sampler_name": "DPM++ 2M Karras",
|
||||
"seed": -1,
|
||||
"batch_size": 1,
|
||||
"n_iter": 1
|
||||
}
|
||||
```
|
||||
|
||||
#### Node 5: Code - Save Image to File
|
||||
```javascript
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const imageData = $input.first().json.images[0]; // Base64 image
|
||||
const projectId = $json.projectId;
|
||||
const timestamp = Date.now();
|
||||
|
||||
// Create directory if doesn't exist
|
||||
const uploadDir = '/app/public/generated-images';
|
||||
if (!fs.existsSync(uploadDir)) {
|
||||
fs.mkdirSync(uploadDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Save image
|
||||
const filename = `project-${projectId}-${timestamp}.png`;
|
||||
const filepath = path.join(uploadDir, filename);
|
||||
|
||||
fs.writeFileSync(filepath, Buffer.from(imageData, 'base64'));
|
||||
|
||||
return {
|
||||
json: {
|
||||
projectId: projectId,
|
||||
imageUrl: `/generated-images/${filename}`,
|
||||
filepath: filepath
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### Node 6: Postgres - Update Project
|
||||
```sql
|
||||
UPDATE projects
|
||||
SET image_url = $json.imageUrl,
|
||||
updated_at = NOW()
|
||||
WHERE id = $json.projectId;
|
||||
```
|
||||
|
||||
#### Node 7: Webhook Response
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"projectId": "={{ $json.projectId }}",
|
||||
"imageUrl": "={{ $json.imageUrl }}",
|
||||
"message": "Image generated successfully"
|
||||
}
|
||||
```
|
||||
|
||||
## API Integration
|
||||
|
||||
### Generate Image for Project
|
||||
|
||||
**Endpoint:** `POST /api/n8n/generate-image`
|
||||
|
||||
**Request:**
|
||||
```json
|
||||
{
|
||||
"projectId": 123,
|
||||
"regenerate": false
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"projectId": 123,
|
||||
"imageUrl": "/generated-images/project-123-1234567890.png",
|
||||
"generatedAt": "2024-01-15T10:30:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
### Automatic Generation on Project Creation
|
||||
|
||||
Add this to your project creation API:
|
||||
|
||||
```typescript
|
||||
// After creating project in database
|
||||
if (process.env.AUTO_GENERATE_IMAGES === 'true') {
|
||||
await fetch(`${process.env.N8N_WEBHOOK_URL}/ai-image-generation`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${process.env.N8N_SECRET_TOKEN}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
projectId: newProject.id
|
||||
})
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Add to `.env.local`:
|
||||
|
||||
```bash
|
||||
# AI Image Generation
|
||||
N8N_WEBHOOK_URL=http://localhost:5678/webhook
|
||||
N8N_SECRET_TOKEN=your-secure-token-here
|
||||
AUTO_GENERATE_IMAGES=true
|
||||
|
||||
# Stable Diffusion API
|
||||
SD_API_URL=http://localhost:7860
|
||||
SD_API_KEY=optional-if-protected
|
||||
|
||||
# Image Storage
|
||||
GENERATED_IMAGES_DIR=/app/public/generated-images
|
||||
```
|
||||
|
||||
## Prompt Engineering Tips
|
||||
|
||||
### Good Prompts for Tech Projects
|
||||
|
||||
**Web Application:**
|
||||
```
|
||||
modern web dashboard interface, clean UI design, gradient background,
|
||||
glass morphism, floating panels, data visualization, charts and graphs,
|
||||
vibrant blue and purple color scheme, isometric view, 4k quality
|
||||
```
|
||||
|
||||
**Mobile App:**
|
||||
```
|
||||
sleek mobile app interface mockup, smartphone screen, modern app design,
|
||||
minimalist UI, smooth gradients, app icons, notification badges,
|
||||
floating elements, teal and pink accents, professional photography
|
||||
```
|
||||
|
||||
**DevOps/Infrastructure:**
|
||||
```
|
||||
cloud infrastructure diagram, server network visualization,
|
||||
interconnected nodes, data flow arrows, container icons,
|
||||
modern tech illustration, isometric perspective, cyan and orange colors
|
||||
```
|
||||
|
||||
**AI/ML Project:**
|
||||
```
|
||||
artificial intelligence concept, neural network visualization,
|
||||
glowing nodes and connections, data streams, futuristic interface,
|
||||
holographic elements, purple and blue neon lighting, high tech
|
||||
```
|
||||
|
||||
### Negative Prompts (What to Avoid)
|
||||
|
||||
```
|
||||
text, watermark, signature, logo, brand name, letters, numbers,
|
||||
people, faces, hands, fingers, human figures,
|
||||
low quality, blurry, pixelated, jpeg artifacts,
|
||||
dark, gloomy, depressing, messy, cluttered,
|
||||
realistic photo, stock photo
|
||||
```
|
||||
|
||||
## Image Specifications
|
||||
|
||||
**Recommended Settings:**
|
||||
- **Resolution:** 1024x768 (4:3 aspect ratio for cards)
|
||||
- **Format:** PNG (with transparency support)
|
||||
- **Size:** < 500KB (optimize after generation)
|
||||
- **Color Profile:** sRGB
|
||||
- **Sampling Steps:** 25-35 (balance quality vs speed)
|
||||
- **CFG Scale:** 6-8 (how closely to follow prompt)
|
||||
|
||||
## Optimization
|
||||
|
||||
### Post-Processing Pipeline
|
||||
|
||||
```bash
|
||||
# Install image optimization tools
|
||||
npm install sharp tinypng-cli
|
||||
|
||||
# Optimize generated images
|
||||
sharp input.png -o optimized.png --webp --quality 85
|
||||
|
||||
# Or use TinyPNG
|
||||
tinypng input.png --key YOUR_API_KEY
|
||||
```
|
||||
|
||||
### Caching Strategy
|
||||
|
||||
```typescript
|
||||
// Cache generated images in Redis
|
||||
await redis.set(
|
||||
`project:${projectId}:image`,
|
||||
imageUrl,
|
||||
'EX',
|
||||
60 * 60 * 24 * 30 // 30 days
|
||||
);
|
||||
```
|
||||
|
||||
## Monitoring & Debugging
|
||||
|
||||
### Check Stable Diffusion Status
|
||||
|
||||
```bash
|
||||
curl http://localhost:7860/sdapi/v1/sd-models
|
||||
```
|
||||
|
||||
### View n8n Execution Logs
|
||||
|
||||
1. Open n8n UI → Executions
|
||||
2. Filter by workflow "AI Image Generator"
|
||||
3. Check error logs and execution time
|
||||
|
||||
### Test Image Generation
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:7860/sdapi/v1/txt2img \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"prompt": "modern tech interface, blue gradient",
|
||||
"steps": 20,
|
||||
"width": 512,
|
||||
"height": 512
|
||||
}'
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "CUDA out of memory"
|
||||
- Reduce image resolution (768x576 instead of 1024x768)
|
||||
- Lower batch size to 1
|
||||
- Use `--lowvram` or `--medvram` flags when starting SD
|
||||
|
||||
### "Connection refused to SD API"
|
||||
- Check if SD WebUI is running: `ps aux | grep webui`
|
||||
- Verify API is enabled: `--api` flag in startup
|
||||
- Check firewall: `sudo ufw allow 7860`
|
||||
|
||||
### "Poor image quality"
|
||||
- Increase sampling steps (30-40)
|
||||
- Try different samplers (Euler a, DPM++ 2M Karras)
|
||||
- Adjust CFG scale (7-9)
|
||||
- Use better checkpoint model (SDXL, Realistic Vision)
|
||||
|
||||
### "Images don't match project theme"
|
||||
- Refine prompts with more specific keywords
|
||||
- Use category-specific style templates
|
||||
- Add technical keywords from project tags
|
||||
- Experiment with different negative prompts
|
||||
|
||||
## Advanced: Multi-Model Strategy
|
||||
|
||||
Use different models for different project types:
|
||||
|
||||
```javascript
|
||||
const modelMap = {
|
||||
'web': 'dreamshaper_8.safetensors',
|
||||
'mobile': 'realisticVision_v51.safetensors',
|
||||
'devops': 'juggernautXL_v8.safetensors',
|
||||
'ai': 'sdxl_base_1.0.safetensors'
|
||||
};
|
||||
|
||||
// Switch model before generation
|
||||
await fetch('http://localhost:7860/sdapi/v1/options', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
sd_model_checkpoint: modelMap[project.category]
|
||||
})
|
||||
});
|
||||
```
|
||||
|
||||
## Security Considerations
|
||||
|
||||
1. **Isolate SD WebUI:** Run in Docker container, not exposed to internet
|
||||
2. **Authentication:** Protect n8n webhooks with tokens
|
||||
3. **Rate Limiting:** Limit image generation requests
|
||||
4. **Content Filtering:** Validate prompts to prevent abuse
|
||||
5. **Resource Limits:** Set GPU memory limits in Docker
|
||||
|
||||
## Cost & Performance
|
||||
|
||||
**Hardware Requirements:**
|
||||
- **Minimum:** 8GB RAM, GTX 1060 6GB
|
||||
- **Recommended:** 16GB RAM, RTX 3060 12GB
|
||||
- **Optimal:** 32GB RAM, RTX 4090 24GB
|
||||
|
||||
**Generation Time:**
|
||||
- **512x512:** ~5-10 seconds
|
||||
- **1024x768:** ~15-30 seconds
|
||||
- **1024x1024 (SDXL):** ~30-60 seconds
|
||||
|
||||
**Storage:**
|
||||
- ~500KB per optimized image
|
||||
- ~50MB for 100 projects
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
- [ ] Style transfer from existing brand assets
|
||||
- [ ] A/B testing different image variants
|
||||
- [ ] User feedback loop for prompt refinement
|
||||
- [ ] Batch generation for multiple projects
|
||||
- [ ] Integration with DALL-E 3 / Midjourney as fallback
|
||||
- [ ] Automatic alt text generation for accessibility
|
||||
- [ ] Version history for generated images
|
||||
|
||||
---
|
||||
|
||||
**Next Steps:**
|
||||
1. Set up Stable Diffusion WebUI locally
|
||||
2. Import n8n workflow
|
||||
3. Test with sample project
|
||||
4. Refine prompts based on results
|
||||
5. Enable auto-generation for new projects
|
||||
340
docs/ai-image-generation/n8n-workflow-ai-image-generator.json
Normal file
340
docs/ai-image-generation/n8n-workflow-ai-image-generator.json
Normal file
@@ -0,0 +1,340 @@
|
||||
{
|
||||
"name": "AI Project Image Generator",
|
||||
"nodes": [
|
||||
{
|
||||
"parameters": {
|
||||
"httpMethod": "POST",
|
||||
"path": "ai-image-generation",
|
||||
"responseMode": "responseNode",
|
||||
"options": {
|
||||
"authType": "headerAuth"
|
||||
}
|
||||
},
|
||||
"id": "webhook-trigger",
|
||||
"name": "Webhook Trigger",
|
||||
"type": "n8n-nodes-base.webhook",
|
||||
"typeVersion": 1,
|
||||
"position": [250, 300],
|
||||
"webhookId": "ai-image-gen-webhook",
|
||||
"credentials": {
|
||||
"httpHeaderAuth": {
|
||||
"id": "1",
|
||||
"name": "Header Auth"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"parameters": {
|
||||
"operation": "executeQuery",
|
||||
"query": "SELECT id, title, description, tags, category, content, tech_stack FROM projects WHERE id = $1 LIMIT 1",
|
||||
"additionalFields": {
|
||||
"queryParameters": "={{ $json.body.projectId }}"
|
||||
}
|
||||
},
|
||||
"id": "get-project-data",
|
||||
"name": "Get Project Data",
|
||||
"type": "n8n-nodes-base.postgres",
|
||||
"typeVersion": 2,
|
||||
"position": [450, 300],
|
||||
"credentials": {
|
||||
"postgres": {
|
||||
"id": "2",
|
||||
"name": "PostgreSQL"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"parameters": {
|
||||
"jsCode": "// Extract project data\nconst project = $input.first().json;\n\n// Style keywords by category\nconst styleKeywords = {\n 'web': 'modern web interface, clean UI dashboard, gradient backgrounds, glass morphism effect, floating panels',\n 'mobile': 'mobile app mockup, sleek smartphone design, app icons, modern UI elements, notification badges',\n 'devops': 'server infrastructure, cloud network diagram, container orchestration, CI/CD pipeline visualization',\n 'backend': 'API architecture, database systems, microservices diagram, server endpoints, data flow',\n 'game': 'game environment scene, 3D rendered world, gaming interface, player HUD elements',\n 'ai': 'neural network visualization, AI chip design, machine learning data flow, futuristic technology',\n 'automation': 'workflow automation diagram, process flows, interconnected systems, automated pipeline',\n 'security': 'cybersecurity shields, encrypted data streams, security locks, firewall visualization',\n 'iot': 'Internet of Things devices, sensor networks, smart home technology, connected devices',\n 'blockchain': 'blockchain network, crypto technology, distributed ledger, decentralized nodes'\n};\n\nconst categoryStyle = styleKeywords[project.category?.toLowerCase()] || 'modern technology concept visualization';\n\n// Extract tech-specific keywords from tags and tech_stack\nconst techKeywords = [];\nif (project.tags) {\n const tags = Array.isArray(project.tags) ? project.tags : JSON.parse(project.tags || '[]');\n techKeywords.push(...tags.slice(0, 3));\n}\nif (project.tech_stack) {\n const stack = Array.isArray(project.tech_stack) ? project.tech_stack : JSON.parse(project.tech_stack || '[]');\n techKeywords.push(...stack.slice(0, 2));\n}\n\nconst techContext = techKeywords.length > 0 ? techKeywords.join(', ') + ' technology,' : '';\n\n// Build sophisticated prompt\nconst prompt = `\nProfessional tech project cover image, ${categoryStyle},\nrepresenting the concept of \"${project.title}\",\n${techContext}\nmodern minimalist design, vibrant gradient colors,\nhigh quality digital art, isometric perspective,\nclean composition, soft lighting,\ncolor palette: cyan, purple, pink, blue accents,\n4k resolution, trending on artstation,\nno text, no watermarks, no people, no logos,\nfuturistic, professional, tech-focused\n`.trim().replace(/\\s+/g, ' ');\n\n// Comprehensive negative prompt\nconst negativePrompt = `\nlow quality, blurry, pixelated, grainy, jpeg artifacts,\ntext, letters, words, watermark, signature, logo, brand name,\npeople, faces, hands, fingers, human figures, person,\ncluttered, messy, chaotic, disorganized,\ndark, gloomy, depressing, ugly, distorted,\nrealistic photo, stock photo, photograph,\nbad anatomy, deformed, mutation, extra limbs,\nduplication, duplicate elements, repetitive patterns\n`.trim().replace(/\\s+/g, ' ');\n\nreturn {\n json: {\n projectId: project.id,\n prompt: prompt,\n negativePrompt: negativePrompt,\n title: project.title,\n category: project.category,\n timestamp: Date.now()\n }\n};"
|
||||
},
|
||||
"id": "build-ai-prompt",
|
||||
"name": "Build AI Prompt",
|
||||
"type": "n8n-nodes-base.code",
|
||||
"typeVersion": 2,
|
||||
"position": [650, 300]
|
||||
},
|
||||
{
|
||||
"parameters": {
|
||||
"method": "POST",
|
||||
"url": "={{ $env.SD_API_URL || 'http://localhost:7860' }}/sdapi/v1/txt2img",
|
||||
"authentication": "genericCredentialType",
|
||||
"genericAuthType": "httpHeaderAuth",
|
||||
"sendBody": true,
|
||||
"bodyParameters": {
|
||||
"parameters": [
|
||||
{
|
||||
"name": "prompt",
|
||||
"value": "={{ $json.prompt }}"
|
||||
},
|
||||
{
|
||||
"name": "negative_prompt",
|
||||
"value": "={{ $json.negativePrompt }}"
|
||||
},
|
||||
{
|
||||
"name": "steps",
|
||||
"value": "30"
|
||||
},
|
||||
{
|
||||
"name": "cfg_scale",
|
||||
"value": "7"
|
||||
},
|
||||
{
|
||||
"name": "width",
|
||||
"value": "1024"
|
||||
},
|
||||
{
|
||||
"name": "height",
|
||||
"value": "768"
|
||||
},
|
||||
{
|
||||
"name": "sampler_name",
|
||||
"value": "DPM++ 2M Karras"
|
||||
},
|
||||
{
|
||||
"name": "seed",
|
||||
"value": "-1"
|
||||
},
|
||||
{
|
||||
"name": "batch_size",
|
||||
"value": "1"
|
||||
},
|
||||
{
|
||||
"name": "n_iter",
|
||||
"value": "1"
|
||||
},
|
||||
{
|
||||
"name": "save_images",
|
||||
"value": "false"
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {
|
||||
"timeout": 180000
|
||||
}
|
||||
},
|
||||
"id": "generate-image-sd",
|
||||
"name": "Generate Image (Stable Diffusion)",
|
||||
"type": "n8n-nodes-base.httpRequest",
|
||||
"typeVersion": 4,
|
||||
"position": [850, 300],
|
||||
"credentials": {
|
||||
"httpHeaderAuth": {
|
||||
"id": "3",
|
||||
"name": "SD API Auth"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"parameters": {
|
||||
"jsCode": "const fs = require('fs');\nconst path = require('path');\n\n// Get the base64 image data from Stable Diffusion response\nconst response = $input.first().json;\nconst imageData = response.images[0]; // Base64 encoded PNG\n\nconst projectId = $('Build AI Prompt').first().json.projectId;\nconst timestamp = Date.now();\n\n// Define upload directory (adjust path based on your setup)\nconst uploadDir = process.env.GENERATED_IMAGES_DIR || '/app/public/generated-images';\n\n// Create directory if it doesn't exist\nif (!fs.existsSync(uploadDir)) {\n fs.mkdirSync(uploadDir, { recursive: true });\n}\n\n// Generate filename\nconst filename = `project-${projectId}-${timestamp}.png`;\nconst filepath = path.join(uploadDir, filename);\n\n// Convert base64 to buffer and save\ntry {\n const imageBuffer = Buffer.from(imageData, 'base64');\n fs.writeFileSync(filepath, imageBuffer);\n \n // Get file size for logging\n const stats = fs.statSync(filepath);\n const fileSizeKB = (stats.size / 1024).toFixed(2);\n \n return {\n json: {\n projectId: projectId,\n imageUrl: `/generated-images/${filename}`,\n filepath: filepath,\n filename: filename,\n fileSize: fileSizeKB + ' KB',\n generatedAt: new Date().toISOString(),\n success: true\n }\n };\n} catch (error) {\n return {\n json: {\n projectId: projectId,\n error: error.message,\n success: false\n }\n };\n}"
|
||||
},
|
||||
"id": "save-image-file",
|
||||
"name": "Save Image to File",
|
||||
"type": "n8n-nodes-base.code",
|
||||
"typeVersion": 2,
|
||||
"position": [1050, 300]
|
||||
},
|
||||
{
|
||||
"parameters": {
|
||||
"operation": "executeQuery",
|
||||
"query": "UPDATE projects SET image_url = $1, updated_at = NOW() WHERE id = $2 RETURNING id, title, image_url",
|
||||
"additionalFields": {
|
||||
"queryParameters": "={{ $json.imageUrl }},={{ $json.projectId }}"
|
||||
}
|
||||
},
|
||||
"id": "update-project-image",
|
||||
"name": "Update Project Image URL",
|
||||
"type": "n8n-nodes-base.postgres",
|
||||
"typeVersion": 2,
|
||||
"position": [1250, 300],
|
||||
"credentials": {
|
||||
"postgres": {
|
||||
"id": "2",
|
||||
"name": "PostgreSQL"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"parameters": {
|
||||
"respondWith": "json",
|
||||
"responseBody": "={\n \"success\": true,\n \"projectId\": {{ $json.id }},\n \"title\": \"{{ $json.title }}\",\n \"imageUrl\": \"{{ $json.image_url }}\",\n \"generatedAt\": \"{{ $('Save Image to File').first().json.generatedAt }}\",\n \"fileSize\": \"{{ $('Save Image to File').first().json.fileSize }}\",\n \"message\": \"Project image generated successfully\"\n}",
|
||||
"options": {}
|
||||
},
|
||||
"id": "webhook-response",
|
||||
"name": "Webhook Response",
|
||||
"type": "n8n-nodes-base.respondToWebhook",
|
||||
"typeVersion": 1,
|
||||
"position": [1450, 300]
|
||||
},
|
||||
{
|
||||
"parameters": {
|
||||
"conditions": {
|
||||
"boolean": [
|
||||
{
|
||||
"value1": "={{ $json.success }}",
|
||||
"value2": true
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"id": "check-save-success",
|
||||
"name": "Check Save Success",
|
||||
"type": "n8n-nodes-base.if",
|
||||
"typeVersion": 1,
|
||||
"position": [1050, 450]
|
||||
},
|
||||
{
|
||||
"parameters": {
|
||||
"respondWith": "json",
|
||||
"responseBody": "={\n \"success\": false,\n \"error\": \"{{ $json.error || 'Failed to save image' }}\",\n \"projectId\": {{ $json.projectId }},\n \"message\": \"Image generation failed\"\n}",
|
||||
"options": {
|
||||
"responseCode": 500
|
||||
}
|
||||
},
|
||||
"id": "error-response",
|
||||
"name": "Error Response",
|
||||
"type": "n8n-nodes-base.respondToWebhook",
|
||||
"typeVersion": 1,
|
||||
"position": [1250, 500]
|
||||
},
|
||||
{
|
||||
"parameters": {
|
||||
"operation": "executeQuery",
|
||||
"query": "INSERT INTO activity_logs (type, action, details, created_at) VALUES ('ai_generation', 'image_generated', $1, NOW())",
|
||||
"additionalFields": {
|
||||
"queryParameters": "={{ JSON.stringify({ projectId: $json.id, imageUrl: $json.image_url, timestamp: new Date().toISOString() }) }}"
|
||||
}
|
||||
},
|
||||
"id": "log-activity",
|
||||
"name": "Log Generation Activity",
|
||||
"type": "n8n-nodes-base.postgres",
|
||||
"typeVersion": 2,
|
||||
"position": [1250, 150],
|
||||
"credentials": {
|
||||
"postgres": {
|
||||
"id": "2",
|
||||
"name": "PostgreSQL"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"connections": {
|
||||
"Webhook Trigger": {
|
||||
"main": [
|
||||
[
|
||||
{
|
||||
"node": "Get Project Data",
|
||||
"type": "main",
|
||||
"index": 0
|
||||
}
|
||||
]
|
||||
]
|
||||
},
|
||||
"Get Project Data": {
|
||||
"main": [
|
||||
[
|
||||
{
|
||||
"node": "Build AI Prompt",
|
||||
"type": "main",
|
||||
"index": 0
|
||||
}
|
||||
]
|
||||
]
|
||||
},
|
||||
"Build AI Prompt": {
|
||||
"main": [
|
||||
[
|
||||
{
|
||||
"node": "Generate Image (Stable Diffusion)",
|
||||
"type": "main",
|
||||
"index": 0
|
||||
}
|
||||
]
|
||||
]
|
||||
},
|
||||
"Generate Image (Stable Diffusion)": {
|
||||
"main": [
|
||||
[
|
||||
{
|
||||
"node": "Save Image to File",
|
||||
"type": "main",
|
||||
"index": 0
|
||||
}
|
||||
]
|
||||
]
|
||||
},
|
||||
"Save Image to File": {
|
||||
"main": [
|
||||
[
|
||||
{
|
||||
"node": "Check Save Success",
|
||||
"type": "main",
|
||||
"index": 0
|
||||
}
|
||||
]
|
||||
]
|
||||
},
|
||||
"Check Save Success": {
|
||||
"main": [
|
||||
[
|
||||
{
|
||||
"node": "Update Project Image URL",
|
||||
"type": "main",
|
||||
"index": 0
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"node": "Error Response",
|
||||
"type": "main",
|
||||
"index": 0
|
||||
}
|
||||
]
|
||||
]
|
||||
},
|
||||
"Update Project Image URL": {
|
||||
"main": [
|
||||
[
|
||||
{
|
||||
"node": "Log Generation Activity",
|
||||
"type": "main",
|
||||
"index": 0
|
||||
},
|
||||
{
|
||||
"node": "Webhook Response",
|
||||
"type": "main",
|
||||
"index": 0
|
||||
}
|
||||
]
|
||||
]
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"executionOrder": "v1",
|
||||
"saveManualExecutions": true,
|
||||
"callerPolicy": "workflowsFromSameOwner",
|
||||
"errorWorkflow": ""
|
||||
},
|
||||
"staticData": null,
|
||||
"tags": [
|
||||
{
|
||||
"name": "AI",
|
||||
"id": "ai-tag"
|
||||
},
|
||||
{
|
||||
"name": "Automation",
|
||||
"id": "automation-tag"
|
||||
},
|
||||
{
|
||||
"name": "Image Generation",
|
||||
"id": "image-gen-tag"
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"instanceId": "your-instance-id"
|
||||
},
|
||||
"id": "ai-image-generator-workflow",
|
||||
"versionId": "1",
|
||||
"triggerCount": 1,
|
||||
"active": true
|
||||
}
|
||||
91
docs/setup_activity_status.sql
Normal file
91
docs/setup_activity_status.sql
Normal file
@@ -0,0 +1,91 @@
|
||||
-- Activity Status Table Setup for n8n Integration
|
||||
-- This table stores real-time activity data from various sources
|
||||
|
||||
-- Drop existing table if it exists
|
||||
DROP TABLE IF EXISTS activity_status CASCADE;
|
||||
|
||||
-- Create the activity_status table
|
||||
CREATE TABLE activity_status (
|
||||
id SERIAL PRIMARY KEY,
|
||||
|
||||
-- Activity (Coding, Reading, etc.)
|
||||
activity_type VARCHAR(50), -- 'coding', 'listening', 'watching', 'gaming', 'reading'
|
||||
activity_details TEXT,
|
||||
activity_project VARCHAR(255),
|
||||
activity_language VARCHAR(50),
|
||||
activity_repo VARCHAR(255),
|
||||
|
||||
-- Music (Spotify, Apple Music)
|
||||
music_playing BOOLEAN DEFAULT FALSE,
|
||||
music_track VARCHAR(255),
|
||||
music_artist VARCHAR(255),
|
||||
music_album VARCHAR(255),
|
||||
music_platform VARCHAR(50), -- 'spotify', 'apple'
|
||||
music_progress INTEGER, -- 0-100 (percentage)
|
||||
music_album_art TEXT, -- URL to album art
|
||||
|
||||
-- Watching (YouTube, Netflix, Twitch)
|
||||
watching_title VARCHAR(255),
|
||||
watching_platform VARCHAR(50), -- 'youtube', 'netflix', 'twitch'
|
||||
watching_type VARCHAR(50), -- 'video', 'stream', 'movie', 'series'
|
||||
|
||||
-- Gaming (Steam, PlayStation, Xbox, Discord)
|
||||
gaming_game VARCHAR(255),
|
||||
gaming_platform VARCHAR(50), -- 'steam', 'playstation', 'xbox', 'discord'
|
||||
gaming_status VARCHAR(50), -- 'playing', 'idle'
|
||||
|
||||
-- Status (Mood & Custom Message)
|
||||
status_mood VARCHAR(10), -- emoji like '😊', '💻', '🎮', '😴'
|
||||
status_message TEXT,
|
||||
|
||||
-- Timestamps
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Create index for faster queries
|
||||
CREATE INDEX idx_activity_status_updated_at ON activity_status(updated_at DESC);
|
||||
|
||||
-- Insert default row (will be updated by n8n workflows)
|
||||
INSERT INTO activity_status (
|
||||
id,
|
||||
activity_type,
|
||||
activity_details,
|
||||
music_playing,
|
||||
status_mood,
|
||||
status_message
|
||||
) VALUES (
|
||||
1,
|
||||
NULL,
|
||||
NULL,
|
||||
FALSE,
|
||||
'💻',
|
||||
'Getting started...'
|
||||
);
|
||||
|
||||
-- Create function to automatically update updated_at timestamp
|
||||
CREATE OR REPLACE FUNCTION update_activity_status_timestamp()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
NEW.updated_at = NOW();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- Create trigger to call the function on UPDATE
|
||||
CREATE TRIGGER trigger_update_activity_status_timestamp
|
||||
BEFORE UPDATE ON activity_status
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_activity_status_timestamp();
|
||||
|
||||
-- Grant permissions (adjust as needed)
|
||||
-- GRANT SELECT, INSERT, UPDATE ON activity_status TO your_app_user;
|
||||
-- GRANT USAGE, SELECT ON SEQUENCE activity_status_id_seq TO your_app_user;
|
||||
|
||||
-- Display success message
|
||||
DO $$
|
||||
BEGIN
|
||||
RAISE NOTICE '✅ Activity Status table created successfully!';
|
||||
RAISE NOTICE '📝 You can now configure your n8n workflows to update this table.';
|
||||
RAISE NOTICE '🔗 See docs/N8N_INTEGRATION.md for setup instructions.';
|
||||
END $$;
|
||||
Reference in New Issue
Block a user