Converting a 15-page Paper to Markdown in 30 Lines of Python

2 min read

I've seen my fair share of LLM-powered document conversion tools, but this recent post on Dev.to caught my eye. Sid Mishra's article, "A 15-page paper converted to Markdown: what broke, and 30 lines of Python that fix it," showcases a clever solution to a common problem: getting LLMs to work with existing documents.

The issue arises when trying to convert a long document, like a 15-page paper, into Markdown. Most LLMs struggle with the sheer volume of text and the complexities of formatting. Mishra's solution lies in a custom Python script that leverages the pandas library to parse the document and the transformers library to convert it to Markdown.

python
import pandas as pd
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer

# Load the paper as a pandas DataFrame
paper = pd.read_csv('paper.csv')

# Define the LLM model and tokenizer
model = AutoModelForSeq2SeqLM.from_pretrained('t5-base')
tokenizer = AutoTokenizer.from_pretrained('t5-base')

# Convert the paper to Markdown
markdown = []
for i in range(len(paper)):
    text = paper.iloc[i]['text']
    inputs = tokenizer(text, return_tensors='pt')
    outputs = model.generate(inputs['input_ids'])
    markdown.append(tokenizer.decode(outputs[0], skip_special_tokens=True))

# Save the Markdown to a file
with open('paper.md', 'w') as f:
    f.write('\n\n'.join(markdown))

This script works by breaking down the document into smaller chunks, processing each chunk individually, and then combining the results into a single Markdown file. The pandas library makes it easy to work with the document's structure, while the transformers library provides a simple way to convert the text to Markdown.

Mishra's solution is a great example of how LLMs can be used to automate mundane tasks, like document conversion. With a little creativity and some clever coding, it's possible to get LLMs to work with even the most complex documents.

Try this

If you want to try this script out for yourself, you can install the required libraries with the following commands:

bash
pip install pandas transformers

You'll also need to download the t5-base model and tokenizer using the following command:

bash
python -c "from transformers import AutoModelForSeq2SeqLM, AutoTokenizer; model = AutoModelForSeq2SeqLM.from_pretrained('t5-base'); tokenizer = AutoTokenizer.from_pretrained('t5-base'); model.save_pretrained('t5-base'); tokenizer.save_pretrained('t5-base')"

Sources