powershell-speech-service/Program.cs

100 lines
3.6 KiB
C#
Raw Normal View History

2024-07-12 22:33:03 -04:00

using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Timers;
namespace powershellspeechservice
{
public class Program
{
private static string uploadCache, audioPath = "";
private static TimeSpan expiration = TimeSpan.FromHours(1);
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthorization();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
uploadCache = Path.Combine(Environment.CurrentDirectory, "uploadcache");
if (!Directory.Exists(uploadCache))
Directory.CreateDirectory(uploadCache);
audioPath = builder.Configuration["audioOutputTargetPath"] ?? "./";
Console.WriteLine(audioPath);
if (!Directory.Exists(audioPath))
Directory.CreateDirectory(audioPath);
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapPost("/speak", (HttpContext httpContext) =>
{
var saved = new List<string>();
foreach (var submitted in httpContext.Request.Form.Files)
{
var trustedFileName = Path.GetRandomFileName();
var fullUploadedPath = Path.Combine(uploadCache, trustedFileName);
using (FileStream fs = new(fullUploadedPath, FileMode.Create))
{
submitted.OpenReadStream().CopyTo(fs);
}
var randomishFilename = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".wav";
var p = new System.Diagnostics.Process();
p.StartInfo.FileName = "pwsh";
p.StartInfo.ArgumentList.Add("-c");
p.StartInfo.ArgumentList.Add("ttsf.ps1");
p.StartInfo.ArgumentList.Add("-inputPath");
p.StartInfo.ArgumentList.Add(fullUploadedPath);
p.StartInfo.ArgumentList.Add("-outputPath");
p.StartInfo.ArgumentList.Add(Path.Combine(audioPath, randomishFilename));
p.StartInfo.UseShellExecute = true;
p.Start();
saved.Add(randomishFilename);
}
return saved;
})
.WithName("speak")
.WithOpenApi();
var aTimer = new System.Timers.Timer(TimeSpan.FromHours(4));
aTimer.Elapsed += TimedCleanup;
aTimer.AutoReset = true;
aTimer.Enabled = true;
app.Run();
}
private static void TimedCleanup(Object source, ElapsedEventArgs e)
{
var now = DateTime.Now;
var files = Directory.GetFiles(uploadCache)
//.Union(Directory.GetFiles(audioPath))
.ToList();
foreach(var f in files)
{
var diff = now - File.GetLastAccessTime(f);
if(diff > expiration)
{
File.Delete(f);
}
}
}
}
}