mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-08-11 19:32:10 +00:00
added a DocumentManager.cs to buffer only the active document page and its images
This commit is contained in:
parent
ed26fbd9db
commit
35829302e9
58
app/MindWork AI Studio/Tools/DocumentManager.cs
Normal file
58
app/MindWork AI Studio/Tools/DocumentManager.cs
Normal file
@ -0,0 +1,58 @@
|
||||
using System.Text;
|
||||
|
||||
namespace AIStudio.Tools;
|
||||
|
||||
/// <summary>
|
||||
/// Buffers only the active document page so that its image segments can follow
|
||||
/// the page Markdown without retaining the complete document in memory.
|
||||
/// </summary>
|
||||
public sealed class DocumentManager
|
||||
{
|
||||
private int currentPageNumber;
|
||||
private StringBuilder? currentPageContent;
|
||||
|
||||
public string? AddPage(ContentStreamDocumentMetadata metadata, string? content, bool extractImages)
|
||||
{
|
||||
var pageNumber = metadata.Document?.PageNumber ?? 0;
|
||||
if (pageNumber == 0)
|
||||
return content;
|
||||
|
||||
var image = metadata.Document?.Image;
|
||||
if (image is null)
|
||||
{
|
||||
var completedPage = this.Flush();
|
||||
this.currentPageNumber = pageNumber;
|
||||
this.currentPageContent = new StringBuilder();
|
||||
this.currentPageContent.AppendLine($"# Page {pageNumber}");
|
||||
this.currentPageContent.Append(content);
|
||||
return completedPage;
|
||||
}
|
||||
|
||||
if (!extractImages || this.currentPageContent is null || string.IsNullOrWhiteSpace(image.Id))
|
||||
return null;
|
||||
|
||||
if (ContentStreamSseHandler.ProcessImageSegment(image.Id, image))
|
||||
{
|
||||
var base64 = ContentStreamSseHandler.BuildImage(image.Id);
|
||||
if (!string.IsNullOrWhiteSpace(base64))
|
||||
{
|
||||
var mediaType = string.IsNullOrWhiteSpace(image.MediaType) ? "image/jpeg" : image.MediaType;
|
||||
this.currentPageContent.AppendLine();
|
||||
this.currentPageContent.AppendLine($"");
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public string? Flush()
|
||||
{
|
||||
if (this.currentPageContent is null)
|
||||
return null;
|
||||
|
||||
var result = this.currentPageContent.ToString();
|
||||
this.currentPageContent = null;
|
||||
this.currentPageNumber = 0;
|
||||
return string.IsNullOrWhiteSpace(result) ? null : result;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user