File size: 11,035 Bytes
89f19e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
#!/bin/bash

# Knowledge Base Synchronization Script
# Syncs content from multiple GitHub repositories and generates embeddings
# Usage: ./sync-knowledge.sh

set -euo pipefail

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
KNOWLEDGE_DIR="$PROJECT_ROOT/knowledge"
TEMP_DIR="/tmp/kb-sync-$$"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_debug() {
    echo -e "${BLUE}[DEBUG]${NC} $1"
}

# Cleanup function
cleanup() {
    log_info "Cleaning up temporary files..."
    rm -rf "$TEMP_DIR"
}

# Set trap for cleanup
trap cleanup EXIT

# Check dependencies
check_dependencies() {
    local deps=("git" "curl" "jq")
    
    for dep in "${deps[@]}"; do
        if ! command -v "$dep" > /dev/null; then
            log_error "Required dependency not found: $dep"
            exit 1
        fi
    done
}

# Load environment variables
load_env() {
    if [[ -f "$PROJECT_ROOT/.env" ]]; then
        source "$PROJECT_ROOT/.env"
    else
        log_error ".env file not found. Copy .env.example and configure it."
        exit 1
    fi
}

# Clone or update repository
sync_repository() {
    local repo_url="$1"
    local target_path="$2"
    local branch="${3:-main}"
    local subpath="$4"
    
    log_info "Syncing repository: $repo_url"
    log_debug "Target: $target_path, Branch: $branch, Subpath: $subpath"
    
    local repo_name=$(basename "$repo_url" .git)
    local temp_repo_path="$TEMP_DIR/$repo_name"
    
    # Clone repository to temp directory
    git clone --depth 1 --branch "$branch" "$repo_url" "$temp_repo_path" || {
        log_error "Failed to clone repository: $repo_url"
        return 1
    }
    
    # Copy specific subpath to target
    local source_path="$temp_repo_path/$subpath"
    if [[ -d "$source_path" ]]; then
        mkdir -p "$(dirname "$target_path")"
        cp -r "$source_path/." "$target_path/"
        log_info "Successfully synced to: $target_path"
    else
        log_warn "Subpath not found: $subpath in $repo_url"
        return 1
    fi
}

# Generate embeddings for knowledge content
generate_embeddings() {
    local knowledge_path="$1"
    local collection_name="$2"
    
    log_info "Generating embeddings for: $collection_name"
    
    # Create Python script for embedding generation
    cat > "$TEMP_DIR/generate_embeddings.py" << 'EOF'
import os
import json
import sys
from pathlib import Path
import hashlib
import requests
from sentence_transformers import SentenceTransformer

def load_model():
    """Load sentence transformer model"""
    try:
        model = SentenceTransformer('all-MiniLM-L6-v2')
        return model
    except Exception as e:
        print(f"Error loading model: {e}")
        return None

def process_text_files(knowledge_path, collection_name):
    """Process text files and generate embeddings"""
    model = load_model()
    if not model:
        return False
    
    embeddings_data = []
    knowledge_path = Path(knowledge_path)
    
    # Process markdown and text files
    for file_path in knowledge_path.rglob("*.md"):
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # Generate embedding
            embedding = model.encode(content).tolist()
            
            # Create document metadata
            doc_id = hashlib.md5(str(file_path).encode()).hexdigest()
            
            embeddings_data.append({
                "id": doc_id,
                "content": content,
                "embedding": embedding,
                "metadata": {
                    "file_path": str(file_path.relative_to(knowledge_path)),
                    "file_name": file_path.name,
                    "collection": collection_name,
                    "content_type": "markdown",
                    "size": len(content)
                }
            })
            
        except Exception as e:
            print(f"Error processing file {file_path}: {e}")
    
    # Save embeddings to JSON file
    output_file = knowledge_path / f"{collection_name}_embeddings.json"
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(embeddings_data, f, indent=2, ensure_ascii=False)
    
    print(f"Generated {len(embeddings_data)} embeddings for {collection_name}")
    return True

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python generate_embeddings.py <knowledge_path> <collection_name>")
        sys.exit(1)
    
    knowledge_path = sys.argv[1]
    collection_name = sys.argv[2]
    
    if process_text_files(knowledge_path, collection_name):
        print("Embedding generation completed successfully")
    else:
        print("Embedding generation failed")
        sys.exit(1)
EOF

    # Run embedding generation
    python3 "$TEMP_DIR/generate_embeddings.py" "$knowledge_path" "$collection_name" || {
        log_error "Failed to generate embeddings for $collection_name"
        return 1
    }
}

# Upload embeddings to vector store
upload_embeddings() {
    local embeddings_file="$1"
    local collection_name="$2"
    
    log_info "Uploading embeddings to vector store: $collection_name"
    
    if [[ ! -f "$embeddings_file" ]]; then
        log_error "Embeddings file not found: $embeddings_file"
        return 1
    fi
    
    # Upload to ChromaDB
    local chroma_url="http://${CHROMA_HOST:-localhost}:${CHROMA_PORT:-8000}"
    
    curl -X POST "$chroma_url/api/v1/collections" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer ${CHROMA_AUTH_TOKEN}" \
        -d "{\"name\": \"$collection_name\"}" || true
    
    # Process and upload embeddings in batches
    python3 - << EOF
import json
import requests
import sys
from pathlib import Path

def upload_batch(embeddings_data, collection_name, chroma_url, auth_token):
    """Upload embeddings in batches to ChromaDB"""
    batch_size = 100
    total_docs = len(embeddings_data)
    
    for i in range(0, total_docs, batch_size):
        batch = embeddings_data[i:i+batch_size]
        
        # Prepare batch data for ChromaDB
        ids = [doc["id"] for doc in batch]
        embeddings = [doc["embedding"] for doc in batch]
        metadatas = [doc["metadata"] for doc in batch]
        documents = [doc["content"] for doc in batch]
        
        payload = {
            "ids": ids,
            "embeddings": embeddings,
            "metadatas": metadatas,
            "documents": documents
        }
        
        try:
            response = requests.post(
                f"{chroma_url}/api/v1/collections/{collection_name}/add",
                json=payload,
                headers={
                    "Content-Type": "application/json",
                    "Authorization": f"Bearer {auth_token}"
                },
                timeout=30
            )
            
            if response.status_code == 200:
                print(f"Uploaded batch {i//batch_size + 1} ({len(batch)} documents)")
            else:
                print(f"Error uploading batch {i//batch_size + 1}: {response.status_code}")
                print(f"Response: {response.text}")
                
        except Exception as e:
            print(f"Error uploading batch {i//batch_size + 1}: {e}")
            continue

# Load and upload embeddings
embeddings_file = "$embeddings_file"
collection_name = "$collection_name"
chroma_url = "$chroma_url"
auth_token = "${CHROMA_AUTH_TOKEN:-}"

try:
    with open(embeddings_file, 'r', encoding='utf-8') as f:
        embeddings_data = json.load(f)
    
    upload_batch(embeddings_data, collection_name, chroma_url, auth_token)
    print(f"Successfully uploaded {len(embeddings_data)} embeddings to {collection_name}")
    
except Exception as e:
    print(f"Error: {e}")
    sys.exit(1)
EOF
}

# Sync all knowledge repositories
sync_all_repositories() {
    log_info "Starting knowledge base synchronization..."
    
    mkdir -p "$TEMP_DIR"
    
    # Repository configurations
    declare -A repos=(
        ["n8n"]="${KB_REPO_N8N:-}:${KB_PATH_N8N:-projects/n8n}"
        ["videos-e-animacoes"]="${KB_REPO_N8N:-}:${KB_PATH_VIDEOS:-projects/videos-e-animacoes}"
        ["midjourney-prompt"]="${KB_REPO_N8N:-}:${KB_PATH_MIDJOURNEY:-projects/midjorney-prompt}"
    )
    
    for collection in "${!repos[@]}"; do
        local repo_config="${repos[$collection]}"
        local repo_url=$(echo "$repo_config" | cut -d':' -f1)
        local subpath=$(echo "$repo_config" | cut -d':' -f2)
        local target_path="$KNOWLEDGE_DIR/$collection"
        
        if [[ -n "$repo_url" ]]; then
            log_info "Syncing collection: $collection"
            
            # Sync repository
            sync_repository "$repo_url" "$target_path" "${KB_BRANCH_N8N:-main}" "$subpath"
            
            # Generate embeddings
            generate_embeddings "$target_path" "$collection"
            
            # Upload to vector store
            local embeddings_file="$target_path/${collection}_embeddings.json"
            if [[ -f "$embeddings_file" ]]; then
                upload_embeddings "$embeddings_file" "$collection"
            fi
            
        else
            log_warn "Repository URL not configured for collection: $collection"
        fi
    done
}

# Update n8n with new knowledge
update_n8n_knowledge() {
    log_info "Notifying n8n of knowledge base updates..."
    
    # Create a webhook trigger to refresh knowledge in n8n workflows
    if [[ -n "${WEBHOOK_URL:-}" ]]; then
        local webhook_endpoint="$WEBHOOK_URL/webhook/knowledge-sync"
        
        curl -X POST "$webhook_endpoint" \
            -H "Content-Type: application/json" \
            -d "{\"event\": \"knowledge_updated\", \"timestamp\": \"$(date -Iseconds)\"}" \
            > /dev/null 2>&1 || {
            log_warn "Failed to notify n8n of knowledge updates"
        }
    fi
}

# Main synchronization process
main() {
    log_info "Starting knowledge base synchronization"
    
    # Preliminary checks
    check_dependencies
    load_env
    
    # Create knowledge directories
    mkdir -p "$KNOWLEDGE_DIR"/{n8n,videos-e-animacoes,midjourney-prompt}
    
    # Sync all repositories
    sync_all_repositories
    
    # Update n8n
    update_n8n_knowledge
    
    log_info "Knowledge base synchronization completed"
    
    # Generate summary
    log_info "Synchronization Summary:"
    find "$KNOWLEDGE_DIR" -name "*_embeddings.json" -exec basename {} \; | while read file; do
        local collection=$(echo "$file" | sed 's/_embeddings.json//')
        local count=$(jq '. | length' "$KNOWLEDGE_DIR/$collection/$file" 2>/dev/null || echo "0")
        log_info "  - $collection: $count documents"
    done
}

# Run main function
main "$@"