Files
jobtrackingapp/JobTrackerApi/Services/SummarizerService.cs
T
2026-03-21 11:55:27 +01:00

60 lines
2.0 KiB
C#

using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
namespace JobTrackerApi.Services
{
public interface ISummarizerService
{
Task<string?> SummarizeAsync(string text, int maxLength = 150, int minLength = 30);
}
public class SummarizerService : ISummarizerService
{
private readonly IHttpClientFactory _httpFactory;
private readonly IMemoryCache _cache;
public SummarizerService(IHttpClientFactory httpFactory, IMemoryCache cache)
{
_httpFactory = httpFactory;
_cache = cache;
}
public async Task<string?> SummarizeAsync(string text, int maxLength = 150, int minLength = 30)
{
if (string.IsNullOrWhiteSpace(text)) return null;
var key = $"summ:{text.GetHashCode()}:{maxLength}:{minLength}";
if (_cache.TryGetValue<string>(key, out var cached)) return cached;
var client = _httpFactory.CreateClient("summarizer");
var payload = JsonSerializer.Serialize(new { text, max_length = maxLength, min_length = minLength });
using var content = new StringContent(payload, Encoding.UTF8, "application/json");
try
{
var res = await client.PostAsync("/summarize", content);
if (!res.IsSuccessStatusCode) return null;
using var stream = await res.Content.ReadAsStreamAsync();
using var doc = await JsonDocument.ParseAsync(stream);
if (doc.RootElement.TryGetProperty("summary", out var el))
{
var s = el.GetString();
if (!string.IsNullOrWhiteSpace(s)) _cache.Set(key, s, TimeSpan.FromHours(6));
return s;
}
return null;
}
catch
{
return null;
}
}
}
}