namespace AIStudio.Tools.DocumentSegments; /// /// How large the text of a document may be for a format which holds it in memory, as the memory of this computer /// allows, see IDocumentSegmentFormat.MaxTextSize. /// /// /// /// A format takes many times the size of the text of a document while reading and writing it, as bytes, as text, as /// the tree of its parser or the DOM of the Open XML SDK, and for the new words: its memory factor, measured with /// dense documents of many short paragraphs. The document may take a quarter of the memory of the computer; the rest /// belongs to the system, to other programs, to AI Studio itself, and maybe to a local model. A Raspberry Pi with /// 4 GB thus edits a web page of up to 11 MB, a computer with 16 GB one of up to 45 MB. /// /// /// The limit is 512 MB on any computer, since .NET holds no string with more than about a billion characters, and at /// least 1 MB, so that a message never names a limit of 0 MB. /// /// public static class DocumentMemoryBudget { /// /// The size of the largest text of a document on any computer, in bytes. /// public const long LARGEST_TEXT_SIZE = 512 * BYTES_PER_MEGABYTE; /// /// The number of bytes in a megabyte, in which the limit is counted and named. /// public const long BYTES_PER_MEGABYTE = 1024 * 1024; /// /// The part of the memory a document may take: a quarter. /// private const int SHARE_OF_MEMORY = 4; /// /// The memory to assume when .NET does not know it: as much as a small Raspberry Pi has. /// private const long ASSUMED_MEMORY = 4L * 1024 * BYTES_PER_MEGABYTE; /// /// Gets the size of the largest text of a document of a format on this computer. /// /// How many times the size of its text a document of the format takes in memory. /// The size in bytes, in whole megabytes. public static long MaxTextSize(int memoryFactor) => MaxTextSize(memoryFactor, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes); /// /// Gets the size of the largest text of a document of a format on a computer with the given memory. /// /// How many times the size of its text a document of the format takes in memory. /// The memory of the computer, or the limit of its container, in bytes; 0 when unknown. /// The size in bytes, in whole megabytes. public static long MaxTextSize(int memoryFactor, long totalMemory) { var memory = totalMemory > 0 ? totalMemory : ASSUMED_MEMORY; var megabytes = memory / SHARE_OF_MEMORY / memoryFactor / BYTES_PER_MEGABYTE; return Math.Clamp(megabytes * BYTES_PER_MEGABYTE, BYTES_PER_MEGABYTE, LARGEST_TEXT_SIZE); } /// /// Gets a size in whole megabytes, rounded up, so that a text just above a limit never reads as large as the limit. /// /// The size in bytes. public static long MegabytesOf(long bytes) => (bytes + BYTES_PER_MEGABYTE - 1) / BYTES_PER_MEGABYTE; }