Spaces:
Sleeping
Sleeping
Vanderson da Silva Quintino commited on
Commit ·
360e31b
1
Parent(s): 56d8c4f
feat: Bing images for specific topics
Browse files
src/ClipForge.Infrastructure/Services/GoogleImageSearchService.cs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
using System.Text.Json;
|
|
|
|
| 2 |
using ClipForge.Core.Interfaces.Services;
|
| 3 |
using ClipForge.Infrastructure.Configuration;
|
| 4 |
using Microsoft.Extensions.Logging;
|
|
@@ -7,8 +8,8 @@ using Microsoft.Extensions.Options;
|
|
| 7 |
namespace ClipForge.Infrastructure.Services;
|
| 8 |
|
| 9 |
/// <summary>
|
| 10 |
-
/// Downloads
|
| 11 |
-
///
|
| 12 |
/// </summary>
|
| 13 |
public class GoogleImageSearchService : IStockMediaService
|
| 14 |
{
|
|
@@ -21,8 +22,6 @@ public class GoogleImageSearchService : IStockMediaService
|
|
| 21 |
_httpClient = httpClient;
|
| 22 |
_settings = settings.Value;
|
| 23 |
_logger = logger;
|
| 24 |
-
|
| 25 |
-
_httpClient.DefaultRequestHeaders.Add("Authorization", _settings.ApiKey);
|
| 26 |
}
|
| 27 |
|
| 28 |
public async Task<string> DownloadVideoAsync(string query, string outputDir, CancellationToken ct = default)
|
|
@@ -38,71 +37,137 @@ public class GoogleImageSearchService : IStockMediaService
|
|
| 38 |
|
| 39 |
private async Task<IReadOnlyList<string>> DownloadImagesAsync(string query, int count, string outputDir, CancellationToken ct)
|
| 40 |
{
|
| 41 |
-
_logger.LogInformation("Searching
|
| 42 |
Directory.CreateDirectory(outputDir);
|
| 43 |
|
| 44 |
var downloadedFiles = new List<string>();
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
try
|
| 47 |
{
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
-
var response = await _httpClient.
|
|
|
|
| 52 |
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
{
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
| 57 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
var json = await response.Content.ReadAsStringAsync(ct);
|
| 60 |
using var doc = JsonDocument.Parse(json);
|
| 61 |
|
| 62 |
-
if (!doc.RootElement.TryGetProperty("photos", out var photos))
|
| 63 |
-
return downloadedFiles;
|
| 64 |
|
| 65 |
foreach (var photo in photos.EnumerateArray())
|
| 66 |
{
|
| 67 |
-
if (
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
? large2x.GetString()
|
| 77 |
-
: src.GetProperty("large").GetString();
|
| 78 |
-
|
| 79 |
-
if (string.IsNullOrEmpty(imageUrl)) continue;
|
| 80 |
-
|
| 81 |
-
var imageResponse = await _httpClient.GetAsync(imageUrl, ct);
|
| 82 |
-
if (!imageResponse.IsSuccessStatusCode) continue;
|
| 83 |
-
|
| 84 |
-
var bytes = await imageResponse.Content.ReadAsByteArrayAsync(ct);
|
| 85 |
-
if (bytes.Length < 5000) continue;
|
| 86 |
-
|
| 87 |
-
var fileName = $"{Guid.NewGuid()}.jpg";
|
| 88 |
-
var filePath = Path.Combine(outputDir, fileName);
|
| 89 |
-
await File.WriteAllBytesAsync(filePath, bytes, ct);
|
| 90 |
-
|
| 91 |
-
downloadedFiles.Add(filePath);
|
| 92 |
-
_logger.LogInformation("Downloaded Pexels photo ({Size}KB) for '{Query}'", bytes.Length / 1024, query);
|
| 93 |
-
}
|
| 94 |
-
catch (Exception ex)
|
| 95 |
-
{
|
| 96 |
-
_logger.LogDebug(ex, "Failed to download photo");
|
| 97 |
-
}
|
| 98 |
}
|
| 99 |
}
|
| 100 |
catch (Exception ex)
|
| 101 |
{
|
| 102 |
-
_logger.
|
| 103 |
}
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
}
|
|
|
|
| 1 |
using System.Text.Json;
|
| 2 |
+
using System.Text.RegularExpressions;
|
| 3 |
using ClipForge.Core.Interfaces.Services;
|
| 4 |
using ClipForge.Infrastructure.Configuration;
|
| 5 |
using Microsoft.Extensions.Logging;
|
|
|
|
| 8 |
namespace ClipForge.Infrastructure.Services;
|
| 9 |
|
| 10 |
/// <summary>
|
| 11 |
+
/// Downloads images using multiple sources: Bing scraping + Pexels fallback.
|
| 12 |
+
/// Ensures images are relevant to the specific topic.
|
| 13 |
/// </summary>
|
| 14 |
public class GoogleImageSearchService : IStockMediaService
|
| 15 |
{
|
|
|
|
| 22 |
_httpClient = httpClient;
|
| 23 |
_settings = settings.Value;
|
| 24 |
_logger = logger;
|
|
|
|
|
|
|
| 25 |
}
|
| 26 |
|
| 27 |
public async Task<string> DownloadVideoAsync(string query, string outputDir, CancellationToken ct = default)
|
|
|
|
| 37 |
|
| 38 |
private async Task<IReadOnlyList<string>> DownloadImagesAsync(string query, int count, string outputDir, CancellationToken ct)
|
| 39 |
{
|
| 40 |
+
_logger.LogInformation("Searching images for '{Query}', need {Count}", query, count);
|
| 41 |
Directory.CreateDirectory(outputDir);
|
| 42 |
|
| 43 |
var downloadedFiles = new List<string>();
|
| 44 |
|
| 45 |
+
// Try Bing first (has real images of specific topics)
|
| 46 |
+
var bingUrls = await SearchBingAsync(query, count + 5, ct);
|
| 47 |
+
_logger.LogInformation("Bing returned {Count} URLs for '{Query}'", bingUrls.Count, query);
|
| 48 |
+
|
| 49 |
+
foreach (var url in bingUrls)
|
| 50 |
+
{
|
| 51 |
+
if (downloadedFiles.Count >= count) break;
|
| 52 |
+
var file = await TryDownloadImageAsync(url, outputDir, ct);
|
| 53 |
+
if (file != null) downloadedFiles.Add(file);
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
// If Bing didn't get enough, use Pexels as fallback
|
| 57 |
+
if (downloadedFiles.Count < count)
|
| 58 |
+
{
|
| 59 |
+
_logger.LogInformation("Bing got {Got}/{Need}, trying Pexels fallback", downloadedFiles.Count, count);
|
| 60 |
+
var pexelsFiles = await SearchPexelsAsync(query, count - downloadedFiles.Count, outputDir, ct);
|
| 61 |
+
downloadedFiles.AddRange(pexelsFiles);
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
_logger.LogInformation("Total: {Count} images for '{Query}'", downloadedFiles.Count, query);
|
| 65 |
+
return downloadedFiles;
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
private async Task<List<string>> SearchBingAsync(string query, int count, CancellationToken ct)
|
| 69 |
+
{
|
| 70 |
+
var urls = new List<string>();
|
| 71 |
try
|
| 72 |
{
|
| 73 |
+
var searchUrl = $"https://www.bing.com/images/search?q={Uri.EscapeDataString(query)}&first=1&count={count}&qft=+filterui:imagesize-large+filterui:aspect-tall";
|
| 74 |
+
|
| 75 |
+
using var request = new HttpRequestMessage(HttpMethod.Get, searchUrl);
|
| 76 |
+
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");
|
| 77 |
+
request.Headers.Add("Accept", "text/html,application/xhtml+xml");
|
| 78 |
+
request.Headers.Add("Accept-Language", "pt-BR,pt;q=0.9,en;q=0.8");
|
| 79 |
|
| 80 |
+
var response = await _httpClient.SendAsync(request, ct);
|
| 81 |
+
if (!response.IsSuccessStatusCode) return urls;
|
| 82 |
|
| 83 |
+
var html = await response.Content.ReadAsStringAsync(ct);
|
| 84 |
+
|
| 85 |
+
// Extract murl (media URL) from Bing results
|
| 86 |
+
var matches = Regex.Matches(html, @"murl":"(https?://[^&""]+)"");
|
| 87 |
+
foreach (Match match in matches)
|
| 88 |
{
|
| 89 |
+
if (urls.Count >= count) break;
|
| 90 |
+
var url = match.Groups[1].Value;
|
| 91 |
+
if (IsImageUrl(url))
|
| 92 |
+
urls.Add(url);
|
| 93 |
}
|
| 94 |
+
}
|
| 95 |
+
catch (Exception ex)
|
| 96 |
+
{
|
| 97 |
+
_logger.LogWarning(ex, "Bing search failed for '{Query}'", query);
|
| 98 |
+
}
|
| 99 |
+
return urls;
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
private async Task<List<string>> SearchPexelsAsync(string query, int count, string outputDir, CancellationToken ct)
|
| 103 |
+
{
|
| 104 |
+
var files = new List<string>();
|
| 105 |
+
try
|
| 106 |
+
{
|
| 107 |
+
using var request = new HttpRequestMessage(HttpMethod.Get,
|
| 108 |
+
$"https://api.pexels.com/v1/search?query={Uri.EscapeDataString(query)}&per_page={count}&orientation=portrait&size=large");
|
| 109 |
+
request.Headers.Add("Authorization", _settings.ApiKey);
|
| 110 |
+
|
| 111 |
+
var response = await _httpClient.SendAsync(request, ct);
|
| 112 |
+
if (!response.IsSuccessStatusCode) return files;
|
| 113 |
|
| 114 |
var json = await response.Content.ReadAsStringAsync(ct);
|
| 115 |
using var doc = JsonDocument.Parse(json);
|
| 116 |
|
| 117 |
+
if (!doc.RootElement.TryGetProperty("photos", out var photos)) return files;
|
|
|
|
| 118 |
|
| 119 |
foreach (var photo in photos.EnumerateArray())
|
| 120 |
{
|
| 121 |
+
if (files.Count >= count) break;
|
| 122 |
+
var src = photo.GetProperty("src");
|
| 123 |
+
var imageUrl = src.TryGetProperty("portrait", out var p) ? p.GetString()
|
| 124 |
+
: src.TryGetProperty("large2x", out var l) ? l.GetString()
|
| 125 |
+
: src.GetProperty("large").GetString();
|
| 126 |
+
|
| 127 |
+
if (string.IsNullOrEmpty(imageUrl)) continue;
|
| 128 |
+
var file = await TryDownloadImageAsync(imageUrl, outputDir, ct);
|
| 129 |
+
if (file != null) files.Add(file);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
}
|
| 131 |
}
|
| 132 |
catch (Exception ex)
|
| 133 |
{
|
| 134 |
+
_logger.LogWarning(ex, "Pexels search failed for '{Query}'", query);
|
| 135 |
}
|
| 136 |
+
return files;
|
| 137 |
+
}
|
| 138 |
|
| 139 |
+
private async Task<string?> TryDownloadImageAsync(string url, string outputDir, CancellationToken ct)
|
| 140 |
+
{
|
| 141 |
+
try
|
| 142 |
+
{
|
| 143 |
+
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
| 144 |
+
request.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
|
| 145 |
+
request.Headers.Add("Accept", "image/*");
|
| 146 |
+
|
| 147 |
+
using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct);
|
| 148 |
+
if (!response.IsSuccessStatusCode) return null;
|
| 149 |
+
|
| 150 |
+
var contentType = response.Content.Headers.ContentType?.MediaType ?? "";
|
| 151 |
+
if (!contentType.StartsWith("image/")) return null;
|
| 152 |
+
|
| 153 |
+
var bytes = await response.Content.ReadAsByteArrayAsync(ct);
|
| 154 |
+
if (bytes.Length < 15000) return null; // Skip tiny images
|
| 155 |
+
|
| 156 |
+
var ext = contentType.Contains("png") ? ".png" : ".jpg";
|
| 157 |
+
var filePath = Path.Combine(outputDir, $"{Guid.NewGuid()}{ext}");
|
| 158 |
+
await File.WriteAllBytesAsync(filePath, bytes, ct);
|
| 159 |
+
return filePath;
|
| 160 |
+
}
|
| 161 |
+
catch
|
| 162 |
+
{
|
| 163 |
+
return null;
|
| 164 |
+
}
|
| 165 |
}
|
| 166 |
+
|
| 167 |
+
private static bool IsImageUrl(string url)
|
| 168 |
+
=> url.Contains(".jpg", StringComparison.OrdinalIgnoreCase) ||
|
| 169 |
+
url.Contains(".jpeg", StringComparison.OrdinalIgnoreCase) ||
|
| 170 |
+
url.Contains(".png", StringComparison.OrdinalIgnoreCase) ||
|
| 171 |
+
url.Contains(".webp", StringComparison.OrdinalIgnoreCase) ||
|
| 172 |
+
url.Contains("image", StringComparison.OrdinalIgnoreCase);
|
| 173 |
}
|