Files
AI-Studio/app/MindWork AI Studio/Components/SelectDocument.razor.cs
T

73 lines
2.8 KiB
C#

using AIStudio.Tools.DocumentSegments;
using AIStudio.Tools.Rust;
using Microsoft.AspNetCore.Components;
namespace AIStudio.Components;
/// <summary>
/// The field with which the user chooses the document an assistant works on, e.g., to translate it.
/// </summary>
/// <remarks>
/// It offers the kinds of files of all document formats and refuses any other file, see DocumentSegmentFormats, as
/// well as a document whose text is larger than its format reads on this computer, see IDocumentSegmentFormat.MaxTextSize.
/// </remarks>
public partial class SelectDocument : MSGComponentBase
{
/// <summary>
/// The path of the chosen document; empty while none is chosen.
/// </summary>
[Parameter]
public string Document { get; set; } = string.Empty;
/// <summary>
/// Called with the path of the document the user chose.
/// </summary>
[Parameter]
public EventCallback<string> DocumentChanged { get; set; }
/// <summary>
/// The title of the file dialog, e.g., "Select a document to translate".
/// </summary>
[Parameter, EditorRequired]
public string DialogTitle { get; set; } = string.Empty;
/// <summary>
/// Whether the field is disabled, e.g., while the assistant works.
/// </summary>
[Parameter]
public bool Disabled { get; set; }
// Built anew, since the name of the entry follows the language of the user interface:
private FileTypeFilter[] Filter => [DocumentSegmentFormats.AllKinds];
private string? Validate(string path)
{
if (string.IsNullOrWhiteSpace(path))
return TA("Please choose a document.");
if (DocumentSegmentFormats.For(path) is not { } format)
return TA("This kind of file is not supported. Please choose a Word, PowerPoint, LaTeX, Markdown, or HTML file.");
if (TextSizeOf(format, path) is { } textSize && textSize > format.MaxTextSize)
return string.Format(TA("The text of this document takes {0} MB, more than the {1} MB which AI Studio can edit for this kind of document with the memory of this computer. Please split it into smaller files or choose another one."), DocumentMemoryBudget.MegabytesOf(textSize), DocumentMemoryBudget.MegabytesOf(format.MaxTextSize));
return null;
}
/// <summary>
/// Measures the text of a document; null when the document cannot be read, e.g., because it is gone or broken,
/// which the run reports then.
/// </summary>
private static long? TextSizeOf(IDocumentSegmentFormat format, string path)
{
try
{
return File.Exists(path) ? format.TextSizeOf(path) : null;
}
catch (Exception e) when (e is IOException or InvalidDataException or UnauthorizedAccessException)
{
return null;
}
}
}