Spaces:
Sleeping
Sleeping
Download src/ClipForge.Infrastructure/Services/GoogleImageSearchService.cs from clipeforge/app: direct link, hf CLI and curl.
- Browser
- Download file 7.39 kB
-
https://huggingface.co/spaces/clipeforge/app/resolve/main/src/ClipForge.Infrastructure/Services/GoogleImageSearchService.cs
- Command line
-
hf download hf://spaces/clipeforge/app/src/ClipForge.Infrastructure/Services/GoogleImageSearchService.cs
-
curl -L -o GoogleImageSearchService.cs https://huggingface.co/spaces/clipeforge/app/resolve/main/src/ClipForge.Infrastructure/Services/GoogleImageSearchService.cs
7.39 kB
| using System.Text.Json; | |
| using System.Text.RegularExpressions; | |
| using ClipForge.Core.Interfaces.Services; | |
| using ClipForge.Infrastructure.Configuration; | |
| using Microsoft.Extensions.Logging; | |
| using Microsoft.Extensions.Options; | |
| namespace ClipForge.Infrastructure.Services; | |
| /// <summary> | |
| /// Downloads images using multiple sources: Bing scraping + Pexels fallback. | |
| /// Ensures images are relevant to the specific topic. | |
| /// </summary> | |
| public class GoogleImageSearchService : IStockMediaService | |
| { | |
| private readonly HttpClient _httpClient; | |
| private readonly PexelsSettings _settings; | |
| private readonly ILogger<GoogleImageSearchService> _logger; | |
| public GoogleImageSearchService(HttpClient httpClient, IOptions<PexelsSettings> settings, ILogger<GoogleImageSearchService> logger) | |
| { | |
| _httpClient = httpClient; | |
| _settings = settings.Value; | |
| _logger = logger; | |
| } | |
| public async Task<string> DownloadVideoAsync(string query, string outputDir, CancellationToken ct = default) | |
| { | |
| var images = await DownloadImagesAsync(query, 1, outputDir, ct); | |
| return images.FirstOrDefault() ?? string.Empty; | |
| } | |
| public async Task<IReadOnlyList<string>> DownloadMultipleVideosAsync(string query, int count, string outputDir, CancellationToken ct = default) | |
| { | |
| return await DownloadImagesAsync(query, count, outputDir, ct); | |
| } | |
| private async Task<IReadOnlyList<string>> DownloadImagesAsync(string query, int count, string outputDir, CancellationToken ct) | |
| { | |
| _logger.LogInformation("Searching images for '{Query}', need {Count}", query, count); | |
| Directory.CreateDirectory(outputDir); | |
| var downloadedFiles = new List<string>(); | |
| // Try Bing first (has real images of specific topics) | |
| var bingUrls = await SearchBingAsync(query, count + 5, ct); | |
| _logger.LogInformation("Bing returned {Count} URLs for '{Query}'", bingUrls.Count, query); | |
| foreach (var url in bingUrls) | |
| { | |
| if (downloadedFiles.Count >= count) break; | |
| var file = await TryDownloadImageAsync(url, outputDir, ct); | |
| if (file != null) downloadedFiles.Add(file); | |
| } | |
| // If Bing didn't get enough, use Pexels as fallback | |
| if (downloadedFiles.Count < count) | |
| { | |
| _logger.LogInformation("Bing got {Got}/{Need}, trying Pexels fallback", downloadedFiles.Count, count); | |
| var pexelsFiles = await SearchPexelsAsync(query, count - downloadedFiles.Count, outputDir, ct); | |
| downloadedFiles.AddRange(pexelsFiles); | |
| } | |
| _logger.LogInformation("Total: {Count} images for '{Query}'", downloadedFiles.Count, query); | |
| return downloadedFiles; | |
| } | |
| private async Task<List<string>> SearchBingAsync(string query, int count, CancellationToken ct) | |
| { | |
| var urls = new List<string>(); | |
| try | |
| { | |
| var searchUrl = $"https://www.bing.com/images/search?q={Uri.EscapeDataString(query)}&first=1&count={count}&qft=+filterui:imagesize-large+filterui:aspect-tall"; | |
| using var request = new HttpRequestMessage(HttpMethod.Get, searchUrl); | |
| request.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36"); | |
| request.Headers.Add("Accept", "text/html,application/xhtml+xml"); | |
| request.Headers.Add("Accept-Language", "pt-BR,pt;q=0.9,en;q=0.8"); | |
| var response = await _httpClient.SendAsync(request, ct); | |
| if (!response.IsSuccessStatusCode) return urls; | |
| var html = await response.Content.ReadAsStringAsync(ct); | |
| // Extract murl (media URL) from Bing results | |
| var matches = Regex.Matches(html, @"murl":"(https?://[^&""]+)""); | |
| foreach (Match match in matches) | |
| { | |
| if (urls.Count >= count) break; | |
| var url = match.Groups[1].Value; | |
| if (IsImageUrl(url)) | |
| urls.Add(url); | |
| } | |
| } | |
| catch (Exception ex) | |
| { | |
| _logger.LogWarning(ex, "Bing search failed for '{Query}'", query); | |
| } | |
| return urls; | |
| } | |
| private async Task<List<string>> SearchPexelsAsync(string query, int count, string outputDir, CancellationToken ct) | |
| { | |
| var files = new List<string>(); | |
| try | |
| { | |
| using var request = new HttpRequestMessage(HttpMethod.Get, | |
| $"https://api.pexels.com/v1/search?query={Uri.EscapeDataString(query)}&per_page={count}&orientation=portrait&size=large"); | |
| request.Headers.Add("Authorization", _settings.ApiKey); | |
| var response = await _httpClient.SendAsync(request, ct); | |
| if (!response.IsSuccessStatusCode) return files; | |
| var json = await response.Content.ReadAsStringAsync(ct); | |
| using var doc = JsonDocument.Parse(json); | |
| if (!doc.RootElement.TryGetProperty("photos", out var photos)) return files; | |
| foreach (var photo in photos.EnumerateArray()) | |
| { | |
| if (files.Count >= count) break; | |
| var src = photo.GetProperty("src"); | |
| var imageUrl = src.TryGetProperty("portrait", out var p) ? p.GetString() | |
| : src.TryGetProperty("large2x", out var l) ? l.GetString() | |
| : src.GetProperty("large").GetString(); | |
| if (string.IsNullOrEmpty(imageUrl)) continue; | |
| var file = await TryDownloadImageAsync(imageUrl, outputDir, ct); | |
| if (file != null) files.Add(file); | |
| } | |
| } | |
| catch (Exception ex) | |
| { | |
| _logger.LogWarning(ex, "Pexels search failed for '{Query}'", query); | |
| } | |
| return files; | |
| } | |
| private async Task<string?> TryDownloadImageAsync(string url, string outputDir, CancellationToken ct) | |
| { | |
| try | |
| { | |
| using var request = new HttpRequestMessage(HttpMethod.Get, url); | |
| request.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"); | |
| request.Headers.Add("Accept", "image/*"); | |
| using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct); | |
| if (!response.IsSuccessStatusCode) return null; | |
| var contentType = response.Content.Headers.ContentType?.MediaType ?? ""; | |
| if (!contentType.StartsWith("image/")) return null; | |
| var bytes = await response.Content.ReadAsByteArrayAsync(ct); | |
| if (bytes.Length < 15000) return null; // Skip tiny images | |
| var ext = contentType.Contains("png") ? ".png" : ".jpg"; | |
| var filePath = Path.Combine(outputDir, $"{Guid.NewGuid()}{ext}"); | |
| await File.WriteAllBytesAsync(filePath, bytes, ct); | |
| return filePath; | |
| } | |
| catch | |
| { | |
| return null; | |
| } | |
| } | |
| private static bool IsImageUrl(string url) | |
| => url.Contains(".jpg", StringComparison.OrdinalIgnoreCase) || | |
| url.Contains(".jpeg", StringComparison.OrdinalIgnoreCase) || | |
| url.Contains(".png", StringComparison.OrdinalIgnoreCase) || | |
| url.Contains(".webp", StringComparison.OrdinalIgnoreCase) || | |
| url.Contains("image", StringComparison.OrdinalIgnoreCase); | |
| } | |