-
Notifications
You must be signed in to change notification settings - Fork 841
Introduce Markdown readers #6969
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 11 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
ae35f1d
add Markdig dependency
adamsitnik d453475
move code as-is
adamsitnik 00980a3
solve the warnings
adamsitnik 6461a66
add MarkItDownReader as-is
adamsitnik 5ea4489
solve the warnings
adamsitnik 198bb33
add tests
adamsitnik dde3cf5
fix the build
adamsitnik bb6e4b7
code cleanup after reading it again
adamsitnik 7c0e0ce
[ConditionalTheory] does not skip test cases that throw SkipTestExcep…
adamsitnik 2148921
apply to [ConditionalFact] that can also throw when MarkItDown is not…
adamsitnik fbf5235
rename Microsoft.Extensions.DataIngestion.Markdown to Microsoft.Exten…
adamsitnik c01c970
Merge remote-tracking branch 'upstream/main' into markdownReaders
adamsitnik 19ece18
address code review feedback:
adamsitnik 8d548d2
address code review feedback: manually set ProcessStartInfo.WorkingDi…
adamsitnik fc15d01
remove the need of storing test files:
adamsitnik a172cd1
Merge remote-tracking branch 'upstream/main' into markdownReaders
adamsitnik 5cac324
fix static analysis warning...
adamsitnik File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
121 changes: 121 additions & 0 deletions
121
src/Libraries/Microsoft.Extensions.DataIngestion.MarkItDown/MarkItDownReader.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.Diagnostics; | ||
| using System.IO; | ||
| using System.Text; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Shared.Diagnostics; | ||
|
|
||
| namespace Microsoft.Extensions.DataIngestion; | ||
|
|
||
| /// <summary> | ||
| /// Reads documents by converting them to Markdown using the <see href="https://github.com/microsoft/markitdown">MarkItDown</see> tool. | ||
| /// </summary> | ||
| public class MarkItDownReader : IngestionDocumentReader | ||
| { | ||
| private readonly string _exePath; | ||
| private readonly bool _extractImages; | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="MarkItDownReader"/> class. | ||
| /// </summary> | ||
| /// <param name="exePath">The path to the MarkItDown executable. When not provided, "markitdown" needs to be added to PATH.</param> | ||
| /// <param name="extractImages">A value indicating whether to extract images.</param> | ||
| public MarkItDownReader(string exePath = "markitdown", bool extractImages = false) | ||
| { | ||
| _exePath = Throw.IfNullOrEmpty(exePath); | ||
| _extractImages = extractImages; | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public override async Task<IngestionDocument> ReadAsync(FileInfo source, string identifier, string? mediaType = null, CancellationToken cancellationToken = default) | ||
| { | ||
| _ = Throw.IfNull(source); | ||
| _ = Throw.IfNullOrEmpty(identifier); | ||
|
|
||
| if (!source.Exists) | ||
| { | ||
| throw new FileNotFoundException("The specified file does not exist.", source.FullName); | ||
| } | ||
|
|
||
| ProcessStartInfo startInfo = new() | ||
| { | ||
| FileName = _exePath, | ||
| UseShellExecute = false, | ||
| CreateNoWindow = true, | ||
| RedirectStandardOutput = true, | ||
| StandardOutputEncoding = Encoding.UTF8, | ||
| }; | ||
|
|
||
| // Force UTF-8 encoding in the environment (will produce garbage otherwise). | ||
| startInfo.Environment["PYTHONIOENCODING"] = "utf-8"; | ||
| startInfo.Environment["LC_ALL"] = "C.UTF-8"; | ||
| startInfo.Environment["LANG"] = "C.UTF-8"; | ||
|
|
||
| #if NET | ||
| startInfo.ArgumentList.Add(source.FullName); | ||
| if (_extractImages) | ||
| { | ||
| startInfo.ArgumentList.Add("--keep-data-uris"); | ||
| } | ||
| #else | ||
| startInfo.Arguments = $"\"{source.FullName}\"" + (_extractImages ? " --keep-data-uris" : string.Empty); | ||
| #endif | ||
|
|
||
| string outputContent = string.Empty; | ||
| using (Process process = new() { StartInfo = startInfo }) | ||
| { | ||
| process.Start(); | ||
|
|
||
| outputContent = await process.StandardOutput.ReadToEndAsync(cancellationToken).ConfigureAwait(false); | ||
adamsitnik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| #if NET | ||
| await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false); | ||
| #else | ||
| process.WaitForExit(); | ||
| #endif | ||
|
|
||
| if (process.ExitCode != 0) | ||
| { | ||
| throw new InvalidOperationException($"MarkItDown process failed with exit code {process.ExitCode}."); | ||
| } | ||
| } | ||
|
|
||
| return MarkdownParser.Parse(outputContent, identifier); | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| /// <remarks>The contents of <paramref name="source"/> are copied to a temporary file.</remarks> | ||
| public override async Task<IngestionDocument> ReadAsync(Stream source, string identifier, string mediaType, CancellationToken cancellationToken = default) | ||
| { | ||
| _ = Throw.IfNull(source); | ||
| _ = Throw.IfNullOrEmpty(identifier); | ||
|
|
||
| // Instead of creating a temporary file, we could write to the StandardInput of the process. | ||
| // MarkItDown says it supports reading from stdin, but it does not work as expected. | ||
| // Even the sample command line does not work with stdin: "cat example.pdf | markitdown" | ||
| // I can be doing something wrong, but for now, let's write to a temporary file. | ||
| string inputFilePath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); | ||
| using (FileStream inputFile = new(inputFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 1, FileOptions.Asynchronous)) | ||
adamsitnik marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
adamsitnik marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| await source | ||
| #if NET | ||
| .CopyToAsync(inputFile, cancellationToken) | ||
| #else | ||
| .CopyToAsync(inputFile) | ||
| #endif | ||
| .ConfigureAwait(false); | ||
| } | ||
|
|
||
| try | ||
| { | ||
| return await ReadAsync(new FileInfo(inputFilePath), identifier, mediaType, cancellationToken).ConfigureAwait(false); | ||
| } | ||
| finally | ||
| { | ||
| File.Delete(inputFilePath); | ||
| } | ||
| } | ||
| } | ||
25 changes: 25 additions & 0 deletions
25
....Extensions.DataIngestion.MarkItDown/Microsoft.Extensions.DataIngestion.MarkItDown.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFrameworks>$(TargetFrameworks);netstandard2.0</TargetFrameworks> | ||
| <RootNamespace>Microsoft.Extensions.DataIngestion</RootNamespace> | ||
|
|
||
| <!-- we are not ready to publish yet --> | ||
| <IsPackable>false</IsPackable> | ||
| <Stage>preview</Stage> | ||
| <EnablePackageValidation>false</EnablePackageValidation> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <Compile Include="..\Microsoft.Extensions.DataIngestion.Markdig\MarkdownParser.cs" Link="MarkdownParser.cs" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\Microsoft.Extensions.DataIngestion.Abstractions\Microsoft.Extensions.DataIngestion.Abstractions.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Markdig.Signed" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.