|
| 1 | + |
| 2 | + |
| 3 | +from nano_graphrag._utils import encode_string_by_tiktoken |
| 4 | +from nano_graphrag.base import QueryParam |
| 5 | +from nano_graphrag.graphrag import GraphRAG |
| 6 | + |
| 7 | + |
| 8 | +def chunking_by_specific_separators( |
| 9 | + content: str, overlap_token_size=128, max_token_size=1024, tiktoken_model="gpt-4o", |
| 10 | +): |
| 11 | + from langchain_text_splitters import RecursiveCharacterTextSplitter |
| 12 | + |
| 13 | + |
| 14 | + text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(chunk_size=max_token_size, |
| 15 | + chunk_overlap=overlap_token_size, |
| 16 | + # length_function=lambda x: len(encode_string_by_tiktoken(x)), |
| 17 | + model_name=tiktoken_model, |
| 18 | + is_separator_regex=False, |
| 19 | + separators=[ |
| 20 | + # Paragraph separators |
| 21 | + "\n\n", |
| 22 | + "\r\n\r\n", |
| 23 | + # Line breaks |
| 24 | + "\n", |
| 25 | + "\r\n", |
| 26 | + # Sentence ending punctuation |
| 27 | + "。", # Chinese period |
| 28 | + ".", # Full-width dot |
| 29 | + ".", # English period |
| 30 | + "!", # Chinese exclamation mark |
| 31 | + "!", # English exclamation mark |
| 32 | + "?", # Chinese question mark |
| 33 | + "?", # English question mark |
| 34 | + # Whitespace characters |
| 35 | + " ", # Space |
| 36 | + "\t", # Tab |
| 37 | + "\u3000", # Full-width space |
| 38 | + # Special characters |
| 39 | + "\u200b", # Zero-width space (used in some Asian languages) |
| 40 | + # Final fallback |
| 41 | + "", |
| 42 | + ]) |
| 43 | + texts = text_splitter.split_text(content) |
| 44 | + |
| 45 | + results = [] |
| 46 | + for index, chunk_content in enumerate(texts): |
| 47 | + |
| 48 | + results.append( |
| 49 | + { |
| 50 | + # "tokens": None, |
| 51 | + "content": chunk_content.strip(), |
| 52 | + "chunk_order_index": index, |
| 53 | + } |
| 54 | + ) |
| 55 | + return results |
| 56 | + |
| 57 | + |
| 58 | +WORKING_DIR = "./nano_graphrag_cache_local_embedding_TEST" |
| 59 | +rag = GraphRAG( |
| 60 | + working_dir=WORKING_DIR, |
| 61 | + chunk_func=chunking_by_specific_separators, |
| 62 | +) |
| 63 | + |
| 64 | +with open("../tests/mock_data.txt", encoding="utf-8-sig") as f: |
| 65 | + FAKE_TEXT = f.read() |
| 66 | + |
| 67 | +# rag.insert(FAKE_TEXT) |
| 68 | +print(rag.query("What the main theme of this story?", param=QueryParam(mode="local"))) |
0 commit comments