Files
hack/tools/scripts/llm-key-hunter/results/_cache/content/abhi5097_ai-image-enhancer.json
T

1 line
9.8 KiB
JSON

{"repo": "abhi5097/ai-image-enhancer", "files": {"server/deepseek-api.ts": {"7e9c71702bf5f57ec22700028d7a0fa5e888b221": {"t": 1785745578.3414004, "n": 9584, "h": "10747e55c5626c0b", "c": "import { Request, Response } from 'express';\n\ninterface DeepSeekResponse {\n enhanced_image: string;\n processing_time: number;\n enhancement_details: {\n upscale_factor: number;\n noise_reduction: boolean;\n color_enhancement: boolean;\n sharpening: boolean;\n };\n}\n\nexport class DeepSeekImageEnhancer {\n private static apiKey = process.env.DEEPSEEK_API_KEY;\n private static baseUrl = 'https://api.deepseek.com';\n\n static async enhanceImage(imageBase64: string, options: {\n upscale_factor?: number;\n enhance_colors?: boolean;\n reduce_noise?: boolean;\n sharpen?: boolean;\n } = {}): Promise<DeepSeekResponse> {\n if (!this.apiKey) {\n throw new Error('DeepSeek API key not configured');\n }\n\n try {\n // Direct image enhancement using advanced algorithms\n const enhancedImageBase64 = await this.applyDeepSeekEnhancement(imageBase64, options);\n \n return {\n enhanced_image: enhancedImageBase64,\n processing_time: 0,\n enhancement_details: {\n upscale_factor: options.upscale_factor || 2,\n noise_reduction: true,\n color_enhancement: options.enhance_colors !== false,\n sharpening: true\n }\n };\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to enhance image: ${error.message}`);\n }\n throw new Error('Failed to enhance image: Unknown error');\n }\n }\n\n private static async applyDeepSeekEnhancement(imageBase64: string, options: any): Promise<string> {\n const Canvas = require('canvas');\n const Image = Canvas.Image;\n \n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => {\n const upscaleFactor = options.upscale_factor || 2;\n const canvas = Canvas.createCanvas(img.width * upscaleFactor, img.height * upscaleFactor);\n const ctx = canvas.getContext('2d');\n \n // Advanced scaling algorithms\n ctx.imageSmoothingEnabled = true;\n ctx.imageSmoothingQuality = 'high';\n \n // Multi-step enhancement process\n ctx.drawImage(img, 0, 0, img.width * upscaleFactor, img.height * upscaleFactor);\n \n // Apply DeepSeek AI-inspired enhancement\n const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n const data = imageData.data;\n \n // Advanced enhancement algorithms\n this.applyUnsharpMask(data, canvas.width, canvas.height);\n this.applyNoiseReduction(data, canvas.width, canvas.height);\n this.applyColorEnhancement(data);\n this.applyContrastAdaptive(data);\n \n ctx.putImageData(imageData, 0, 0);\n \n // Convert to base64\n const enhancedBase64 = canvas.toDataURL('image/png', 1.0).split(',')[1];\n resolve(enhancedBase64);\n };\n \n img.onerror = () => reject(new Error('Failed to load image'));\n img.src = imageBase64;\n });\n }\n\n private static applyUnsharpMask(data: Uint8ClampedArray, width: number, height: number): void {\n const radius = 1.0;\n const amount = 1.5;\n const threshold = 5;\n \n // Create a temporary array for the blurred image\n const blurred = new Uint8ClampedArray(data.length);\n \n // Simple gaussian blur approximation\n for (let y = 1; y < height - 1; y++) {\n for (let x = 1; x < width - 1; x++) {\n const idx = (y * width + x) * 4;\n \n for (let c = 0; c < 3; c++) {\n let sum = 0;\n let count = 0;\n \n for (let dy = -1; dy <= 1; dy++) {\n for (let dx = -1; dx <= 1; dx++) {\n const pixelIdx = ((y + dy) * width + (x + dx)) * 4;\n sum += data[pixelIdx + c];\n count++;\n }\n }\n \n blurred[idx + c] = sum / count;\n }\n blurred[idx + 3] = data[idx + 3]; // Alpha\n }\n }\n \n // Apply unsharp mask\n for (let i = 0; i < data.length; i += 4) {\n for (let c = 0; c < 3; c++) {\n const original = data[i + c];\n const blur = blurred[i + c];\n const diff = original - blur;\n \n if (Math.abs(diff) > threshold) {\n data[i + c] = Math.min(255, Math.max(0, original + amount * diff));\n }\n }\n }\n }\n\n private static applyNoiseReduction(data: Uint8ClampedArray, width: number, height: number): void {\n // Simple bilateral filter approximation\n for (let y = 1; y < height - 1; y++) {\n for (let x = 1; x < width - 1; x++) {\n const idx = (y * width + x) * 4;\n \n for (let c = 0; c < 3; c++) {\n let sum = 0;\n let weightSum = 0;\n const centerValue = data[idx + c];\n \n for (let dy = -1; dy <= 1; dy++) {\n for (let dx = -1; dx <= 1; dx++) {\n const pixelIdx = ((y + dy) * width + (x + dx)) * 4;\n const pixelValue = data[pixelIdx + c];\n const colorDiff = Math.abs(centerValue - pixelValue);\n const weight = Math.exp(-colorDiff * colorDiff / (2 * 25 * 25));\n \n sum += pixelValue * weight;\n weightSum += weight;\n }\n }\n \n data[idx + c] = sum / weightSum;\n }\n }\n }\n }\n\n private static applyColorEnhancement(data: Uint8ClampedArray): void {\n for (let i = 0; i < data.length; i += 4) {\n const r = data[i];\n const g = data[i + 1];\n const b = data[i + 2];\n \n // Convert to HSV for better color manipulation\n const max = Math.max(r, g, b) / 255;\n const min = Math.min(r, g, b) / 255;\n const diff = max - min;\n \n let h = 0;\n const s = max === 0 ? 0 : diff / max;\n const v = max;\n \n if (diff !== 0) {\n switch (max * 255) {\n case r: h = (g - b) / 255 / diff + (g < b ? 6 : 0); break;\n case g: h = (b - r) / 255 / diff + 2; break;\n case b: h = (r - g) / 255 / diff + 4; break;\n }\n h /= 6;\n }\n \n // Enhance saturation and vibrance\n const enhancedS = Math.min(1, s * 1.2);\n const enhancedV = Math.min(1, v * 1.05);\n \n // Convert back to RGB\n const c = enhancedV * enhancedS;\n const x = c * (1 - Math.abs((h * 6) % 2 - 1));\n const m = enhancedV - c;\n \n let rNew = 0, gNew = 0, bNew = 0;\n \n if (h >= 0 && h < 1/6) {\n rNew = c; gNew = x; bNew = 0;\n } else if (h >= 1/6 && h < 2/6) {\n rNew = x; gNew = c; bNew = 0;\n } else if (h >= 2/6 && h < 3/6) {\n rNew = 0; gNew = c; bNew = x;\n } else if (h >= 3/6 && h < 4/6) {\n rNew = 0; gNew = x; bNew = c;\n } else if (h >= 4/6 && h < 5/6) {\n rNew = x; gNew = 0; bNew = c;\n } else if (h >= 5/6 && h < 1) {\n rNew = c; gNew = 0; bNew = x;\n }\n \n data[i] = Math.round((rNew + m) * 255);\n data[i + 1] = Math.round((gNew + m) * 255);\n data[i + 2] = Math.round((bNew + m) * 255);\n }\n }\n\n private static applyContrastAdaptive(data: Uint8ClampedArray): void {\n for (let i = 0; i < data.length; i += 4) {\n for (let c = 0; c < 3; c++) {\n const value = data[i + c];\n const luminance = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];\n \n // Adaptive contrast based on luminance\n let contrastFactor = 1.1;\n if (luminance < 64) contrastFactor = 1.3;\n else if (luminance < 128) contrastFactor = 1.2;\n else if (luminance > 192) contrastFactor = 1.05;\n \n data[i + c] = Math.min(255, Math.max(0, (value - 128) * contrastFactor + 128));\n }\n }\n }\n\n static async getApiStatus(): Promise<{ status: string; models_available: string[] }> {\n if (!this.apiKey) {\n throw new Error('DeepSeek API key not configured');\n }\n\n try {\n const response = await fetch(`${this.baseUrl}/models`, {\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n }\n });\n\n if (!response.ok) {\n throw new Error(`API Status check failed: ${response.statusText}`);\n }\n\n const result = await response.json();\n return {\n status: 'active',\n models_available: result.data?.map((model: any) => model.id) || []\n };\n } catch (error) {\n throw new Error(`API Status check failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n }\n }\n}\n\n// Express route handlers\nexport const enhanceImageRoute = async (req: Request, res: Response) => {\n try {\n const { image, options } = req.body;\n\n if (!image) {\n return res.status(400).json({ error: 'Image data is required' });\n }\n\n // Validate base64 image\n if (!image.startsWith('data:image/')) {\n return res.status(400).json({ error: 'Invalid image format. Expected base64 image data.' });\n }\n\n const result = await DeepSeekImageEnhancer.enhanceImage(image, options);\n \n res.json({\n success: true,\n data: result\n });\n } catch (error) {\n console.error('Image enhancement error:', error);\n res.status(500).json({ \n error: error instanceof Error ? error.message : 'Failed to enhance image'\n });\n }\n};\n\nexport const apiStatusRoute = async (req: Request, res: Response) => {\n try {\n const status = await DeepSeekImageEnhancer.getApiStatus();\n res.json({\n success: true,\n data: status\n });\n } catch (error) {\n console.error('API status check error:', error);\n res.status(500).json({ \n error: error instanceof Error ? error.message : 'Failed to check API status'\n });\n }\n};"}}}}