Skip to content
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

[Draft] Add Web API for MarkItDown #202

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
ffmpeg \
&& rm -rf /var/lib/apt/lists/*

RUN pip install markitdown
RUN pip install markitdown fastapi uvicorn

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
RUN pip install markitdown fastapi uvicorn
RUN pip install markitdown fastapi uvicorn python-multipart

Without python-multipart the API won't start.

It's still weird that markitdown is being installed here. This means if the source gets changed and you want to check if the Docker image works you first need to publish the package to pip... It would be better if the current src folder would be included here.

Copy link

@markthepixel markthepixel Jan 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use pip install "fastapi[standard]"

When you install with pip install "fastapi[standard]" it comes with some default optional standard dependencies.

If you don't want to have those optional dependencies, you can instead install pip install fastapi.


# Default USERID and GROUPID
ARG USERID=10000
ARG GROUPID=10000

USER $USERID:$GROUPID

ENTRYPOINT [ "markitdown" ]
ENTRYPOINT ["uvicorn", "src.markitdown.api:app", "--host", "0.0.0.0", "--port", "8000"]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't work: src/markitdown/api.py doesn't exists, so the API will not start.

You must copy the src directory:

Suggested change
ENTRYPOINT ["uvicorn", "src.markitdown.api:app", "--host", "0.0.0.0", "--port", "8000"]
COPY src /src
ENTRYPOINT ["uvicorn", "src.markitdown.api:app", "--host", "0.0.0.0", "--port", "8000"]

Note that in .dockerignore that everything is ignored, so the COPY won't work.
Modify the .dockerignore so the src/-folder gets included:

*
!/src

36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,42 @@ print(result.text_content)
docker build -t markitdown:latest .
docker run --rm -i markitdown:latest < ~/your-file.pdf > output.md
```

### Web API

You can also use MarkItDown via a REST endpoint. The Web API is built using FastAPI and can be run using Docker.

#### Running the Web API

1. Build the Docker image:

```sh
docker build -t markitdown-api:latest .
```

2. Run the Docker container:

```sh
docker run --rm -p 8000:8000 markitdown-api:latest
```

The Web API will be available at `http://localhost:8000`.

#### Using the Web API

The Web API provides a single endpoint `/convert` that accepts a file and returns the converted markdown.

- **Endpoint:** `/convert`
- **Method:** `POST`
- **Request Body:** Multipart form data with a file field named `file`
- **Response:** JSON object with a `markdown` field containing the converted markdown

Example using `curl`:

```sh
curl -X POST "http://localhost:8000/convert" -F "[email protected]"
```

<details>

<summary>Batch Processing Multiple Files</summary>
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ dependencies = [
"pathvalidate",
"charset-normalizer",
"openai",
"fastapi",
"uvicorn",
]

[project.urls]
Expand Down
10 changes: 9 additions & 1 deletion src/markitdown/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from textwrap import dedent
from .__about__ import __version__
from ._markitdown import MarkItDown, DocumentConverterResult
import uvicorn


def main():
Expand Down Expand Up @@ -57,9 +58,16 @@ def main():
"--output",
help="Output file name. If not provided, output is written to stdout.",
)
parser.add_argument(
"--api",
action="api",
help="Start the API server",
)
args = parser.parse_args()

if args.filename is None:
if args.api:
uvicorn.run("src.markitdown.api:app", host="0.0.0.0", port=8000)
elif args.filename is None:
markitdown = MarkItDown()
result = markitdown.convert_stream(sys.stdin.buffer)
_handle_output(args, result)
Expand Down
32 changes: 32 additions & 0 deletions src/markitdown/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import FileResponse
from markitdown import MarkItDown
import os

app = FastAPI()

@app.post("/convert")
async def convert(file: UploadFile = File(...)):
if not file.filename:
raise HTTPException(status_code=400, detail="No file uploaded")

try:
contents = await file.read()
temp_file_path = f"/tmp/{file.filename}"
with open(temp_file_path, "wb") as temp_file:
temp_file.write(contents)

markitdown = MarkItDown()
result = markitdown.convert(temp_file_path)

# output_file_path = f"/tmp/{os.path.splitext(file.filename)[0]}.md"
# with open(output_file_path, "w") as output_file:
# output_file.write(result.text_content)

os.remove(temp_file_path)

# return FileResponse(output_file_path, filename=f"{os.path.splitext(file.filename)[0]}.md")
return {"markdown": result.text_content}

except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
Loading