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 | import { Injectable, Logger } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import axios, { AxiosInstance } from 'axios'; import { EmbeddingRequest, EmbeddingResponse, ImageAnalysisRequest, ImageAnalysisResponse, AIProvider, } from '../interfaces/ai.interface'; @Injectable() export class HuggingFaceService implements AIProvider { private readonly logger = new Logger(HuggingFaceService.name); private readonly httpClient: AxiosInstance; private readonly apiKey: string; private readonly baseUrl: string; // Model configurations private readonly models = { embeddings: 'sentence-transformers/all-MiniLM-L6-v2', imageClassification: 'microsoft/resnet-50', textClassification: 'distilbert-base-uncased', zeroShotClassification: 'facebook/bart-large-mnli', clipModel: 'openai/clip-vit-large-patch14', }; // Rate limiting and cost tracking private requestCount = 0; private dailyRequestCount = 0; private lastResetTime = new Date(); constructor(private configService: ConfigService) { this.apiKey = this.configService.get<string>('ai.huggingface.apiKey'); this.baseUrl = this.configService.get<string>('ai.huggingface.baseUrl'); this.httpClient = axios.create({ baseURL: this.baseUrl, headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json', }, timeout: 30000, // 30 seconds timeout }); // Reset daily counter at midnight this.scheduleReset(); } get name(): string { return 'HuggingFace'; } async isAvailable(): Promise<boolean> { try { const response = await this.httpClient.get('/models'); return response.status === 200; } catch (error) { this.logger.error('HuggingFace API is not available', error); return false; } } getCost(operation: string, tokens: number): number { // HuggingFace Inference API is free for most models // Return estimated cost for premium models if needed const costPerToken = { embeddings: 0.0001, imageAnalysis: 0.001, textClassification: 0.0001, }; return (costPerToken[operation] || 0.0001) * tokens; } getRateLimit(): { requestsPerMinute: number; requestsPerDay: number } { return this.configService.get('ai.rateLimits.huggingface', { requestsPerMinute: 100, requestsPerDay: 10000, }); } async generateEmbeddings(request: EmbeddingRequest): Promise<EmbeddingResponse> { const startTime = Date.now(); try { await this.checkRateLimit(); const model = request.model || this.models.embeddings; const response = await this.httpClient.post(`/models/${model}`, { inputs: request.text, options: { wait_for_model: true, }, }); const embeddings = Array.isArray(response.data) ? response.data : response.data.embeddings; this.trackUsage('embeddings', request.text.length, Date.now() - startTime); return { embeddings, model, usage: { tokens: request.text.length, }, }; } catch (error) { this.logger.error('Failed to generate embeddings', error); throw new Error(`HuggingFace embeddings failed: ${error.message}`); } } async analyzeImage(request: ImageAnalysisRequest): Promise<ImageAnalysisResponse> { const startTime = Date.now(); try { await this.checkRateLimit(); const model = request.model || this.models.imageClassification; // For image analysis, we need to send the image data const response = await this.httpClient.post(`/models/${model}`, { inputs: request.imageUrl, options: { wait_for_model: true, }, }); const results = response.data; // Extract tags and confidence from classification results const tags = results.slice(0, 5).map(item => item.label); const confidence = results[0]?.score || 0; this.trackUsage('imageAnalysis', 1, Date.now() - startTime); return { description: `Image classified as ${tags[0]} with ${(confidence * 100).toFixed(1)}% confidence`, tags, colors: [], // Would need a separate color detection model confidence, model, }; } catch (error) { this.logger.error('Failed to analyze image', error); throw new Error(`HuggingFace image analysis failed: ${error.message}`); } } async classifyText(text: string, labels: string[]): Promise<any> { const startTime = Date.now(); try { await this.checkRateLimit(); const response = await this.httpClient.post(`/models/${this.models.zeroShotClassification}`, { inputs: text, parameters: { candidate_labels: labels, }, options: { wait_for_model: true, }, }); this.trackUsage('textClassification', text.length, Date.now() - startTime); return response.data; } catch (error) { this.logger.error('Failed to classify text', error); throw new Error(`HuggingFace text classification failed: ${error.message}`); } } async extractProductFeatures(productDescription: string): Promise<{ category: string; style: string[]; colors: string[]; materials: string[]; occasions: string[]; }> { try { // Use zero-shot classification for different aspects const [categoryResult, styleResult, colorResult] = await Promise.all([ this.classifyText(productDescription, [ 'clothing', 'shoes', 'accessories', 'bags', 'jewelry', 'beauty', 'home' ]), this.classifyText(productDescription, [ 'casual', 'formal', 'sporty', 'elegant', 'trendy', 'classic', 'bohemian' ]), this.classifyText(productDescription, [ 'black', 'white', 'red', 'blue', 'green', 'yellow', 'pink', 'brown', 'gray' ]), ]); return { category: categoryResult.labels[0], style: styleResult.labels.slice(0, 3), colors: colorResult.labels.slice(0, 2), materials: [], // Would need additional processing occasions: [], // Would need additional processing }; } catch (error) { this.logger.error('Failed to extract product features', error); return { category: 'unknown', style: [], colors: [], materials: [], occasions: [], }; } } private async checkRateLimit(): Promise<void> { const limits = this.getRateLimit(); // Check daily limit Iif (this.dailyRequestCount >= limits.requestsPerDay) { throw new Error('Daily rate limit exceeded for HuggingFace API'); } // Check per-minute limit (simple implementation) Iif (this.requestCount >= limits.requestsPerMinute) { await new Promise(resolve => setTimeout(resolve, 60000)); // Wait 1 minute this.requestCount = 0; } this.requestCount++; this.dailyRequestCount++; } private trackUsage(operation: string, tokens: number, latency: number): void { const cost = this.getCost(operation, tokens); this.logger.log(`HuggingFace ${operation}: ${tokens} tokens, ${latency}ms, $${cost.toFixed(4)}`); // Here you could emit an event or save to database for analytics } private scheduleReset(): void { const now = new Date(); const tomorrow = new Date(now); tomorrow.setDate(tomorrow.getDate() + 1); tomorrow.setHours(0, 0, 0, 0); const msUntilMidnight = tomorrow.getTime() - now.getTime(); setTimeout(() => { this.dailyRequestCount = 0; this.lastResetTime = new Date(); this.scheduleReset(); // Schedule next reset }, msUntilMidnight); } } |