poe2-bot/tools/OcrDaemon/Daemon.cs
2026-02-11 02:11:50 -05:00

87 lines
3.1 KiB
C#

namespace OcrDaemon;
using System.Text.Json;
using System.Text.Json.Serialization;
using Tesseract;
static class Daemon
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
public static int Run()
{
ScreenCapture.InitDpiAwareness();
// Pre-create the Tesseract OCR engine (reused across all requests)
var tessdataPath = Path.Combine(AppContext.BaseDirectory, "tessdata");
var tessLang = File.Exists(Path.Combine(tessdataPath, "poe2.traineddata")) ? "poe2" : "eng";
TesseractEngine tessEngine;
try
{
tessEngine = new TesseractEngine(tessdataPath, tessLang, EngineMode.LstmOnly);
tessEngine.DefaultPageSegMode = PageSegMode.SingleBlock;
tessEngine.SetVariable("preserve_interword_spaces", "1");
Console.Error.WriteLine($"Tesseract engine loaded with language: {tessLang}");
}
catch (Exception ex)
{
WriteResponse(new ErrorResponse($"Failed to create Tesseract engine: {ex.Message}. Ensure tessdata/eng.traineddata exists."));
return 1;
}
// Signal ready
WriteResponse(new ReadyResponse());
var ocrHandler = new OcrHandler(tessEngine);
var gridHandler = new GridHandler();
var detectGridHandler = new DetectGridHandler();
// Main loop: read one JSON line, handle, write one JSON line
string? line;
while ((line = Console.In.ReadLine()) != null)
{
line = line.Trim();
if (line.Length == 0) continue;
try
{
var request = JsonSerializer.Deserialize<Request>(line, JsonOptions);
if (request == null)
{
WriteResponse(new ErrorResponse("Failed to parse request"));
continue;
}
object response = request.Cmd?.ToLowerInvariant() switch
{
"ocr" => ocrHandler.HandleOcr(request),
"screenshot" => ocrHandler.HandleScreenshot(request),
"capture" => ocrHandler.HandleCapture(request),
"snapshot" => ocrHandler.HandleSnapshot(request),
"diff-ocr" => ocrHandler.HandleDiffOcr(request),
"grid" => gridHandler.HandleGrid(request),
"detect-grid" => detectGridHandler.HandleDetectGrid(request),
_ => new ErrorResponse($"Unknown command: {request.Cmd}"),
};
WriteResponse(response);
}
catch (Exception ex)
{
WriteResponse(new ErrorResponse(ex.Message));
}
}
return 0;
}
private static void WriteResponse(object response)
{
var json = JsonSerializer.Serialize(response, JsonOptions);
Console.Out.WriteLine(json);
Console.Out.Flush();
}
}