-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #129 from knmlprz/chunking
Documents with chunks
- Loading branch information
Showing
3 changed files
with
62 additions
and
8 deletions.
There are no files selected for viewing
This file contains 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,36 @@ | ||
from documents.models import Document | ||
from pydantic import BaseModel | ||
from itertools import batched | ||
|
||
|
||
class ChunkData(BaseModel): | ||
text: str | ||
chunk_idx: int | ||
start_char: int | ||
end_char: int | ||
document_idx: int | ||
|
||
|
||
def split_document_into_chunks( | ||
document: Document, chunk_size: int = 100 | ||
) -> list[ChunkData]: | ||
"""Splits document into chunks of size chunk_size and returns them as ChunkData objects.""" | ||
chunks = [] | ||
start_char = 0 | ||
|
||
for i, chunk in enumerate(batched(document.text, chunk_size)): | ||
next_start_char = start_char + len(chunk) | ||
|
||
chunks.append( | ||
ChunkData( | ||
text="".join(chunk), | ||
chunk_idx=i, | ||
start_char=start_char, | ||
end_char=next_start_char - 1, | ||
document_idx=document.id, | ||
) | ||
) | ||
|
||
start_char = next_start_char | ||
|
||
return chunks |
This file contains 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 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