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

Add docx reader #205

Open
wants to merge 2 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
1 change: 1 addition & 0 deletions dev-requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ pymupdf
build
types-requests
numpy
unstructured==0.10.30
20 changes: 19 additions & 1 deletion paperqa/readers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from typing import List

from html2text import html2text
from langchain.document_loaders import UnstructuredWordDocumentLoader
from langchain.text_splitter import TokenTextSplitter

from .types import Doc, Text
Expand Down Expand Up @@ -125,6 +126,21 @@ def parse_code_txt(path: Path, doc: Doc, chunk_chars: int, overlap: int) -> List
return texts


def parse_docx(
path: Path,
doc: Doc,
chunk_chars: int,
overlap: int,
) -> List[Text]:
docs = UnstructuredWordDocumentLoader(path).load()
text_splitter = TokenTextSplitter(chunk_size=chunk_chars, chunk_overlap=overlap)
docs = text_splitter.split_documents(docs)
return [
Text(text=d.page_content, name=f"{doc.docname} chunk {i}", doc=doc)
for i, d in enumerate(docs)
]


def read_doc(
path: Path,
doc: Doc,
Expand All @@ -134,7 +150,7 @@ def read_doc(
) -> List[Text]:
"""Parse a document into chunks."""
str_path = str(path)
if str_path.endswith(".pdf"):
if str_path.endswith((".pdf", ".PDF")):
if force_pypdf:
return parse_pdf(path, doc, chunk_chars, overlap)
try:
Expand All @@ -145,5 +161,7 @@ def read_doc(
return parse_txt(path, doc, chunk_chars, overlap)
elif str_path.endswith(".html"):
return parse_txt(path, doc, chunk_chars, overlap, html=True)
elif str_path.endswith(".docx"):
return parse_docx(path, doc, chunk_chars, overlap)
else:
return parse_code_txt(path, doc, chunk_chars, overlap)
2 changes: 2 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
"PyCryptodome",
"html2text",
"tiktoken>=0.4.0",
"python-docx>=1.1.0",
"unstructured>=0.10.30",
],
test_suite="tests",
long_description=long_description,
Expand Down