|
| 1 | +from html.parser import HTMLParser |
| 2 | +from typing import Annotated |
| 3 | + |
| 4 | +import httpx |
| 5 | + |
| 6 | +from vechord.chunk import RegexChunker |
| 7 | +from vechord.embedding import SpacyDenseEmbedding |
| 8 | +from vechord.registry import VechordRegistry |
| 9 | +from vechord.rerank import CohereReranker |
| 10 | +from vechord.spec import ForeignKey, Keyword, PrimaryKeyAutoIncrease, Table, Vector |
| 11 | + |
| 12 | +URL = "https://paulgraham.com/{}.html" |
| 13 | +DenseVector = Vector[96] |
| 14 | +emb = SpacyDenseEmbedding() |
| 15 | +chunker = RegexChunker(size=1024, overlap=0) |
| 16 | +reranker = CohereReranker() |
| 17 | + |
| 18 | + |
| 19 | +class EssayParser(HTMLParser): |
| 20 | + def __init__(self, *, convert_charrefs: bool = ...) -> None: |
| 21 | + super().__init__(convert_charrefs=convert_charrefs) |
| 22 | + self.content = [] |
| 23 | + self.skip = False |
| 24 | + |
| 25 | + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: |
| 26 | + if tag in ("script", "style"): |
| 27 | + self.skip = True |
| 28 | + |
| 29 | + def handle_endtag(self, tag: str) -> None: |
| 30 | + if tag in ("script", "style"): |
| 31 | + self.skip = False |
| 32 | + |
| 33 | + def handle_data(self, data: str) -> None: |
| 34 | + if not self.skip: |
| 35 | + self.content.append(data.strip()) |
| 36 | + |
| 37 | + |
| 38 | +class Document(Table, kw_only=True): |
| 39 | + uid: PrimaryKeyAutoIncrease | None = None |
| 40 | + title: str = "" |
| 41 | + text: str |
| 42 | + |
| 43 | + |
| 44 | +class Chunk(Table, kw_only=True): |
| 45 | + uid: PrimaryKeyAutoIncrease | None = None |
| 46 | + doc_id: Annotated[int, ForeignKey[Document.uid]] |
| 47 | + text: str |
| 48 | + vector: DenseVector |
| 49 | + keyword: Keyword |
| 50 | + |
| 51 | + |
| 52 | +vr = VechordRegistry("hybrid", "postgresql://postgres:postgres@172.17.0.1:5432/") |
| 53 | +vr.register([Document, Chunk]) |
| 54 | + |
| 55 | + |
| 56 | +@vr.inject(output=Document) |
| 57 | +def load_document(title: str) -> Document: |
| 58 | + with httpx.Client() as client: |
| 59 | + resp = client.get(URL.format(title)) |
| 60 | + if resp.is_error: |
| 61 | + raise RuntimeError(f"Failed to fetch the document `{title}`") |
| 62 | + parser = EssayParser() |
| 63 | + parser.feed(resp.text) |
| 64 | + return Document(title=title, text="\n".join(t for t in parser.content if t)) |
| 65 | + |
| 66 | + |
| 67 | +@vr.inject(input=Document, output=Chunk) |
| 68 | +def chunk_document(uid: int, text: str) -> list[Chunk]: |
| 69 | + chunks = chunker.segment(text) |
| 70 | + return [ |
| 71 | + Chunk( |
| 72 | + doc_id=uid, |
| 73 | + text=chunk, |
| 74 | + vector=emb.vectorize_chunk(chunk), |
| 75 | + keyword=Keyword(chunk), |
| 76 | + ) |
| 77 | + for chunk in chunks |
| 78 | + ] |
| 79 | + |
| 80 | + |
| 81 | +def search_and_rerank(query: str, topk: int) -> list[Chunk]: |
| 82 | + text_retrieves = vr.search_by_keyword(Chunk, query, topk=topk) |
| 83 | + vec_retrievse = vr.search_by_vector(Chunk, emb.vectorize_query(query), topk=topk) |
| 84 | + chunks = list( |
| 85 | + {chunk.uid: chunk for chunk in text_retrieves + vec_retrievse}.values() |
| 86 | + ) |
| 87 | + indices = reranker.rerank(query, [chunk.text for chunk in chunks]) |
| 88 | + return [chunks[i] for i in indices[:topk]] |
| 89 | + |
| 90 | + |
| 91 | +if __name__ == "__main__": |
| 92 | + load_document("smart") |
| 93 | + chunk_document() |
| 94 | + chunks = search_and_rerank("smart", 3) |
| 95 | + print(chunks) |
0 commit comments