using AIStudio.Tools.DocumentSegments; using AIStudio.Tools.Rust; using Microsoft.AspNetCore.Components; namespace AIStudio.Components; /// /// The field with which the user chooses the document an assistant works on, e.g., to translate it. /// /// /// 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. /// public partial class SelectDocument : MSGComponentBase { /// /// The path of the chosen document; empty while none is chosen. /// [Parameter] public string Document { get; set; } = string.Empty; /// /// Called with the path of the document the user chose. /// [Parameter] public EventCallback DocumentChanged { get; set; } /// /// The title of the file dialog, e.g., "Select a document to translate". /// [Parameter, EditorRequired] public string DialogTitle { get; set; } = string.Empty; /// /// Whether the field is disabled, e.g., while the assistant works. /// [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; } /// /// 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. /// 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; } } }