All files / src/modules/recommendations/services vector-search.service.ts

0% Statements 0/192
0% Branches 0/56
0% Functions 0/28
0% Lines 0/176

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Product, ProductDocument } from '../../../database/schemas/product.schema';
import { AIService } from '../../ai/services/ai.service';
 
export interface VectorSearchOptions {
  categories?: string[];
  brands?: string[];
  priceRange?: { min: number; max: number };
  excludeIds?: string[];
  limit?: number;
  threshold?: number; // Minimum similarity threshold (0-1)
}
 
export interface SimilarProduct {
  productId: string;
  similarity: number;
  product?: ProductDocument;
}
 
@Injectable()
export class VectorSearchService {
  private readonly logger = new Logger(VectorSearchService.name);
 
  constructor(
    @InjectModel(Product.name) private productModel: Model<ProductDocument>,
    private aiService: AIService,
  ) {}
 
  async findSimilarProducts(
    queryVector: number[],
    options: VectorSearchOptions = {},
  ): Promise<SimilarProduct[]> {
    try {
      Iif (!queryVector || queryVector.length === 0) {
        this.logger.warn('Empty query vector provided');
        return [];
      }
 
      // Build MongoDB aggregation pipeline for vector search
      const pipeline = this.buildVectorSearchPipeline(queryVector, options);
      
      const results = await this.productModel.aggregate(pipeline);
      
      return results.map(result => ({
        productId: result._id.toString(),
        similarity: result.similarity,
        product: result,
      }));
 
    } catch (error) {
      this.logger.error('Error in vector search', error);
      throw error;
    }
  }
 
  async findSimilarProductsByProduct(
    productId: string,
    options: VectorSearchOptions = {},
  ): Promise<SimilarProduct[]> {
    try {
      const product = await this.productModel.findById(productId);
      Iif (!product || !product.aiFeatures?.embeddings) {
        throw new Error('Product not found or no embeddings available');
      }
 
      // Exclude the original product
      const searchOptions = {
        ...options,
        excludeIds: [...(options.excludeIds || []), productId],
      };
 
      return this.findSimilarProducts(product.aiFeatures.embeddings, searchOptions);
 
    } catch (error) {
      this.logger.error(`Error finding similar products for ${productId}`, error);
      throw error;
    }
  }
 
  async searchByText(
    query: string,
    options: VectorSearchOptions = {},
  ): Promise<SimilarProduct[]> {
    try {
      // Generate embeddings for the text query
      const queryEmbeddings = await this.generateTextEmbeddings(query);
      
      return this.findSimilarProducts(queryEmbeddings, options);
 
    } catch (error) {
      this.logger.error(`Error in text-based vector search for: ${query}`, error);
      throw error;
    }
  }
 
  async searchByImage(
    imageUrl: string,
    options: VectorSearchOptions = {},
  ): Promise<SimilarProduct[]> {
    try {
      // Generate embeddings for the image
      const imageEmbeddings = await this.generateImageEmbeddings(imageUrl);
      
      return this.findSimilarProducts(imageEmbeddings, options);
 
    } catch (error) {
      this.logger.error(`Error in image-based vector search for: ${imageUrl}`, error);
      throw error;
    }
  }
 
  async generateProductEmbeddings(productId: string): Promise<number[]> {
    try {
      const product = await this.productModel.findById(productId);
      Iif (!product) {
        throw new Error('Product not found');
      }
 
      // Create a comprehensive text representation of the product
      const productText = this.createProductTextRepresentation(product);
      
      // Generate embeddings
      const embeddings = await this.generateTextEmbeddings(productText);
      
      // Store embeddings in the product document
      await this.productModel.findByIdAndUpdate(productId, {
        'aiFeatures.embeddings': embeddings,
        'aiFeatures.lastEmbeddingUpdate': new Date(),
      });
 
      return embeddings;
 
    } catch (error) {
      this.logger.error(`Error generating embeddings for product ${productId}`, error);
      throw error;
    }
  }
 
  async batchGenerateEmbeddings(productIds: string[]): Promise<void> {
    try {
      this.logger.log(`Generating embeddings for ${productIds.length} products`);
 
      // Process in batches to avoid overwhelming the AI service
      const batchSize = 10;
      for (let i = 0; i < productIds.length; i += batchSize) {
        const batch = productIds.slice(i, i + batchSize);
        
        await Promise.all(
          batch.map(productId => 
            this.generateProductEmbeddings(productId).catch(error => {
              this.logger.error(`Failed to generate embeddings for product ${productId}`, error);
            })
          )
        );
 
        // Small delay between batches to respect rate limits
        Iif (i + batchSize < productIds.length) {
          await new Promise(resolve => setTimeout(resolve, 1000));
        }
      }
 
      this.logger.log(`Completed embedding generation for ${productIds.length} products`);
 
    } catch (error) {
      this.logger.error('Error in batch embedding generation', error);
      throw error;
    }
  }
 
  async updateAllProductEmbeddings(): Promise<void> {
    try {
      // Find products without embeddings or with old embeddings
      const productsNeedingEmbeddings = await this.productModel.find({
        $or: [
          { 'aiFeatures.embeddings': { $exists: false } },
          { 'aiFeatures.embeddings': { $size: 0 } },
          { 
            'aiFeatures.lastEmbeddingUpdate': { 
              $lt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) // 30 days old
            }
          },
        ],
      }).select('_id');
 
      const productIds = productsNeedingEmbeddings.map(p => p._id.toString());
      
      if (productIds.length > 0) {
        this.logger.log(`Found ${productIds.length} products needing embedding updates`);
        await this.batchGenerateEmbeddings(productIds);
      } else {
        this.logger.log('All products have up-to-date embeddings');
      }
 
    } catch (error) {
      this.logger.error('Error updating all product embeddings', error);
      throw error;
    }
  }
 
  private buildVectorSearchPipeline(
    queryVector: number[],
    options: VectorSearchOptions,
  ): any[] {
    const pipeline = [];
 
    // Match stage for filtering
    const matchStage: any = {
      'aiFeatures.embeddings': { $exists: true, $ne: [] },
      isActive: true,
    };
 
    Iif (options.categories?.length) {
      matchStage['category.main'] = { $in: options.categories };
    }
 
    Iif (options.brands?.length) {
      matchStage.brand = { $in: options.brands };
    }
 
    Iif (options.priceRange) {
      matchStage['variants.price.current'] = {
        $gte: options.priceRange.min,
        $lte: options.priceRange.max,
      };
    }
 
    Iif (options.excludeIds?.length) {
      matchStage._id = { $nin: options.excludeIds.map(id => id) };
    }
 
    pipeline.push({ $match: matchStage });
 
    // Add similarity calculation stage
    pipeline.push({
      $addFields: {
        similarity: {
          $let: {
            vars: {
              dotProduct: {
                $reduce: {
                  input: { $range: [0, { $size: '$aiFeatures.embeddings' }] },
                  initialValue: 0,
                  in: {
                    $add: [
                      '$$value',
                      {
                        $multiply: [
                          { $arrayElemAt: ['$aiFeatures.embeddings', '$$this'] },
                          { $arrayElemAt: [queryVector, '$$this'] },
                        ],
                      },
                    ],
                  },
                },
              },
              queryMagnitude: Math.sqrt(queryVector.reduce((sum, val) => sum + val * val, 0)),
              productMagnitude: {
                $sqrt: {
                  $reduce: {
                    input: '$aiFeatures.embeddings',
                    initialValue: 0,
                    in: { $add: ['$$value', { $multiply: ['$$this', '$$this'] }] },
                  },
                },
              },
            },
            in: {
              $cond: {
                if: { $and: [{ $gt: ['$$queryMagnitude', 0] }, { $gt: ['$$productMagnitude', 0] }] },
                then: {
                  $divide: [
                    '$$dotProduct',
                    { $multiply: ['$$queryMagnitude', '$$productMagnitude'] },
                  ],
                },
                else: 0,
              },
            },
          },
        },
      },
    });
 
    // Filter by similarity threshold
    Iif (options.threshold) {
      pipeline.push({
        $match: {
          similarity: { $gte: options.threshold },
        },
      });
    }
 
    // Sort by similarity (descending)
    pipeline.push({ $sort: { similarity: -1 as any } });
 
    // Limit results
    Iif (options.limit) {
      pipeline.push({ $limit: options.limit });
    }
 
    return pipeline;
  }
 
  private async generateTextEmbeddings(text: string): Promise<number[]> {
    try {
      // Use the AI service to generate embeddings
      const response = await this.aiService.generateEmbeddings({
        text,
        model: 'sentence-transformers/all-MiniLM-L6-v2',
      });
 
      return response.embeddings;
 
    } catch (error) {
      this.logger.error('Error generating text embeddings', error);
      throw error;
    }
  }
 
  private async generateImageEmbeddings(imageUrl: string): Promise<number[]> {
    try {
      // Use the AI service to generate image embeddings
      const response = await this.aiService.analyzeImage({
        imageUrl,
        model: 'openai/clip-vit-base-patch32',
      });
 
      return (response as any).features || [];
 
    } catch (error) {
      this.logger.error('Error generating image embeddings', error);
      throw error;
    }
  }
 
  private createProductTextRepresentation(product: ProductDocument): string {
    const parts = [];
 
    // Basic product information
    parts.push(product.title);
    parts.push(product.description);
    parts.push(product.brand);
    
    // Category information
    parts.push(product.category.main);
    parts.push(product.category.sub);
    Iif (product.category.tags?.length) {
      parts.push(product.category.tags.join(' '));
    }
 
    // Specifications
    Iif (product.specifications) {
      Iif (product.specifications.material) {
        parts.push(`material: ${product.specifications.material}`);
      }
      Iif (product.specifications.careInstructions) {
        parts.push(`care: ${product.specifications.careInstructions}`);
      }
    }
 
    // AI features
    Iif (product.aiFeatures) {
      Iif (product.aiFeatures.colorPalette?.length) {
        parts.push(`colors: ${product.aiFeatures.colorPalette.join(' ')}`);
      }
      Iif (product.aiFeatures.seasonality?.length) {
        parts.push(`seasons: ${product.aiFeatures.seasonality.join(' ')}`);
      }
      Iif (product.aiFeatures.occasions?.length) {
        parts.push(`occasions: ${product.aiFeatures.occasions.join(' ')}`);
      }
    }
 
    // Price information (for context)
    const price = product.variants[0]?.price?.current;
    Iif (price) {
      parts.push(`price: ${price}`);
    }
 
    return parts.filter(Boolean).join(' ');
  }
 
  async getProductEmbeddingStats(): Promise<{
    totalProducts: number;
    productsWithEmbeddings: number;
    averageEmbeddingDimensions: number;
    lastUpdateStats: {
      today: number;
      thisWeek: number;
      thisMonth: number;
    };
  }> {
    try {
      const [totalCount, embeddingStats, updateStats] = await Promise.all([
        this.productModel.countDocuments({ isActive: true }),
        this.productModel.aggregate([
          {
            $match: {
              isActive: true,
              'aiFeatures.embeddings': { $exists: true, $ne: [] },
            },
          },
          {
            $group: {
              _id: null,
              count: { $sum: 1 },
              avgDimensions: { $avg: { $size: '$aiFeatures.embeddings' } },
            },
          },
        ]),
        this.productModel.aggregate([
          {
            $match: {
              isActive: true,
              'aiFeatures.lastEmbeddingUpdate': { $exists: true },
            },
          },
          {
            $group: {
              _id: {
                $dateToString: {
                  format: '%Y-%m-%d',
                  date: '$aiFeatures.lastEmbeddingUpdate',
                },
              },
              count: { $sum: 1 },
            },
          },
          { $sort: { _id: -1 as any } },
          { $limit: 30 },
        ]),
      ]);
 
      const embeddingData = embeddingStats[0] || { count: 0, avgDimensions: 0 };
      
      // Calculate update stats
      const today = new Date().toISOString().split('T')[0];
      const oneWeekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
      const oneMonthAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
 
      const lastUpdateStats = {
        today: updateStats.filter(stat => stat._id === today).reduce((sum, stat) => sum + stat.count, 0),
        thisWeek: updateStats.filter(stat => stat._id >= oneWeekAgo).reduce((sum, stat) => sum + stat.count, 0),
        thisMonth: updateStats.filter(stat => stat._id >= oneMonthAgo).reduce((sum, stat) => sum + stat.count, 0),
      };
 
      return {
        totalProducts: totalCount,
        productsWithEmbeddings: embeddingData.count,
        averageEmbeddingDimensions: Math.round(embeddingData.avgDimensions),
        lastUpdateStats,
      };
 
    } catch (error) {
      this.logger.error('Error getting embedding stats', error);
      throw error;
    }
  }
 
  async findProductClusters(
    options: {
      categories?: string[];
      minClusterSize?: number;
      maxClusters?: number;
    } = {},
  ): Promise<Array<{
    clusterId: string;
    products: string[];
    centroid: number[];
    characteristics: string[];
  }>> {
    try {
      // This is a simplified clustering algorithm
      // In production, you might want to use more sophisticated clustering like K-means
      
      const products = await this.productModel.find({
        isActive: true,
        'aiFeatures.embeddings': { $exists: true, $ne: [] },
        ...(options.categories && { 'category.main': { $in: options.categories } }),
      }).select('_id aiFeatures.embeddings category brand');
 
      Iif (products.length < (options.minClusterSize || 5)) {
        return [];
      }
 
      // Simple clustering based on similarity threshold
      const clusters = [];
      const processed = new Set<string>();
      const similarityThreshold = 0.7;
 
      for (const product of products) {
        Iif (processed.has(product._id.toString())) continue;
 
        const cluster = {
          clusterId: `cluster_${clusters.length + 1}`,
          products: [product._id.toString()],
          centroid: [...product.aiFeatures.embeddings],
          characteristics: [product.category.main, product.brand],
        };
 
        processed.add(product._id.toString());
 
        // Find similar products for this cluster
        for (const otherProduct of products) {
          Iif (processed.has(otherProduct._id.toString())) continue;
 
          const similarity = this.calculateCosineSimilarity(
            product.aiFeatures.embeddings,
            otherProduct.aiFeatures.embeddings,
          );
 
          Iif (similarity >= similarityThreshold) {
            cluster.products.push(otherProduct._id.toString());
            processed.add(otherProduct._id.toString());
            
            // Update centroid (simple average)
            for (let i = 0; i < cluster.centroid.length; i++) {
              cluster.centroid[i] = (cluster.centroid[i] + otherProduct.aiFeatures.embeddings[i]) / 2;
            }
            
            // Add characteristics
            Iif (!cluster.characteristics.includes(otherProduct.category.main)) {
              cluster.characteristics.push(otherProduct.category.main);
            }
            Iif (!cluster.characteristics.includes(otherProduct.brand)) {
              cluster.characteristics.push(otherProduct.brand);
            }
          }
        }
 
        // Only keep clusters with minimum size
        Iif (cluster.products.length >= (options.minClusterSize || 3)) {
          clusters.push(cluster);
        }
 
        // Limit number of clusters
        Iif (clusters.length >= (options.maxClusters || 20)) {
          break;
        }
      }
 
      return clusters;
 
    } catch (error) {
      this.logger.error('Error finding product clusters', error);
      throw error;
    }
  }
 
  private calculateCosineSimilarity(vectorA: number[], vectorB: number[]): number {
    Iif (vectorA.length !== vectorB.length) return 0;
 
    let dotProduct = 0;
    let magnitudeA = 0;
    let magnitudeB = 0;
 
    for (let i = 0; i < vectorA.length; i++) {
      dotProduct += vectorA[i] * vectorB[i];
      magnitudeA += vectorA[i] * vectorA[i];
      magnitudeB += vectorB[i] * vectorB[i];
    }
 
    magnitudeA = Math.sqrt(magnitudeA);
    magnitudeB = Math.sqrt(magnitudeB);
 
    Iif (magnitudeA === 0 || magnitudeB === 0) return 0;
 
    return dotProduct / (magnitudeA * magnitudeB);
  }
}